diff options
Diffstat (limited to 'browser/components')
923 files changed, 0 insertions, 78552 deletions
diff --git a/browser/components/contextualidentity/test/browser/.eslintrc.js b/browser/components/contextualidentity/test/browser/.eslintrc.js deleted file mode 100644 index e25a6863e..000000000 --- a/browser/components/contextualidentity/test/browser/.eslintrc.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ], - - "rules": { - "no-undef": "error" - } -}; diff --git a/browser/components/contextualidentity/test/browser/browser.ini b/browser/components/contextualidentity/test/browser/browser.ini deleted file mode 100644 index 55083f8d2..000000000 --- a/browser/components/contextualidentity/test/browser/browser.ini +++ /dev/null @@ -1,30 +0,0 @@ -[DEFAULT] -support-files = - empty_file.html - file_reflect_cookie_into_title.html - favicon-normal32.png - file_set_storages.html - serviceworker.html - worker.js - -[browser_aboutURLs.js] -[browser_eme.js] -[browser_favicon.js] -[browser_forgetaboutsite.js] -[browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js] -[browser_forgetAPI_EME_forgetThisSite.js] -[browser_forgetAPI_quota_clearStoragesForPrincipal.js] -[browser_newtabButton.js] -[browser_usercontext.js] -[browser_usercontextid_tabdrop.js] -skip-if = os == "mac" || os == "win" # Intermittent failure - bug 1268276 -[browser_windowName.js] -tags = openwindow -[browser_windowOpen.js] -tags = openwindow -[browser_serviceworkers.js] -[browser_broadcastchannel.js] -[browser_blobUrl.js] -[browser_middleClick.js] -[browser_imageCache.js] -[browser_count_and_remove.js] diff --git a/browser/components/contextualidentity/test/browser/browser_aboutURLs.js b/browser/components/contextualidentity/test/browser/browser_aboutURLs.js deleted file mode 100644 index 586bca37f..000000000 --- a/browser/components/contextualidentity/test/browser/browser_aboutURLs.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; - -// For some about: URLs, they will take more time to load and cause timeout. -// See Bug 1270998. -requestLongerTimeout(2); - -add_task(function* () { - let aboutURLs = []; - - // List of about: URLs that will initiate network requests. - let networkURLs = [ - "credits", - "telemetry" // about:telemetry will fetch Telemetry asynchrounously and takes - // longer, we skip this for now. - ]; - - let ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); - for (let cid in Cc) { - let result = cid.match(/@mozilla.org\/network\/protocol\/about;1\?what\=(.*)$/); - if (!result) { - continue; - } - - let aboutType = result[1]; - let contract = "@mozilla.org/network/protocol/about;1?what=" + aboutType; - try { - let am = Cc[contract].getService(Ci.nsIAboutModule); - let uri = ios.newURI("about:"+aboutType, null, null); - let flags = am.getURIFlags(uri); - if (!(flags & Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT) && - networkURLs.indexOf(aboutType) == -1) { - aboutURLs.push(aboutType); - } - } catch (e) { - // getService might have thrown if the component doesn't actually - // implement nsIAboutModule - } - } - - for (let url of aboutURLs) { - info("Loading about:" + url); - let tab = gBrowser.addTab("about:"+url, {userContextId: 1}); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - ok(true, "Done loading about:" + url); - - yield BrowserTestUtils.removeTab(tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_blobUrl.js b/browser/components/contextualidentity/test/browser/browser_blobUrl.js deleted file mode 100644 index 8a441311e..000000000 --- a/browser/components/contextualidentity/test/browser/browser_blobUrl.js +++ /dev/null @@ -1,78 +0,0 @@ -"use strict"; - -// Here we want to test that blob URLs are not available cross containers. - -const BASE_URI = "http://mochi.test:8888/browser/browser/components/" - + "contextualidentity/test/browser/empty_file.html"; - -add_task(function* setup() { - yield new Promise((resolve) => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}, resolve); - }); -}); - - -add_task(function* test() { - info("Creating a tab with UCI = 1..."); - let tab1 = gBrowser.addTab(BASE_URI, {userContextId: 1}); - is(tab1.getAttribute('usercontextid'), 1, "New tab has UCI equal 1"); - - let browser1 = gBrowser.getBrowserForTab(tab1); - yield BrowserTestUtils.browserLoaded(browser1); - - let blobURL; - - info("Creating a blob URL..."); - yield ContentTask.spawn(browser1, null, function() { - return Promise.resolve(content.window.URL.createObjectURL(new content.window.Blob([123]))); - }).then(newURL => { blobURL = newURL }); - - info("Blob URL: " + blobURL); - - info("Creating a tab with UCI = 2..."); - let tab2 = gBrowser.addTab(BASE_URI, {userContextId: 2}); - is(tab2.getAttribute('usercontextid'), 2, "New tab has UCI equal 2"); - - let browser2 = gBrowser.getBrowserForTab(tab2); - yield BrowserTestUtils.browserLoaded(browser2); - - yield ContentTask.spawn(browser2, blobURL, function(url) { - return new Promise(resolve => { - var xhr = new content.window.XMLHttpRequest(); - xhr.onerror = function() { resolve("SendErrored"); } - xhr.onload = function() { resolve("SendLoaded"); } - xhr.open("GET", url); - xhr.send(); - }); - }).then(status => { - is(status, "SendErrored", "Using a blob URI from one user context id in another should not work"); - }); - - info("Creating a tab with UCI = 1..."); - let tab3 = gBrowser.addTab(BASE_URI, {userContextId: 1}); - is(tab3.getAttribute('usercontextid'), 1, "New tab has UCI equal 1"); - - let browser3 = gBrowser.getBrowserForTab(tab3); - yield BrowserTestUtils.browserLoaded(browser3); - - yield ContentTask.spawn(browser3, blobURL, function(url) { - return new Promise(resolve => { - var xhr = new content.window.XMLHttpRequest(); - xhr.open("GET", url); - try { - xhr.send(); - resolve("SendSucceeded"); - } catch (e) { - resolve("SendThrew"); - } - }); - }).then(status => { - is(status, "SendSucceeded", "Using a blob URI within a single user context id should work"); - }); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); - yield BrowserTestUtils.removeTab(tab3); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js b/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js deleted file mode 100644 index a821ce96b..000000000 --- a/browser/components/contextualidentity/test/browser/browser_broadcastchannel.js +++ /dev/null @@ -1,80 +0,0 @@ -let { classes: Cc, interfaces: Ci } = Components; - -const BASE_ORIGIN = "http://example.com"; -const URI = BASE_ORIGIN + - "/browser/browser/components/contextualidentity/test/browser/empty_file.html"; - -// opens `uri' in a new tab with the provided userContextId and focuses it. -// returns the newly opened tab -function* openTabInUserContext(uri, userContextId) { - // open the tab in the correct userContextId - let tab = gBrowser.addTab(uri, {userContextId}); - - // select tab and make sure its browser is focused - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -add_task(function* setup() { - // make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}, resolve); - }); -}); - -add_task(function* test() { - let receiver = yield* openTabInUserContext(URI, 2); - - let channelName = "contextualidentity-broadcastchannel"; - - // reflect the received message on title - yield ContentTask.spawn(receiver.browser, channelName, - function (name) { - content.window.testPromise = new content.window.Promise(resolve => { - content.window.bc = new content.window.BroadcastChannel(name); - content.window.bc.onmessage = function (e) { - content.document.title += e.data; - resolve(); - } - }); - } - ); - - let sender1 = yield* openTabInUserContext(URI, 1); - let sender2 = yield* openTabInUserContext(URI, 2); - sender1.message = "Message from user context #1"; - sender2.message = "Message from user context #2"; - - // send a message from a tab in different user context first - // then send a message from a tab in the same user context - for (let sender of [sender1, sender2]) { - yield ContentTask.spawn( - sender.browser, - { name: channelName, message: sender.message }, - function (opts) { - let bc = new content.window.BroadcastChannel(opts.name); - bc.postMessage(opts.message); - }); - } - - // Since sender1 sends before sender2, if the title is exactly - // sender2's message, sender1's message must've been blocked - yield ContentTask.spawn(receiver.browser, sender2.message, - function* (message) { - yield content.window.testPromise.then(function() { - is(content.document.title, message, - "should only receive messages from the same user context"); - }); - } - ); - - gBrowser.removeTab(sender1.tab); - gBrowser.removeTab(sender2.tab); - gBrowser.removeTab(receiver.tab); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_count_and_remove.js b/browser/components/contextualidentity/test/browser/browser_count_and_remove.js deleted file mode 100644 index 23b7e948a..000000000 --- a/browser/components/contextualidentity/test/browser/browser_count_and_remove.js +++ /dev/null @@ -1,34 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -Cu.import("resource://gre/modules/ContextualIdentityService.jsm"); - -function openTabInUserContext(userContextId) { - let tab = gBrowser.addTab("about:blank", {userContextId}); - gBrowser.selectedTab = tab; -} - -add_task(function* setup() { - // make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}); -}); - -add_task(function* test() { - is(ContextualIdentityService.countContainerTabs(), 0, "0 container tabs by default."); - - openTabInUserContext(1); - is(ContextualIdentityService.countContainerTabs(), 1, "1 container tab created"); - - openTabInUserContext(1); - is(ContextualIdentityService.countContainerTabs(), 2, "2 container tab created"); - - openTabInUserContext(2); - is(ContextualIdentityService.countContainerTabs(), 3, "3 container tab created"); - - ContextualIdentityService.closeAllContainerTabs(); - is(ContextualIdentityService.countContainerTabs(), 0, "0 container tab at the end."); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_eme.js b/browser/components/contextualidentity/test/browser/browser_eme.js deleted file mode 100644 index 557648d60..000000000 --- a/browser/components/contextualidentity/test/browser/browser_eme.js +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Bug 1283325 - A test case to test the EME is originAttributes aware or not. - */ -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -const TEST_HOST = "example.com"; -const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/"; - -const TESTKEY = { - initDataType: 'keyids', - initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}', - kid: "LwVHf8JLtPrv2GUXFW2v_A", - key: "97b9ddc459c8d5ff23c1f2754c95abe8", - sessionType: 'persistent-license', -}; - -const USER_ID_DEFAULT = 0; -const USER_ID_PERSONAL = 1; - -function* openTabInUserContext(uri, userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(uri, {userContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerDocument.defaultView.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function HexToBase64(hex) -{ - var bin = ""; - for (var i = 0; i < hex.length; i += 2) { - bin += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return window.btoa(bin).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} - -function Base64ToHex(str) -{ - var bin = window.atob(str.replace(/-/g, "+").replace(/_/g, "/")); - var res = ""; - for (var i = 0; i < bin.length; i++) { - res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2); - } - return res; -} - -function ByteArrayToHex(array) { - let bin = String.fromCharCode.apply(null, new Uint8Array(array)); - let res = ""; - - for (let i = 0; i < bin.length; i++) { - res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2); - } - - return res; -} - -function generateKeyObject(aKid, aKey) { - let keyObj = { - kty: 'oct', - kid: aKid, - k: HexToBase64(aKey), - }; - - return new TextEncoder().encode(JSON.stringify({ - keys: [keyObj] - })); -} - -function generateKeyInfo(aData) { - let keyInfo = { - initDataType: aData.initDataType, - initData: new TextEncoder().encode(aData.initData), - sessionType: aData.sessionType, - keyObj: generateKeyObject(aData.kid, aData.key), - }; - - return keyInfo; -} - -add_task(function* setup() { - // Make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - [ "privacy.userContext.enabled", true ], - [ "media.mediasource.enabled", true ], - [ "media.eme.apiVisible", true ], - [ "media.mediasource.webm.enabled", true ], - [ "media.clearkey.persistent-license.enabled", true ], - ]}, resolve); - }); -}); - -add_task(function* test() { - // Open a tab with the default container. - let defaultContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_DEFAULT); - - // Generate the key info for the default container. - let keyInfo = generateKeyInfo(TESTKEY); - - // Update the media key for the default container. - let result = yield ContentTask.spawn(defaultContainer.browser, keyInfo, function* (aKeyInfo) { - let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey', - [{ - initDataTypes: [aKeyInfo.initDataType], - videoCapabilities: [{contentType: 'video/webm'}], - sessionTypes: ['persistent-license'], - persistentState: 'required', - }]); - let mediaKeys = yield access.createMediaKeys(); - let session = mediaKeys.createSession(aKeyInfo.sessionType); - let res = {}; - - // Insert the media key. - yield new Promise(resolve => { - session.addEventListener("message", function(event) { - session.update(aKeyInfo.keyObj).then( - () => { resolve(); } - ).catch( - () => { - ok(false, "Update the media key fail."); - resolve(); - } - ); - }); - - session.generateRequest(aKeyInfo.initDataType, aKeyInfo.initData); - }); - - let map = session.keyStatuses; - - is(map.size, 1, "One media key has been added."); - - if (map.size === 1) { - res.keyId = map.keys().next().value; - res.sessionId = session.sessionId; - } - - // Close the session. - session.close(); - yield session.closed; - - return res; - }); - - // Check the media key ID. - is(ByteArrayToHex(result.keyId), Base64ToHex(TESTKEY.kid), "The key Id of the default container is correct."); - - // Store the sessionId for the further checking. - keyInfo.sessionId = result.sessionId; - - // Open a tab with personal container. - let personalContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_PERSONAL); - - yield ContentTask.spawn(personalContainer.browser, keyInfo, function* (aKeyInfo) { - let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey', - [{ - initDataTypes: [aKeyInfo.initDataType], - videoCapabilities: [{contentType: 'video/webm'}], - sessionTypes: ['persistent-license'], - persistentState: 'required', - }]); - let mediaKeys = yield access.createMediaKeys(); - let session = mediaKeys.createSession(aKeyInfo.sessionType); - - // First, load the session to check that mediakeys do not share with - // default container. - yield session.load(aKeyInfo.sessionId); - - let map = session.keyStatuses; - - // Check that there is no media key here. - is(map.size, 0, "No media key should be here for the personal container."); - }); - - // Close default container tab. - yield BrowserTestUtils.removeTab(defaultContainer.tab); - - // Close personal container tab. - yield BrowserTestUtils.removeTab(personalContainer.tab); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_favicon.js b/browser/components/contextualidentity/test/browser/browser_favicon.js deleted file mode 100644 index a0a7eb208..000000000 --- a/browser/components/contextualidentity/test/browser/browser_favicon.js +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Bug 1270678 - A test case to test does the favicon obey originAttributes. - */ -let { classes: Cc, interfaces: Ci, utils: Cu } = Components; - -Cu.import("resource://gre/modules/PlacesUtils.jsm"); -Cu.import("resource://gre/modules/NetUtil.jsm"); -let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {}); - -const USER_CONTEXTS = [ - "default", - "personal", - "work", -]; - -let gHttpServer = null; -let gUserContextId; -let gFaviconData; - -function getIconFile() { - new Promise(resolve => { - NetUtil.asyncFetch({ - uri: "http://www.example.com/browser/browser/components/contextualidentity/test/browser/favicon-normal32.png", - loadUsingSystemPrincipal: true, - contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_FAVICON - }, function(inputStream, status) { - let size = inputStream.available(); - gFaviconData = NetUtil.readInputStreamToString(inputStream, size); - resolve(); - }); - }); -} - -function* openTabInUserContext(uri, userContextId) { - // open the tab in the correct userContextId - let tab = gBrowser.addTab(uri, {userContextId}); - - // select tab and make sure its browser is focused - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function loadIndexHandler(metadata, response) { - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "text/html", false); - let body = ` - <!DOCTYPE HTML> - <html> - <head> - <meta charset='utf-8'> - <title>Favicon Test</title> - </head> - <body> - Favicon!! - </body> - </html>`; - response.bodyOutputStream.write(body, body.length); -} - -function loadFaviconHandler(metadata, response) { - let expectedCookie = "userContext=" + USER_CONTEXTS[gUserContextId]; - - if (metadata.hasHeader("Cookie")) { - is(metadata.getHeader("Cookie"), expectedCookie, "The cookie has matched with the expected cookie."); - } else { - ok(false, "The request should have a cookie."); - } - - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "image/png", false); - response.bodyOutputStream.write(gFaviconData, gFaviconData.length); -} - -add_task(function* setup() { - // Make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}, resolve); - }); - - // Create a http server for the image cache test. - if (!gHttpServer) { - gHttpServer = new HttpServer(); - gHttpServer.registerPathHandler('/', loadIndexHandler); - gHttpServer.registerPathHandler('/favicon.png', loadFaviconHandler); - gHttpServer.start(-1); - } -}); - -registerCleanupFunction(() => { - gHttpServer.stop(() => { - gHttpServer = null; - }); -}); - -add_task(function* test() { - waitForExplicitFinish(); - - // First, get the icon data. - yield getIconFile(); - - let serverPort = gHttpServer.identity.primaryPort; - let testURL = "http://localhost:" + serverPort + "/"; - let testFaviconURL = "http://localhost:" + serverPort + "/favicon.png"; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - gUserContextId = userContextId; - - // Load the page in 3 different contexts and set a cookie - // which should only be visible in that context. - - // Open our tab in the given user context. - let tabInfo = yield* openTabInUserContext(testURL, userContextId); - - // Write a cookie according to the userContext. - yield ContentTask.spawn(tabInfo.browser, { userContext: USER_CONTEXTS[userContextId] }, function (arg) { - content.document.cookie = "userContext=" + arg.userContext; - }); - - let pageURI = NetUtil.newURI(testURL); - let favIconURI = NetUtil.newURI(testFaviconURL); - - yield new Promise(resolve => { - PlacesUtils.favicons.setAndFetchFaviconForPage(pageURI, favIconURI, - true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, { - onComplete() { - resolve(); - }, - }, - tabInfo.browser.contentPrincipal); - }); - - yield BrowserTestUtils.removeTab(tabInfo.tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js deleted file mode 100644 index 1a97448c0..000000000 --- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Bug 1278037 - A Test case for checking whether forgetting APIs are working for the media key. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -const TEST_HOST = "example.com"; -const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/"; - -const USER_CONTEXTS = [ - "default", - "personal", -]; - -const TEST_EME_KEY = { - initDataType: 'keyids', - initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}', - kid: "LwVHf8JLtPrv2GUXFW2v_A", - key: "97b9ddc459c8d5ff23c1f2754c95abe8", - sessionType: 'persistent-license', -}; - -// -// Support functions. -// - -function* openTabInUserContext(uri, userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(uri, {userContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function HexToBase64(hex) { - var bin = ""; - for (var i = 0; i < hex.length; i += 2) { - bin += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return window.btoa(bin).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); -} - -function Base64ToHex(str) { - var bin = window.atob(str.replace(/-/g, "+").replace(/_/g, "/")); - var res = ""; - for (var i = 0; i < bin.length; i++) { - res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2); - } - return res; -} - -function ByteArrayToHex(array) { - let bin = String.fromCharCode.apply(null, new Uint8Array(array)); - let res = ""; - - for (let i = 0; i < bin.length; i++) { - res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2); - } - - return res; -} - -function generateKeyObject(aKid, aKey) { - let keyObj = { - kty: 'oct', - kid: aKid, - k: HexToBase64(aKey), - }; - - return new TextEncoder().encode(JSON.stringify({ - keys: [keyObj] - })); -} - -function generateKeyInfo(aData) { - let keyInfo = { - initDataType: aData.initDataType, - initData: new TextEncoder().encode(aData.initData), - sessionType: aData.sessionType, - keyObj: generateKeyObject(aData.kid, aData.key), - }; - - return keyInfo; -} - -// Setup a EME key for the given browser, and return the sessionId. -function* setupEMEKey(browser) { - // Generate the key info. - let keyInfo = generateKeyInfo(TEST_EME_KEY); - - // Setup the EME key. - let result = yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) { - let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey', - [{ - initDataTypes: [aKeyInfo.initDataType], - videoCapabilities: [{contentType: 'video/webm'}], - sessionTypes: ['persistent-license'], - persistentState: 'required', - }]); - let mediaKeys = yield access.createMediaKeys(); - let session = mediaKeys.createSession(aKeyInfo.sessionType); - let res = {}; - - // Insert the EME key. - yield new Promise(resolve => { - session.addEventListener("message", function(event) { - session.update(aKeyInfo.keyObj).then( - () => { resolve(); } - ).catch( - () => { - ok(false, "Update the EME key fail."); - resolve(); - } - ); - }); - - session.generateRequest(aKeyInfo.initDataType, aKeyInfo.initData); - }); - - let map = session.keyStatuses; - - is(map.size, 1, "One EME key has been added."); - - if (map.size === 1) { - res.keyId = map.keys().next().value; - res.sessionId = session.sessionId; - } - - // Close the session. - session.close(); - yield session.closed; - - return res; - }); - - // Check the EME key ID. - is(ByteArrayToHex(result.keyId), Base64ToHex(TEST_EME_KEY.kid), "The key Id is correct."); - return result.sessionId; -} - -// Check whether the EME key has been cleared. -function* checkEMEKey(browser, emeSessionId) { - // Generate the key info. - let keyInfo = generateKeyInfo(TEST_EME_KEY); - keyInfo.sessionId = emeSessionId; - - yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) { - let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey', - [{ - initDataTypes: [aKeyInfo.initDataType], - videoCapabilities: [{contentType: 'video/webm'}], - sessionTypes: ['persistent-license'], - persistentState: 'required', - }]); - let mediaKeys = yield access.createMediaKeys(); - let session = mediaKeys.createSession(aKeyInfo.sessionType); - - // First, load the session with the sessionId. - yield session.load(aKeyInfo.sessionId); - - let map = session.keyStatuses; - - // Check that there is no media key here. - is(map.size, 0, "No media key should be here after forgetThisSite() was called."); - }); -} - -// -// Test functions. -// - -add_task(function* setup() { - // Make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - [ "privacy.userContext.enabled", true ], - [ "media.mediasource.enabled", true ], - [ "media.eme.apiVisible", true ], - [ "media.mediasource.webm.enabled", true ], - [ "media.clearkey.persistent-license.enabled", true ], - ]}); -}); - -add_task(function* test_EME_forgetThisSite() { - let tabs = []; - let emeSessionIds = []; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId); - - // Setup EME Key. - emeSessionIds[userContextId] = yield setupEMEKey(tabs[userContextId].browser); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - - // Clear all EME data for a given domain with originAttributes pattern. - let mps = Cc["@mozilla.org/gecko-media-plugin-service;1"]. - getService(Ci.mozIGeckoMediaPluginChromeService); - mps.forgetThisSite(TEST_HOST, JSON.stringify({})); - - // Open tabs again to check EME keys have been cleared. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId); - - // Check whether EME Key has been cleared. - yield checkEMEKey(tabs[userContextId].browser, emeSessionIds[userContextId]); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js deleted file mode 100644 index 1d9024d25..000000000 --- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_cookie_getCookiesWithOriginAttributes.js +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Bug 1278037 - A Test case for checking whether forgetting APIs are working for cookies. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -const TEST_HOST = "example.com"; -const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/"; - -const USER_CONTEXTS = [ - "default", - "personal", -]; - -// -// Support functions. -// - -function* openTabInUserContext(uri, userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(uri, {userContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function getCookiesForOA(host, userContextId) { - return Services.cookies.getCookiesFromHost(host, {userContextId}); -} - -// -// Test functions. -// - -add_task(function* setup() { - // Make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - [ "privacy.userContext.enabled", true ], - ]}); -}); - -add_task(function* test_cookie_getCookiesWithOriginAttributes() { - let tabs = []; - let cookieName = "userContextId"; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Load the page in 2 different contexts and set a cookie - // which should only be visible in that context. - let value = USER_CONTEXTS[userContextId]; - - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "file_reflect_cookie_into_title.html?" + value, userContextId); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - - // Check that cookies have been set properly. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let enumerator = getCookiesForOA(TEST_HOST, userContextId); - ok(enumerator.hasMoreElements(), "Cookies available"); - - let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2); - is(foundCookie["name"], cookieName, "Check cookie name"); - is(foundCookie["value"], USER_CONTEXTS[userContextId], "Check cookie value"); - } - - // Using getCookiesWithOriginAttributes() to get all cookies for a certain - // domain by using the originAttributes pattern, and clear all these cookies. - let enumerator = Services.cookies.getCookiesWithOriginAttributes(JSON.stringify({}), TEST_HOST); - while (enumerator.hasMoreElements()) { - let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie); - Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes); - } - - // Check that whether cookies has been cleared. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let enumerator = getCookiesForOA(TEST_HOST, userContextId); - ok(!enumerator.hasMoreElements(), "No Cookie should be here"); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js b/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js deleted file mode 100644 index 6a4b37c55..000000000 --- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_quota_clearStoragesForPrincipal.js +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Bug 1278037 - A Test case for checking whether forgetting APIs are working for the quota manager. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -const TEST_HOST = "example.com"; -const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/"; - -const USER_CONTEXTS = [ - "default", - "personal", -]; - -// -// Support functions. -// - -function* openTabInUserContext(uri, userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(uri, {userContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -// Setup an entry for the indexedDB. -function* setupIndexedDB(browser) { - yield ContentTask.spawn(browser, { input: "TestForgetAPIs" }, function* (arg) { - let request = content.indexedDB.open("idb", 1); - - request.onerror = function() { - throw new Error("error opening db connection"); - }; - - request.onupgradeneeded = event => { - let db = event.target.result; - let store = db.createObjectStore("obj", { keyPath: "id" }); - store.createIndex("userContext", "userContext", { unique: false }); - }; - - let db = yield new Promise(resolve => { - request.onsuccess = event => { - resolve(event.target.result); - }; - }); - - // Add an entry into the indexedDB. - let transaction = db.transaction(["obj"], "readwrite"); - let store = transaction.objectStore("obj"); - store.add({id: 1, userContext: arg.input}); - - yield new Promise(resolve => { - transaction.oncomplete = () => { - resolve(); - }; - }); - - // Check the indexedDB has been set properly. - transaction = db.transaction(["obj"], "readonly"); - store = transaction.objectStore("obj"); - let getRequest = store.get(1); - yield new Promise(resolve => { - getRequest.onsuccess = () => { - let res = getRequest.result; - is(res.userContext, arg.input, "Check the indexedDB value"); - resolve(); - }; - }); - }); -} - -// Check whether the indexedDB has been cleared. -function* checkIndexedDB(browser) { - yield ContentTask.spawn(browser, null, function* () { - let request = content.indexedDB.open("idb", 1); - - let db = yield new Promise(done => { - request.onsuccess = event => { - done(event.target.result); - }; - }); - - try { - db.transaction(["obj"], "readonly"); - ok(false, "The indexedDB should not exist"); - } catch (e) { - is(e.name, "NotFoundError", "The indexedDB does not exist as expected"); - } - }); -} - -// -// Test functions. -// - -add_task(function* setup() { - // Make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - [ "privacy.userContext.enabled", true ], - ]}); -}); - -add_task(function* test_quota_clearStoragesForPrincipal() { - let tabs = []; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId); - - // Setup an entry for the indexedDB. - yield setupIndexedDB(tabs[userContextId].browser); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - - // Using quota manager to clear all indexed DB for a given domain. - let qms = Cc["@mozilla.org/dom/quota-manager-service;1"]. - getService(Ci.nsIQuotaManagerService); - - let caUtils = {}; - let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); - scriptLoader.loadSubScript("chrome://global/content/contentAreaUtils.js", - caUtils); - let httpURI = caUtils.makeURI("http://" + TEST_HOST); - let httpPrincipal = Services.scriptSecurityManager - .createCodebasePrincipal(httpURI, {}); - qms.clearStoragesForPrincipal(httpPrincipal, null, true); - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "empty_file.html", userContextId); - - // Check whether indexed DB has been cleared. - yield checkIndexedDB(tabs[userContextId].browser); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js deleted file mode 100644 index 9efc86e0c..000000000 --- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Bug 1238183 - Test cases for forgetAboutSite with userContextId. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -Cu.import("resource://gre/modules/ForgetAboutSite.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {}); -let LoadContextInfo = Cc["@mozilla.org/load-context-info-factory;1"] - .getService(Ci.nsILoadContextInfoFactory); -let css = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - -const USER_CONTEXTS = [ - "default", - "personal", -]; -const TEST_HOST = "example.com"; -const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/"; -const COOKIE_NAME = "userContextId"; - -// Counter for image load hits. -let gHits = 0; - -let gHttpServer = null; - -function imageHandler(metadata, response) { - // A 1x1 PNG image. - // Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain) - const IMAGE = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" + - "ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII="); - gHits++; - response.setHeader("Cache-Control", "max-age=10000", false); - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "image/png", false); - response.write(IMAGE); -} - -function loadImagePageHandler(metadata, response) { - response.setHeader("Cache-Control", "max-age=10000", false); - response.setStatusLine(metadata.httpVersion, 200, "Ok"); - response.setHeader("Content-Type", "text/html", false); - let body = "<!DOCTYPE HTML>\ - <html>\ - <head>\ - <meta charset='utf-8'>\ - <title>Load Image</title>\ - </head>\ - <body>\ - <img src='image.png'>\ - </body>\ - </html>"; - response.bodyOutputStream.write(body, body.length); -} - -function* openTabInUserContext(uri, userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(uri, {userContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function getCookiesForOA(host, userContextId) { - return Services.cookies.getCookiesFromHost(host, {userContextId}); -} - -function createURI(uri) -{ - let ioServ = Cc["@mozilla.org/network/io-service;1"] - .getService(Components.interfaces.nsIIOService); - return ioServ.newURI(uri, null, null); -} - -function getCacheStorage(where, lci, appcache) -{ - if (!lci) lci = LoadContextInfo.default; - switch (where) { - case "disk": return css.diskCacheStorage(lci, false); - case "memory": return css.memoryCacheStorage(lci); - case "appcache": return css.appCacheStorage(lci, appcache); - case "pin": return css.pinningCacheStorage(lci); - } - return null; -} - -function OpenCacheEntry(key, where, flags, lci) -{ - return new Promise(resolve => { - key = createURI(key); - function CacheListener() { } - CacheListener.prototype = { - _appCache: null, - - QueryInterface: function (iid) { - if (iid.equals(Components.interfaces.nsICacheEntryOpenCallback) || - iid.equals(Components.interfaces.nsISupports)) - return this; - throw Components.results.NS_ERROR_NO_INTERFACE; - }, - - onCacheEntryCheck: function(entry, appCache) { - return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; - }, - - onCacheEntryAvailable: function (entry, isnew, appCache, status) { - resolve(); - }, - - run: function () { - let storage = getCacheStorage(where, lci, this._appCache); - storage.asyncOpenURI(key, "", flags, this); - } - }; - - (new CacheListener()).run(); - }); -} - -// -// Test functions. -// - -// Cookies -function* test_cookie_cleared() { - let tabs = []; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Load the page in 2 different contexts and set a cookie - // which should only be visible in that context. - let value = USER_CONTEXTS[userContextId]; - - // Open our tab in the given user context. - tabs[userContextId] = yield* openTabInUserContext(TEST_URL+ "file_reflect_cookie_into_title.html?" + value, userContextId); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - // Check that cookies have been set properly. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let enumerator = getCookiesForOA(TEST_HOST, userContextId); - ok(enumerator.hasMoreElements(), "Cookies available"); - - let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2); - Assert.equal(foundCookie["name"], COOKIE_NAME, "Check cookie name"); - Assert.equal(foundCookie["value"], USER_CONTEXTS[userContextId], "Check cookie value"); - } - - // Forget the site. - ForgetAboutSite.removeDataFromDomain(TEST_HOST); - - // Check that whether cookies has been cleared or not. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let enumerator = getCookiesForOA(TEST_HOST, userContextId); - ok(!enumerator.hasMoreElements(), "No Cookie should be here"); - } -} - -// Cache -function* test_cache_cleared() { - // First, add some caches. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - yield OpenCacheEntry("http://" + TEST_HOST + "/", - "disk", - Ci.nsICacheStorage.OPEN_NORMALLY, - LoadContextInfo.custom(false, {userContextId})); - - yield OpenCacheEntry("http://" + TEST_HOST + "/", - "memory", - Ci.nsICacheStorage.OPEN_NORMALLY, - LoadContextInfo.custom(false, {userContextId})); - } - - - // Check that caches have been set correctly. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId})); - let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId})); - - Assert.ok(mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache has been set correctly"); - Assert.ok(disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache has been set correctly"); - } - - // Forget the site. - ForgetAboutSite.removeDataFromDomain(TEST_HOST); - - // Check that do caches be removed or not? - for (let userContextId of Object.keys(USER_CONTEXTS)) { - let mem = getCacheStorage("memory", LoadContextInfo.custom(false, {userContextId})); - let disk = getCacheStorage("disk", LoadContextInfo.custom(false, {userContextId})); - - Assert.ok(!mem.exists(createURI("http://" + TEST_HOST + "/"), ""), "The memory cache is cleared"); - Assert.ok(!disk.exists(createURI("http://" + TEST_HOST + "/"), ""), "The disk cache is cleared"); - } -} - -// Image Cache -function* test_image_cache_cleared() { - let tabs = []; - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context to cache image. - tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html', - userContextId); - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - - let expectedHits = USER_CONTEXTS.length; - - // Check that image cache works with the userContextId. - is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times."); - - // Reset the cache count. - gHits = 0; - - // Forget the site. - ForgetAboutSite.removeDataFromDomain("localhost:" + gHttpServer.identity.primaryPort + "/"); - - // Load again. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context to cache image. - tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html', - userContextId); - yield BrowserTestUtils.removeTab(tabs[userContextId].tab); - } - - // Check that image cache was cleared and the server gets another two hits. - is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times."); -} - -// Offline Storage -function* test_storage_cleared() { - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Load the page in 2 different contexts and set the local storage - // which should only be visible in that context. - let value = USER_CONTEXTS[userContextId]; - - // Open our tab in the given user context. - let tabInfo = yield* openTabInUserContext(TEST_URL+ "file_set_storages.html?" + value, userContextId); - - // Check that the storages has been set correctly. - yield ContentTask.spawn(tabInfo.browser, { userContext: USER_CONTEXTS[userContextId] }, function* (arg) { - // Check that the local storage has been set correctly. - Assert.equal(content.localStorage.getItem("userContext"), arg.userContext, "Check the local storage value"); - - // Check that the session storage has been set correctly. - Assert.equal(content.sessionStorage.getItem("userContext"), arg.userContext, "Check the session storage value"); - - // Check that the indexedDB has been set correctly. - let request = content.indexedDB.open("idb", 1); - - let db = yield new Promise(done => { - request.onsuccess = event => { - done(event.target.result); - }; - }); - - let transaction = db.transaction(["obj"], "readonly"); - let store = transaction.objectStore("obj"); - let storeRequest = store.get(1); - - yield new Promise(done => { - storeRequest.onsuccess = event => { - let res = storeRequest.result; - Assert.equal(res.userContext, arg.userContext, "Check the indexedDB value"); - done(); - }; - }); - }); - - // Close this tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - } - - // Forget the site. - ForgetAboutSite.removeDataFromDomain(TEST_HOST); - - // Open the tab again without setting the localStorage and check that the - // local storage has been cleared or not. - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Open our tab in the given user context without setting local storage. - let tabInfo = yield* openTabInUserContext(TEST_URL+ "file_set_storages.html", userContextId); - - // Check that do storages be cleared or not. - yield ContentTask.spawn(tabInfo.browser, null, function* () { - // Check that does the local storage be cleared or not. - Assert.ok(!content.localStorage.getItem("userContext"), "The local storage has been cleared"); - - // Check that does the session storage be cleared or not. - Assert.ok(!content.sessionStorage.getItem("userContext"), "The session storage has been cleared"); - - // Check that does the indexedDB be cleared or not. - let request = content.indexedDB.open("idb", 1); - - let db = yield new Promise(done => { - request.onsuccess = event => { - done(event.target.result); - }; - }); - try { - db.transaction(["obj"], "readonly"); - Assert.ok(false, "The indexedDB should not exist"); - } catch (e) { - Assert.equal(e.name, "NotFoundError", "The indexedDB does not exist as expected"); - } - }); - - // Close the tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - } -} - -add_task(function* setup() { - // Make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}, resolve); - }); - - // Create a http server for the image cache test. - if (!gHttpServer) { - gHttpServer = new HttpServer(); - gHttpServer.registerPathHandler('/image.png', imageHandler); - gHttpServer.registerPathHandler('/loadImage.html', loadImagePageHandler); - gHttpServer.start(-1); - } -}); - -let tests = [ - test_cookie_cleared, - test_cache_cleared, - test_image_cache_cleared, - test_storage_cleared, -]; - -add_task(function* test() { - for (let i = 0; i < tests.length; i++) - add_task(tests[i]); -}); - -registerCleanupFunction(() => { - gHttpServer.stop(() => { - gHttpServer = null; - }); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_imageCache.js b/browser/components/contextualidentity/test/browser/browser_imageCache.js deleted file mode 100644 index df36d44c1..000000000 --- a/browser/components/contextualidentity/test/browser/browser_imageCache.js +++ /dev/null @@ -1,59 +0,0 @@ -let Cu = Components.utils; -let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {}); - -const NUM_USER_CONTEXTS = 3; - -let gHits = 0; - -let server = new HttpServer(); -server.registerPathHandler('/image.png', imageHandler); -server.registerPathHandler('/file.html', fileHandler); -server.start(-1); - -let BASE_URI = 'http://localhost:' + server.identity.primaryPort; -let IMAGE_URI = BASE_URI + '/image.png'; -let FILE_URI = BASE_URI + '/file.html'; - -function imageHandler(metadata, response) { - gHits++; - response.setHeader("Cache-Control", "max-age=10000", false); - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "image/png", false); - var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII="; - response.bodyOutputStream.write(body, body.length); -} - -function fileHandler(metadata, response) { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - let body = `<html><body><image src=${IMAGE_URI}></body></html>`; - response.bodyOutputStream.write(body, body.length); -} - -add_task(function* setup() { - // make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [["privacy.userContext.enabled", true]]}); -}); - -// opens `uri' in a new tab with the provided userContextId and focuses it. -// returns the newly opened tab -function* openTabInUserContext(uri, userContextId) { - // open the tab in the correct userContextId - let tab = gBrowser.addTab(uri, {userContextId}); - - // select tab and make sure its browser is focused - gBrowser.selectedTab = tab; - tab.ownerDocument.defaultView.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return tab; -} - -add_task(function* test() { - for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) { - let tab = yield* openTabInUserContext(FILE_URI, userContextId); - gBrowser.removeTab(tab); - } - is(gHits, NUM_USER_CONTEXTS, "should get an image request for each user contexts"); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_middleClick.js b/browser/components/contextualidentity/test/browser/browser_middleClick.js deleted file mode 100644 index f3bed2b53..000000000 --- a/browser/components/contextualidentity/test/browser/browser_middleClick.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; - -const BASE_ORIGIN = "http://example.com"; -const URI = BASE_ORIGIN + - "/browser/browser/components/contextualidentity/test/browser/empty_file.html"; - -add_task(function* () { - info("Opening a new container tab..."); - - let tab = gBrowser.addTab(URI, { userContextId: 1 }); - gBrowser.selectedTab = tab; - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - - info("Create a HTMLAnchorElement..."); - yield ContentTask.spawn(browser, URI, - function(URI) { - let anchor = content.document.createElement("a"); - anchor.setAttribute('id', 'clickMe'); - anchor.setAttribute("href", URI); - anchor.appendChild(content.document.createTextNode("click me!")); - content.document.body.appendChild(anchor); - } - ); - - info("Synthesize a mouse click and wait for a new tab..."); - let newTab = yield new Promise((resolve, reject) => { - gBrowser.tabContainer.addEventListener("TabOpen", function onTabOpen(openEvent) { - gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen); - resolve(openEvent.target); - }) - - BrowserTestUtils.synthesizeMouseAtCenter("#clickMe", { button: 1 }, browser); - }); - - is(newTab.getAttribute("usercontextid"), 1, "Correct UserContextId?"); - - yield BrowserTestUtils.removeTab(tab); - yield BrowserTestUtils.removeTab(newTab); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_newtabButton.js b/browser/components/contextualidentity/test/browser/browser_newtabButton.js deleted file mode 100644 index 228e6f971..000000000 --- a/browser/components/contextualidentity/test/browser/browser_newtabButton.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; - -// Testing that when the user opens the add tab menu and clicks menu items -// the correct context id is opened - -add_task(function* test() { - yield SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}); - - let newTab = document.getElementById('tabbrowser-tabs'); - let newTabButton = document.getAnonymousElementByAttribute(newTab, "anonid", "tabs-newtab-button"); - ok(newTabButton, "New tab button exists"); - ok(!newTabButton.hidden, "New tab button is visible"); - yield BrowserTestUtils.waitForCondition(() => !!document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup"), "Wait for popup to exist"); - let popup = document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup"); - - for (let i = 1; i <= 4; i++) { - let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(newTabButton, {type: "mousedown"}); - - yield popupShownPromise; - let contextIdItem = popup.querySelector(`menuitem[data-usercontextid="${i}"]`); - - ok(contextIdItem, `User context id ${i} exists`); - - let waitForTabPromise = BrowserTestUtils.waitForNewTab(gBrowser); - EventUtils.synthesizeMouseAtCenter(contextIdItem, {}); - - let tab = yield waitForTabPromise; - - is(tab.getAttribute('usercontextid'), i, `New tab has UCI equal ${i}`); - yield BrowserTestUtils.removeTab(tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js b/browser/components/contextualidentity/test/browser/browser_serviceworkers.js deleted file mode 100644 index b074b91ac..000000000 --- a/browser/components/contextualidentity/test/browser/browser_serviceworkers.js +++ /dev/null @@ -1,108 +0,0 @@ -let { classes: Cc, interfaces: Ci } = Components; - -let swm = Cc["@mozilla.org/serviceworkers/manager;1"]. - getService(Ci.nsIServiceWorkerManager); - -const BASE_ORIGIN = "https://example.com"; -const URI = BASE_ORIGIN + - "/browser/browser/components/contextualidentity/test/browser/serviceworker.html"; -const NUM_USER_CONTEXTS = 3; - -// opens `uri' in a new tab with the provided userContextId and focuses it. -// returns the newly opened tab -function openTabInUserContext(uri, userContextId) { - // open the tab in the correct userContextId - let tab = gBrowser.addTab(uri, {userContextId}); - - // select tab and make sure its browser is focused - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - return tab; -} - -add_task(function* setup() { - // make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true], - ["dom.serviceWorkers.enabled", true], - ["dom.serviceWorkers.openWindow.enabled", true], - ["dom.ipc.processCount", 1] - ]}, resolve); - }); -}); - -let infos = []; - -add_task(function* test() { - // Open the same URI in multiple user contexts, and make sure we have a - // separate service worker in each of the contexts - for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) { - // Open a tab in given user contexts - let tab = openTabInUserContext(URI, userContextId); - - // wait for tab load - yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab)); - - // remove the tab - gBrowser.removeTab(tab); - } - - if (!allRegistered()) { - yield promiseAllRegistered(); - } - ok(true, "all service workers are registered"); - - // Unregistered all service workers added in this test - for (let info of infos) { - yield promiseUnregister(info); - } -}); - -function allRegistered() { - let results = []; - let registrations = swm.getAllRegistrations(); - for (let i = 0; i < registrations.length; i++) { - let info = registrations.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo); - let principal = info.principal; - if (principal.originNoSuffix === BASE_ORIGIN) { - results[principal.userContextId] = true; - infos[principal.userContextId] = info; - } - } - for (let userContextId = 0; userContextId < NUM_USER_CONTEXTS; userContextId++) { - if (!results[userContextId]) { - return false; - } - } - return true; -} - -function promiseAllRegistered() { - return new Promise(function(resolve) { - let listener = { - onRegister: function() { - if (allRegistered()) { - swm.removeListener(listener); - resolve(); - } - } - } - swm.addListener(listener); - }); -} - -function promiseUnregister(info) { - return new Promise(function(resolve) { - swm.unregister(info.principal, { - unregisterSucceeded: function(aState) { - ok(aState, "ServiceWorkerRegistration exists"); - resolve(); - }, - unregisterFailed: function(aState) { - ok(false, "unregister should succeed"); - } - }, info.scope); - }); -} diff --git a/browser/components/contextualidentity/test/browser/browser_usercontext.js b/browser/components/contextualidentity/test/browser/browser_usercontext.js deleted file mode 100644 index e0e785d3f..000000000 --- a/browser/components/contextualidentity/test/browser/browser_usercontext.js +++ /dev/null @@ -1,86 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - - -const USER_CONTEXTS = [ - "default", - "personal", - "work", -]; - -const BASE_URI = "http://mochi.test:8888/browser/browser/components/" - + "contextualidentity/test/browser/file_reflect_cookie_into_title.html"; - - -// opens `uri' in a new tab with the provided userContextId and focuses it. -// returns the newly opened tab -function openTabInUserContext(uri, userContextId) { - // open the tab in the correct userContextId - let tab = gBrowser.addTab(uri, {userContextId}); - - // select tab and make sure its browser is focused - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - return tab; -} - -add_task(function* setup() { - // make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true], - ["dom.ipc.processCount", 1] - ]}, resolve); - }); -}); - -add_task(function* test() { - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // load the page in 3 different contexts and set a cookie - // which should only be visible in that context - let cookie = USER_CONTEXTS[userContextId]; - - // open our tab in the given user context - let tab = openTabInUserContext(BASE_URI+"?"+cookie, userContextId); - - // wait for tab load - yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab)); - - // remove the tab - gBrowser.removeTab(tab); - } - - { - // Set a cookie in a different context so we can detect if that affects - // cross-context properly. If we don't do that, we get an UNEXPECTED-PASS - // for the localStorage case for the last tab we set. - let tab = openTabInUserContext(BASE_URI+"?foo", 9999); - yield BrowserTestUtils.browserLoaded(gBrowser.getBrowserForTab(tab)); - gBrowser.removeTab(tab); - } - - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Load the page without setting the cookie this time - let expectedContext = USER_CONTEXTS[userContextId]; - - let tab = openTabInUserContext(BASE_URI, userContextId); - - // wait for load - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - - // get the title - let title = browser.contentDocument.title.trim().split("|"); - - // check each item in the title and validate it meets expectatations - for (let part of title) { - let [storageMethodName, value] = part.split("="); - is(value, expectedContext, - "the title reflects the expected contextual identity of " + - expectedContext + " for method " + storageMethodName + ": " + value); - } - - gBrowser.removeTab(tab); - } -}); diff --git a/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js b/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js deleted file mode 100644 index 6a8fbc591..000000000 --- a/browser/components/contextualidentity/test/browser/browser_usercontextid_tabdrop.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; - -let EventUtils = {}; -Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - -/** - * Dragging an URL to a tab without userContextId set. - */ -add_task(function* () { - let tab = gBrowser.addTab("http://example.com/"); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop"); - let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://test1.example.com/"); - - // A drop type of "link" onto an existing tab would normally trigger a - // load in that same tab, but tabbrowser code in _getDragTargetTab treats - // drops on the outer edges of a tab differently (loading a new tab - // instead). Make events created by synthesizeDrop have all of their - // coordinates set to 0 (screenX/screenY), so they're treated as drops - // on the outer edge of the tab, thus they open new tabs. - let event = { - clientX: 0, - clientY: 0, - screenX: 0, - screenY: 0, - }; - EventUtils.synthesizeDrop(tab, tab, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window, undefined, event); - - yield awaitDrop; - - let tab2 = yield newTabPromise; - Assert.ok(!tab2.hasAttribute("usercontextid"), "Tab shouldn't have usercontextid attribute"); - - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser); - - yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () { - Assert.equal(content.document.documentURI, "http://test1.example.com/"); - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 0); - - // referrer is empty when urls are dragged to new or existing tabs. - // If this changes in the future, it would be okay to send the referrer - // in this case because we are creating a new tab with the default - // usercontextid as the original tab. - Assert.equal(content.document.referrer, "", "referrer should be empty"); - }); - - yield BrowserTestUtils.removeTab(tab); - yield BrowserTestUtils.removeTab(tab2); -}); - -/** - * When dragging an URL to a new tab, the new tab should have the same - * userContextId as the original tab. - */ -add_task(function* () { - let tab = gBrowser.addTab("http://example.com/", {userContextId: 1}); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop"); - let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://test1.example.com/"); - - // A drop type of "link" onto an existing tab would normally trigger a - // load in that same tab, but tabbrowser code in _getDragTargetTab treats - // drops on the outer edges of a tab differently (loading a new tab - // instead). Make events created by synthesizeDrop have all of their - // coordinates set to 0 (screenX/screenY), so they're treated as drops - // on the outer edge of the tab, thus they open new tabs. - let event = { - clientX: 0, - clientY: 0, - screenX: 0, - screenY: 0, - }; - EventUtils.synthesizeDrop(tab, tab, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window, undefined, event); - - yield awaitDrop; - - let tab2 = yield newTabPromise; - Assert.equal(tab2.getAttribute("usercontextid"), 1); - - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser); - - yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () { - Assert.equal(content.document.documentURI, "http://test1.example.com/"); - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 1); - - // referrer is empty when urls are dragged to new or existing tabs. - // If this changes in the future, it would be okay to send the referrer - // in this case because we are creating a new tab with the same - // usercontextid as the original tab. - Assert.equal(content.document.referrer, "", "referrer should be empty"); - }); - - yield BrowserTestUtils.removeTab(tab); - yield BrowserTestUtils.removeTab(tab2); -}); - -/** - * When dragging a URL from one tab or link on a tab to an existing tab, the - * existing tab should not change its userContextId. - * Ex: if you drag a link from tab 1 with userContext 1 to tab 2 with - * userContext 2, the link will open in tab 2 with userContext 2. - */ -add_task(function* () { - let tab = gBrowser.addTab("http://example.com/", {userContextId: 1}); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - let tab2 = gBrowser.addTab("http://example.org/", {userContextId: 2}); - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser); - - let awaitDrop = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "drop"); - - EventUtils.synthesizeDrop(tab, tab2, [[{type: "text/plain", data: "http://test1.example.com/"}]], "link", window); - - yield awaitDrop; - Assert.equal(tab2.getAttribute("usercontextid"), 2); - - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser); - - yield ContentTask.spawn(tab2.linkedBrowser, {}, function* () { - Assert.equal(content.document.documentURI, "http://test1.example.com/"); - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, 2); - - // referrer is empty when urls are dragged to new or existing tabs. - // If this changes in the future, we should ensure that we are not sending - // a referrer for this case! When opening links across user contexts, we - // don't want the referrer to follow the user from one context to another. - Assert.equal(content.document.referrer, "", "referrer should be empty"); - }); - - yield BrowserTestUtils.removeTab(tab); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_windowName.js b/browser/components/contextualidentity/test/browser/browser_windowName.js deleted file mode 100644 index 555c421ce..000000000 --- a/browser/components/contextualidentity/test/browser/browser_windowName.js +++ /dev/null @@ -1,74 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - - -const USER_CONTEXTS = [ - "default", - "personal", - "work", -]; - -const BASE_URI = "http://mochi.test:8888/browser/browser/components/" - + "contextualidentity/test/browser/empty_file.html"; - -add_task(function* setup() { - // make sure userContext is enabled. - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true], - ["browser.link.open_newwindow", 3], - ]}, resolve); - }); -}); - -add_task(function* test() { - info("Creating first tab..."); - let tab1 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 1}); - let browser1 = gBrowser.getBrowserForTab(tab1); - yield BrowserTestUtils.browserLoaded(browser1); - yield ContentTask.spawn(browser1, null, function(opts) { - content.window.name = 'tab-1'; - }); - - info("Creating second tab..."); - let tab2 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 2}); - let browser2 = gBrowser.getBrowserForTab(tab2); - yield BrowserTestUtils.browserLoaded(browser2); - yield ContentTask.spawn(browser2, null, function(opts) { - content.window.name = 'tab-2'; - }); - - // Let's try to open a window from tab1 with a name 'tab-2'. - info("Opening a window from the first tab..."); - yield ContentTask.spawn(browser1, { url: BASE_URI + '?new' }, function* (opts) { - yield (new content.window.wrappedJSObject.Promise(resolve => { - let w = content.window.wrappedJSObject.open(opts.url, 'tab-2'); - w.onload = function() { resolve(); } - })); - }); - - is(browser1.contentTitle, '?old', "Tab1 title must be 'old'"); - is(browser1.contentPrincipal.userContextId, 1, "Tab1 UCI must be 1"); - - is(browser2.contentTitle, '?old', "Tab2 title must be 'old'"); - is(browser2.contentPrincipal.userContextId, 2, "Tab2 UCI must be 2"); - - let found = false; - for (let i = 0; i < gBrowser.tabContainer.childNodes.length; ++i) { - let tab = gBrowser.tabContainer.childNodes[i]; - let browser = gBrowser.getBrowserForTab(tab); - if (browser.contentTitle == '?new') { - is(browser.contentPrincipal.userContextId, 1, "Tab3 UCI must be 1"); - isnot(browser, browser1, "Tab3 is not browser 1"); - isnot(browser, browser2, "Tab3 is not browser 2"); - gBrowser.removeTab(tab); - found = true; - break; - } - } - - ok(found, "We have tab3"); - - gBrowser.removeTab(tab1); - gBrowser.removeTab(tab2); -}); diff --git a/browser/components/contextualidentity/test/browser/browser_windowOpen.js b/browser/components/contextualidentity/test/browser/browser_windowOpen.js deleted file mode 100644 index 00c6e0aa0..000000000 --- a/browser/components/contextualidentity/test/browser/browser_windowOpen.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; - -// Here we want to test that a new opened window shows the same UI of the -// parent one if this has been loaded from a particular container. - -const BASE_URI = "http://mochi.test:8888/browser/browser/components/" - + "contextualidentity/test/browser/empty_file.html"; - -add_task(function* setup() { - yield new Promise((resolve) => { - SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true], - ["browser.link.open_newwindow", 2], - ]}, resolve); - }); -}); - - -add_task(function* test() { - info("Creating a tab with UCI = 1..."); - let tab = gBrowser.addTab(BASE_URI, {userContextId: 1}); - is(tab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1"); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - - info("Opening a new window from this tab..."); - ContentTask.spawn(browser, BASE_URI, function(url) { - content.window.newWindow = content.window.open(url, "_blank"); - }); - - let newWin = yield BrowserTestUtils.waitForNewWindow(); - let newTab = newWin.gBrowser.selectedTab; - - yield BrowserTestUtils.browserLoaded(newTab.linkedBrowser); - is(newTab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1"); - - info("Closing the new window and tab..."); - yield BrowserTestUtils.closeWindow(newWin); - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/contextualidentity/test/browser/empty_file.html b/browser/components/contextualidentity/test/browser/empty_file.html deleted file mode 100644 index c6d11dcd5..000000000 --- a/browser/components/contextualidentity/test/browser/empty_file.html +++ /dev/null @@ -1,5 +0,0 @@ -<html><body> -<script> -document.title = window.location.search; -</script> -</body></html> diff --git a/browser/components/contextualidentity/test/browser/favicon-normal32.png b/browser/components/contextualidentity/test/browser/favicon-normal32.png Binary files differdeleted file mode 100644 index 5535363c9..000000000 --- a/browser/components/contextualidentity/test/browser/favicon-normal32.png +++ /dev/null diff --git a/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html b/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html deleted file mode 100644 index b04f3fd5c..000000000 --- a/browser/components/contextualidentity/test/browser/file_reflect_cookie_into_title.html +++ /dev/null @@ -1,23 +0,0 @@ -<html> - <head> - <meta charset="UTF-8"> - <title>title not set</title> - <script> - // if we have a query string, use it to set the cookie and localStorage - if (window.location.search.length > 0) { - let context_name = window.location.search.substr(1); - document.cookie = "userContextId=" + context_name; - localStorage.setItem("userContext", context_name); - } - - // get the cookie - let [name, val] = document.cookie.split("="); - - // set the title to reflect the cookie and local storage values we find - document.title = "cookie=" + val + "|" - + "local=" + localStorage.getItem("userContext"); - </script> - </head> - <body></body> -</html> - diff --git a/browser/components/contextualidentity/test/browser/file_set_storages.html b/browser/components/contextualidentity/test/browser/file_set_storages.html deleted file mode 100644 index c6adcbdde..000000000 --- a/browser/components/contextualidentity/test/browser/file_set_storages.html +++ /dev/null @@ -1,41 +0,0 @@ -<html> - <head> - <meta charset="UTF-8"> - <title>Bug 1238183</title> - </head> - <body> - <script type="application/javascript;version=1.7"> - "use strict"; - - // if we have a query string, use it to set storages - if (window.location.search.length > 0) { - let context_name = window.location.search.substr(1); - localStorage.setItem("userContext", context_name); - sessionStorage.setItem("userContext", context_name); - - let request = indexedDB.open("idb", 1); - - request.onerror = function() { - throw new Error("error opening db connection"); - }; - - request.onupgradeneeded = event => { - let db = event.target.result; - let store = db.createObjectStore("obj", { keyPath: "id" }); - store.createIndex("userContext", "userContext", { unique: false }); - }; - - request.onsuccess = event => { - let db = request.result; - let transaction = db.transaction(["obj"], "readwrite"); - let store = transaction.objectStore("obj"); - store.add({id: 1, userContext: context_name}); - - transaction.oncomplete = () => { - db.close(); - }; - }; - } - </script> - </body> -</html> diff --git a/browser/components/contextualidentity/test/browser/serviceworker.html b/browser/components/contextualidentity/test/browser/serviceworker.html deleted file mode 100644 index 11edd001a..000000000 --- a/browser/components/contextualidentity/test/browser/serviceworker.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8"> - <script> - navigator.serviceWorker.register("worker.js"); - </script> - </head> - <body> - This is a test page. - </body> -<html> diff --git a/browser/components/contextualidentity/test/browser/worker.js b/browser/components/contextualidentity/test/browser/worker.js deleted file mode 100644 index 2aba167d1..000000000 --- a/browser/components/contextualidentity/test/browser/worker.js +++ /dev/null @@ -1 +0,0 @@ -// empty worker, always succeed! diff --git a/browser/components/customizableui/test/.eslintrc.js b/browser/components/customizableui/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/customizableui/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/customizableui/test/browser.ini b/browser/components/customizableui/test/browser.ini deleted file mode 100644 index 1c1f30498..000000000 --- a/browser/components/customizableui/test/browser.ini +++ /dev/null @@ -1,154 +0,0 @@ -[DEFAULT] -support-files = - head.js - support/test_967000_charEncoding_page.html - support/feeds_test_page.html - support/test-feed.xml - -[browser_873501_handle_specials.js] -[browser_876926_customize_mode_wrapping.js] -[browser_876944_customize_mode_create_destroy.js] -[browser_877006_missing_view.js] -[browser_877178_unregisterArea.js] -[browser_877447_skip_missing_ids.js] -[browser_878452_drag_to_panel.js] -[browser_880164_customization_context_menus.js] -[browser_880382_drag_wide_widgets_in_panel.js] -[browser_884402_customize_from_overflow.js] -skip-if = os == "linux" -[browser_885052_customize_mode_observers_disabed.js] -tags = fullscreen -# Bug 951403 - Disabled on OSX for frequent failures -skip-if = os == "mac" - -[browser_885530_showInPrivateBrowsing.js] -[browser_886323_buildArea_removable_nodes.js] -[browser_887438_currentset_shim.js] -[browser_888817_currentset_updating.js] -[browser_890140_orphaned_placeholders.js] -[browser_890262_destroyWidget_after_add_to_panel.js] -[browser_892955_isWidgetRemovable_for_removed_widgets.js] -[browser_892956_destroyWidget_defaultPlacements.js] -[browser_909779_overflow_toolbars_new_window.js] -skip-if = os == "linux" - -[browser_901207_searchbar_in_panel.js] -[browser_913972_currentset_overflow.js] -skip-if = os == "linux" - -[browser_914138_widget_API_overflowable_toolbar.js] -skip-if = os == "linux" - -[browser_914863_disabled_help_quit_buttons.js] -[browser_918049_skipintoolbarset_dnd.js] -[browser_923857_customize_mode_event_wrapping_during_reset.js] -[browser_927717_customize_drag_empty_toolbar.js] - -# Bug 1163231 - Causes failures on Developer Edition on Windows 7. -# [browser_932928_show_notice_when_palette_empty.js] - -[browser_934113_menubar_removable.js] -# Because this test is about the menubar, it can't be run on mac -skip-if = os == "mac" - -[browser_934951_zoom_in_toolbar.js] -[browser_938980_navbar_collapsed.js] -[browser_938995_indefaultstate_nonremovable.js] -[browser_940013_registerToolbarNode_calls_registerArea.js] -[browser_940307_panel_click_closure_handling.js] -[browser_940946_removable_from_navbar_customizemode.js] -[browser_941083_invalidate_wrapper_cache_createWidget.js] -[browser_942581_unregisterArea_keeps_placements.js] -[browser_943683_migration_test.js] -[browser_944887_destroyWidget_should_destroy_in_palette.js] -[browser_945739_showInPrivateBrowsing_customize_mode.js] -[browser_947914_button_addons.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_copy.js] -subsuite = clipboard -skip-if = os == "linux" # Intermittent failures on Linux -[browser_947914_button_cut.js] -subsuite = clipboard -skip-if = os == "linux" # Intermittent failures on Linux -[browser_947914_button_find.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_history.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_newPrivateWindow.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_newWindow.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_paste.js] -subsuite = clipboard -skip-if = os == "linux" # Intermittent failures on Linux -[browser_947914_button_print.js] -skip-if = os == "linux" # Intermittent failures on Linux -[browser_947914_button_savePage.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_zoomIn.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_zoomOut.js] -skip-if = os == "linux" # Intermittent failures -[browser_947914_button_zoomReset.js] -skip-if = os == "linux" # Intermittent failures -[browser_947987_removable_default.js] -[browser_948985_non_removable_defaultArea.js] -[browser_952963_areaType_getter_no_area.js] -[browser_956602_remove_special_widget.js] -[browser_962069_drag_to_overflow_chevron.js] -[browser_962884_opt_in_disable_hyphens.js] -[browser_963639_customizing_attribute_non_customizable_toolbar.js] -[browser_967000_button_charEncoding.js] -[browser_967000_button_feeds.js] -[browser_967000_button_sync.js] -[browser_968447_bookmarks_toolbar_items_in_panel.js] -skip-if = os == "linux" # Intemittent failures - bug 979207 -[browser_968565_insert_before_hidden_items.js] -[browser_969427_recreate_destroyed_widget_after_reset.js] -[browser_969661_character_encoding_navbar_disabled.js] -[browser_970511_undo_restore_default.js] -[browser_972267_customizationchange_events.js] -[browser_973641_button_addon.js] -[browser_973932_addonbar_currentset.js] -[browser_975719_customtoolbars_behaviour.js] -[browser_976792_insertNodeInWindow.js] -skip-if = os == "linux" -[browser_978084_dragEnd_after_move.js] -[browser_980155_add_overflow_toolbar.js] -[browser_981305_separator_insertion.js] -[browser_981418-widget-onbeforecreated-handler.js] -[browser_982656_restore_defaults_builtin_widgets.js] -[browser_984455_bookmarks_items_reparenting.js] -skip-if = os == "linux" -[browser_985815_propagate_setToolbarVisibility.js] -[browser_987177_destroyWidget_xul.js] -[browser_987177_xul_wrapper_updating.js] -[browser_987185_syncButton.js] -[browser_987492_window_api.js] -[browser_987640_charEncoding.js] -[browser_988072_sidebar_events.js] -[browser_989338_saved_placements_not_resaved.js] -[browser_989751_subviewbutton_class.js] -[browser_992747_toggle_noncustomizable_toolbar.js] -[browser_993322_widget_notoolbar.js] -[browser_995164_registerArea_during_customize_mode.js] -[browser_996364_registerArea_different_properties.js] -[browser_996635_remove_non_widgets.js] -[browser_1003588_no_specials_in_panel.js] -[browser_1007336_lwthemes_in_customize_mode.js] -skip-if = os == "linux" # crashing on Linux due to bug 1271683 -[browser_1008559_anchor_undo_restore.js] -[browser_1042100_default_placements_update.js] -[browser_1058573_showToolbarsDropdown.js] -[browser_1087303_button_fullscreen.js] -tags = fullscreen -skip-if = os == "mac" -[browser_1087303_button_preferences.js] -[browser_1089591_still_customizable_after_reset.js] -[browser_1096763_seen_widgets_post_reset.js] -[browser_1161838_inserted_new_default_buttons.js] -[browser_bootstrapped_custom_toolbar.js] -[browser_customizemode_contextmenu_menubuttonstate.js] -[browser_panel_toggle.js] -[browser_switch_to_customize_mode.js] -[browser_check_tooltips_in_navbar.js] diff --git a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js b/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js deleted file mode 100644 index 22fbb5c0c..000000000 --- a/browser/components/customizableui/test/browser_1003588_no_specials_in_panel.js +++ /dev/null @@ -1,107 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -function simulateItemDragAndEnd(aToDrag, aTarget) { - var ds = Components.classes["@mozilla.org/widget/dragservice;1"]. - getService(Components.interfaces.nsIDragService); - - ds.startDragSession(); - try { - var [result, dataTransfer] = EventUtils.synthesizeDragOver(aToDrag.parentNode, aTarget); - EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, aTarget); - // Send dragend to move dragging item back to initial place. - EventUtils.sendDragEvent({ type: "dragend", dataTransfer: dataTransfer }, - aToDrag.parentNode); - } finally { - ds.endDragSession(true); - } -} - -add_task(function* checkNoAddingToPanel() { - let area = CustomizableUI.AREA_PANEL; - let previousPlacements = getAreaWidgetIds(area); - CustomizableUI.addWidgetToArea("separator", area); - CustomizableUI.addWidgetToArea("spring", area); - CustomizableUI.addWidgetToArea("spacer", area); - assertAreaPlacements(area, previousPlacements); - - let oldNumberOfItems = previousPlacements.length; - if (getAreaWidgetIds(area).length != oldNumberOfItems) { - CustomizableUI.reset(); - } -}); - -add_task(function* checkAddingToToolbar() { - let area = CustomizableUI.AREA_NAVBAR; - let previousPlacements = getAreaWidgetIds(area); - CustomizableUI.addWidgetToArea("separator", area); - CustomizableUI.addWidgetToArea("spring", area); - CustomizableUI.addWidgetToArea("spacer", area); - let expectedPlacements = [...previousPlacements].concat([ - /separator/, - /spring/, - /spacer/ - ]); - assertAreaPlacements(area, expectedPlacements); - - let newlyAddedElements = getAreaWidgetIds(area).slice(-3); - while (newlyAddedElements.length) { - CustomizableUI.removeWidgetFromArea(newlyAddedElements.shift()); - } - - assertAreaPlacements(area, previousPlacements); - - let oldNumberOfItems = previousPlacements.length; - if (getAreaWidgetIds(area).length != oldNumberOfItems) { - CustomizableUI.reset(); - } -}); - - -add_task(function* checkDragging() { - let startArea = CustomizableUI.AREA_NAVBAR; - let targetArea = CustomizableUI.AREA_PANEL; - let startingToolbarPlacements = getAreaWidgetIds(startArea); - let startingTargetPlacements = getAreaWidgetIds(targetArea); - - CustomizableUI.addWidgetToArea("separator", startArea); - CustomizableUI.addWidgetToArea("spring", startArea); - CustomizableUI.addWidgetToArea("spacer", startArea); - - let placementsWithSpecials = getAreaWidgetIds(startArea); - let elementsToMove = []; - for (let id of placementsWithSpecials) { - if (CustomizableUI.isSpecialWidget(id)) { - elementsToMove.push(id); - } - } - is(elementsToMove.length, 3, "Should have 3 elements to try and drag."); - - yield startCustomizing(); - for (let id of elementsToMove) { - simulateItemDragAndEnd(document.getElementById(id), PanelUI.contents); - } - - assertAreaPlacements(startArea, placementsWithSpecials); - assertAreaPlacements(targetArea, startingTargetPlacements); - - for (let id of elementsToMove) { - simulateItemDrag(document.getElementById(id), gCustomizeMode.visiblePalette); - } - - assertAreaPlacements(startArea, startingToolbarPlacements); - assertAreaPlacements(targetArea, startingTargetPlacements); - - ok(!gCustomizeMode.visiblePalette.querySelector("toolbarspring,toolbarseparator,toolbarspacer"), - "No specials should make it to the palette alive."); - yield endCustomizing(); -}); - - -add_task(function* asyncCleanup() { - yield endCustomizing(); - CustomizableUI.reset(); -}); - diff --git a/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js b/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js deleted file mode 100644 index db4f88e6d..000000000 --- a/browser/components/customizableui/test/browser_1007336_lwthemes_in_customize_mode.js +++ /dev/null @@ -1,108 +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 DEFAULT_THEME_ID = "{972ce4c6-7e08-4474-a285-3208198ce6fd}"; -const {LightweightThemeManager} = Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", {}); - -add_task(function* () { - Services.prefs.clearUserPref("lightweightThemes.usedThemes"); - Services.prefs.clearUserPref("lightweightThemes.recommendedThemes"); - LightweightThemeManager.clearBuiltInThemes(); - - yield startCustomizing(); - - let themesButton = document.getElementById("customization-lwtheme-button"); - let popup = document.getElementById("customization-lwtheme-menu"); - - let popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button"); - yield popupShownPromise; - - // close current tab and re-open Customize menu to confirm correct number of Themes - yield endCustomizing(); - info("Exited customize mode"); - yield startCustomizing(); - info("Started customizing a second time"); - popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button a second time"); - yield popupShownPromise; - - let header = document.getElementById("customization-lwtheme-menu-header"); - let recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended"); - - is(header.nextSibling.nextSibling, recommendedHeader, - "There should only be one theme (default) in the 'My Themes' section by default"); - is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "That theme should be the default theme"); - - let firstLWTheme = recommendedHeader.nextSibling; - let firstLWThemeId = firstLWTheme.theme.id; - let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed"); - firstLWTheme.doCommand(); - info("Clicked on first theme"); - yield themeChangedPromise; - - popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button"); - yield popupShownPromise; - - is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "The first theme should be the Default theme"); - let installedThemeId = header.nextSibling.nextSibling.theme.id; - ok(installedThemeId.startsWith(firstLWThemeId), - "The second theme in the 'My Themes' section should be the newly installed theme: " + - "Installed theme id: " + installedThemeId + "; First theme ID: " + firstLWThemeId); - is(header.nextSibling.nextSibling.nextSibling, recommendedHeader, - "There should be two themes in the 'My Themes' section"); - - let defaultTheme = header.nextSibling; - defaultTheme.doCommand(); - is(Services.prefs.getCharPref("lightweightThemes.selectedThemeID"), "", "No lwtheme should be selected"); - - // ensure current theme isn't set to "Default" - popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button a second time"); - yield popupShownPromise; - - firstLWTheme = recommendedHeader.nextSibling; - themeChangedPromise = promiseObserverNotified("lightweight-theme-changed"); - firstLWTheme.doCommand(); - info("Clicked on first theme again"); - yield themeChangedPromise; - - // check that "Restore Defaults" button resets theme - yield gCustomizeMode.reset(); - is(LightweightThemeManager.currentTheme, null, "Current theme reset to default"); - - yield endCustomizing(); - Services.prefs.setCharPref("lightweightThemes.usedThemes", "[]"); - Services.prefs.setCharPref("lightweightThemes.recommendedThemes", "[]"); - info("Removed all recommended themes"); - yield startCustomizing(); - popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button a second time"); - yield popupShownPromise; - header = document.getElementById("customization-lwtheme-menu-header"); - is(header.hidden, false, "Header should never be hidden"); - is(header.nextSibling.theme.id, DEFAULT_THEME_ID, "The first theme should be the Default theme"); - is(header.nextSibling.hidden, false, "The default theme should never be hidden"); - recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended"); - is(header.nextSibling.nextSibling, recommendedHeader, - "There should only be one theme (default) in the 'My Themes' section by default"); - let footer = document.getElementById("customization-lwtheme-menu-footer"); - is(recommendedHeader.nextSibling.id, footer.id, "There should be no recommended themes in the menu"); - is(recommendedHeader.hidden, true, "The recommendedHeader should be hidden since there are no recommended themes"); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - - Services.prefs.clearUserPref("lightweightThemes.usedThemes"); - Services.prefs.clearUserPref("lightweightThemes.recommendedThemes"); -}); diff --git a/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js b/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js deleted file mode 100644 index 56657914b..000000000 --- a/browser/components/customizableui/test/browser_1008559_anchor_undo_restore.js +++ /dev/null @@ -1,71 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const kAnchorAttribute = "cui-anchorid"; - -/** - * Check that anchor gets set correctly when moving an item from the panel to the toolbar - * using 'undo' - */ -add_task(function*() { - yield startCustomizing(); - let button = document.getElementById("history-panelmenu"); - is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button", - "Button (" + button.id + ") starts out with correct anchor"); - - let navbar = document.getElementById("nav-bar").customizationTarget; - simulateItemDrag(button, navbar); - is(CustomizableUI.getPlacementOfWidget(button.id).area, "nav-bar", - "Button (" + button.id + ") ends up in nav-bar"); - - ok(!button.hasAttribute(kAnchorAttribute), - "Button (" + button.id + ") has no anchor in toolbar"); - - let resetButton = document.getElementById("customization-reset-button"); - ok(!resetButton.hasAttribute("disabled"), "Should be able to reset now."); - yield gCustomizeMode.reset(); - - is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button", - "Button (" + button.id + ") has anchor again"); - - let undoButton = document.getElementById("customization-undo-reset-button"); - ok(!undoButton.hasAttribute("disabled"), "Should be able to undo now."); - yield gCustomizeMode.undoReset(); - - ok(!button.hasAttribute(kAnchorAttribute), - "Button (" + button.id + ") once again has no anchor in toolbar"); - - yield gCustomizeMode.reset(); - - yield endCustomizing(); -}); - - -/** - * Check that anchor gets set correctly when moving an item from the panel to the toolbar - * using 'reset' - */ -add_task(function*() { - yield startCustomizing(); - let button = document.getElementById("bookmarks-menu-button"); - ok(!button.hasAttribute(kAnchorAttribute), - "Button (" + button.id + ") has no anchor in toolbar"); - - let panel = document.getElementById("PanelUI-contents"); - simulateItemDrag(button, panel); - is(CustomizableUI.getPlacementOfWidget(button.id).area, "PanelUI-contents", - "Button (" + button.id + ") ends up in panel"); - is(button.getAttribute(kAnchorAttribute), "PanelUI-menu-button", - "Button (" + button.id + ") has correct anchor in the panel"); - - let resetButton = document.getElementById("customization-reset-button"); - ok(!resetButton.hasAttribute("disabled"), "Should be able to reset now."); - yield gCustomizeMode.reset(); - - ok(!button.hasAttribute(kAnchorAttribute), - "Button (" + button.id + ") once again has no anchor in toolbar"); - - yield endCustomizing(); -}); diff --git a/browser/components/customizableui/test/browser_1042100_default_placements_update.js b/browser/components/customizableui/test/browser_1042100_default_placements_update.js deleted file mode 100644 index 129dbd754..000000000 --- a/browser/components/customizableui/test/browser_1042100_default_placements_update.js +++ /dev/null @@ -1,107 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -// NB: This uses some ugly hacks to get into the CUI module from elsewhere... -// don't try this at home, kids. -function test() { - // Customize something to make sure stuff changed: - CustomizableUI.addWidgetToArea("feed-button", CustomizableUI.AREA_NAVBAR); - - // Check what version we're on: - let CustomizableUIBSPass = Cu.import("resource:///modules/CustomizableUI.jsm", {}); - - is(CustomizableUIBSPass.gFuturePlacements.size, 0, - "All future placements should be dealt with by now."); - - let {CustomizableUIInternal, gFuturePlacements, gPalette} = CustomizableUIBSPass; - CustomizableUIInternal._introduceNewBuiltinWidgets(); - is(gFuturePlacements.size, 0, - "No change to future placements initially."); - - let currentVersion = CustomizableUIBSPass.kVersion; - - - // Add our widget to the defaults: - let testWidgetNew = { - id: "test-messing-with-default-placements-new", - label: "Test messing with default placements - should be inserted", - defaultArea: CustomizableUI.AREA_NAVBAR, - introducedInVersion: currentVersion + 1, - }; - - let normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetNew, - CustomizableUI.SOURCE_BUILTIN); - ok(normalizedWidget, "Widget should be normalizable"); - if (!normalizedWidget) { - return; - } - CustomizableUIBSPass.gPalette.set(testWidgetNew.id, normalizedWidget); - - let testWidgetOld = { - id: "test-messing-with-default-placements-old", - label: "Test messing with default placements - should NOT be inserted", - defaultArea: CustomizableUI.AREA_NAVBAR, - introducedInVersion: currentVersion, - }; - - normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetOld, - CustomizableUI.SOURCE_BUILTIN); - ok(normalizedWidget, "Widget should be normalizable"); - if (!normalizedWidget) { - return; - } - CustomizableUIBSPass.gPalette.set(testWidgetOld.id, normalizedWidget); - - - // Now increase the version in the module: - CustomizableUIBSPass.kVersion++; - - let hadSavedState = !!CustomizableUIBSPass.gSavedState - if (!hadSavedState) { - CustomizableUIBSPass.gSavedState = {currentVersion: CustomizableUIBSPass.kVersion - 1}; - } - - // Then call the re-init routine so we re-add the builtin widgets - CustomizableUIInternal._introduceNewBuiltinWidgets(); - is(gFuturePlacements.size, 1, - "Should have 1 more future placement"); - let haveNavbarPlacements = gFuturePlacements.has(CustomizableUI.AREA_NAVBAR); - ok(haveNavbarPlacements, "Should have placements for nav-bar"); - if (haveNavbarPlacements) { - let placements = [...gFuturePlacements.get(CustomizableUI.AREA_NAVBAR)]; - - // Ignore widgets that are placed using the pref facility and not the - // versioned facility. They're independent of kVersion and the saved - // state's current version, so they may be present in the placements. - for (let i = 0; i < placements.length; ) { - if (placements[i] == testWidgetNew.id) { - i++; - continue; - } - let pref = "browser.toolbarbuttons.introduced." + placements[i]; - let introduced = false; - try { - introduced = Services.prefs.getBoolPref(pref); - } catch (ex) {} - if (!introduced) { - i++; - continue; - } - placements.splice(i, 1); - } - - is(placements.length, 1, "Should have 1 newly placed widget in nav-bar"); - is(placements[0], testWidgetNew.id, "Should have our test widget to be placed in nav-bar"); - } - - gFuturePlacements.delete(CustomizableUI.AREA_NAVBAR); - CustomizableUIBSPass.kVersion--; - gPalette.delete(testWidgetNew.id); - gPalette.delete(testWidgetOld.id); - if (!hadSavedState) { - CustomizableUIBSPass.gSavedState = null; - } -} - diff --git a/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js b/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js deleted file mode 100644 index 42a032ff8..000000000 --- a/browser/components/customizableui/test/browser_1058573_showToolbarsDropdown.js +++ /dev/null @@ -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/. */ - -"use strict"; - -add_task(function*() { - info("Check that toggleable toolbars dropdown in always shown"); - - info("Remove all possible custom toolbars"); - yield removeCustomToolbars(); - - info("Enter customization mode"); - yield startCustomizing(); - - let toolbarsToggle = document.getElementById("customization-toolbar-visibility-button"); - ok(toolbarsToggle, "The toolbars toggle dropdown exists"); - ok(!toolbarsToggle.hasAttribute("hidden"), - "The toolbars toggle dropdown is displayed"); -}); - -add_task(function* asyncCleanup() { - info("Exit customization mode"); - yield endCustomizing(); -}); diff --git a/browser/components/customizableui/test/browser_1087303_button_fullscreen.js b/browser/components/customizableui/test/browser_1087303_button_fullscreen.js deleted file mode 100644 index c6b87d6ab..000000000 --- a/browser/components/customizableui/test/browser_1087303_button_fullscreen.js +++ /dev/null @@ -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/. */ - -"use strict"; - -add_task(function*() { - info("Check fullscreen button existence and functionality"); - - yield PanelUI.show(); - - let fullscreenButton = document.getElementById("fullscreen-button"); - ok(fullscreenButton, "Fullscreen button appears in Panel Menu"); - - let fullscreenPromise = promiseFullscreenChange(); - fullscreenButton.click(); - yield fullscreenPromise; - - ok(window.fullScreen, "Fullscreen mode was opened"); - - // exit full screen mode - fullscreenPromise = promiseFullscreenChange(); - window.fullScreen = !window.fullScreen; - yield fullscreenPromise; - - ok(!window.fullScreen, "Successfully exited fullscreen"); -}); - -function promiseFullscreenChange() { - let deferred = Promise.defer(); - info("Wait for fullscreen change"); - - let timeoutId = setTimeout(() => { - window.removeEventListener("fullscreen", onFullscreenChange, true); - deferred.reject("Fullscreen change did not happen within " + 20000 + "ms"); - }, 20000); - - function onFullscreenChange(event) { - clearTimeout(timeoutId); - window.removeEventListener("fullscreen", onFullscreenChange, true); - info("Fullscreen event received"); - deferred.resolve(); - } - window.addEventListener("fullscreen", onFullscreenChange, true); - return deferred.promise; -} diff --git a/browser/components/customizableui/test/browser_1087303_button_preferences.js b/browser/components/customizableui/test/browser_1087303_button_preferences.js deleted file mode 100644 index b1fdb85b6..000000000 --- a/browser/components/customizableui/test/browser_1087303_button_preferences.js +++ /dev/null @@ -1,50 +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"; - -var newTab = null; - -add_task(function*() { - info("Check preferences button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let preferencesButton = document.getElementById("preferences-button"); - ok(preferencesButton, "Preferences button exists in Panel Menu"); - preferencesButton.click(); - - newTab = gBrowser.selectedTab; - yield waitForPageLoad(newTab); - - let openedPage = gBrowser.currentURI.spec; - is(openedPage, "about:preferences", "Preferences page was opened"); -}); - -add_task(function asyncCleanup() { - if (gBrowser.tabs.length == 1) - gBrowser.addTab("about:blank"); - - gBrowser.removeTab(gBrowser.selectedTab); - info("Tabs were restored"); -}); - -function waitForPageLoad(aTab) { - let deferred = Promise.defer(); - - let timeoutId = setTimeout(() => { - aTab.linkedBrowser.removeEventListener("load", onTabLoad, true); - deferred.reject("Page didn't load within " + 20000 + "ms"); - }, 20000); - - function onTabLoad(event) { - clearTimeout(timeoutId); - aTab.linkedBrowser.removeEventListener("load", onTabLoad, true); - info("Tab event received: " + "load"); - deferred.resolve(); - } - aTab.linkedBrowser.addEventListener("load", onTabLoad, true, true); - return deferred.promise; -} diff --git a/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js b/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js deleted file mode 100644 index 1f502e8e2..000000000 --- a/browser/components/customizableui/test/browser_1089591_still_customizable_after_reset.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; - -// Dragging the elements again after a reset should work -add_task(function* () { - yield startCustomizing(); - let historyButton = document.getElementById("wrapper-history-panelmenu"); - let devButton = document.getElementById("wrapper-developer-button"); - - ok(historyButton && devButton, "Draggable elements should exist"); - simulateItemDrag(historyButton, devButton); - yield gCustomizeMode.reset(); - ok(CustomizableUI.inDefaultState, "Should be back in default state"); - - historyButton = document.getElementById("wrapper-history-panelmenu"); - devButton = document.getElementById("wrapper-developer-button"); - ok(historyButton && devButton, "Draggable elements should exist"); - simulateItemDrag(historyButton, devButton); - - yield endCustomizing(); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js b/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js deleted file mode 100644 index b5a325afb..000000000 --- a/browser/components/customizableui/test/browser_1096763_seen_widgets_post_reset.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; - -const BUTTONID = "test-seenwidget-post-reset"; - -add_task(function*() { - CustomizableUI.createWidget({ - id: BUTTONID, - label: "Test widget seen post reset", - defaultArea: CustomizableUI.AREA_NAVBAR - }); - - const kPrefCustomizationState = "browser.uiCustomization.state"; - let bsPass = Cu.import("resource:///modules/CustomizableUI.jsm", {}); - ok(bsPass.gSeenWidgets.has(BUTTONID), "Widget should be seen after createWidget is called."); - CustomizableUI.reset(); - ok(bsPass.gSeenWidgets.has(BUTTONID), "Widget should still be seen after reset."); - ok(!Services.prefs.prefHasUserValue(kPrefCustomizationState), "Pref shouldn't be set right now, because that'd break undo."); - CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR); - gCustomizeMode.removeFromArea(document.getElementById(BUTTONID)); - let hasUserValue = Services.prefs.prefHasUserValue(kPrefCustomizationState); - ok(hasUserValue, "Pref should be set right now."); - if (hasUserValue) { - let seenArray = JSON.parse(Services.prefs.getCharPref(kPrefCustomizationState)).seen; - isnot(seenArray.indexOf(BUTTONID), -1, "Widget should be in saved 'seen' list."); - } -}); - -registerCleanupFunction(function() { - CustomizableUI.destroyWidget(BUTTONID); - CustomizableUI.reset(); -}); diff --git a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js b/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js deleted file mode 100644 index 42768debf..000000000 --- a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js +++ /dev/null @@ -1,78 +0,0 @@ -"use strict"; - -// NB: This uses some ugly hacks to get into the CUI module from elsewhere... -// don't try this at home, kids. -function test() { - // Customize something to make sure stuff changed: - CustomizableUI.addWidgetToArea("feed-button", CustomizableUI.AREA_NAVBAR); - - let CustomizableUIBSPass = Cu.import("resource:///modules/CustomizableUI.jsm", {}); - - is(CustomizableUIBSPass.gFuturePlacements.size, 0, - "All future placements should be dealt with by now."); - - let {CustomizableUIInternal, gFuturePlacements, gPalette} = CustomizableUIBSPass; - - // Force us to have a saved state: - CustomizableUIInternal.saveState(); - CustomizableUIInternal.loadSavedState(); - - CustomizableUIInternal._introduceNewBuiltinWidgets(); - is(gFuturePlacements.size, 0, - "No change to future placements initially."); - - // Add our widget to the defaults: - let testWidgetNew = { - id: "test-messing-with-default-placements-new-pref", - label: "Test messing with default placements - pref-based", - defaultArea: CustomizableUI.AREA_NAVBAR, - introducedInVersion: "pref", - }; - - let normalizedWidget = CustomizableUIInternal.normalizeWidget(testWidgetNew, - CustomizableUI.SOURCE_BUILTIN); - ok(normalizedWidget, "Widget should be normalizable"); - if (!normalizedWidget) { - return; - } - CustomizableUIBSPass.gPalette.set(testWidgetNew.id, normalizedWidget); - - // Now adjust default placements for area: - let navbarArea = CustomizableUIBSPass.gAreas.get(CustomizableUI.AREA_NAVBAR); - let navbarPlacements = navbarArea.get("defaultPlacements"); - navbarPlacements.splice(navbarPlacements.indexOf("bookmarks-menu-button") + 1, 0, testWidgetNew.id); - - let savedPlacements = CustomizableUIBSPass.gSavedState.placements[CustomizableUI.AREA_NAVBAR]; - // Then call the re-init routine so we re-add the builtin widgets - CustomizableUIInternal._introduceNewBuiltinWidgets(); - is(gFuturePlacements.size, 1, - "Should have 1 more future placement"); - let futureNavbarPlacements = gFuturePlacements.get(CustomizableUI.AREA_NAVBAR); - ok(futureNavbarPlacements, "Should have placements for nav-bar"); - if (futureNavbarPlacements) { - ok(futureNavbarPlacements.has(testWidgetNew.id), "widget should be in future placements"); - } - CustomizableUIInternal._placeNewDefaultWidgetsInArea(CustomizableUI.AREA_NAVBAR); - - let indexInSavedPlacements = savedPlacements.indexOf(testWidgetNew.id); - info("Saved placements: " + savedPlacements.join(', ')); - isnot(indexInSavedPlacements, -1, "Widget should have been inserted"); - is(indexInSavedPlacements, savedPlacements.indexOf("bookmarks-menu-button") + 1, - "Widget should be in the right place."); - - if (futureNavbarPlacements) { - ok(!futureNavbarPlacements.has(testWidgetNew.id), "widget should be out of future placements"); - } - - if (indexInSavedPlacements != -1) { - savedPlacements.splice(indexInSavedPlacements, 1); - } - - gFuturePlacements.delete(CustomizableUI.AREA_NAVBAR); - let indexInDefaultPlacements = navbarPlacements.indexOf(testWidgetNew.id); - if (indexInDefaultPlacements != -1) { - navbarPlacements.splice(indexInDefaultPlacements, 1); - } - gPalette.delete(testWidgetNew.id); - CustomizableUI.reset(); -} diff --git a/browser/components/customizableui/test/browser_873501_handle_specials.js b/browser/components/customizableui/test/browser_873501_handle_specials.js deleted file mode 100644 index b07c8e0d7..000000000 --- a/browser/components/customizableui/test/browser_873501_handle_specials.js +++ /dev/null @@ -1,79 +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 kToolbarName = "test-specials-toolbar"; - -registerCleanupFunction(removeCustomToolbars); - -// Add a toolbar with two springs and the downloads button. -add_task(function* addToolbarWith2SpringsAndDownloadsButton() { - // Create the toolbar with a single spring: - createToolbarWithPlacements(kToolbarName, ["spring"]); - ok(document.getElementById(kToolbarName), "Toolbar should be created."); - - // Check it's there with a generated ID: - assertAreaPlacements(kToolbarName, [/customizableui-special-spring\d+/]); - let [springId] = getAreaWidgetIds(kToolbarName); - - // Add a second spring, check if that's there and doesn't share IDs - CustomizableUI.addWidgetToArea("spring", kToolbarName); - assertAreaPlacements(kToolbarName, [springId, - /customizableui-special-spring\d+/]); - let [, spring2Id] = getAreaWidgetIds(kToolbarName); - - isnot(springId, spring2Id, "Springs shouldn't have identical IDs."); - - // Try moving the downloads button to this new toolbar, between the two springs: - CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1); - assertAreaPlacements(kToolbarName, [springId, "downloads-button", spring2Id]); - yield removeCustomToolbars(); -}); - -// Add separators around the downloads button. -add_task(function* addSeparatorsAroundDownloadsButton() { - createToolbarWithPlacements(kToolbarName, ["separator"]); - ok(document.getElementById(kToolbarName), "Toolbar should be created."); - - // Check it's there with a generated ID: - assertAreaPlacements(kToolbarName, [/customizableui-special-separator\d+/]); - let [separatorId] = getAreaWidgetIds(kToolbarName); - - CustomizableUI.addWidgetToArea("separator", kToolbarName); - assertAreaPlacements(kToolbarName, [separatorId, - /customizableui-special-separator\d+/]); - let [, separator2Id] = getAreaWidgetIds(kToolbarName); - - isnot(separatorId, separator2Id, "Separator ids shouldn't be equal."); - - CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1); - assertAreaPlacements(kToolbarName, [separatorId, "downloads-button", separator2Id]); - yield removeCustomToolbars(); -}); - -// Add spacers around the downloads button. -add_task(function* addSpacersAroundDownloadsButton() { - createToolbarWithPlacements(kToolbarName, ["spacer"]); - ok(document.getElementById(kToolbarName), "Toolbar should be created."); - - // Check it's there with a generated ID: - assertAreaPlacements(kToolbarName, [/customizableui-special-spacer\d+/]); - let [spacerId] = getAreaWidgetIds(kToolbarName); - - CustomizableUI.addWidgetToArea("spacer", kToolbarName); - assertAreaPlacements(kToolbarName, [spacerId, - /customizableui-special-spacer\d+/]); - let [, spacer2Id] = getAreaWidgetIds(kToolbarName); - - isnot(spacerId, spacer2Id, "Spacer ids shouldn't be equal."); - - CustomizableUI.addWidgetToArea("downloads-button", kToolbarName, 1); - assertAreaPlacements(kToolbarName, [spacerId, "downloads-button", spacer2Id]); - yield removeCustomToolbars(); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js b/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js deleted file mode 100644 index a3204c271..000000000 --- a/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js +++ /dev/null @@ -1,185 +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 kXULWidgetId = "a-test-button"; // we'll create a button with this ID. -const kAPIWidgetId = "feed-button"; -const kPanel = CustomizableUI.AREA_PANEL; -const kToolbar = CustomizableUI.AREA_NAVBAR; -const kVisiblePalette = "customization-palette"; -const kPlaceholderClass = "panel-customization-placeholder"; - -function checkWrapper(id) { - is(document.querySelectorAll("#wrapper-" + id).length, 1, "There should be exactly 1 wrapper for " + id + " in the customizing window."); -} - -var move = { - "drag": function(id, target) { - let targetNode = document.getElementById(target); - if (targetNode.customizationTarget) { - targetNode = targetNode.customizationTarget; - } - simulateItemDrag(document.getElementById(id), targetNode); - }, - "dragToItem": function(id, target) { - let targetNode = document.getElementById(target); - if (targetNode.customizationTarget) { - targetNode = targetNode.customizationTarget; - } - let items = targetNode.querySelectorAll("toolbarpaletteitem:not(." + kPlaceholderClass + ")"); - if (target == kPanel) { - targetNode = items[items.length - 1]; - } else { - targetNode = items[0]; - } - simulateItemDrag(document.getElementById(id), targetNode); - }, - "API": function(id, target) { - if (target == kVisiblePalette) { - return CustomizableUI.removeWidgetFromArea(id); - } - return CustomizableUI.addWidgetToArea(id, target, null); - } -}; - -function isLast(containerId, defaultPlacements, id) { - assertAreaPlacements(containerId, defaultPlacements.concat([id])); - is(document.getElementById(containerId).customizationTarget.lastChild.firstChild.id, id, - "Widget " + id + " should be in " + containerId + " in customizing window."); - is(otherWin.document.getElementById(containerId).customizationTarget.lastChild.id, id, - "Widget " + id + " should be in " + containerId + " in other window."); -} - -function getLastVisibleNodeInToolbar(containerId, win=window) { - let container = win.document.getElementById(containerId).customizationTarget; - let rv = container.lastChild; - while (rv && (rv.getAttribute('hidden') == 'true' || (rv.firstChild && rv.firstChild.getAttribute('hidden') == 'true'))) { - rv = rv.previousSibling; - } - return rv; -} - -function isLastVisibleInToolbar(containerId, defaultPlacements, id) { - let newPlacements; - for (let i = defaultPlacements.length - 1; i >= 0; i--) { - let el = document.getElementById(defaultPlacements[i]); - if (el && el.getAttribute('hidden') != 'true') { - newPlacements = [...defaultPlacements]; - newPlacements.splice(i + 1, 0, id); - break; - } - } - if (!newPlacements) { - assertAreaPlacements(containerId, defaultPlacements.concat([id])); - } else { - assertAreaPlacements(containerId, newPlacements); - } - is(getLastVisibleNodeInToolbar(containerId).firstChild.id, id, - "Widget " + id + " should be in " + containerId + " in customizing window."); - is(getLastVisibleNodeInToolbar(containerId, otherWin).id, id, - "Widget " + id + " should be in " + containerId + " in other window."); -} - -function isFirst(containerId, defaultPlacements, id) { - assertAreaPlacements(containerId, [id].concat(defaultPlacements)); - is(document.getElementById(containerId).customizationTarget.firstChild.firstChild.id, id, - "Widget " + id + " should be in " + containerId + " in customizing window."); - is(otherWin.document.getElementById(containerId).customizationTarget.firstChild.id, id, - "Widget " + id + " should be in " + containerId + " in other window."); -} - -function checkToolbar(id, method) { - // Place at start of the toolbar: - let toolbarPlacements = getAreaWidgetIds(kToolbar); - move[method](id, kToolbar); - if (method == "dragToItem") { - isFirst(kToolbar, toolbarPlacements, id); - } else if (method == "drag") { - isLastVisibleInToolbar(kToolbar, toolbarPlacements, id); - } else { - isLast(kToolbar, toolbarPlacements, id); - } - checkWrapper(id); -} - -function checkPanel(id, method) { - let panelPlacements = getAreaWidgetIds(kPanel); - move[method](id, kPanel); - let children = document.getElementById(kPanel).querySelectorAll("toolbarpaletteitem:not(." + kPlaceholderClass + ")"); - let otherChildren = otherWin.document.getElementById(kPanel).children; - let newPlacements = panelPlacements.concat([id]); - // Relative position of the new item from the end: - let position = -1; - // For the drag to item case, we drag to the last item, making the dragged item the - // penultimate item. We can't well use the first item because the panel has complicated - // rules about rearranging wide items (which, by default, the first two items are). - if (method == "dragToItem") { - newPlacements.pop(); - newPlacements.splice(panelPlacements.length - 1, 0, id); - position = -2; - } - assertAreaPlacements(kPanel, newPlacements); - is(children[children.length + position].firstChild.id, id, - "Widget " + id + " should be in " + kPanel + " in customizing window."); - is(otherChildren[otherChildren.length + position].id, id, - "Widget " + id + " should be in " + kPanel + " in other window."); - checkWrapper(id); -} - -function checkPalette(id, method) { - // Move back to palette: - move[method](id, kVisiblePalette); - ok(CustomizableUI.inDefaultState, "Should end in default state"); - let visibleChildren = gCustomizeMode.visiblePalette.children; - let expectedChild = method == "dragToItem" ? visibleChildren[0] : visibleChildren[visibleChildren.length - 1]; - is(expectedChild.firstChild.id, id, "Widget " + id + " was moved using " + method + " and should now be wrapped in palette in customizing window."); - if (id == kXULWidgetId) { - ok(otherWin.gNavToolbox.palette.querySelector("#" + id), "Widget " + id + " should be in invisible palette in other window."); - } - checkWrapper(id); -} - -// This test needs a XUL button that's in the palette by default. No such -// button currently exists, so we create a simple one. -function createXULButtonForWindow(win) { - createDummyXULButton(kXULWidgetId, "test-button", win); -} - -function removeXULButtonForWindow(win) { - win.gNavToolbox.palette.querySelector(`#${kXULWidgetId}`).remove(); -} - -var otherWin; - -// Moving widgets in two windows, one with customize mode and one without, should work. -add_task(function* MoveWidgetsInTwoWindows() { - yield startCustomizing(); - otherWin = yield openAndLoadWindow(null, true); - yield otherWin.PanelUI.ensureReady(); - // Create the XUL button to use in the test in both windows. - createXULButtonForWindow(window); - createXULButtonForWindow(otherWin); - ok(CustomizableUI.inDefaultState, "Should start in default state"); - - for (let widgetId of [kXULWidgetId, kAPIWidgetId]) { - for (let method of ["API", "drag", "dragToItem"]) { - info("Moving widget " + widgetId + " using " + method); - checkToolbar(widgetId, method); - checkPanel(widgetId, method); - checkPalette(widgetId, method); - checkPanel(widgetId, method); - checkToolbar(widgetId, method); - checkPalette(widgetId, method); - } - } - yield promiseWindowClosed(otherWin); - otherWin = null; - yield endCustomizing(); - removeXULButtonForWindow(window); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js b/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js deleted file mode 100644 index ec454dc8d..000000000 --- a/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js +++ /dev/null @@ -1,61 +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 kTestWidget1 = "test-customize-mode-create-destroy1"; -const kTestWidget2 = "test-customize-mode-create-destroy2"; - -// Creating and destroying a widget should correctly wrap/unwrap stuff -add_task(function* testWrapUnwrap() { - yield startCustomizing(); - CustomizableUI.createWidget({id: kTestWidget1, label: 'Pretty label', tooltiptext: 'Pretty tooltip'}); - let elem = document.getElementById(kTestWidget1); - let wrapper = document.getElementById("wrapper-" + kTestWidget1); - ok(elem, "There should be an item"); - ok(wrapper, "There should be a wrapper"); - is(wrapper.firstChild.id, kTestWidget1, "Wrapper should have test widget"); - is(wrapper.parentNode.id, "customization-palette", "Wrapper should be in palette"); - CustomizableUI.destroyWidget(kTestWidget1); - wrapper = document.getElementById("wrapper-" + kTestWidget1); - ok(!wrapper, "There should be a wrapper"); - let item = document.getElementById(kTestWidget1); - ok(!item, "There should no longer be an item"); -}); - -// Creating and destroying a widget should correctly deal with panel placeholders -add_task(function* testPanelPlaceholders() { - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - // The value of expectedPlaceholders depends on the default palette layout. - // Bug 1229236 is for these tests to be smarter so the test doesn't need to - // change when the default placements change. - let expectedPlaceholders = 1 + (isInDevEdition() ? 1 : 0); - is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct."); - CustomizableUI.createWidget({id: kTestWidget2, label: 'Pretty label', tooltiptext: 'Pretty tooltip', defaultArea: CustomizableUI.AREA_PANEL}); - let elem = document.getElementById(kTestWidget2); - let wrapper = document.getElementById("wrapper-" + kTestWidget2); - ok(elem, "There should be an item"); - ok(wrapper, "There should be a wrapper"); - is(wrapper.firstChild.id, kTestWidget2, "Wrapper should have test widget"); - is(wrapper.parentNode, panel, "Wrapper should be in panel"); - expectedPlaceholders = isInDevEdition() ? 1 : 3; - is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct."); - CustomizableUI.destroyWidget(kTestWidget2); - wrapper = document.getElementById("wrapper-" + kTestWidget2); - ok(!wrapper, "There should be a wrapper"); - let item = document.getElementById(kTestWidget2); - ok(!item, "There should no longer be an item"); - yield endCustomizing(); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - try { - CustomizableUI.destroyWidget(kTestWidget1); - } catch (ex) {} - try { - CustomizableUI.destroyWidget(kTestWidget2); - } catch (ex) {} - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_877006_missing_view.js b/browser/components/customizableui/test/browser_877006_missing_view.js deleted file mode 100644 index a1495c1fe..000000000 --- a/browser/components/customizableui/test/browser_877006_missing_view.js +++ /dev/null @@ -1,41 +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"; - -// Should be able to add broken view widget -add_task(function testAddbrokenViewWidget() { - const kWidgetId = 'test-877006-broken-widget'; - let widgetSpec = { - id: kWidgetId, - type: 'view', - viewId: 'idontexist', - /* Empty handler so we try to attach it maybe? */ - onViewShowing: function() { - } - }; - - let noError = true; - try { - CustomizableUI.createWidget(widgetSpec); - CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Should not throw an exception trying to add a broken view widget."); - - noError = true; - try { - CustomizableUI.destroyWidget(kWidgetId); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Should not throw an exception trying to remove the broken view widget."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_877178_unregisterArea.js b/browser/components/customizableui/test/browser_877178_unregisterArea.js deleted file mode 100644 index 28037787b..000000000 --- a/browser/components/customizableui/test/browser_877178_unregisterArea.js +++ /dev/null @@ -1,50 +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"; - -registerCleanupFunction(removeCustomToolbars); - -// Sanity checks -add_task(function sanityChecks() { - SimpleTest.doesThrow(() => CustomizableUI.registerArea("@foo"), - "Registering areas with an invalid ID should throw."); - - SimpleTest.doesThrow(() => CustomizableUI.registerArea([]), - "Registering areas with an invalid ID should throw."); - - SimpleTest.doesThrow(() => CustomizableUI.unregisterArea("@foo"), - "Unregistering areas with an invalid ID should throw."); - - SimpleTest.doesThrow(() => CustomizableUI.unregisterArea([]), - "Unregistering areas with an invalid ID should throw."); - - SimpleTest.doesThrow(() => CustomizableUI.unregisterArea("unknown"), - "Unregistering an area that's not registered should throw."); -}); - -// Check areas are loaded with their default placements. -add_task(function checkLoadedAres() { - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); -}); - -// Check registering and unregistering a new area. -add_task(function checkRegisteringAndUnregistering() { - const kToolbarId = "test-registration-toolbar"; - const kButtonId = "test-registration-button"; - createDummyXULButton(kButtonId); - createToolbarWithPlacements(kToolbarId, ["spring", kButtonId, "spring"]); - assertAreaPlacements(kToolbarId, - [/customizableui-special-spring\d+/, - kButtonId, - /customizableui-special-spring\d+/]); - ok(!CustomizableUI.inDefaultState, "With a new toolbar it is no longer in a default state."); - removeCustomToolbars(); // Will call unregisterArea for us - ok(CustomizableUI.inDefaultState, "When the toolbar is unregistered, " + - "everything will return to the default state."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_877447_skip_missing_ids.js b/browser/components/customizableui/test/browser_877447_skip_missing_ids.js deleted file mode 100644 index 0cba7ae4f..000000000 --- a/browser/components/customizableui/test/browser_877447_skip_missing_ids.js +++ /dev/null @@ -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/. */ - -"use strict"; - -registerCleanupFunction(removeCustomToolbars); - -add_task(function skipMissingIDS() { - const kButtonId = "look-at-me-disappear-button"; - CustomizableUI.reset(); - ok(CustomizableUI.inDefaultState, "Should be in the default state."); - let btn = createDummyXULButton(kButtonId, "Gone!"); - CustomizableUI.addWidgetToArea(kButtonId, CustomizableUI.AREA_NAVBAR); - ok(!CustomizableUI.inDefaultState, "Should no longer be in the default state."); - is(btn.parentNode.parentNode.id, CustomizableUI.AREA_NAVBAR, "Button should be in navbar"); - btn.remove(); - is(btn.parentNode, null, "Button is no longer in the navbar"); - ok(CustomizableUI.inDefaultState, "Should be back in the default state, " + - "despite unknown button ID in placements."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_878452_drag_to_panel.js b/browser/components/customizableui/test/browser_878452_drag_to_panel.js deleted file mode 100644 index 8a8d82294..000000000 --- a/browser/components/customizableui/test/browser_878452_drag_to_panel.js +++ /dev/null @@ -1,65 +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"; - -// Dragging an item from the palette to another button in the panel should work. -add_task(function*() { - yield startCustomizing(); - let btn = document.getElementById("feed-button"); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - - let lastButtonIndex = placements.length - 1; - let lastButton = placements[lastButtonIndex]; - let placementsAfterInsert = placements.slice(0, lastButtonIndex).concat(["feed-button", lastButton]); - let lastButtonNode = document.getElementById(lastButton); - simulateItemDrag(btn, lastButtonNode); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let palette = document.getElementById("customization-palette"); - simulateItemDrag(btn, palette); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging an item from the palette to the panel itself should also work. -add_task(function*() { - yield startCustomizing(); - let btn = document.getElementById("feed-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - - let placementsAfterAppend = placements.concat(["feed-button"]); - simulateItemDrag(btn, panel); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let palette = document.getElementById("customization-palette"); - simulateItemDrag(btn, palette); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging an item from the palette to an empty panel should also work. -add_task(function*() { - let widgetIds = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - while (widgetIds.length) { - CustomizableUI.removeWidgetFromArea(widgetIds.shift()); - } - yield startCustomizing(); - let btn = document.getElementById("feed-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - - assertAreaPlacements(panel.id, []); - - let placementsAfterAppend = ["feed-button"]; - simulateItemDrag(btn, panel); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let palette = document.getElementById("customization-palette"); - simulateItemDrag(btn, palette); - assertAreaPlacements(panel.id, []); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_880164_customization_context_menus.js b/browser/components/customizableui/test/browser_880164_customization_context_menus.js deleted file mode 100644 index 57a0db773..000000000 --- a/browser/components/customizableui/test/browser_880164_customization_context_menus.js +++ /dev/null @@ -1,414 +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"; - -requestLongerTimeout(2); - -const isOSX = (Services.appinfo.OS === "Darwin"); - -// Right-click on the home button should -// show a context menu with options to move it. -add_task(function*() { - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownPromise = popupShown(contextMenu); - let homeButton = document.getElementById("home-button"); - EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2 }); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToPanel", true], - [".customize-context-removeFromToolbar", true], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; -}); - -// Right-click on an empty bit of tabstrip should -// show a context menu without options to move it, -// but with tab-specific options instead. -add_task(function*() { - // ensure there are tabs to reload/bookmark: - let extraTab = gBrowser.selectedTab = gBrowser.addTab(); - yield promiseTabLoadEvent(extraTab, "http://example.com/"); - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownPromise = popupShown(contextMenu); - let tabstrip = document.getElementById("tabbrowser-tabs"); - let rect = tabstrip.getBoundingClientRect(); - EventUtils.synthesizeMouse(tabstrip, rect.width - 2, 2, {type: "contextmenu", button: 2 }); - yield shownPromise; - - let closedTabsAvailable = SessionStore.getClosedTabCount(window) == 0; - info("Closed tabs: " + closedTabsAvailable); - let expectedEntries = [ - ["#toolbar-context-reloadAllTabs", true], - ["#toolbar-context-bookmarkAllTabs", true], - ["#toolbar-context-undoCloseTab", !closedTabsAvailable], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; - gBrowser.removeTab(extraTab); -}); - -// Right-click on an empty bit of extra toolbar should -// show a context menu with moving options disabled, -// and a toggle option for the extra toolbar -add_task(function*() { - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownPromise = popupShown(contextMenu); - let toolbar = createToolbarWithPlacements("880164_empty_toolbar", []); - toolbar.setAttribute("context", "toolbar-context-menu"); - toolbar.setAttribute("toolbarname", "Fancy Toolbar for Context Menu"); - EventUtils.synthesizeMouseAtCenter(toolbar, {type: "contextmenu", button: 2 }); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToPanel", false], - [".customize-context-removeFromToolbar", false], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["#toggle_880164_empty_toolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; - removeCustomToolbars(); -}); - - -// Right-click on the urlbar-container should -// show a context menu with disabled options to move it. -add_task(function*() { - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownPromise = popupShown(contextMenu); - let urlBarContainer = document.getElementById("urlbar-container"); - // Need to make sure not to click within an edit field. - EventUtils.synthesizeMouse(urlBarContainer, 100, 1, {type: "contextmenu", button: 2 }); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToPanel", false], - [".customize-context-removeFromToolbar", false], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; -}); - -// Right-click on the searchbar and moving it to the menu -// and back should move the search-container instead. -add_task(function*() { - let searchbar = document.getElementById("searchbar"); - gCustomizeMode.addToPanel(searchbar); - let placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel"); - - let shownPanelPromise = promisePanelShown(window); - PanelUI.toggle({type: "command"}); - yield shownPanelPromise; - let hiddenPanelPromise = promisePanelHidden(window); - PanelUI.toggle({type: "command"}); - yield hiddenPanelPromise; - - gCustomizeMode.addToToolbar(searchbar); - placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in navbar"); - gCustomizeMode.removeFromArea(searchbar); - placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement, null, "Should be in palette"); - CustomizableUI.reset(); - placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in navbar"); -}); - -// Right-click on an item within the menu panel should -// show a context menu with options to move it. -add_task(function*() { - let shownPanelPromise = promisePanelShown(window); - PanelUI.toggle({type: "command"}); - yield shownPanelPromise; - - let contextMenu = document.getElementById("customizationPanelItemContextMenu"); - let shownContextPromise = popupShown(contextMenu); - let newWindowButton = document.getElementById("new-window-button"); - ok(newWindowButton, "new-window-button was found"); - EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownContextPromise; - - is(PanelUI.panel.state, "open", "The PanelUI should still be open."); - - let expectedEntries = [ - [".customize-context-moveToToolbar", true], - [".customize-context-removeFromPanel", true], - ["---"], - [".viewCustomizeToolbar", true] - ]; - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; - - let hiddenPromise = promisePanelHidden(window); - PanelUI.toggle({type: "command"}); - yield hiddenPromise; -}); - -// Right-click on the home button while in customization mode -// should show a context menu with options to move it. -add_task(function*() { - yield startCustomizing(); - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownPromise = popupShown(contextMenu); - let homeButton = document.getElementById("wrapper-home-button"); - EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToPanel", true], - [".customize-context-removeFromToolbar", true], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", false] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; -}); - -// Right-click on an item in the palette should -// show a context menu with options to move it. -add_task(function*() { - let contextMenu = document.getElementById("customizationPaletteItemContextMenu"); - let shownPromise = popupShown(contextMenu); - let openFileButton = document.getElementById("wrapper-open-file-button"); - EventUtils.synthesizeMouse(openFileButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-addToToolbar", true], - [".customize-context-addToPanel", true] - ]; - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; -}); - -// Right-click on an item in the panel while in customization mode -// should show a context menu with options to move it. -add_task(function*() { - let contextMenu = document.getElementById("customizationPanelItemContextMenu"); - let shownPromise = popupShown(contextMenu); - let newWindowButton = document.getElementById("wrapper-new-window-button"); - EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToToolbar", true], - [".customize-context-removeFromPanel", true], - ["---"], - [".viewCustomizeToolbar", false] - ]; - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; - yield endCustomizing(); -}); - -// Test the toolbarbutton panel context menu in customization mode -// without opening the panel before customization mode -add_task(function*() { - this.otherWin = yield openAndLoadWindow(null, true); - - yield new Promise(resolve => waitForFocus(resolve, this.otherWin)); - - yield startCustomizing(this.otherWin); - - let contextMenu = this.otherWin.document.getElementById("customizationPanelItemContextMenu"); - let shownPromise = popupShown(contextMenu); - let newWindowButton = this.otherWin.document.getElementById("wrapper-new-window-button"); - EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}, this.otherWin); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToToolbar", true], - [".customize-context-removeFromPanel", true], - ["---"], - [".viewCustomizeToolbar", false] - ]; - checkContextMenu(contextMenu, expectedEntries, this.otherWin); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; - yield endCustomizing(this.otherWin); - yield promiseWindowClosed(this.otherWin); - this.otherWin = null; - - yield new Promise(resolve => waitForFocus(resolve, window)); -}); - -// Bug 945191 - Combined buttons show wrong context menu options -// when they are in the toolbar. -add_task(function*() { - yield startCustomizing(); - let contextMenu = document.getElementById("customizationPanelItemContextMenu"); - let shownPromise = popupShown(contextMenu); - let zoomControls = document.getElementById("wrapper-zoom-controls"); - EventUtils.synthesizeMouse(zoomControls, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - // Execute the command to move the item from the panel to the toolbar. - contextMenu.childNodes[0].doCommand(); - let hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; - yield endCustomizing(); - - zoomControls = document.getElementById("zoom-controls"); - is(zoomControls.parentNode.id, "nav-bar-customization-target", "Zoom-controls should be on the nav-bar"); - - contextMenu = document.getElementById("toolbar-context-menu"); - shownPromise = popupShown(contextMenu); - EventUtils.synthesizeMouse(zoomControls, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - - let expectedEntries = [ - [".customize-context-moveToPanel", true], - [".customize-context-removeFromToolbar", true], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - hiddenPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenPromise; - yield resetCustomization(); -}); - -// Bug 947586 - After customization, panel items show wrong context menu options -add_task(function*() { - yield startCustomizing(); - yield endCustomizing(); - - yield PanelUI.show(); - - let contextMenu = document.getElementById("customizationPanelItemContextMenu"); - let shownContextPromise = popupShown(contextMenu); - let newWindowButton = document.getElementById("new-window-button"); - ok(newWindowButton, "new-window-button was found"); - EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownContextPromise; - - is(PanelUI.panel.state, "open", "The PanelUI should still be open."); - - let expectedEntries = [ - [".customize-context-moveToToolbar", true], - [".customize-context-removeFromPanel", true], - ["---"], - [".viewCustomizeToolbar", true] - ]; - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; - - let hiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield hiddenPromise; -}); - - -// Bug 982027 - moving icon around removes custom context menu. -add_task(function*() { - let widgetId = "custom-context-menu-toolbarbutton"; - let expectedContext = "myfancycontext"; - let widget = createDummyXULButton(widgetId, "Test ctxt menu"); - widget.setAttribute("context", expectedContext); - CustomizableUI.addWidgetToArea(widgetId, CustomizableUI.AREA_NAVBAR); - is(widget.getAttribute("context"), expectedContext, "Should have context menu when added to the toolbar."); - - yield startCustomizing(); - is(widget.getAttribute("context"), "", "Should not have own context menu in the toolbar now that we're customizing."); - is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped when in toolbar."); - - let panel = PanelUI.contents; - simulateItemDrag(widget, panel); - is(widget.getAttribute("context"), "", "Should not have own context menu when in the panel."); - is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped now that we're in the panel."); - - simulateItemDrag(widget, document.getElementById("nav-bar").customizationTarget); - is(widget.getAttribute("context"), "", "Should not have own context menu when back in toolbar because we're still customizing."); - is(widget.getAttribute("wrapped-context"), expectedContext, "Should keep own context menu wrapped now that we're back in the toolbar."); - - yield endCustomizing(); - is(widget.getAttribute("context"), expectedContext, "Should have context menu again now that we're out of customize mode."); - CustomizableUI.removeWidgetFromArea(widgetId); - widget.remove(); - ok(CustomizableUI.inDefaultState, "Should be in default state after removing button."); -}); diff --git a/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js b/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js deleted file mode 100644 index 9057d0557..000000000 --- a/browser/components/customizableui/test/browser_880382_drag_wide_widgets_in_panel.js +++ /dev/null @@ -1,497 +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"; - -requestLongerTimeout(5); - -// Dragging the zoom controls to be before the print button should not move any controls. -add_task(function*() { - yield startCustomizing(); - let zoomControls = document.getElementById("zoom-controls"); - let printButton = document.getElementById("print-button"); - let placementsAfterMove = ["edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "zoom-controls", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(zoomControls, printButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let newWindowButton = document.getElementById("new-window-button"); - simulateItemDrag(zoomControls, newWindowButton); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging the zoom controls to be before the save button should not move any controls. -add_task(function*() { - yield startCustomizing(); - let zoomControls = document.getElementById("zoom-controls"); - let savePageButton = document.getElementById("save-page-button"); - let placementsAfterMove = ["edit-controls", - "zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(zoomControls, savePageButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(CustomizableUI.inDefaultState, "Should be in default state."); -}); - - -// Dragging the zoom controls to be before the new-window button should not move any widgets. -add_task(function*() { - yield startCustomizing(); - let zoomControls = document.getElementById("zoom-controls"); - let newWindowButton = document.getElementById("new-window-button"); - let placementsAfterMove = ["edit-controls", - "zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(zoomControls, newWindowButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the zoom controls to be before the history-panelmenu should move the zoom-controls in to the row higher than the history-panelmenu. -add_task(function*() { - yield startCustomizing(); - let zoomControls = document.getElementById("zoom-controls"); - let historyPanelMenu = document.getElementById("history-panelmenu"); - let placementsAfterMove = ["edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "zoom-controls", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(zoomControls, historyPanelMenu); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let newWindowButton = document.getElementById("new-window-button"); - simulateItemDrag(zoomControls, newWindowButton); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging the zoom controls to be before the preferences-button should move the zoom-controls -// in to the row higher than the preferences-button. -add_task(function*() { - yield startCustomizing(); - let zoomControls = document.getElementById("zoom-controls"); - let preferencesButton = document.getElementById("preferences-button"); - let placementsAfterMove = ["edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "zoom-controls", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(zoomControls, preferencesButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let newWindowButton = document.getElementById("new-window-button"); - simulateItemDrag(zoomControls, newWindowButton); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging an item from the palette to before the zoom-controls should move it and two other buttons before the zoom controls. -add_task(function*() { - yield startCustomizing(); - let openFileButton = document.getElementById("open-file-button"); - let zoomControls = document.getElementById("zoom-controls"); - let placementsAfterInsert = ["edit-controls", - "open-file-button", - "new-window-button", - "privatebrowsing-button", - "zoom-controls", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterInsert); - simulateItemDrag(openFileButton, zoomControls); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let palette = document.getElementById("customization-palette"); - // Check that the palette items are re-wrapped correctly. - let feedWrapper = document.getElementById("wrapper-feed-button"); - let feedButton = document.getElementById("feed-button"); - is(feedButton.parentNode, feedWrapper, - "feed-button should be a child of wrapper-feed-button"); - is(feedWrapper.getAttribute("place"), "palette", - "The feed-button wrapper should have it's place set to 'palette'"); - simulateItemDrag(openFileButton, palette); - is(openFileButton.parentNode.tagName, "toolbarpaletteitem", - "The open-file-button should be wrapped by a toolbarpaletteitem"); - let newWindowButton = document.getElementById("new-window-button"); - simulateItemDrag(zoomControls, newWindowButton); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging an item from the palette to before the edit-controls -// should move it and two other buttons before the edit and zoom controls. -add_task(function*() { - yield startCustomizing(); - let openFileButton = document.getElementById("open-file-button"); - let editControls = document.getElementById("edit-controls"); - let placementsAfterInsert = ["open-file-button", - "new-window-button", - "privatebrowsing-button", - "edit-controls", - "zoom-controls", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterInsert); - simulateItemDrag(openFileButton, editControls); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterInsert); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - let palette = document.getElementById("customization-palette"); - // Check that the palette items are re-wrapped correctly. - let feedWrapper = document.getElementById("wrapper-feed-button"); - let feedButton = document.getElementById("feed-button"); - is(feedButton.parentNode, feedWrapper, - "feed-button should be a child of wrapper-feed-button"); - is(feedWrapper.getAttribute("place"), "palette", - "The feed-button wrapper should have it's place set to 'palette'"); - simulateItemDrag(openFileButton, palette); - is(openFileButton.parentNode.tagName, "toolbarpaletteitem", - "The open-file-button should be wrapped by a toolbarpaletteitem"); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Dragging the edit-controls to be before the zoom-controls button -// should not move any widgets. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let zoomControls = document.getElementById("zoom-controls"); - let placementsAfterMove = ["edit-controls", - "zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, zoomControls); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to be before the new-window-button should -// move the zoom-controls before the edit-controls. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let newWindowButton = document.getElementById("new-window-button"); - let placementsAfterMove = ["zoom-controls", - "edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, newWindowButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to be before the privatebrowsing-button -// should move the edit-controls in to the row higher than the -// privatebrowsing-button. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let privateBrowsingButton = document.getElementById("privatebrowsing-button"); - let placementsAfterMove = ["zoom-controls", - "edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, privateBrowsingButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to be before the save-page-button -// should move the edit-controls in to the row higher than the -// save-page-button. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let savePageButton = document.getElementById("save-page-button"); - let placementsAfterMove = ["zoom-controls", - "edit-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, savePageButton); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to the panel itself should append -// the edit controls to the bottom of the panel. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let placementsAfterMove = ["zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "edit-controls", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, panel); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to the customization-palette and -// back should work. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let palette = document.getElementById("customization-palette"); - let placementsAfterMove = ["zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "developer-button", - "sync-button", - ]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - let paletteChildElementCount = palette.childElementCount; - simulateItemDrag(editControls, palette); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - is(paletteChildElementCount + 1, palette.childElementCount, - "The palette should have a new child, congratulations!"); - is(editControls.parentNode.id, "wrapper-edit-controls", - "The edit-controls should be properly wrapped."); - is(editControls.parentNode.getAttribute("place"), "palette", - "The edit-controls should have the place of 'palette'."); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - is(paletteChildElementCount, palette.childElementCount, - "The palette child count should have returned to its prior value."); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging the edit-controls to each of the panel placeholders -// should append the edit-controls to the bottom of the panel. -add_task(function*() { - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let numPlaceholders = 2; - for (let i = 0; i < numPlaceholders; i++) { - // This test relies on there being a specific number of widgets in the - // panel. The addition of sync-button screwed this up, so we remove it - // here. We should either fix the tests to not rely on the specific layout, - // or fix bug 1007910 which would change the placeholder logic in different - // ways. Bug 1229236 is for these tests to be smarter. - CustomizableUI.removeWidgetFromArea("sync-button"); - // NB: We can't just iterate over all of the placeholders - // because each drag-drop action recreates them. - let placeholder = panel.getElementsByClassName("panel-customization-placeholder")[i]; - let placementsAfterMove = ["zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "edit-controls", - "developer-button"]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, placeholder); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(editControls, zoomControls); - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); - } -}); - -// Dragging the open-file-button back on to itself should work. -add_task(function*() { - yield startCustomizing(); - let openFileButton = document.getElementById("open-file-button"); - is(openFileButton.parentNode.tagName, "toolbarpaletteitem", - "open-file-button should be wrapped by a toolbarpaletteitem"); - simulateItemDrag(openFileButton, openFileButton); - is(openFileButton.parentNode.tagName, "toolbarpaletteitem", - "open-file-button should be wrapped by a toolbarpaletteitem"); - let editControls = document.getElementById("edit-controls"); - is(editControls.parentNode.tagName, "toolbarpaletteitem", - "edit-controls should be wrapped by a toolbarpaletteitem"); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -// Dragging a small button onto the last big button should work. -add_task(function*() { - // Bug 1007910 requires there be a placeholder on the final row for this - // test to work as written. The addition of sync-button meant that's not true - // so we remove it from here. Bug 1229236 is for these tests to be smarter. - CustomizableUI.removeWidgetFromArea("sync-button"); - yield startCustomizing(); - let editControls = document.getElementById("edit-controls"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let target = panel.getElementsByClassName("panel-customization-placeholder")[0]; - let placementsAfterMove = ["zoom-controls", - "new-window-button", - "privatebrowsing-button", - "save-page-button", - "print-button", - "history-panelmenu", - "fullscreen-button", - "find-button", - "preferences-button", - "add-ons-button", - "edit-controls", - "developer-button"]; - removeDeveloperButtonIfDevEdition(placementsAfterMove); - simulateItemDrag(editControls, target); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - let itemToDrag = "email-link-button"; // any button in the palette by default. - let button = document.getElementById(itemToDrag); - placementsAfterMove.splice(11, 0, itemToDrag); - simulateItemDrag(button, editControls); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterMove); - - // Put stuff back: - let palette = document.getElementById("customization-palette"); - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(button, palette); - simulateItemDrag(editControls, zoomControls); - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_884402_customize_from_overflow.js b/browser/components/customizableui/test/browser_884402_customize_from_overflow.js deleted file mode 100644 index f50767c06..000000000 --- a/browser/components/customizableui/test/browser_884402_customize_from_overflow.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; - -var overflowPanel = document.getElementById("widget-overflow"); - -const isOSX = (Services.appinfo.OS === "Darwin"); - -var originalWindowWidth; -registerCleanupFunction(function() { - overflowPanel.removeAttribute("animate"); - window.resizeTo(originalWindowWidth, window.outerHeight); -}); - -// Right-click on an item within the overflow panel should -// show a context menu with options to move it. -add_task(function*() { - - overflowPanel.setAttribute("animate", "false"); - - originalWindowWidth = window.outerWidth; - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - window.resizeTo(400, window.outerHeight); - - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - let chevron = document.getElementById("nav-bar-overflow-button"); - let shownPanelPromise = promisePanelElementShown(window, overflowPanel); - chevron.click(); - yield shownPanelPromise; - - let contextMenu = document.getElementById("toolbar-context-menu"); - let shownContextPromise = popupShown(contextMenu); - let homeButton = document.getElementById("home-button"); - ok(homeButton, "home-button was found"); - is(homeButton.getAttribute("overflowedItem"), "true", "Home button is overflowing"); - EventUtils.synthesizeMouse(homeButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownContextPromise; - - is(overflowPanel.state, "open", "The widget overflow panel should still be open."); - - let expectedEntries = [ - [".customize-context-moveToPanel", true], - [".customize-context-removeFromToolbar", true], - ["---"] - ]; - if (!isOSX) { - expectedEntries.push(["#toggle_toolbar-menubar", true]); - } - expectedEntries.push( - ["#toggle_PersonalToolbar", true], - ["---"], - [".viewCustomizeToolbar", true] - ); - checkContextMenu(contextMenu, expectedEntries); - - let hiddenContextPromise = popupHidden(contextMenu); - let hiddenPromise = promisePanelElementHidden(window, overflowPanel); - let moveToPanel = contextMenu.querySelector(".customize-context-moveToPanel"); - if (moveToPanel) { - moveToPanel.click(); - } - contextMenu.hidePopup(); - yield hiddenContextPromise; - yield hiddenPromise; - - let homeButtonPlacement = CustomizableUI.getPlacementOfWidget("home-button"); - ok(homeButtonPlacement, "Home button should still have a placement"); - is(homeButtonPlacement && homeButtonPlacement.area, "PanelUI-contents", "Home button should be in the panel now"); - CustomizableUI.reset(); - - // In some cases, it can take a tick for the navbar to overflow again. Wait for it: - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - homeButtonPlacement = CustomizableUI.getPlacementOfWidget("home-button"); - ok(homeButtonPlacement, "Home button should still have a placement"); - is(homeButtonPlacement && homeButtonPlacement.area, "nav-bar", "Home button should be back in the navbar now"); - - is(homeButton.getAttribute("overflowedItem"), "true", "Home button should still be overflowed"); -}); diff --git a/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js b/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js deleted file mode 100644 index ea6f5a4e3..000000000 --- a/browser/components/customizableui/test/browser_885052_customize_mode_observers_disabed.js +++ /dev/null @@ -1,45 +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"; - -function isFullscreenSizeMode() { - let sizemode = document.documentElement.getAttribute("sizemode"); - return sizemode == "fullscreen"; -} - -// Observers should be disabled when in customization mode. -add_task(function*() { - // Open and close the panel to make sure that the - // area is generated before getting a child of the area. - let shownPanelPromise = promisePanelShown(window); - PanelUI.toggle({type: "command"}); - yield shownPanelPromise; - let hiddenPanelPromise = promisePanelHidden(window); - PanelUI.toggle({type: "command"}); - yield hiddenPanelPromise; - - let fullscreenButton = document.getElementById("fullscreen-button"); - ok(!fullscreenButton.checked, "Fullscreen button should not be checked when not in fullscreen.") - ok(!isFullscreenSizeMode(), "Should not be in fullscreen sizemode before we enter fullscreen."); - - BrowserFullScreen(); - yield waitForCondition(() => isFullscreenSizeMode()); - ok(fullscreenButton.checked, "Fullscreen button should be checked when in fullscreen.") - - yield startCustomizing(); - - let fullscreenButtonWrapper = document.getElementById("wrapper-fullscreen-button"); - ok(fullscreenButtonWrapper.hasAttribute("itemobserves"), "Observer should be moved to wrapper"); - fullscreenButton = document.getElementById("fullscreen-button"); - ok(!fullscreenButton.hasAttribute("observes"), "Observer should be removed from button"); - ok(!fullscreenButton.checked, "Fullscreen button should no longer be checked during customization mode"); - - yield endCustomizing(); - - BrowserFullScreen(); - fullscreenButton = document.getElementById("fullscreen-button"); - yield waitForCondition(() => !isFullscreenSizeMode()); - ok(!fullscreenButton.checked, "Fullscreen button should not be checked when not in fullscreen.") -}); diff --git a/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js b/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js deleted file mode 100644 index e55c21862..000000000 --- a/browser/components/customizableui/test/browser_885530_showInPrivateBrowsing.js +++ /dev/null @@ -1,134 +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 kWidgetId = "some-widget"; - -function assertWidgetExists(aWindow, aExists) { - if (aExists) { - ok(aWindow.document.getElementById(kWidgetId), - "Should have found test widget in the window"); - } else { - is(aWindow.document.getElementById(kWidgetId), null, - "Should not have found test widget in the window"); - } -} - -// A widget that is created with showInPrivateBrowsing undefined should -// have that value default to true. -add_task(function() { - let wrapper = CustomizableUI.createWidget({ - id: kWidgetId - }); - ok(wrapper.showInPrivateBrowsing, - "showInPrivateBrowsing should have defaulted to true."); - CustomizableUI.destroyWidget(kWidgetId); -}); - -// Add a widget via the API with showInPrivateBrowsing set to false -// and ensure it does not appear in pre-existing or newly created -// private windows. -add_task(function*() { - let plain1 = yield openAndLoadWindow(); - let private1 = yield openAndLoadWindow({private: true}); - CustomizableUI.createWidget({ - id: kWidgetId, - removable: true, - showInPrivateBrowsing: false - }); - CustomizableUI.addWidgetToArea(kWidgetId, - CustomizableUI.AREA_NAVBAR); - assertWidgetExists(plain1, true); - assertWidgetExists(private1, false); - - // Now open up some new windows. The widget should exist in the new - // plain window, but not the new private window. - let plain2 = yield openAndLoadWindow(); - let private2 = yield openAndLoadWindow({private: true}); - assertWidgetExists(plain2, true); - assertWidgetExists(private2, false); - - // Try moving the widget around and make sure it doesn't get added - // to the private windows. We'll start by appending it to the tabstrip. - CustomizableUI.addWidgetToArea(kWidgetId, - CustomizableUI.AREA_TABSTRIP); - assertWidgetExists(plain1, true); - assertWidgetExists(plain2, true); - assertWidgetExists(private1, false); - assertWidgetExists(private2, false); - - // And then move it to the beginning of the tabstrip. - CustomizableUI.moveWidgetWithinArea(kWidgetId, 0); - assertWidgetExists(plain1, true); - assertWidgetExists(plain2, true); - assertWidgetExists(private1, false); - assertWidgetExists(private2, false); - - CustomizableUI.removeWidgetFromArea("some-widget"); - assertWidgetExists(plain1, false); - assertWidgetExists(plain2, false); - assertWidgetExists(private1, false); - assertWidgetExists(private2, false); - - yield Promise.all([plain1, plain2, private1, private2].map(promiseWindowClosed)); - - CustomizableUI.destroyWidget("some-widget"); -}); - -// Add a widget via the API with showInPrivateBrowsing set to true, -// and ensure that it appears in pre-existing or newly created -// private browsing windows. -add_task(function*() { - let plain1 = yield openAndLoadWindow(); - let private1 = yield openAndLoadWindow({private: true}); - - CustomizableUI.createWidget({ - id: kWidgetId, - removable: true, - showInPrivateBrowsing: true - }); - CustomizableUI.addWidgetToArea(kWidgetId, - CustomizableUI.AREA_NAVBAR); - assertWidgetExists(plain1, true); - assertWidgetExists(private1, true); - - // Now open up some new windows. The widget should exist in the new - // plain window, but not the new private window. - let plain2 = yield openAndLoadWindow(); - let private2 = yield openAndLoadWindow({private: true}); - - assertWidgetExists(plain2, true); - assertWidgetExists(private2, true); - - // Try moving the widget around and make sure it doesn't get added - // to the private windows. We'll start by appending it to the tabstrip. - CustomizableUI.addWidgetToArea(kWidgetId, - CustomizableUI.AREA_TABSTRIP); - assertWidgetExists(plain1, true); - assertWidgetExists(plain2, true); - assertWidgetExists(private1, true); - assertWidgetExists(private2, true); - - // And then move it to the beginning of the tabstrip. - CustomizableUI.moveWidgetWithinArea(kWidgetId, 0); - assertWidgetExists(plain1, true); - assertWidgetExists(plain2, true); - assertWidgetExists(private1, true); - assertWidgetExists(private2, true); - - CustomizableUI.removeWidgetFromArea("some-widget"); - assertWidgetExists(plain1, false); - assertWidgetExists(plain2, false); - assertWidgetExists(private1, false); - assertWidgetExists(private2, false); - - yield Promise.all([plain1, plain2, private1, private2].map(promiseWindowClosed)); - - CustomizableUI.destroyWidget("some-widget"); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js b/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js deleted file mode 100644 index f46141c4f..000000000 --- a/browser/components/customizableui/test/browser_886323_buildArea_removable_nodes.js +++ /dev/null @@ -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/. */ - -"use strict"; - -const kButtonId = "test-886323-removable-moved-node"; -const kLazyAreaId = "test-886323-lazy-area-for-removability-testing"; - -var gNavBar = document.getElementById(CustomizableUI.AREA_NAVBAR); -var gLazyArea; - -// Removable nodes shouldn't be moved by buildArea -add_task(function*() { - let dummyBtn = createDummyXULButton(kButtonId, "Dummy"); - dummyBtn.setAttribute("removable", "true"); - gNavBar.customizationTarget.appendChild(dummyBtn); - let popupSet = document.getElementById("mainPopupSet"); - gLazyArea = document.createElementNS(kNSXUL, "panel"); - gLazyArea.id = kLazyAreaId; - gLazyArea.setAttribute("hidden", "true"); - popupSet.appendChild(gLazyArea); - CustomizableUI.registerArea(kLazyAreaId, { - type: CustomizableUI.TYPE_MENU_PANEL, - defaultPlacements: [] - }); - CustomizableUI.addWidgetToArea(kButtonId, kLazyAreaId); - assertAreaPlacements(kLazyAreaId, [kButtonId], - "Placements should have changed because widget is removable."); - let btn = document.getElementById(kButtonId); - btn.setAttribute("removable", "false"); - gLazyArea.customizationTarget = gLazyArea; - CustomizableUI.registerToolbarNode(gLazyArea, []); - assertAreaPlacements(kLazyAreaId, [], "Placements should no longer include widget."); - is(btn.parentNode.id, gNavBar.customizationTarget.id, - "Button shouldn't actually have moved as it's not removable"); - btn = document.getElementById(kButtonId); - if (btn) btn.remove(); - CustomizableUI.removeWidgetFromArea(kButtonId); - CustomizableUI.unregisterArea(kLazyAreaId); - gLazyArea.remove(); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_887438_currentset_shim.js b/browser/components/customizableui/test/browser_887438_currentset_shim.js deleted file mode 100644 index a04299819..000000000 --- a/browser/components/customizableui/test/browser_887438_currentset_shim.js +++ /dev/null @@ -1,75 +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"; - -var navbar = document.getElementById("nav-bar"); -var navbarCT = navbar.customizationTarget; -var overflowPanelList = document.getElementById("widget-overflow-list"); - -// Reading currentset -add_task(function() { - let nodeIds = []; - for (let node of navbarCT.childNodes) { - if (node.getAttribute("skipintoolbarset") != "true") { - nodeIds.push(node.id); - } - } - for (let node of overflowPanelList.childNodes) { - if (node.getAttribute("skipintoolbarset") != "true") { - nodeIds.push(node.id); - } - } - let currentSet = navbar.currentSet; - is(currentSet.split(',').length, nodeIds.length, "Should be just as many nodes as there are."); - is(currentSet, nodeIds.join(','), "Current set and node IDs should match."); -}); - -// Insert, then remove items -add_task(function() { - let currentSet = navbar.currentSet; - let newCurrentSet = currentSet.replace('home-button', 'feed-button,sync-button,home-button'); - navbar.currentSet = newCurrentSet; - is(newCurrentSet, navbar.currentSet, "Current set should match expected current set."); - let feedBtn = document.getElementById("feed-button"); - let syncBtn = document.getElementById("sync-button"); - ok(feedBtn, "Feed button should have been added."); - ok(syncBtn, "Sync button should have been added."); - if (feedBtn && syncBtn) { - let feedParent = feedBtn.parentNode; - let syncParent = syncBtn.parentNode; - ok(feedParent == navbarCT || feedParent == overflowPanelList, - "Feed button should be in navbar or overflow"); - ok(syncParent == navbarCT || syncParent == overflowPanelList, - "Feed button should be in navbar or overflow"); - is(feedBtn.nextElementSibling, syncBtn, "Feed button should be next to sync button."); - let homeBtn = document.getElementById("home-button"); - is(syncBtn.nextElementSibling, homeBtn, "Sync button should be next to home button."); - } - navbar.currentSet = currentSet; - is(currentSet, navbar.currentSet, "Should be able to remove the added items."); -}); - -// Simultaneous insert/remove: -add_task(function() { - let currentSet = navbar.currentSet; - let newCurrentSet = currentSet.replace('home-button', 'feed-button'); - navbar.currentSet = newCurrentSet; - is(newCurrentSet, navbar.currentSet, "Current set should match expected current set."); - let feedBtn = document.getElementById("feed-button"); - ok(feedBtn, "Feed button should have been added."); - let homeBtn = document.getElementById("home-button"); - ok(!homeBtn, "Home button should have been removed."); - if (feedBtn) { - let feedParent = feedBtn.parentNode; - ok(feedParent == navbarCT || feedParent == overflowPanelList, - "Feed button should be in navbar or overflow"); - } - navbar.currentSet = currentSet; - is(currentSet, navbar.currentSet, "Should be able to return to original state."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_888817_currentset_updating.js b/browser/components/customizableui/test/browser_888817_currentset_updating.js deleted file mode 100644 index 6e7c4e95a..000000000 --- a/browser/components/customizableui/test/browser_888817_currentset_updating.js +++ /dev/null @@ -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/. */ - -"use strict"; - -// Adding, moving and removing items should update the relevant currentset attributes -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Should be in the default state when we start"); - let personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS); - setToolbarVisibility(personalbar, true); - ok(!CustomizableUI.inDefaultState, "Making the bookmarks toolbar visible takes it out of the default state"); - - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS); - let navbarCurrentset = navbar.getAttribute("currentset") || navbar.currentSet; - let personalbarCurrentset = personalbar.getAttribute("currentset") || personalbar.currentSet; - - let otherWin = yield openAndLoadWindow(); - let otherNavbar = otherWin.document.getElementById(CustomizableUI.AREA_NAVBAR); - let otherPersonalbar = otherWin.document.getElementById(CustomizableUI.AREA_BOOKMARKS); - - CustomizableUI.moveWidgetWithinArea("home-button", 0); - navbarCurrentset = "home-button," + navbarCurrentset.replace(",home-button", ""); - is(navbar.getAttribute("currentset"), navbarCurrentset, - "Should have updated currentSet after move."); - is(otherNavbar.getAttribute("currentset"), navbarCurrentset, - "Should have updated other window's currentSet after move."); - - CustomizableUI.addWidgetToArea("home-button", CustomizableUI.AREA_BOOKMARKS); - navbarCurrentset = navbarCurrentset.replace("home-button,", ""); - personalbarCurrentset = personalbarCurrentset + ",home-button"; - is(navbar.getAttribute("currentset"), navbarCurrentset, - "Should have updated navbar currentSet after implied remove."); - is(otherNavbar.getAttribute("currentset"), navbarCurrentset, - "Should have updated other window's navbar currentSet after implied remove."); - is(personalbar.getAttribute("currentset"), personalbarCurrentset, - "Should have updated personalbar currentSet after add."); - is(otherPersonalbar.getAttribute("currentset"), personalbarCurrentset, - "Should have updated other window's personalbar currentSet after add."); - - CustomizableUI.removeWidgetFromArea("home-button"); - personalbarCurrentset = personalbarCurrentset.replace(",home-button", ""); - is(personalbar.getAttribute("currentset"), personalbarCurrentset, - "Should have updated currentSet after remove."); - is(otherPersonalbar.getAttribute("currentset"), personalbarCurrentset, - "Should have updated other window's currentSet after remove."); - - yield promiseWindowClosed(otherWin); - // Reset in asyncCleanup will put our button back for us. -}); - -add_task(function* asyncCleanup() { - let personalbar = document.getElementById(CustomizableUI.AREA_BOOKMARKS); - setToolbarVisibility(personalbar, false); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js b/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js deleted file mode 100644 index 84b126a9b..000000000 --- a/browser/components/customizableui/test/browser_890140_orphaned_placeholders.js +++ /dev/null @@ -1,210 +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"; - -requestLongerTimeout(2); - -// One orphaned item should have two placeholders next to it. -add_task(function*() { - yield startCustomizing(); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - } - if (!isInDevEdition()) { - ok(CustomizableUI.inDefaultState, "Should be in default state."); - } else { - ok(!CustomizableUI.inDefaultState, "Should not be in default state if on DevEdition."); - } - - // This test relies on an exact number of widgets being in the panel. - // Remove the sync-button to satisfy that. (bug 1229236) - CustomizableUI.removeWidgetFromArea("sync-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - - assertAreaPlacements(CustomizableUI.AREA_PANEL, placements); - is(getVisiblePlaceholderCount(panel), 2, "Should only have 2 visible placeholders before exiting"); - - yield endCustomizing(); - yield startCustomizing(); - is(getVisiblePlaceholderCount(panel), 2, "Should only have 2 visible placeholders after re-entering"); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2); - } - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Two orphaned items should have one placeholder next to them (case 1). -add_task(function*() { - yield startCustomizing(); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL); - } - - // This test relies on an exact number of widgets being in the panel. - // Remove the sync-button to satisfy that. (bug 1229236) - CustomizableUI.removeWidgetFromArea("sync-button"); - - let btn = document.getElementById("open-file-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - let placementsAfterAppend = placements; - - placementsAfterAppend = placements.concat(["open-file-button"]); - simulateItemDrag(btn, panel); - - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend); - - ok(!CustomizableUI.inDefaultState, "Should not be in default state."); - - is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder before exiting"); - - yield endCustomizing(); - yield startCustomizing(); - is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder after re-entering"); - - let palette = document.getElementById("customization-palette"); - simulateItemDrag(btn, palette); - - btn = document.getElementById("open-file-button"); - simulateItemDrag(btn, palette); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2); - } - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// Two orphaned items should have one placeholder next to them (case 2). -add_task(function*() { - yield startCustomizing(); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL); - } - // This test relies on an exact number of widgets being in the panel. - // Remove the sync-button to satisfy that. (bug 1229236) - CustomizableUI.removeWidgetFromArea("sync-button"); - - let btn = document.getElementById("add-ons-button"); - let btn2 = document.getElementById("developer-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let palette = document.getElementById("customization-palette"); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - - let placementsAfterAppend = placements.filter(p => p != btn.id && p != btn2.id); - simulateItemDrag(btn, palette); - simulateItemDrag(btn2, palette); - - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder before exiting"); - - yield endCustomizing(); - yield startCustomizing(); - is(getVisiblePlaceholderCount(panel), 1, "Should only have 1 visible placeholder after re-entering"); - - simulateItemDrag(btn, panel); - simulateItemDrag(btn2, panel); - - assertAreaPlacements(CustomizableUI.AREA_PANEL, placements); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2); - } - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// A wide widget at the bottom of the panel should have three placeholders after it. -add_task(function*() { - yield startCustomizing(); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_PANEL); - } - - // This test relies on an exact number of widgets being in the panel. - // Remove the sync-button to satisfy that. (bug 1229236) - CustomizableUI.removeWidgetFromArea("sync-button"); - - let btn = document.getElementById("edit-controls"); - let btn2 = document.getElementById("developer-button"); - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - let palette = document.getElementById("customization-palette"); - let placements = getAreaWidgetIds(CustomizableUI.AREA_PANEL); - - placements.pop(); - simulateItemDrag(btn2, palette); - - let placementsAfterAppend = placements.concat([placements.shift()]); - simulateItemDrag(btn, panel); - assertAreaPlacements(CustomizableUI.AREA_PANEL, placementsAfterAppend); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state."); - is(getVisiblePlaceholderCount(panel), 3, "Should have 3 visible placeholders before exiting"); - - yield endCustomizing(); - yield startCustomizing(); - is(getVisiblePlaceholderCount(panel), 3, "Should have 3 visible placeholders after re-entering"); - - simulateItemDrag(btn2, panel); - - let zoomControls = document.getElementById("zoom-controls"); - simulateItemDrag(btn, zoomControls); - - if (isInDevEdition()) { - CustomizableUI.addWidgetToArea("developer-button", CustomizableUI.AREA_NAVBAR, 2); - } - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state again."); -}); - -// The default placements should have two placeholders at the bottom (or 1 in win8). -add_task(function*() { - yield startCustomizing(); - let numPlaceholders = -1; - - if (isInDevEdition()) { - numPlaceholders = 3; - } else { - numPlaceholders = 2; - } - - let panel = document.getElementById(CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should be in default state."); - - // This test relies on an exact number of widgets being in the panel. - // Remove the sync-button to satisfy that. (bug 1229236) - CustomizableUI.removeWidgetFromArea("sync-button"); - - is(getVisiblePlaceholderCount(panel), numPlaceholders, "Should have " + numPlaceholders + " visible placeholders before exiting"); - - yield endCustomizing(); - yield startCustomizing(); - is(getVisiblePlaceholderCount(panel), numPlaceholders, "Should have " + numPlaceholders + " visible placeholders after re-entering"); - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - ok(CustomizableUI.inDefaultState, "Should still be in default state."); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); - -function getVisiblePlaceholderCount(aPanel) { - let visiblePlaceholders = aPanel.querySelectorAll(".panel-customization-placeholder:not([hidden=true])"); - return visiblePlaceholders.length; -} diff --git a/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js b/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js deleted file mode 100644 index 13f2bd7ba..000000000 --- a/browser/components/customizableui/test/browser_890262_destroyWidget_after_add_to_panel.js +++ /dev/null @@ -1,68 +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 kLazyAreaId = "test-890262-lazy-area"; -const kWidget1Id = "test-890262-widget1"; -const kWidget2Id = "test-890262-widget2"; - -setupArea(); - -// Destroying a widget after defaulting it to a non-legacy area should work. -add_task(function() { - CustomizableUI.createWidget({ - id: kWidget1Id, - removable: true, - defaultArea: kLazyAreaId - }); - let noError = true; - try { - CustomizableUI.destroyWidget(kWidget1Id); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Shouldn't throw an exception for a widget that was created in a not-yet-constructed area"); -}); - -// Destroying a widget after moving it to a non-legacy area should work. -add_task(function() { - CustomizableUI.createWidget({ - id: kWidget2Id, - removable: true, - defaultArea: CustomizableUI.AREA_NAVBAR - }); - - CustomizableUI.addWidgetToArea(kWidget2Id, kLazyAreaId); - let noError = true; - try { - CustomizableUI.destroyWidget(kWidget2Id); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Shouldn't throw an exception for a widget that was added to a not-yet-constructed area"); -}); - -add_task(function* asyncCleanup() { - let lazyArea = document.getElementById(kLazyAreaId); - if (lazyArea) { - lazyArea.remove(); - } - try { - CustomizableUI.unregisterArea(kLazyAreaId); - } catch (ex) {} // If we didn't register successfully for some reason - yield resetCustomization(); -}); - -function setupArea() { - let lazyArea = document.createElementNS(kNSXUL, "hbox"); - lazyArea.id = kLazyAreaId; - document.getElementById("nav-bar").appendChild(lazyArea); - CustomizableUI.registerArea(kLazyAreaId, { - type: CustomizableUI.TYPE_TOOLBAR, - defaultPlacements: [] - }); -} diff --git a/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js b/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js deleted file mode 100644 index 67ef82b82..000000000 --- a/browser/components/customizableui/test/browser_892955_isWidgetRemovable_for_removed_widgets.js +++ /dev/null @@ -1,30 +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 kWidgetId = "test-892955-remove-widget"; - -// Removing a destroyed widget should work. -add_task(function*() { - let widgetSpec = { - id: kWidgetId, - defaultArea: CustomizableUI.AREA_NAVBAR - }; - - CustomizableUI.createWidget(widgetSpec); - CustomizableUI.destroyWidget(kWidgetId); - let noError = true; - try { - CustomizableUI.removeWidgetFromArea(kWidgetId); - } catch (ex) { - noError = false; - Cu.reportError(ex); - } - ok(noError, "Shouldn't throw an error removing a destroyed widget."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js b/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js deleted file mode 100644 index c7047c797..000000000 --- a/browser/components/customizableui/test/browser_892956_destroyWidget_defaultPlacements.js +++ /dev/null @@ -1,24 +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 kWidgetId = "test-892956-destroyWidget-defaultPlacement"; - -// destroyWidget should clean up defaultPlacements if the widget had a defaultArea -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Should be in the default state when we start"); - - let widgetSpec = { - id: kWidgetId, - defaultArea: CustomizableUI.AREA_NAVBAR - }; - CustomizableUI.createWidget(widgetSpec); - CustomizableUI.destroyWidget(kWidgetId); - ok(CustomizableUI.inDefaultState, "Should be in the default state when we finish"); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js b/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js deleted file mode 100644 index 3bc449add..000000000 --- a/browser/components/customizableui/test/browser_901207_searchbar_in_panel.js +++ /dev/null @@ -1,113 +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"; - -logActiveElement(); - -function* waitForSearchBarFocus() -{ - let searchbar = document.getElementById("searchbar"); - yield waitForCondition(function () { - logActiveElement(); - return document.activeElement === searchbar.textbox.inputField; - }); -} - -// Ctrl+K should open the menu panel and focus the search bar if the search bar is in the panel. -add_task(function*() { - let searchbar = document.getElementById("searchbar"); - gCustomizeMode.addToPanel(searchbar); - let placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel"); - - let shownPanelPromise = promisePanelShown(window); - sendWebSearchKeyCommand(); - yield shownPanelPromise; - - yield waitForSearchBarFocus(); - - let hiddenPanelPromise = promisePanelHidden(window); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield hiddenPanelPromise; - CustomizableUI.reset(); -}); - -// Ctrl+K should give focus to the searchbar when the searchbar is in the menupanel and the panel is already opened. -add_task(function*() { - let searchbar = document.getElementById("searchbar"); - gCustomizeMode.addToPanel(searchbar); - let placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel"); - - let shownPanelPromise = promisePanelShown(window); - PanelUI.toggle({type: "command"}); - yield shownPanelPromise; - - sendWebSearchKeyCommand(); - - yield waitForSearchBarFocus(); - - let hiddenPanelPromise = promisePanelHidden(window); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield hiddenPanelPromise; - CustomizableUI.reset(); -}); - -// Ctrl+K should open the overflow panel and focus the search bar if the search bar is overflowed. -add_task(function*() { - this.originalWindowWidth = window.outerWidth; - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - - window.resizeTo(360, window.outerHeight); - yield waitForCondition(() => navbar.getAttribute("overflowing") == "true"); - ok(!navbar.querySelector("#search-container"), "Search container should be overflowing"); - - let shownPanelPromise = promiseOverflowShown(window); - sendWebSearchKeyCommand(); - yield shownPanelPromise; - - let chevron = document.getElementById("nav-bar-overflow-button"); - yield waitForCondition(() => chevron.open); - - yield waitForSearchBarFocus(); - - let hiddenPanelPromise = promiseOverflowHidden(window); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield hiddenPanelPromise; - navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - window.resizeTo(this.originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar."); -}); - -// Ctrl+K should focus the search bar if it is in the navbar and not overflowing. -add_task(function*() { - let placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_NAVBAR, "Should be in nav-bar"); - - sendWebSearchKeyCommand(); - - yield waitForSearchBarFocus(); -}); - - -function sendWebSearchKeyCommand() { - if (Services.appinfo.OS === "Darwin") - EventUtils.synthesizeKey("k", { accelKey: true }); - else - EventUtils.synthesizeKey("k", { ctrlKey: true }); -} - -function logActiveElement() { - let element = document.activeElement; - let str = ""; - while (element && element.parentNode) { - str = " (" + element.localName + "#" + element.id + "." + [...element.classList].join(".") + ") >" + str; - element = element.parentNode; - } - info("Active element: " + element ? str : "null"); -} diff --git a/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js b/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js deleted file mode 100644 index f39d13ff4..000000000 --- a/browser/components/customizableui/test/browser_909779_overflow_toolbars_new_window.js +++ /dev/null @@ -1,31 +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"; - -// Resize to a small window, open a new window, check that new window handles overflow properly -add_task(function*() { - let originalWindowWidth = window.outerWidth; - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - let oldChildCount = navbar.customizationTarget.childElementCount; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - ok(navbar.customizationTarget.childElementCount < oldChildCount, "Should have fewer children."); - let newWindow = yield openAndLoadWindow(); - let otherNavBar = newWindow.document.getElementById(CustomizableUI.AREA_NAVBAR); - yield waitForCondition(() => otherNavBar.hasAttribute("overflowing")); - ok(otherNavBar.hasAttribute("overflowing"), "Other window should have an overflowing toolbar."); - yield promiseWindowClosed(newWindow); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should no longer have an overflowing toolbar."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_913972_currentset_overflow.js b/browser/components/customizableui/test/browser_913972_currentset_overflow.js deleted file mode 100644 index 7d754d79b..000000000 --- a/browser/components/customizableui/test/browser_913972_currentset_overflow.js +++ /dev/null @@ -1,55 +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"; - -var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - -// Resize to a small window, resize back, shouldn't affect currentSet -add_task(function*() { - let originalWindowWidth = window.outerWidth; - let oldCurrentSet = navbar.currentSet; - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - let oldChildCount = navbar.customizationTarget.childElementCount; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - is(navbar.currentSet, oldCurrentSet, "Currentset should be the same when overflowing."); - ok(CustomizableUI.inDefaultState, "Should still be in default state when overflowing."); - ok(navbar.customizationTarget.childElementCount < oldChildCount, "Should have fewer children."); - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should no longer have an overflowing toolbar."); - is(navbar.currentSet, oldCurrentSet, "Currentset should still be the same now we're no longer overflowing."); - ok(CustomizableUI.inDefaultState, "Should still be in default state now we're no longer overflowing."); - - // Verify actual physical placements match those of the placement array: - let placementCounter = 0; - let placements = CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR); - for (let node of navbar.customizationTarget.childNodes) { - if (node.getAttribute("skipintoolbarset") == "true") { - continue; - } - is(placements[placementCounter++], node.id, "Nodes should match after overflow"); - } - is(placements.length, placementCounter, "Should have as many nodes as expected"); - is(navbar.customizationTarget.childElementCount, oldChildCount, "Number of nodes should match"); -}); - -// Enter and exit customization mode, check that currentSet works -add_task(function*() { - let oldCurrentSet = navbar.currentSet; - ok(CustomizableUI.inDefaultState, "Should start in default state."); - yield startCustomizing(); - ok(CustomizableUI.inDefaultState, "Should be in default state in customization mode."); - is(navbar.currentSet, oldCurrentSet, "Currentset should be the same in customization mode."); - yield endCustomizing(); - ok(CustomizableUI.inDefaultState, "Should be in default state after customization mode."); - is(navbar.currentSet, oldCurrentSet, "Currentset should be the same after customization mode."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js b/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js deleted file mode 100644 index 35ba79bec..000000000 --- a/browser/components/customizableui/test/browser_914138_widget_API_overflowable_toolbar.js +++ /dev/null @@ -1,131 +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"; - -var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); -var overflowList = document.getElementById(navbar.getAttribute("overflowtarget")); - -const kTestBtn1 = "test-addWidgetToArea-overflow"; -const kTestBtn2 = "test-removeWidgetFromArea-overflow"; -const kTestBtn3 = "test-createWidget-overflow"; -const kHomeBtn = "home-button"; -const kDownloadsBtn = "downloads-button"; -const kSearchBox = "search-container"; -const kStarBtn = "bookmarks-menu-button"; - -var originalWindowWidth; - -// Adding a widget should add it next to the widget it's being inserted next to. -add_task(function*() { - originalWindowWidth = window.outerWidth; - createDummyXULButton(kTestBtn1, "Test"); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - ok(!navbar.querySelector("#" + kHomeBtn), "Home button should no longer be in the navbar"); - let homeBtnNode = overflowList.querySelector("#" + kHomeBtn); - ok(homeBtnNode, "Home button should be overflowing"); - ok(homeBtnNode && homeBtnNode.getAttribute("overflowedItem") == "true", "Home button should have overflowedItem attribute"); - - let placementOfHomeButton = CustomizableUI.getWidgetIdsInArea(navbar.id).indexOf(kHomeBtn); - CustomizableUI.addWidgetToArea(kTestBtn1, navbar.id, placementOfHomeButton); - ok(!navbar.querySelector("#" + kTestBtn1), "New button should not be in the navbar"); - let newButtonNode = overflowList.querySelector("#" + kTestBtn1); - ok(newButtonNode, "New button should be overflowing"); - ok(newButtonNode && newButtonNode.getAttribute("overflowedItem") == "true", "New button should have overflowedItem attribute"); - let nextEl = newButtonNode && newButtonNode.nextSibling; - is(nextEl && nextEl.id, kHomeBtn, "Test button should be next to home button."); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar."); - ok(navbar.querySelector("#" + kHomeBtn), "Home button should be in the navbar"); - ok(homeBtnNode && (homeBtnNode.getAttribute("overflowedItem") != "true"), "Home button should no longer have overflowedItem attribute"); - ok(!overflowList.querySelector("#" + kHomeBtn), "Home button should no longer be overflowing"); - ok(navbar.querySelector("#" + kTestBtn1), "Test button should be in the navbar"); - ok(!overflowList.querySelector("#" + kTestBtn1), "Test button should no longer be overflowing"); - ok(newButtonNode && (newButtonNode.getAttribute("overflowedItem") != "true"), "New button should no longer have overflowedItem attribute"); - let el = document.getElementById(kTestBtn1); - if (el) { - CustomizableUI.removeWidgetFromArea(kTestBtn1); - el.remove(); - } - window.resizeTo(originalWindowWidth, window.outerHeight); -}); - -// Removing a widget should remove it from the overflow list if that is where it is, and update it accordingly. -add_task(function*() { - createDummyXULButton(kTestBtn2, "Test"); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - CustomizableUI.addWidgetToArea(kTestBtn2, navbar.id); - ok(!navbar.hasAttribute("overflowing"), "Should still have a non-overflowing toolbar."); - - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - ok(!navbar.querySelector("#" + kTestBtn2), "Test button should not be in the navbar"); - ok(overflowList.querySelector("#" + kTestBtn2), "Test button should be overflowing"); - - CustomizableUI.removeWidgetFromArea(kTestBtn2); - - ok(!overflowList.querySelector("#" + kTestBtn2), "Test button should not be overflowing."); - ok(!navbar.querySelector("#" + kTestBtn2), "Test button should not be in the navbar"); - ok(gNavToolbox.palette.querySelector("#" + kTestBtn2), "Test button should be in the palette"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar."); - let el = document.getElementById(kTestBtn2); - if (el) { - CustomizableUI.removeWidgetFromArea(kTestBtn2); - el.remove(); - } - window.resizeTo(originalWindowWidth, window.outerHeight); -}); - -// Constructing a widget while overflown should set the right class on it. -add_task(function*() { - originalWindowWidth = window.outerWidth; - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - ok(!navbar.querySelector("#" + kHomeBtn), "Home button should no longer be in the navbar"); - let homeBtnNode = overflowList.querySelector("#" + kHomeBtn); - ok(homeBtnNode, "Home button should be overflowing"); - ok(homeBtnNode && homeBtnNode.getAttribute("overflowedItem") == "true", "Home button should have overflowedItem class"); - - let testBtnSpec = {id: kTestBtn3, label: "Overflowable widget test", defaultArea: "nav-bar"}; - CustomizableUI.createWidget(testBtnSpec); - let testNode = overflowList.querySelector("#" + kTestBtn3); - ok(testNode, "Test button should be overflowing"); - ok(testNode && testNode.getAttribute("overflowedItem") == "true", "Test button should have overflowedItem class"); - - CustomizableUI.destroyWidget(kTestBtn3); - testNode = document.getElementById(kTestBtn3); - ok(!testNode, "Test button should be gone"); - - CustomizableUI.createWidget(testBtnSpec); - testNode = overflowList.querySelector("#" + kTestBtn3); - ok(testNode, "Test button should be overflowing"); - ok(testNode && testNode.getAttribute("overflowedItem") == "true", "Test button should have overflowedItem class"); - - CustomizableUI.removeWidgetFromArea(kTestBtn3); - testNode = document.getElementById(kTestBtn3); - ok(!testNode, "Test button should be gone"); - CustomizableUI.destroyWidget(kTestBtn3); - window.resizeTo(originalWindowWidth, window.outerHeight); -}); - -add_task(function* asyncCleanup() { - window.resizeTo(originalWindowWidth, window.outerHeight); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js b/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js deleted file mode 100644 index b5757eabb..000000000 --- a/browser/components/customizableui/test/browser_914863_disabled_help_quit_buttons.js +++ /dev/null @@ -1,16 +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/. */ - -// Entering then exiting customization mode should reenable the Help and Exit buttons. -add_task(function*() { - yield startCustomizing(); - let helpButton = document.getElementById("PanelUI-help"); - let quitButton = document.getElementById("PanelUI-quit"); - ok(helpButton.getAttribute("disabled") == "true", "Help button should be disabled while in customization mode."); - ok(quitButton.getAttribute("disabled") == "true", "Quit button should be disabled while in customization mode."); - yield endCustomizing(); - - ok(!helpButton.hasAttribute("disabled"), "Help button should not be disabled."); - ok(!quitButton.hasAttribute("disabled"), "Quit button should not be disabled."); -}); diff --git a/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js b/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js deleted file mode 100644 index dffe388dc..000000000 --- a/browser/components/customizableui/test/browser_918049_skipintoolbarset_dnd.js +++ /dev/null @@ -1,38 +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"; - -var navbar; -var skippedItem; - -// Attempting to drag a skipintoolbarset item should work. -add_task(function*() { - navbar = document.getElementById("nav-bar"); - skippedItem = document.createElement("toolbarbutton"); - skippedItem.id = "test-skipintoolbarset-item"; - skippedItem.setAttribute("label", "Test"); - skippedItem.setAttribute("skipintoolbarset", "true"); - skippedItem.setAttribute("removable", "true"); - navbar.customizationTarget.appendChild(skippedItem); - let downloadsButton = document.getElementById("downloads-button"); - yield startCustomizing(); - ok(CustomizableUI.inDefaultState, "Should still be in default state"); - simulateItemDrag(skippedItem, downloadsButton); - ok(CustomizableUI.inDefaultState, "Should still be in default state"); - let skippedItemWrapper = skippedItem.parentNode; - is(skippedItemWrapper.nextSibling && skippedItemWrapper.nextSibling.id, - downloadsButton.parentNode.id, "Should be next to downloads button"); - simulateItemDrag(downloadsButton, skippedItem); - let downloadWrapper = downloadsButton.parentNode; - is(downloadWrapper.nextSibling && downloadWrapper.nextSibling.id, - skippedItem.parentNode.id, "Should be next to skipintoolbarset item"); - ok(CustomizableUI.inDefaultState, "Should still be in default state"); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - skippedItem.remove(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js b/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js deleted file mode 100644 index 87aca51eb..000000000 --- a/browser/components/customizableui/test/browser_923857_customize_mode_event_wrapping_during_reset.js +++ /dev/null @@ -1,24 +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"; - -// Customize mode reset button should revert correctly -add_task(function*() { - yield startCustomizing(); - let devButton = document.getElementById("developer-button"); - let downloadsButton = document.getElementById("downloads-button"); - let searchBox = document.getElementById("search-container"); - let palette = document.getElementById("customization-palette"); - ok(devButton && downloadsButton && searchBox && palette, "Stuff should exist"); - simulateItemDrag(devButton, downloadsButton); - simulateItemDrag(searchBox, palette); - yield gCustomizeMode.reset(); - ok(CustomizableUI.inDefaultState, "Should be back in default state"); - yield endCustomizing(); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js b/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js deleted file mode 100644 index d79f6e364..000000000 --- a/browser/components/customizableui/test/browser_927717_customize_drag_empty_toolbar.js +++ /dev/null @@ -1,26 +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 kTestToolbarId = "test-empty-drag"; - -// Attempting to drag an item to an empty container should work. -add_task(function*() { - yield createToolbarWithPlacements(kTestToolbarId, []); - yield startCustomizing(); - let downloadButton = document.getElementById("downloads-button"); - let customToolbar = document.getElementById(kTestToolbarId); - simulateItemDrag(downloadButton, customToolbar); - assertAreaPlacements(kTestToolbarId, ["downloads-button"]); - ok(downloadButton.parentNode && downloadButton.parentNode.parentNode == customToolbar, - "Button should really be in toolbar"); - yield endCustomizing(); - removeCustomToolbars(); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js b/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js deleted file mode 100644 index 3cbf6be42..000000000 --- a/browser/components/customizableui/test/browser_932928_show_notice_when_palette_empty.js +++ /dev/null @@ -1,35 +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"; - -// There should be an advert to get more addons when the palette is empty. -add_task(function*() { - yield startCustomizing(); - let visiblePalette = document.getElementById("customization-palette"); - let emptyPaletteNotice = document.getElementById("customization-empty"); - is(emptyPaletteNotice.hidden, true, "The empty palette notice should not be shown when there are items in the palette."); - - while (visiblePalette.childElementCount) { - gCustomizeMode.addToToolbar(visiblePalette.children[0]); - } - is(visiblePalette.childElementCount, 0, "There shouldn't be any items remaining in the visible palette."); - is(emptyPaletteNotice.hidden, false, "The empty palette notice should be shown when there are no items in the palette."); - - yield endCustomizing(); - yield startCustomizing(); - visiblePalette = document.getElementById("customization-palette"); - emptyPaletteNotice = document.getElementById("customization-empty"); - is(emptyPaletteNotice.hidden, false, - "The empty palette notice should be shown when there are no items in the palette and cust. mode is re-entered."); - - gCustomizeMode.removeFromArea(document.getElementById("wrapper-home-button")); - is(emptyPaletteNotice.hidden, true, - "The empty palette notice should not be shown when there is at least one item in the palette."); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_934113_menubar_removable.js b/browser/components/customizableui/test/browser_934113_menubar_removable.js deleted file mode 100644 index 1d788bced..000000000 --- a/browser/components/customizableui/test/browser_934113_menubar_removable.js +++ /dev/null @@ -1,30 +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"; - -// Attempting to drag the menubar to the navbar shouldn't work. -add_task(function*() { - yield startCustomizing(); - let menuItems = document.getElementById("menubar-items"); - let navbar = document.getElementById("nav-bar"); - let menubar = document.getElementById("toolbar-menubar"); - // Force the menu to be shown. - const kAutohide = menubar.getAttribute("autohide"); - menubar.setAttribute("autohide", "false"); - simulateItemDrag(menuItems, navbar.customizationTarget); - - is(getAreaWidgetIds("nav-bar").indexOf("menubar-items"), -1, "Menu bar shouldn't be in the navbar."); - ok(!navbar.querySelector("#menubar-items"), "Shouldn't find menubar items in the navbar."); - ok(menubar.querySelector("#menubar-items"), "Should find menubar items in the menubar."); - isnot(getAreaWidgetIds("toolbar-menubar").indexOf("menubar-items"), -1, - "Menubar items shouldn't be missing from the navbar."); - menubar.setAttribute("autohide", kAutohide); - yield endCustomizing(); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js b/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js deleted file mode 100644 index dcc183051..000000000 --- a/browser/components/customizableui/test/browser_934951_zoom_in_toolbar.js +++ /dev/null @@ -1,89 +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 kTimeoutInMS = 20000; - -// Bug 934951 - Zoom controls percentage label doesn't update when it's in the toolbar and you navigate. -add_task(function*() { - CustomizableUI.addWidgetToArea("zoom-controls", CustomizableUI.AREA_NAVBAR); - let tab1 = gBrowser.addTab("about:mozilla"); - yield BrowserTestUtils.browserLoaded(tab1.linkedBrowser); - let tab2 = gBrowser.addTab("about:robots"); - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser); - gBrowser.selectedTab = tab1; - let zoomResetButton = document.getElementById("zoom-reset-button"); - - registerCleanupFunction(() => { - info("Cleaning up."); - CustomizableUI.reset(); - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab1); - }); - - is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:mozilla"); - let zoomChangePromise = promiseObserverNotification("browser-fullZoom:zoomChange"); - FullZoom.enlarge(); - yield zoomChangePromise; - is(parseInt(zoomResetButton.label, 10), 110, "Zoom is changed to 110% for about:mozilla"); - - let tabSelectPromise = promiseTabSelect(); - gBrowser.selectedTab = tab2; - yield tabSelectPromise; - is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:robots"); - - gBrowser.selectedTab = tab1; - let zoomResetPromise = promiseObserverNotification("browser-fullZoom:zoomReset"); - FullZoom.reset(); - yield zoomResetPromise; - is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:mozilla"); - - // Test zoom label updates while navigating pages in the same tab. - FullZoom.enlarge(); - yield zoomChangePromise; - is(parseInt(zoomResetButton.label, 10), 110, "Zoom is changed to 110% for about:mozilla"); - let attributeChangePromise = promiseAttributeMutation(zoomResetButton, "label", (v) => { - return parseInt(v, 10) == 100; - }); - yield promiseTabLoadEvent(tab1, "about:home"); - yield attributeChangePromise; - is(parseInt(zoomResetButton.label, 10), 100, "Default zoom is 100% for about:home"); - yield promiseTabHistoryNavigation(-1, function() { - return parseInt(zoomResetButton.label, 10) == 110; - }); - is(parseInt(zoomResetButton.label, 10), 110, "Zoom is still 110% for about:mozilla"); - FullZoom.reset(); -}); - -function promiseObserverNotification(aObserver) { - let deferred = Promise.defer(); - function notificationCallback(e) { - Services.obs.removeObserver(notificationCallback, aObserver, false); - clearTimeout(timeoutId); - deferred.resolve(); - } - let timeoutId = setTimeout(() => { - Services.obs.removeObserver(notificationCallback, aObserver, false); - deferred.reject("Notification '" + aObserver + "' did not happen within 20 seconds."); - }, kTimeoutInMS); - Services.obs.addObserver(notificationCallback, aObserver, false); - return deferred.promise; -} - -function promiseTabSelect() { - let deferred = Promise.defer(); - let container = window.gBrowser.tabContainer; - let timeoutId = setTimeout(() => { - container.removeEventListener("TabSelect", callback); - deferred.reject("TabSelect did not happen within 20 seconds"); - }, kTimeoutInMS); - function callback(e) { - container.removeEventListener("TabSelect", callback); - clearTimeout(timeoutId); - executeSoon(deferred.resolve); - } - container.addEventListener("TabSelect", callback); - return deferred.promise; -} diff --git a/browser/components/customizableui/test/browser_938980_navbar_collapsed.js b/browser/components/customizableui/test/browser_938980_navbar_collapsed.js deleted file mode 100644 index fc7fa1a0a..000000000 --- a/browser/components/customizableui/test/browser_938980_navbar_collapsed.js +++ /dev/null @@ -1,121 +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"; - -requestLongerTimeout(2); - -var bookmarksToolbar = document.getElementById("PersonalToolbar"); -var navbar = document.getElementById("nav-bar"); -var tabsToolbar = document.getElementById("TabsToolbar"); - -// Customization reset should restore visibility to default-visible toolbars. -add_task(function*() { - is(navbar.collapsed, false, "Test should start with navbar visible"); - setToolbarVisibility(navbar, false); - is(navbar.collapsed, true, "navbar should be hidden now"); - - yield resetCustomization(); - - is(navbar.collapsed, false, "Customization reset should restore visibility to the navbar"); -}); - -// Customization reset should restore collapsed-state to default-collapsed toolbars. -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Everything should be in its default state"); - - is(bookmarksToolbar.collapsed, true, "Test should start with bookmarks toolbar collapsed"); - ok(bookmarksToolbar.collapsed, "bookmarksToolbar should be collapsed"); - ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed"); - is(navbar.collapsed, false, "The nav-bar should be shown by default"); - - setToolbarVisibility(bookmarksToolbar, true); - setToolbarVisibility(navbar, false); - ok(!bookmarksToolbar.collapsed, "bookmarksToolbar should be visible now"); - ok(navbar.collapsed, "navbar should be collapsed"); - is(CustomizableUI.inDefaultState, false, "Should no longer be in default state"); - - yield startCustomizing(); - yield gCustomizeMode.reset(); - yield endCustomizing(); - - is(bookmarksToolbar.collapsed, true, "Customization reset should restore collapsed-state to the bookmarks toolbar"); - ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed"); - ok(bookmarksToolbar.collapsed, "The bookmarksToolbar should be collapsed after reset"); - ok(CustomizableUI.inDefaultState, "Everything should be back to default state"); -}); - -// Check that the menubar will be collapsed by resetting, if the platform supports it. -add_task(function*() { - let menubar = document.getElementById("toolbar-menubar"); - const canMenubarCollapse = CustomizableUI.isToolbarDefaultCollapsed(menubar.id); - if (!canMenubarCollapse) { - return; - } - ok(CustomizableUI.inDefaultState, "Everything should be in its default state"); - - is(menubar.getBoundingClientRect().height, 0, "menubar should be hidden by default"); - setToolbarVisibility(menubar, true); - isnot(menubar.getBoundingClientRect().height, 0, "menubar should be visible now"); - - yield startCustomizing(); - yield gCustomizeMode.reset(); - - is(menubar.getAttribute("autohide"), "true", "The menubar should have autohide=true after reset in customization mode"); - is(menubar.getBoundingClientRect().height, 0, "The menubar should have height=0 after reset in customization mode"); - - yield endCustomizing(); - - is(menubar.getAttribute("autohide"), "true", "The menubar should have autohide=true after reset"); - is(menubar.getBoundingClientRect().height, 0, "The menubar should have height=0 after reset"); -}); - -// Customization reset should restore collapsed-state to default-collapsed toolbars. -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Everything should be in its default state"); - ok(bookmarksToolbar.collapsed, "bookmarksToolbar should be collapsed"); - ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed"); - - setToolbarVisibility(bookmarksToolbar, true); - ok(!bookmarksToolbar.collapsed, "bookmarksToolbar should be visible now"); - is(CustomizableUI.inDefaultState, false, "Should no longer be in default state"); - - yield startCustomizing(); - - ok(!bookmarksToolbar.collapsed, "The bookmarksToolbar should be visible before reset"); - ok(!navbar.collapsed, "The navbar should be visible before reset"); - ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed"); - - yield gCustomizeMode.reset(); - - ok(bookmarksToolbar.collapsed, "The bookmarksToolbar should be collapsed after reset"); - ok(!tabsToolbar.collapsed, "TabsToolbar should not be collapsed"); - ok(!navbar.collapsed, "The navbar should still be visible after reset"); - ok(CustomizableUI.inDefaultState, "Everything should be back to default state"); - yield endCustomizing(); -}); - -// Check that the menubar will be collapsed by resetting, if the platform supports it. -add_task(function*() { - let menubar = document.getElementById("toolbar-menubar"); - const canMenubarCollapse = CustomizableUI.isToolbarDefaultCollapsed(menubar.id); - if (!canMenubarCollapse) { - return; - } - ok(CustomizableUI.inDefaultState, "Everything should be in its default state"); - yield startCustomizing(); - let resetButton = document.getElementById("customization-reset-button"); - is(resetButton.disabled, true, "The reset button should be disabled when in default state"); - - setToolbarVisibility(menubar, true); - is(resetButton.disabled, false, "The reset button should be enabled when not in default state") - ok(!CustomizableUI.inDefaultState, "No longer in default state when the menubar is shown"); - - yield gCustomizeMode.reset(); - - is(resetButton.disabled, true, "The reset button should be disabled when in default state"); - ok(CustomizableUI.inDefaultState, "Everything should be in its default state"); - - yield endCustomizing(); -}); diff --git a/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js b/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js deleted file mode 100644 index 1f06c1aac..000000000 --- a/browser/components/customizableui/test/browser_938995_indefaultstate_nonremovable.js +++ /dev/null @@ -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/. */ - -"use strict"; - -const kWidgetId = "test-non-removable-widget"; - -// Adding non-removable items to a toolbar or the panel shouldn't change inDefaultState -add_task(function() { - ok(CustomizableUI.inDefaultState, "Should start in default state"); - - let button = createDummyXULButton(kWidgetId, "Test non-removable inDefaultState handling"); - CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR); - button.setAttribute("removable", "false"); - ok(CustomizableUI.inDefaultState, "Should still be in default state after navbar addition"); - button.remove(); - - button = createDummyXULButton(kWidgetId, "Test non-removable inDefaultState handling"); - CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_PANEL); - button.setAttribute("removable", "false"); - ok(CustomizableUI.inDefaultState, "Should still be in default state after panel addition"); - button.remove(); - ok(CustomizableUI.inDefaultState, "Should be in default state after destroying both widgets"); -}); diff --git a/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js b/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js deleted file mode 100644 index c554bffab..000000000 --- a/browser/components/customizableui/test/browser_940013_registerToolbarNode_calls_registerArea.js +++ /dev/null @@ -1,70 +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 kToolbarId = "test-registerToolbarNode-toolbar"; -const kButtonId = "test-registerToolbarNode-button"; -registerCleanupFunction(cleanup); - -// Registering a toolbar with defaultset attribute should work -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); - let btn = createDummyXULButton(kButtonId); - let toolbar = document.createElement("toolbar"); - toolbar.id = kToolbarId; - toolbar.setAttribute("customizable", true); - toolbar.setAttribute("defaultset", kButtonId); - gNavToolbox.appendChild(toolbar); - ok(CustomizableUI.areas.indexOf(kToolbarId) != -1, - "Toolbar should have been registered automatically."); - is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR, - "Area should be registered as toolbar"); - assertAreaPlacements(kToolbarId, [kButtonId]); - ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible."); - CustomizableUI.unregisterArea(kToolbarId, true); - toolbar.remove(); - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); - btn.remove(); -}); - -// Registering a toolbar without a defaultset attribute should -// wait for the registerArea call -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); - let btn = createDummyXULButton(kButtonId); - let toolbar = document.createElement("toolbar"); - toolbar.id = kToolbarId; - toolbar.setAttribute("customizable", true); - gNavToolbox.appendChild(toolbar); - ok(CustomizableUI.areas.indexOf(kToolbarId) == -1, - "Toolbar should not yet have been registered automatically."); - CustomizableUI.registerArea(kToolbarId, {defaultPlacements: [kButtonId]}); - ok(CustomizableUI.areas.indexOf(kToolbarId) != -1, - "Toolbar should have been registered now."); - is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR, - "Area should be registered as toolbar"); - assertAreaPlacements(kToolbarId, [kButtonId]); - ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible."); - CustomizableUI.unregisterArea(kToolbarId, true); - toolbar.remove(); - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); - btn.remove(); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); - -function cleanup() { - let toolbar = document.getElementById(kToolbarId); - if (toolbar) { - toolbar.remove(); - } - let btn = document.getElementById(kButtonId) || - gNavToolbox.querySelector("#" + kButtonId); - if (btn) { - btn.remove(); - } -} diff --git a/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js b/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js deleted file mode 100644 index 944879a1b..000000000 --- a/browser/components/customizableui/test/browser_940307_panel_click_closure_handling.js +++ /dev/null @@ -1,136 +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"; - -var button, menuButton; -/* Clicking a button should close the panel */ -add_task(function*() { - button = document.createElement("toolbarbutton"); - button.id = "browser_940307_button"; - button.setAttribute("label", "Button"); - PanelUI.contents.appendChild(button); - yield PanelUI.show(); - let hiddenAgain = promisePanelHidden(window); - EventUtils.synthesizeMouseAtCenter(button, {}); - yield hiddenAgain; - button.remove(); -}); - -/* Clicking a menu button should close the panel, opening the popup shouldn't. */ -add_task(function*() { - menuButton = document.createElement("toolbarbutton"); - menuButton.setAttribute("type", "menu-button"); - menuButton.id = "browser_940307_menubutton"; - menuButton.setAttribute("label", "Menu button"); - - let menuPopup = document.createElement("menupopup"); - menuPopup.id = "browser_940307_menupopup"; - - let menuItem = document.createElement("menuitem"); - menuItem.setAttribute("label", "Menu item"); - menuItem.id = "browser_940307_menuitem"; - - menuPopup.appendChild(menuItem); - menuButton.appendChild(menuPopup); - PanelUI.contents.appendChild(menuButton); - - yield PanelUI.show(); - let hiddenAgain = promisePanelHidden(window); - let innerButton = document.getAnonymousElementByAttribute(menuButton, "anonid", "button"); - EventUtils.synthesizeMouseAtCenter(innerButton, {}); - yield hiddenAgain; - - // Now click the dropmarker to show the menu - yield PanelUI.show(); - hiddenAgain = promisePanelHidden(window); - let menuShown = promisePanelElementShown(window, menuPopup); - let dropmarker = document.getAnonymousElementByAttribute(menuButton, "type", "menu-button"); - EventUtils.synthesizeMouseAtCenter(dropmarker, {}); - yield menuShown; - // Panel should stay open: - ok(isPanelUIOpen(), "Panel should still be open"); - let menuHidden = promisePanelElementHidden(window, menuPopup); - // Then click the menu item to close all the things - EventUtils.synthesizeMouseAtCenter(menuItem, {}); - yield menuHidden; - yield hiddenAgain; - menuButton.remove(); -}); - -add_task(function*() { - let searchbar = document.getElementById("searchbar"); - gCustomizeMode.addToPanel(searchbar); - let placement = CustomizableUI.getPlacementOfWidget("search-container"); - is(placement.area, CustomizableUI.AREA_PANEL, "Should be in panel"); - yield PanelUI.show(); - yield waitForCondition(() => "value" in searchbar && searchbar.value === ""); - - // Focusing a non-empty searchbox will cause us to open the - // autocomplete panel and search for suggestions, which would - // trigger network requests. Temporarily disable suggestions. - yield SpecialPowers.pushPrefEnv({set: [["browser.search.suggest.enabled", false]]}); - - searchbar.value = "foo"; - searchbar.focus(); - // Reaching into this context menu is pretty evil, but hey... it's a test. - let textbox = document.getAnonymousElementByAttribute(searchbar.textbox, "anonid", "textbox-input-box"); - let contextmenu = document.getAnonymousElementByAttribute(textbox, "anonid", "input-box-contextmenu"); - let contextMenuShown = promisePanelElementShown(window, contextmenu); - EventUtils.synthesizeMouseAtCenter(searchbar, {type: "contextmenu", button: 2}); - yield contextMenuShown; - - ok(isPanelUIOpen(), "Panel should still be open"); - - let selectAll = contextmenu.querySelector("[cmd='cmd_selectAll']"); - let contextMenuHidden = promisePanelElementHidden(window, contextmenu); - EventUtils.synthesizeMouseAtCenter(selectAll, {}); - yield contextMenuHidden; - - // Hide the suggestion panel. - searchbar.textbox.popup.hidePopup(); - - ok(isPanelUIOpen(), "Panel should still be open"); - - let hiddenPanelPromise = promisePanelHidden(window); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield hiddenPanelPromise; - ok(!isPanelUIOpen(), "Panel should no longer be open"); - - // We focused the search bar earlier - ensure we don't keep doing that. - gURLBar.select(); - - CustomizableUI.reset(); -}); - -add_task(function*() { - button = document.createElement("toolbarbutton"); - button.id = "browser_946166_button_disabled"; - button.setAttribute("disabled", "true"); - button.setAttribute("label", "Button"); - PanelUI.contents.appendChild(button); - yield PanelUI.show(); - EventUtils.synthesizeMouseAtCenter(button, {}); - is(PanelUI.panel.state, "open", "Popup stays open"); - button.removeAttribute("disabled"); - let hiddenAgain = promisePanelHidden(window); - EventUtils.synthesizeMouseAtCenter(button, {}); - yield hiddenAgain; - button.remove(); -}); - -registerCleanupFunction(function() { - if (button && button.parentNode) { - button.remove(); - } - if (menuButton && menuButton.parentNode) { - menuButton.remove(); - } - // Sadly this isn't task.jsm-enabled, so we can't wait for this to happen. But we should - // definitely close it here and hope it won't interfere with other tests. - // Of course, all the tests are meant to do this themselves, but if they fail... - if (isPanelUIOpen()) { - PanelUI.hide(); - } -}); diff --git a/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js b/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js deleted file mode 100644 index c81b004c1..000000000 --- a/browser/components/customizableui/test/browser_940946_removable_from_navbar_customizemode.js +++ /dev/null @@ -1,22 +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 kTestBtnId = "test-removable-navbar-customize-mode"; - -// Items without the removable attribute in the navbar should be considered non-removable -add_task(function*() { - let btn = createDummyXULButton(kTestBtnId, "Test removable in navbar in customize mode"); - document.getElementById("nav-bar").customizationTarget.appendChild(btn); - yield startCustomizing(); - ok(!CustomizableUI.isWidgetRemovable(kTestBtnId), "Widget should not be considered removable"); - yield endCustomizing(); - document.getElementById(kTestBtnId).remove(); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js b/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js deleted file mode 100644 index 1d7f86fd2..000000000 --- a/browser/components/customizableui/test/browser_941083_invalidate_wrapper_cache_createWidget.js +++ /dev/null @@ -1,31 +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"; - -// See https://bugzilla.mozilla.org/show_bug.cgi?id=941083 - -const kWidgetId = "test-invalidate-wrapper-cache"; - -// Check createWidget invalidates the widget cache -add_task(function() { - let groupWrapper = CustomizableUI.getWidget(kWidgetId); - ok(groupWrapper, "Should get group wrapper."); - let singleWrapper = groupWrapper.forWindow(window); - ok(singleWrapper, "Should get single wrapper."); - - CustomizableUI.createWidget({id: kWidgetId, label: "Test invalidating widgets caching"}); - - let newGroupWrapper = CustomizableUI.getWidget(kWidgetId); - ok(newGroupWrapper, "Should get a group wrapper again."); - isnot(newGroupWrapper, groupWrapper, "Wrappers shouldn't be the same."); - isnot(newGroupWrapper.provider, groupWrapper.provider, "Wrapper providers shouldn't be the same."); - - let newSingleWrapper = newGroupWrapper.forWindow(window); - isnot(newSingleWrapper, singleWrapper, "Single wrappers shouldn't be the same."); - isnot(newSingleWrapper.provider, singleWrapper.provider, "Single wrapper providers shouldn't be the same."); - - CustomizableUI.destroyWidget(kWidgetId); - ok(!CustomizableUI.getWidget(kWidgetId), "Shouldn't get a wrapper after destroying the widget."); -}); diff --git a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js deleted file mode 100644 index 61adac982..000000000 --- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js +++ /dev/null @@ -1,106 +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 kToolbarName = "test-unregisterArea-placements-toolbar"; -const kTestWidgetPfx = "test-widget-for-unregisterArea-placements-"; -const kTestWidgetCount = 3; -registerCleanupFunction(removeCustomToolbars); - -// unregisterArea should keep placements by default and restore them when re-adding the area -add_task(function*() { - let widgetIds = []; - for (let i = 0; i < kTestWidgetCount; i++) { - let id = kTestWidgetPfx + i; - widgetIds.push(id); - let spec = {id: id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - } - for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) { - let id = kTestWidgetPfx + i; - widgetIds.push(id); - createDummyXULButton(id, "unregisterArea XUL test " + i); - } - let toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds); - checkAbstractAndRealPlacements(toolbarNode, widgetIds); - - // Now move one of them: - CustomizableUI.moveWidgetWithinArea(kTestWidgetPfx + kTestWidgetCount, 0); - // Clone the array so we know this is the modified one: - let modifiedWidgetIds = [...widgetIds]; - let movedWidget = modifiedWidgetIds.splice(kTestWidgetCount, 1)[0]; - modifiedWidgetIds.unshift(movedWidget); - - // Check it: - checkAbstractAndRealPlacements(toolbarNode, modifiedWidgetIds); - - // Then unregister - CustomizableUI.unregisterArea(kToolbarName); - - // Check we tell the outside world no dangerous things: - checkWidgetFates(widgetIds); - // Only then remove the real node - toolbarNode.remove(); - - // Now move one of the items to the palette, and another to the navbar: - let lastWidget = modifiedWidgetIds.pop(); - CustomizableUI.removeWidgetFromArea(lastWidget); - lastWidget = modifiedWidgetIds.pop(); - CustomizableUI.addWidgetToArea(lastWidget, CustomizableUI.AREA_NAVBAR); - - // Recreate ourselves with the default placements being the same: - toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds); - // Then check that after doing this, our actual placements match - // the modified list, not the default one. - checkAbstractAndRealPlacements(toolbarNode, modifiedWidgetIds); - - // Now remove completely: - CustomizableUI.unregisterArea(kToolbarName, true); - checkWidgetFates(modifiedWidgetIds); - toolbarNode.remove(); - - // One more time: - // Recreate ourselves with the default placements being the same: - toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds); - // Should now be back to default: - checkAbstractAndRealPlacements(toolbarNode, widgetIds); - CustomizableUI.unregisterArea(kToolbarName, true); - checkWidgetFates(widgetIds); - toolbarNode.remove(); - - // XXXgijs: ensure cleanup function doesn't barf: - gAddedToolbars.delete(kToolbarName); - - // Remove all the XUL widgets, destroy the others: - for (let widget of widgetIds) { - let widgetWrapper = CustomizableUI.getWidget(widget); - if (widgetWrapper.provider == CustomizableUI.PROVIDER_XUL) { - gNavToolbox.palette.querySelector("#" + widget).remove(); - } else { - CustomizableUI.destroyWidget(widget); - } - } -}); - -function checkAbstractAndRealPlacements(aNode, aExpectedPlacements) { - assertAreaPlacements(kToolbarName, aExpectedPlacements); - let physicalWidgetIds = Array.from(aNode.childNodes, (node) => node.id); - placementArraysEqual(aNode.id, physicalWidgetIds, aExpectedPlacements); -} - -function checkWidgetFates(aWidgetIds) { - for (let widget of aWidgetIds) { - ok(!CustomizableUI.getPlacementOfWidget(widget), "Widget should be in palette"); - ok(!document.getElementById(widget), "Widget should not be in the DOM"); - let widgetInPalette = !!gNavToolbox.palette.querySelector("#" + widget); - let widgetProvider = CustomizableUI.getWidget(widget).provider; - let widgetIsXULWidget = widgetProvider == CustomizableUI.PROVIDER_XUL; - is(widgetInPalette, widgetIsXULWidget, "Just XUL Widgets should be in the palette"); - } -} - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_943683_migration_test.js b/browser/components/customizableui/test/browser_943683_migration_test.js deleted file mode 100644 index fe30df9e3..000000000 --- a/browser/components/customizableui/test/browser_943683_migration_test.js +++ /dev/null @@ -1,50 +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 kWidgetId = "test-addonbar-migration"; -const kWidgetId2 = "test-addonbar-migration2"; - -var addonbar = document.getElementById(CustomizableUI.AREA_ADDONBAR); -var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - -var btn; -var btn2; - -// Check we migrate normal stuff to the navbar -add_task(function*() { - btn = createDummyXULButton(kWidgetId, "Test"); - btn2 = createDummyXULButton(kWidgetId2, "Test2"); - addonbar.insertItem(btn.id); - ok(btn.parentNode == navbar.customizationTarget, "Button should end up in navbar"); - let migrationArray = addonbar.getMigratedItems(); - is(migrationArray.length, 1, "Should have migrated 1 item"); - is(migrationArray[0], kWidgetId, "Should have migrated our 1 item"); - - addonbar.currentSet = addonbar.currentSet + "," + kWidgetId2; - ok(btn2.parentNode == navbar.customizationTarget, "Second button should end up in the navbar"); - migrationArray = addonbar.getMigratedItems(); - is(migrationArray.length, 2, "Should have migrated 2 items"); - isnot(migrationArray.indexOf(kWidgetId2), -1, "Should have migrated our second item"); - - let otherWindow = yield openAndLoadWindow(undefined, true); - try { - let addonBar = otherWindow.document.getElementById("addon-bar"); - let otherMigrationArray = addonBar.getMigratedItems(); - is(migrationArray.length, otherMigrationArray.length, - "Other window should have the same number of migrated items."); - if (migrationArray.length == otherMigrationArray.length) { - for (let widget of migrationArray) { - isnot(otherMigrationArray.indexOf(widget), -1, - "Migrated widget " + widget + " should also be listed as migrated in the other window."); - } - } - } finally { - yield promiseWindowClosed(otherWindow); - } - btn.remove(); - btn2.remove(); - CustomizableUI.reset(); -}); diff --git a/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js b/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js deleted file mode 100644 index a724b0c7f..000000000 --- a/browser/components/customizableui/test/browser_944887_destroyWidget_should_destroy_in_palette.js +++ /dev/null @@ -1,17 +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 kWidgetId = "test-destroy-in-palette"; - -// Check destroyWidget destroys the node if it's in the palette -add_task(function*() { - CustomizableUI.createWidget({id: kWidgetId, label: "Test destroying widgets in palette."}); - yield startCustomizing(); - yield endCustomizing(); - ok(gNavToolbox.palette.querySelector("#" + kWidgetId), "Widget still exists in palette."); - CustomizableUI.destroyWidget(kWidgetId); - ok(!gNavToolbox.palette.querySelector("#" + kWidgetId), "Widget no longer exists in palette."); -}); diff --git a/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js b/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js deleted file mode 100644 index 6b8acbee0..000000000 --- a/browser/components/customizableui/test/browser_945739_showInPrivateBrowsing_customize_mode.js +++ /dev/null @@ -1,35 +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 kWidgetId = "test-private-browsing-customize-mode-widget"; - -// Add a widget via the API with showInPrivateBrowsing set to false -// and ensure it does not appear in the list of unused widgets in private -// windows. -add_task(function* testPrivateBrowsingCustomizeModeWidget() { - CustomizableUI.createWidget({ - id: kWidgetId, - showInPrivateBrowsing: false - }); - - let normalWidgetArray = CustomizableUI.getUnusedWidgets(gNavToolbox.palette); - normalWidgetArray = normalWidgetArray.map((w) => w.id); - ok(normalWidgetArray.indexOf(kWidgetId) > -1, - "Widget should appear as unused in non-private window"); - - let privateWindow = yield openAndLoadWindow({private: true}); - let privateWidgetArray = CustomizableUI.getUnusedWidgets(privateWindow.gNavToolbox.palette); - privateWidgetArray = privateWidgetArray.map((w) => w.id); - is(privateWidgetArray.indexOf(kWidgetId), -1, - "Widget should not appear as unused in private window"); - yield promiseWindowClosed(privateWindow); - - CustomizableUI.destroyWidget(kWidgetId); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_addons.js b/browser/components/customizableui/test/browser_947914_button_addons.js deleted file mode 100644 index b942ee771..000000000 --- a/browser/components/customizableui/test/browser_947914_button_addons.js +++ /dev/null @@ -1,33 +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"; - -var initialLocation = gBrowser.currentURI.spec; -var newTab = null; - -add_task(function*() { - info("Check addons button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let addonsButton = document.getElementById("add-ons-button"); - ok(addonsButton, "Add-ons button exists in Panel Menu"); - addonsButton.click(); - - newTab = gBrowser.selectedTab; - yield waitForCondition(() => gBrowser.currentURI && - gBrowser.currentURI.spec == "about:addons"); - - let addonsPage = gBrowser.selectedBrowser.contentWindow.document. - getElementById("addons-page"); - ok(addonsPage, "Add-ons page was opened"); -}); - -add_task(function* asyncCleanup() { - gBrowser.addTab(initialLocation); - gBrowser.removeTab(gBrowser.selectedTab); - info("Tabs were restored"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_copy.js b/browser/components/customizableui/test/browser_947914_button_copy.js deleted file mode 100644 index c778c956f..000000000 --- a/browser/components/customizableui/test/browser_947914_button_copy.js +++ /dev/null @@ -1,59 +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"; - -var initialLocation = gBrowser.currentURI.spec; -var globalClipboard; - -add_task(function*() { - yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() { - info("Check copy button existence and functionality"); - - let testText = "copy text test"; - - gURLBar.focus(); - info("The URL bar was focused"); - yield PanelUI.show(); - info("Menu panel was opened"); - - let copyButton = document.getElementById("copy-button"); - ok(copyButton, "Copy button exists in Panel Menu"); - ok(copyButton.getAttribute("disabled"), "Copy button is initially disabled"); - - // copy text from URL bar - gURLBar.value = testText; - gURLBar.focus(); - gURLBar.select(); - yield PanelUI.show(); - info("Menu panel was opened"); - - ok(!copyButton.hasAttribute("disabled"), "Copy button is enabled when selecting"); - - copyButton.click(); - is(gURLBar.value, testText, "Selected text is unaltered when clicking copy"); - - // check that the text was added to the clipboard - let clipboard = Services.clipboard; - let transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable); - globalClipboard = clipboard.kGlobalClipboard; - - transferable.init(null); - transferable.addDataFlavor("text/unicode"); - clipboard.getData(transferable, globalClipboard); - let str = {}, strLength = {}; - transferable.getTransferData("text/unicode", str, strLength); - let clipboardValue = ""; - - if (str.value) { - str.value.QueryInterface(Ci.nsISupportsString); - clipboardValue = str.value.data; - } - is(clipboardValue, testText, "Data was copied to the clipboard."); - }); -}); - -registerCleanupFunction(function cleanup() { - Services.clipboard.emptyClipboard(globalClipboard); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_cut.js b/browser/components/customizableui/test/browser_947914_button_cut.js deleted file mode 100644 index e6e614368..000000000 --- a/browser/components/customizableui/test/browser_947914_button_cut.js +++ /dev/null @@ -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/. */ - -"use strict"; - -var initialLocation = gBrowser.currentURI.spec; -var globalClipboard; - -add_task(function*() { - yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() { - info("Check cut button existence and functionality"); - - let testText = "cut text test"; - - gURLBar.focus(); - yield PanelUI.show(); - info("Menu panel was opened"); - - let cutButton = document.getElementById("cut-button"); - ok(cutButton, "Cut button exists in Panel Menu"); - ok(cutButton.hasAttribute("disabled"), "Cut button is disabled"); - - // cut text from URL bar - gURLBar.value = testText; - gURLBar.focus(); - gURLBar.select(); - yield PanelUI.show(); - info("Menu panel was opened"); - - ok(!cutButton.hasAttribute("disabled"), "Cut button is enabled when selecting"); - cutButton.click(); - is(gURLBar.value, "", "Selected text is removed from source when clicking on cut"); - - // check that the text was added to the clipboard - let clipboard = Services.clipboard; - let transferable = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable); - globalClipboard = clipboard.kGlobalClipboard; - - transferable.init(null); - transferable.addDataFlavor("text/unicode"); - clipboard.getData(transferable, globalClipboard); - let str = {}, strLength = {}; - transferable.getTransferData("text/unicode", str, strLength); - let clipboardValue = ""; - - if (str.value) { - str.value.QueryInterface(Ci.nsISupportsString); - clipboardValue = str.value.data; - } - is(clipboardValue, testText, "Data was copied to the clipboard."); - }); -}); - -registerCleanupFunction(function cleanup() { - Services.clipboard.emptyClipboard(globalClipboard); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_find.js b/browser/components/customizableui/test/browser_947914_button_find.js deleted file mode 100644 index cf3b79e34..000000000 --- a/browser/components/customizableui/test/browser_947914_button_find.js +++ /dev/null @@ -1,22 +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"; - -add_task(function*() { - info("Check find button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let findButton = document.getElementById("find-button"); - ok(findButton, "Find button exists in Panel Menu"); - - findButton.click(); - ok(!gFindBar.hasAttribute("hidden"), "Findbar opened successfully"); - - // close find bar - gFindBar.close(); - info("Findbar was closed"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_history.js b/browser/components/customizableui/test/browser_947914_button_history.js deleted file mode 100644 index 64080fcc3..000000000 --- a/browser/components/customizableui/test/browser_947914_button_history.js +++ /dev/null @@ -1,24 +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"; - -add_task(function*() { - info("Check history button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let historyButton = document.getElementById("history-panelmenu"); - ok(historyButton, "History button appears in Panel Menu"); - - historyButton.click(); - let historyPanel = document.getElementById("PanelUI-history"); - ok(historyPanel.getAttribute("current"), "History Panel is in view"); - - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise - info("Menu panel was closed"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js b/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js deleted file mode 100644 index c2006bef0..000000000 --- a/browser/components/customizableui/test/browser_947914_button_newPrivateWindow.js +++ /dev/null @@ -1,48 +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"; - -add_task(function*() { - info("Check private browsing button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let windowWasHandled = false; - let privateWindow = null; - - let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - privateWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); - privateWindow.addEventListener("load", function newWindowHandler() { - privateWindow.removeEventListener("load", newWindowHandler, false); - is(privateWindow.location.href, "chrome://browser/content/browser.xul", - "A new browser window was opened"); - ok(PrivateBrowsingUtils.isWindowPrivate(privateWindow), "Window is private"); - windowWasHandled = true; - }, false); - } - } - } - - Services.ww.registerNotification(observerWindowOpened); - - let privateBrowsingButton = document.getElementById("privatebrowsing-button"); - ok(privateBrowsingButton, "Private browsing button exists in Panel Menu"); - privateBrowsingButton.click(); - - try { - yield waitForCondition(() => windowWasHandled); - yield promiseWindowClosed(privateWindow); - info("The new private window was closed"); - } - catch (e) { - ok(false, "The new private browser window was not properly handled"); - } - finally { - Services.ww.unregisterNotification(observerWindowOpened); - } -}); diff --git a/browser/components/customizableui/test/browser_947914_button_newWindow.js b/browser/components/customizableui/test/browser_947914_button_newWindow.js deleted file mode 100644 index 47162ee86..000000000 --- a/browser/components/customizableui/test/browser_947914_button_newWindow.js +++ /dev/null @@ -1,47 +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"; - -add_task(function*() { - info("Check new window button existence and functionality"); - yield PanelUI.show(); - info("Menu panel was opened"); - - let windowWasHandled = false; - let newWindow = null; - - let observerWindowOpened = { - observe: function(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - newWindow = aSubject.QueryInterface(Components.interfaces.nsIDOMWindow); - newWindow.addEventListener("load", function newWindowHandler() { - newWindow.removeEventListener("load", newWindowHandler, false); - is(newWindow.location.href, "chrome://browser/content/browser.xul", - "A new browser window was opened"); - ok(!PrivateBrowsingUtils.isWindowPrivate(newWindow), "Window is not private"); - windowWasHandled = true; - }, false); - } - } - } - - Services.ww.registerNotification(observerWindowOpened); - - let newWindowButton = document.getElementById("new-window-button"); - ok(newWindowButton, "New Window button exists in Panel Menu"); - newWindowButton.click(); - - try { - yield waitForCondition(() => windowWasHandled); - yield promiseWindowClosed(newWindow); - info("The new window was closed"); - } - catch (e) { - ok(false, "The new browser window was not properly handled"); - } - finally { - Services.ww.unregisterNotification(observerWindowOpened); - } -}); diff --git a/browser/components/customizableui/test/browser_947914_button_paste.js b/browser/components/customizableui/test/browser_947914_button_paste.js deleted file mode 100644 index fc83ead56..000000000 --- a/browser/components/customizableui/test/browser_947914_button_paste.js +++ /dev/null @@ -1,41 +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"; - -var initialLocation = gBrowser.currentURI.spec; -var globalClipboard; - -add_task(function*() { - yield BrowserTestUtils.withNewTab({gBrowser, url: "about:blank"}, function*() { - info("Check paste button existence and functionality"); - - let clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper); - globalClipboard = Services.clipboard.kGlobalClipboard; - - yield PanelUI.show(); - info("Menu panel was opened"); - - let pasteButton = document.getElementById("paste-button"); - ok(pasteButton, "Paste button exists in Panel Menu"); - - // add text to clipboard - let text = "Sample text for testing"; - clipboard.copyString(text); - - // test paste button by pasting text to URL bar - gURLBar.focus(); - yield PanelUI.show(); - info("Menu panel was opened"); - - ok(!pasteButton.hasAttribute("disabled"), "Paste button is enabled"); - pasteButton.click(); - - is(gURLBar.value, text, "Text pasted successfully"); - }); -}); - -registerCleanupFunction(function cleanup() { - Services.clipboard.emptyClipboard(globalClipboard); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_print.js b/browser/components/customizableui/test/browser_947914_button_print.js deleted file mode 100644 index af7abcaeb..000000000 --- a/browser/components/customizableui/test/browser_947914_button_print.js +++ /dev/null @@ -1,45 +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 isOSX = (Services.appinfo.OS === "Darwin"); - -add_task(function*() { - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: "http://example.com/", - }, function* () { - info("Check print button existence and functionality"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - yield waitForCondition(() => document.getElementById("print-button") != null); - - let printButton = document.getElementById("print-button"); - ok(printButton, "Print button exists in Panel Menu"); - - if (isOSX) { - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - info("Menu panel was closed"); - } - else { - printButton.click(); - yield waitForCondition(() => gInPrintPreviewMode); - - ok(gInPrintPreviewMode, "Entered print preview mode"); - - // close print preview - if (gInPrintPreviewMode) { - PrintUtils.exitPrintPreview(); - yield waitForCondition(() => !window.gInPrintPreviewMode); - info("Exited print preview") - } - } - }); -}); - diff --git a/browser/components/customizableui/test/browser_947914_button_savePage.js b/browser/components/customizableui/test/browser_947914_button_savePage.js deleted file mode 100644 index 543ff3ca6..000000000 --- a/browser/components/customizableui/test/browser_947914_button_savePage.js +++ /dev/null @@ -1,20 +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"; - -add_task(function*() { - info("Check save page button existence"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let savePageButton = document.getElementById("save-page-button"); - ok(savePageButton, "Save Page button exists in Panel Menu"); - - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - info("Menu panel was closed"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_zoomIn.js b/browser/components/customizableui/test/browser_947914_button_zoomIn.js deleted file mode 100644 index 4463d87d6..000000000 --- a/browser/components/customizableui/test/browser_947914_button_zoomIn.js +++ /dev/null @@ -1,37 +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"; - -var initialPageZoom = ZoomManager.zoom; - -add_task(function*() { - info("Check zoom in button existence and functionality"); - - is(initialPageZoom, 1, "Initial zoom factor should be 1"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let zoomInButton = document.getElementById("zoom-in-button"); - ok(zoomInButton, "Zoom in button exists in Panel Menu"); - - zoomInButton.click(); - let pageZoomLevel = parseInt(ZoomManager.zoom * 100); - let zoomResetButton = document.getElementById("zoom-reset-button"); - let expectedZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10); - ok(pageZoomLevel > 100 && pageZoomLevel == expectedZoomLevel, "Page zoomed in correctly"); - - // close the Panel - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - info("Menu panel was closed"); -}); - -add_task(function* asyncCleanup() { - // reset zoom level - ZoomManager.zoom = initialPageZoom; - info("Zoom level was restored"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_zoomOut.js b/browser/components/customizableui/test/browser_947914_button_zoomOut.js deleted file mode 100644 index f9f51ac9a..000000000 --- a/browser/components/customizableui/test/browser_947914_button_zoomOut.js +++ /dev/null @@ -1,38 +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"; - -var initialPageZoom = ZoomManager.zoom; - -add_task(function*() { - info("Check zoom out button existence and functionality"); - - is(initialPageZoom, 1, "Initial zoom factor should be 1"); - - yield PanelUI.show(); - info("Menu panel was opened"); - - let zoomOutButton = document.getElementById("zoom-out-button"); - ok(zoomOutButton, "Zoom out button exists in Panel Menu"); - - zoomOutButton.click(); - let pageZoomLevel = Math.round(ZoomManager.zoom * 100); - - let zoomResetButton = document.getElementById("zoom-reset-button"); - let expectedZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10); - ok(pageZoomLevel < 100 && pageZoomLevel == expectedZoomLevel, "Page zoomed out correctly"); - - // close the panel - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - info("Menu panel was closed"); -}); - -add_task(function* asyncCleanup() { - // reset zoom level - ZoomManager.zoom = initialPageZoom; - info("Zoom level was restored"); -}); diff --git a/browser/components/customizableui/test/browser_947914_button_zoomReset.js b/browser/components/customizableui/test/browser_947914_button_zoomReset.js deleted file mode 100644 index 372097665..000000000 --- a/browser/components/customizableui/test/browser_947914_button_zoomReset.js +++ /dev/null @@ -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/. */ - -"use strict"; - -var initialPageZoom = ZoomManager.zoom; - -add_task(function*() { - info("Check zoom reset button existence and functionality"); - - is(initialPageZoom, 1, "Page zoom reset correctly"); - ZoomManager.zoom = 0.5; - yield PanelUI.show(); - info("Menu panel was opened"); - - let zoomResetButton = document.getElementById("zoom-reset-button"); - ok(zoomResetButton, "Zoom reset button exists in Panel Menu"); - - zoomResetButton.click(); - yield new Promise(SimpleTest.executeSoon); - - let pageZoomLevel = Math.floor(ZoomManager.zoom * 100); - let expectedZoomLevel = 100; - let buttonZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10); - is(pageZoomLevel, expectedZoomLevel, "Page zoom reset correctly"); - is(pageZoomLevel, buttonZoomLevel, "Button displays the correct zoom level"); - - // close the panel - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - info("Menu panel was closed"); -}); - -add_task(function* asyncCleanup() { - // reset zoom level - ZoomManager.zoom = initialPageZoom; - info("Zoom level was restored"); -}); diff --git a/browser/components/customizableui/test/browser_947987_removable_default.js b/browser/components/customizableui/test/browser_947987_removable_default.js deleted file mode 100644 index 98325ec2a..000000000 --- a/browser/components/customizableui/test/browser_947987_removable_default.js +++ /dev/null @@ -1,68 +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"; - -var kWidgetId = "test-removable-widget-default"; -const kNavBar = CustomizableUI.AREA_NAVBAR; -var widgetCounter = 0; - -registerCleanupFunction(removeCustomToolbars); - -// Sanity checks -add_task(function() { - let brokenSpec = {id: kWidgetId + (widgetCounter++), removable: false}; - SimpleTest.doesThrow(() => CustomizableUI.createWidget(brokenSpec), - "Creating non-removable widget without defaultArea should throw."); - - // Widget without removable set should be removable: - let wrapper = CustomizableUI.createWidget({id: kWidgetId + (widgetCounter++)}); - ok(CustomizableUI.isWidgetRemovable(wrapper.id), "Should be removable by default."); - CustomizableUI.destroyWidget(wrapper.id); -}); - -// Test non-removable widget with defaultArea -add_task(function*() { - // Non-removable widget with defaultArea should work: - let spec = {id: kWidgetId + (widgetCounter++), removable: false, - defaultArea: kNavBar}; - let widgetWrapper; - try { - widgetWrapper = CustomizableUI.createWidget(spec); - } catch (ex) { - ok(false, "Creating a non-removable widget with a default area should not throw."); - return; - } - - let placement = CustomizableUI.getPlacementOfWidget(spec.id); - ok(placement, "Widget should be placed."); - is(placement.area, kNavBar, "Widget should be in navbar"); - let singleWrapper = widgetWrapper.forWindow(window); - ok(singleWrapper, "Widget should exist in window."); - ok(singleWrapper.node, "Widget node should exist in window."); - let expectedParent = CustomizableUI.getCustomizeTargetForArea(kNavBar, window); - is(singleWrapper.node.parentNode, expectedParent, "Widget should be in navbar."); - - let otherWin = yield openAndLoadWindow(true); - placement = CustomizableUI.getPlacementOfWidget(spec.id); - ok(placement, "Widget should be placed."); - is(placement && placement.area, kNavBar, "Widget should be in navbar"); - - singleWrapper = widgetWrapper.forWindow(otherWin); - ok(singleWrapper, "Widget should exist in other window."); - if (singleWrapper) { - ok(singleWrapper.node, "Widget node should exist in other window."); - if (singleWrapper.node) { - let expectedParent = CustomizableUI.getCustomizeTargetForArea(kNavBar, otherWin); - is(singleWrapper.node.parentNode, expectedParent, - "Widget should be in navbar in other window."); - } - } - CustomizableUI.destroyWidget(spec.id); - yield promiseWindowClosed(otherWin); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js b/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js deleted file mode 100644 index 456c9ed02..000000000 --- a/browser/components/customizableui/test/browser_948985_non_removable_defaultArea.js +++ /dev/null @@ -1,32 +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 kWidgetId = "test-destroy-non-removable-defaultArea"; - -add_task(function() { - let spec = {id: kWidgetId, label: "Test non-removable defaultArea re-adding.", - removable: false, defaultArea: CustomizableUI.AREA_NAVBAR}; - CustomizableUI.createWidget(spec); - let placement = CustomizableUI.getPlacementOfWidget(kWidgetId); - ok(placement, "Should have placed the widget."); - is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar"); - CustomizableUI.destroyWidget(kWidgetId); - CustomizableUI.removeWidgetFromArea(kWidgetId); - - CustomizableUI.createWidget(spec); - ok(placement, "Should have placed the widget."); - is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar"); - CustomizableUI.destroyWidget(kWidgetId); - CustomizableUI.removeWidgetFromArea(kWidgetId); - - const kPrefCustomizationAutoAdd = "browser.uiCustomization.autoAdd"; - Services.prefs.setBoolPref(kPrefCustomizationAutoAdd, false); - CustomizableUI.createWidget(spec); - ok(placement, "Should have placed the widget."); - is(placement && placement.area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar"); - CustomizableUI.destroyWidget(kWidgetId); - CustomizableUI.removeWidgetFromArea(kWidgetId); - Services.prefs.clearUserPref(kPrefCustomizationAutoAdd); -}); - diff --git a/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js b/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js deleted file mode 100644 index fc05a99fd..000000000 --- a/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js +++ /dev/null @@ -1,52 +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 kToolbarName = "test-unregisterArea-areaType"; -const kUnregisterAreaTestWidget = "test-widget-for-unregisterArea-areaType"; -const kTestWidget = "test-widget-no-area-areaType"; -registerCleanupFunction(removeCustomToolbars); - -function checkAreaType(widget) { - try { - is(widget.areaType, null, "areaType should be null"); - } catch (ex) { - info("Fetching areaType threw: " + ex); - ok(false, "areaType getter shouldn't throw."); - } -} - -// widget wrappers in unregisterArea'd areas and nowhere shouldn't throw when checking areaTypes. -add_task(function*() { - // Using the ID before it's been created will imply a XUL wrapper; we'll test - // an API-based wrapper below - let toolbarNode = createToolbarWithPlacements(kToolbarName, [kUnregisterAreaTestWidget]); - CustomizableUI.unregisterArea(kToolbarName); - toolbarNode.remove(); - - let w = CustomizableUI.getWidget(kUnregisterAreaTestWidget); - checkAreaType(w); - - w = CustomizableUI.getWidget(kTestWidget); - checkAreaType(w); - - let spec = {id: kUnregisterAreaTestWidget, type: 'button', removable: true, - label: "areaType test", tooltiptext: "areaType test"}; - CustomizableUI.createWidget(spec); - toolbarNode = createToolbarWithPlacements(kToolbarName, [kUnregisterAreaTestWidget]); - CustomizableUI.unregisterArea(kToolbarName); - toolbarNode.remove(); - w = CustomizableUI.getWidget(spec.id); - checkAreaType(w); - CustomizableUI.removeWidgetFromArea(kUnregisterAreaTestWidget); - checkAreaType(w); - // XXXgijs: ensure cleanup function doesn't barf: - gAddedToolbars.delete(kToolbarName); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); - diff --git a/browser/components/customizableui/test/browser_956602_remove_special_widget.js b/browser/components/customizableui/test/browser_956602_remove_special_widget.js deleted file mode 100644 index f87b2e4c8..000000000 --- a/browser/components/customizableui/test/browser_956602_remove_special_widget.js +++ /dev/null @@ -1,31 +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"; - - -// Adding a separator and then dragging it out of the navbar shouldn't throw -add_task(function*() { - try { - let navbar = document.getElementById("nav-bar"); - let separatorSelector = "toolbarseparator[id^=customizableui-special-separator]"; - ok(!navbar.querySelector(separatorSelector), "Shouldn't be a separator in the navbar"); - CustomizableUI.addWidgetToArea('separator', 'nav-bar'); - yield startCustomizing(); - let separator = navbar.querySelector(separatorSelector); - ok(separator, "There should be a separator in the navbar now."); - let palette = document.getElementById("customization-palette"); - simulateItemDrag(separator, palette); - ok(!palette.querySelector(separatorSelector), "No separator in the palette."); - } catch (ex) { - Cu.reportError(ex); - ok(false, "Shouldn't throw an exception moving an item to the navbar."); - } finally { - yield endCustomizing(); - } -}); - -add_task(function* asyncCleanup() { - resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js b/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js deleted file mode 100644 index 7c4f6cfa4..000000000 --- a/browser/components/customizableui/test/browser_962069_drag_to_overflow_chevron.js +++ /dev/null @@ -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"; - -var originalWindowWidth; - -// Drag to overflow chevron should open the overflow panel. -add_task(function*() { - originalWindowWidth = window.outerWidth; - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - ok(!navbar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - ok(navbar.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - let widgetOverflowPanel = document.getElementById("widget-overflow"); - let panelShownPromise = promisePanelElementShown(window, widgetOverflowPanel); - let identityBox = document.getElementById("identity-box"); - let overflowChevron = document.getElementById("nav-bar-overflow-button"); - - // Listen for hiding immediately so we don't miss the event because of the - // async-ness of the 'shown' yield... - let panelHiddenPromise = promisePanelElementHidden(window, widgetOverflowPanel); - - var ds = Components.classes["@mozilla.org/widget/dragservice;1"]. - getService(Components.interfaces.nsIDragService); - - ds.startDragSession(); - try { - var [result, dataTransfer] = EventUtils.synthesizeDragOver(identityBox, overflowChevron); - - // Wait for showing panel before ending drag session. - yield panelShownPromise; - - EventUtils.synthesizeDropAfterDragOver(result, dataTransfer, overflowChevron); - } finally { - ds.endDragSession(true); - } - - info("Overflow panel is shown."); - - widgetOverflowPanel.hidePopup(); - yield panelHiddenPromise; -}); - -add_task(function*() { - window.resizeTo(originalWindowWidth, window.outerHeight); - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); - ok(!navbar.hasAttribute("overflowing"), "Should not have an overflowing toolbar."); -}); diff --git a/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js b/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js deleted file mode 100644 index cf2603999..000000000 --- a/browser/components/customizableui/test/browser_962884_opt_in_disable_hyphens.js +++ /dev/null @@ -1,67 +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"; - -add_task(function*() { - const kNormalLabel = "Character Encoding"; - CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_NAVBAR); - let characterEncoding = document.getElementById("characterencoding-button"); - const kOriginalLabel = characterEncoding.getAttribute("label"); - characterEncoding.setAttribute("label", "\u00ad" + kNormalLabel); - CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_PANEL); - - yield PanelUI.show(); - - is(characterEncoding.getAttribute("auto-hyphens"), "off", - "Hyphens should be disabled if the ­ character is present in the label"); - let multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text"); - let multilineTextCS = getComputedStyle(multilineText); - is(multilineTextCS.MozHyphens, "manual", "-moz-hyphens should be set to manual when the ­ character is present.") - - let hiddenPanelPromise = promisePanelHidden(window); - PanelUI.toggle(); - yield hiddenPanelPromise; - - characterEncoding.setAttribute("label", kNormalLabel); - - yield PanelUI.show(); - - isnot(characterEncoding.getAttribute("auto-hyphens"), "off", - "Hyphens should not be disabled if the ­ character is not present in the label"); - multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text"); - multilineTextCS = getComputedStyle(multilineText); - is(multilineTextCS.MozHyphens, "auto", "-moz-hyphens should be set to auto by default.") - - hiddenPanelPromise = promisePanelHidden(window); - PanelUI.toggle(); - yield hiddenPanelPromise; - - characterEncoding.setAttribute("label", "\u00ad" + kNormalLabel); - CustomizableUI.removeWidgetFromArea("characterencoding-button"); - yield startCustomizing(); - - isnot(characterEncoding.getAttribute("auto-hyphens"), "off", - "Hyphens should not be disabled when the widget is in the palette"); - - gCustomizeMode.addToPanel(characterEncoding); - is(characterEncoding.getAttribute("auto-hyphens"), "off", - "Hyphens should be disabled if the ­ character is present in the label in customization mode"); - multilineText = document.getAnonymousElementByAttribute(characterEncoding, "class", "toolbarbutton-multiline-text"); - multilineTextCS = getComputedStyle(multilineText); - is(multilineTextCS.MozHyphens, "manual", "-moz-hyphens should be set to manual when the ­ character is present in customization mode.") - - yield endCustomizing(); - - CustomizableUI.addWidgetToArea("characterencoding-button", CustomizableUI.AREA_NAVBAR); - ok(!characterEncoding.hasAttribute("auto-hyphens"), - "Removing the widget from the panel should remove the auto-hyphens attribute"); - - characterEncoding.setAttribute("label", kOriginalLabel); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js b/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js deleted file mode 100644 index e5710c50a..000000000 --- a/browser/components/customizableui/test/browser_963639_customizing_attribute_non_customizable_toolbar.js +++ /dev/null @@ -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/. */ - -"use strict"; - -const kToolbar = "test-toolbar-963639-non-customizable-customizing-attribute"; - -add_task(function*() { - info("Test for Bug 963639 - CustomizeMode _onToolbarVisibilityChange sets @customizing on non-customizable toolbars"); - - let toolbar = document.createElement("toolbar"); - toolbar.id = kToolbar; - gNavToolbox.appendChild(toolbar); - - let testToolbar = document.getElementById(kToolbar) - ok(testToolbar, "Toolbar was created."); - is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 1, - "Toolbar was added to the navigator toolbox"); - - toolbar.setAttribute("toolbarname", "NonCustomizableToolbarCustomizingAttribute"); - toolbar.setAttribute("collapsed", "true"); - - yield startCustomizing(); - window.setToolbarVisibility(toolbar, "true"); - isnot(toolbar.getAttribute("customizing"), "true", - "Toolbar doesn't have the customizing attribute"); - - yield endCustomizing(); - gNavToolbox.removeChild(toolbar); - - is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 0, - "Toolbar was removed from the navigator toolbox"); -}); diff --git a/browser/components/customizableui/test/browser_967000_button_charEncoding.js b/browser/components/customizableui/test/browser_967000_button_charEncoding.js deleted file mode 100644 index 0688ebbd6..000000000 --- a/browser/components/customizableui/test/browser_967000_button_charEncoding.js +++ /dev/null @@ -1,62 +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://mochi.test:8888/browser/browser/components/customizableui/test/support/test_967000_charEncoding_page.html"; - -add_task(function*() { - info("Check Character Encoding button functionality"); - - // add the Character Encoding button to the panel - CustomizableUI.addWidgetToArea("characterencoding-button", - CustomizableUI.AREA_PANEL); - - // check the button's functionality - yield PanelUI.show(); - - let charEncodingButton = document.getElementById("characterencoding-button"); - ok(charEncodingButton, "The Character Encoding button was added to the Panel Menu"); - is(charEncodingButton.getAttribute("disabled"), "true", - "The Character encoding button is initially disabled"); - - let panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - - let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_PAGE, true, true); - - yield PanelUI.show(); - ok(!charEncodingButton.hasAttribute("disabled"), "The Character encoding button gets enabled"); - let characterEncodingView = document.getElementById("PanelUI-characterEncodingView"); - let subviewShownPromise = subviewShown(characterEncodingView); - charEncodingButton.click(); - yield subviewShownPromise; - - ok(characterEncodingView.hasAttribute("current"), "The Character encoding panel is displayed"); - - let pinnedEncodings = document.getElementById("PanelUI-characterEncodingView-pinned"); - let charsetsList = document.getElementById("PanelUI-characterEncodingView-charsets"); - ok(pinnedEncodings, "Pinned charsets are available"); - ok(charsetsList, "Charsets list is available"); - - let checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']"); - is(checkedButtons.length, 2, "There should be 2 checked items (1 charset, 1 detector)."); - is(checkedButtons[0].getAttribute("label"), "Unicode", "The unicode encoding is correctly selected"); - is(characterEncodingView.querySelectorAll("#PanelUI-characterEncodingView-autodetect toolbarbutton[checked='true']").length, - 1, - "There should be 1 checked detector."); - - panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - - yield BrowserTestUtils.removeTab(newTab); -}); - -add_task(function* asyncCleanup() { - // reset the panel to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The UI is in default state again."); -}); diff --git a/browser/components/customizableui/test/browser_967000_button_feeds.js b/browser/components/customizableui/test/browser_967000_button_feeds.js deleted file mode 100644 index 8f391941a..000000000 --- a/browser/components/customizableui/test/browser_967000_button_feeds.js +++ /dev/null @@ -1,60 +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://mochi.test:8888/browser/browser/components/customizableui/test/support/feeds_test_page.html"; -const TEST_FEED = "http://mochi.test:8888/browser/browser/components/customizableui/test/support/test-feed.xml" - -var newTab = null; -var initialLocation = gBrowser.currentURI.spec; - -add_task(function*() { - info("Check Subscribe button functionality"); - - // add the Subscribe button to the panel - CustomizableUI.addWidgetToArea("feed-button", - CustomizableUI.AREA_PANEL); - - // check the button's functionality - yield PanelUI.show(); - - let feedButton = document.getElementById("feed-button"); - ok(feedButton, "The Subscribe button was added to the Panel Menu"); - is(feedButton.getAttribute("disabled"), "true", "The Subscribe button is initially disabled"); - - let panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - - newTab = gBrowser.selectedTab; - yield promiseTabLoadEvent(newTab, TEST_PAGE); - - yield PanelUI.show(); - - yield waitForCondition(() => !feedButton.hasAttribute("disabled")); - ok(!feedButton.hasAttribute("disabled"), "The Subscribe button gets enabled"); - - feedButton.click(); - yield promiseTabLoadEvent(newTab, TEST_FEED); - - is(gBrowser.currentURI.spec, TEST_FEED, "Subscribe page opened"); - ok(!isPanelUIOpen(), "Panel is closed"); - - if (isPanelUIOpen()) { - panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - } -}); - -add_task(function* asyncCleanup() { - // reset the panel UI to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The UI is in default state again."); - - // restore the initial location - gBrowser.addTab(initialLocation); - gBrowser.removeTab(newTab); -}); diff --git a/browser/components/customizableui/test/browser_967000_button_sync.js b/browser/components/customizableui/test/browser_967000_button_sync.js deleted file mode 100644 index 15a3235e0..000000000 --- a/browser/components/customizableui/test/browser_967000_button_sync.js +++ /dev/null @@ -1,335 +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"; - -requestLongerTimeout(2); - -let {SyncedTabs} = Cu.import("resource://services-sync/SyncedTabs.jsm", {}); - -XPCOMUtils.defineLazyModuleGetter(this, "UITour", "resource:///modules/UITour.jsm"); - -// These are available on the widget implementation, but it seems impossible -// to grab that impl at runtime. -const DECKINDEX_TABS = 0; -const DECKINDEX_TABSDISABLED = 1; -const DECKINDEX_FETCHING = 2; -const DECKINDEX_NOCLIENTS = 3; - -var initialLocation = gBrowser.currentURI.spec; -var newTab = null; - -// A helper to notify there are new tabs. Returns a promise that is resolved -// once the UI has been updated. -function updateTabsPanel() { - let promiseTabsUpdated = promiseObserverNotified("synced-tabs-menu:test:tabs-updated"); - Services.obs.notifyObservers(null, SyncedTabs.TOPIC_TABS_CHANGED, null); - return promiseTabsUpdated; -} - -// This is the mock we use for SyncedTabs.jsm - tests may override various -// functions. -let mockedInternal = { - get isConfiguredToSyncTabs() { return true; }, - getTabClients() { return []; }, - syncTabs() {}, - hasSyncedThisSession: false, -}; - - -add_task(function* setup() { - let oldInternal = SyncedTabs._internal; - SyncedTabs._internal = mockedInternal; - - registerCleanupFunction(() => { - SyncedTabs._internal = oldInternal; - }); -}); - -// The test expects the about:preferences#sync page to open in the current tab -function* openPrefsFromMenuPanel(expectedPanelId, entryPoint) { - info("Check Sync button functionality"); - Services.prefs.setCharPref("identity.fxaccounts.remote.signup.uri", "http://example.com/"); - - // add the Sync button to the panel - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - - // check the button's functionality - yield PanelUI.show(); - - if (entryPoint == "uitour") { - UITour.tourBrowsersByWindow.set(window, new Set()); - UITour.tourBrowsersByWindow.get(window).add(gBrowser.selectedBrowser); - } - - let syncButton = document.getElementById("sync-button"); - ok(syncButton, "The Sync button was added to the Panel Menu"); - - syncButton.click(); - let syncPanel = document.getElementById("PanelUI-remotetabs"); - ok(syncPanel.getAttribute("current"), "Sync Panel is in view"); - - // Sync is not configured - verify that state is reflected. - let subpanel = document.getElementById(expectedPanelId) - ok(!subpanel.hidden, "sync setup element is visible"); - - // Find and click the "setup" button. - let setupButton = subpanel.querySelector(".PanelUI-remotetabs-prefs-button"); - setupButton.click(); - - let deferred = Promise.defer(); - let handler = (e) => { - if (e.originalTarget != gBrowser.selectedBrowser.contentDocument || - e.target.location.href == "about:blank") { - info("Skipping spurious 'load' event for " + e.target.location.href); - return; - } - gBrowser.selectedBrowser.removeEventListener("load", handler, true); - deferred.resolve(); - } - gBrowser.selectedBrowser.addEventListener("load", handler, true); - - yield deferred.promise; - newTab = gBrowser.selectedTab; - - is(gBrowser.currentURI.spec, "about:preferences?entrypoint=" + entryPoint + "#sync", - "Firefox Sync preference page opened with `menupanel` entrypoint"); - ok(!isPanelUIOpen(), "The panel closed"); - - if (isPanelUIOpen()) { - let panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - } -} - -function* asyncCleanup() { - Services.prefs.clearUserPref("identity.fxaccounts.remote.signup.uri"); - // reset the panel UI to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The panel UI is in default state again."); - - // restore the tabs - gBrowser.addTab(initialLocation); - gBrowser.removeTab(newTab); - UITour.tourBrowsersByWindow.delete(window); -} - -// When Sync is not setup. -add_task(() => openPrefsFromMenuPanel("PanelUI-remotetabs-setupsync", "synced-tabs")); -add_task(asyncCleanup); - -// When Sync is configured in a "needs reauthentication" state. -add_task(function* () { - // configure our broadcasters so we are in the right state. - document.getElementById("sync-reauth-state").hidden = false; - document.getElementById("sync-setup-state").hidden = true; - document.getElementById("sync-syncnow-state").hidden = true; - yield openPrefsFromMenuPanel("PanelUI-remotetabs-reauthsync", "synced-tabs") -}); - -// Test the mobile promo links -add_task(function* () { - // change the preferences for the mobile links. - Services.prefs.setCharPref("identity.mobilepromo.android", "http://example.com/?os=android&tail="); - Services.prefs.setCharPref("identity.mobilepromo.ios", "http://example.com/?os=ios&tail="); - - mockedInternal.getTabClients = () => []; - mockedInternal.syncTabs = () => Promise.resolve(); - - document.getElementById("sync-reauth-state").hidden = true; - document.getElementById("sync-setup-state").hidden = true; - document.getElementById("sync-syncnow-state").hidden = false; - - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - - let syncPanel = document.getElementById("PanelUI-remotetabs"); - let links = syncPanel.querySelectorAll(".remotetabs-promo-link"); - - is(links.length, 2, "found 2 links as expected"); - - // test each link and left and middle mouse buttons - for (let link of links) { - for (let button = 0; button < 2; button++) { - yield PanelUI.show(); - EventUtils.sendMouseEvent({ type: "click", button }, link, window); - // the panel should have been closed. - ok(!isPanelUIOpen(), "click closed the panel"); - // should be a new tab - wait for the load. - is(gBrowser.tabs.length, 2, "there's a new tab"); - yield new Promise(resolve => { - if (gBrowser.selectedBrowser.currentURI.spec == "about:blank") { - gBrowser.selectedBrowser.addEventListener("load", function listener(e) { - gBrowser.selectedBrowser.removeEventListener("load", listener, true); - resolve(); - }, true); - return; - } - // the new tab has already transitioned away from about:blank so we - // are good to go. - resolve(); - }); - - let os = link.getAttribute("mobile-promo-os"); - let expectedUrl = `http://example.com/?os=${os}&tail=synced-tabs`; - is(gBrowser.selectedBrowser.currentURI.spec, expectedUrl, "correct URL"); - gBrowser.removeTab(gBrowser.selectedTab); - } - } - - // test each link and right mouse button - should be a noop. - yield PanelUI.show(); - for (let link of links) { - EventUtils.sendMouseEvent({ type: "click", button: 2 }, link, window); - // the panel should still be open - ok(isPanelUIOpen(), "panel remains open after right-click"); - is(gBrowser.tabs.length, 1, "no new tab was opened"); - } - PanelUI.hide(); - - Services.prefs.clearUserPref("identity.mobilepromo.android"); - Services.prefs.clearUserPref("identity.mobilepromo.ios"); -}); - -// Test the "Sync Now" button -add_task(function* () { - mockedInternal.getTabClients = () => []; - mockedInternal.syncTabs = () => { - return Promise.resolve(); - } - - // configure our broadcasters so we are in the right state. - document.getElementById("sync-reauth-state").hidden = true; - document.getElementById("sync-setup-state").hidden = true; - document.getElementById("sync-syncnow-state").hidden = false; - - // add the Sync button to the panel - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - yield PanelUI.show(); - document.getElementById("sync-button").click(); - let syncPanel = document.getElementById("PanelUI-remotetabs"); - ok(syncPanel.getAttribute("current"), "Sync Panel is in view"); - - let subpanel = document.getElementById("PanelUI-remotetabs-main") - ok(!subpanel.hidden, "main pane is visible"); - let deck = document.getElementById("PanelUI-remotetabs-deck"); - - // The widget is still fetching tabs, as we've neutered everything that - // provides them - is(deck.selectedIndex, DECKINDEX_FETCHING, "first deck entry is visible"); - - let syncNowButton = document.getElementById("PanelUI-remotetabs-syncnow"); - - let didSync = false; - let oldDoSync = gSyncUI.doSync; - gSyncUI.doSync = function() { - didSync = true; - mockedInternal.hasSyncedThisSession = true; - gSyncUI.doSync = oldDoSync; - } - syncNowButton.click(); - ok(didSync, "clicking the button called the correct function"); - - // Tell the widget there are tabs available, but with zero clients. - mockedInternal.getTabClients = () => { - return Promise.resolve([]); - } - yield updateTabsPanel(); - // The UI should be showing the "no clients" pane. - is(deck.selectedIndex, DECKINDEX_NOCLIENTS, "no-clients deck entry is visible"); - - // Tell the widget there are tabs available - we have 3 clients, one with no - // tabs. - mockedInternal.getTabClients = () => { - return Promise.resolve([ - { - id: "guid_mobile", - type: "client", - name: "My Phone", - tabs: [], - }, - { - id: "guid_desktop", - type: "client", - name: "My Desktop", - tabs: [ - { - title: "http://example.com/10", - lastUsed: 10, // the most recent - }, - { - title: "http://example.com/1", - lastUsed: 1, // the least recent. - }, - { - title: "http://example.com/5", - lastUsed: 5, - }, - ], - }, - { - id: "guid_second_desktop", - name: "My Other Desktop", - tabs: [ - { - title: "http://example.com/6", - lastUsed: 6, - } - ], - }, - ]); - }; - yield updateTabsPanel(); - - // The UI should be showing tabs! - is(deck.selectedIndex, DECKINDEX_TABS, "no-clients deck entry is visible"); - let tabList = document.getElementById("PanelUI-remotetabs-tabslist"); - let node = tabList.firstChild; - // First entry should be the client with the most-recent tab. - is(node.getAttribute("itemtype"), "client", "node is a client entry"); - is(node.textContent, "My Desktop", "correct client"); - // Next entry is the most-recent tab - node = node.nextSibling; - is(node.getAttribute("itemtype"), "tab", "node is a tab"); - is(node.getAttribute("label"), "http://example.com/10"); - - // Next entry is the next-most-recent tab - node = node.nextSibling; - is(node.getAttribute("itemtype"), "tab", "node is a tab"); - is(node.getAttribute("label"), "http://example.com/5"); - - // Next entry is the least-recent tab from the first client. - node = node.nextSibling; - is(node.getAttribute("itemtype"), "tab", "node is a tab"); - is(node.getAttribute("label"), "http://example.com/1"); - - // Next is a menuseparator between the clients. - node = node.nextSibling; - is(node.nodeName, "menuseparator"); - - // Next is the client with 1 tab. - node = node.nextSibling; - is(node.getAttribute("itemtype"), "client", "node is a client entry"); - is(node.textContent, "My Other Desktop", "correct client"); - // Its single tab - node = node.nextSibling; - is(node.getAttribute("itemtype"), "tab", "node is a tab"); - is(node.getAttribute("label"), "http://example.com/6"); - - // Next is a menuseparator between the clients. - node = node.nextSibling; - is(node.nodeName, "menuseparator"); - - // Next is the client with no tab. - node = node.nextSibling; - is(node.getAttribute("itemtype"), "client", "node is a client entry"); - is(node.textContent, "My Phone", "correct client"); - // There is a single node saying there's no tabs for the client. - node = node.nextSibling; - is(node.nodeName, "label", "node is a label"); - is(node.getAttribute("itemtype"), "", "node is neither a tab nor a client"); - - node = node.nextSibling; - is(node, null, "no more entries"); -}); diff --git a/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js b/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js deleted file mode 100644 index 88c30bf81..000000000 --- a/browser/components/customizableui/test/browser_968447_bookmarks_toolbar_items_in_panel.js +++ /dev/null @@ -1,65 +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"; - -// Bug 968447 - The Bookmarks Toolbar Items doesn't appear as a -// normal menu panel button in new windows. -add_task(function*() { - const buttonId = "bookmarks-toolbar-placeholder"; - yield startCustomizing(); - CustomizableUI.addWidgetToArea("personal-bookmarks", CustomizableUI.AREA_PANEL); - yield endCustomizing(); - - yield PanelUI.show(); - - let bookmarksToolbarPlaceholder = document.getElementById(buttonId); - ok(bookmarksToolbarPlaceholder.classList.contains("toolbarbutton-1"), - "Button should have toolbarbutton-1 class"); - is(bookmarksToolbarPlaceholder.getAttribute("wrap"), "true", - "Button should have the 'wrap' attribute"); - - info("Waiting for panel to close"); - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - - info("Waiting for window to open"); - let newWin = yield openAndLoadWindow({}, true); - - info("Waiting for panel in new window to open"); - let hideTrace = function() { - info(new Error().stack); - info("Panel was hidden."); - }; - newWin.PanelUI.panel.addEventListener("popuphidden", hideTrace); - - yield newWin.PanelUI.show(); - let newWinBookmarksToolbarPlaceholder = newWin.document.getElementById(buttonId); - ok(newWinBookmarksToolbarPlaceholder.classList.contains("toolbarbutton-1"), - "Button in new window should have toolbarbutton-1 class"); - is(newWinBookmarksToolbarPlaceholder.getAttribute("wrap"), "true", - "Button in new window should have 'wrap' attribute"); - - newWin.PanelUI.panel.removeEventListener("popuphidden", hideTrace); - // XXXgijs on Linux, we're sometimes seeing the panel being hidden early - // in the newly created window, probably because something else steals focus. - if (newWin.PanelUI.panel.state != "closed") { - info("Panel is still open in new window, waiting for it to close"); - panelHiddenPromise = promisePanelHidden(newWin); - newWin.PanelUI.hide(); - yield panelHiddenPromise; - } else { - info("panel was already closed"); - } - - info("Waiting for new window to close"); - yield promiseWindowClosed(newWin); -}); - -add_task(function* asyncCleanUp() { - yield endCustomizing(); - CustomizableUI.reset(); -}); - diff --git a/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js b/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js deleted file mode 100644 index f7504fc41..000000000 --- a/browser/components/customizableui/test/browser_968565_insert_before_hidden_items.js +++ /dev/null @@ -1,56 +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 kHidden1Id = "test-hidden-button-1"; -const kHidden2Id = "test-hidden-button-2"; - -var navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - -// When we drag an item onto a customizable area, and not over a specific target, we -// should assume that we're appending them to the area. If doing so, we should scan -// backwards over any hidden items and insert the item before those hidden items. -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Should be in the default state"); - - // Iterate backwards over the items in the nav-bar until we find the first - // one that is not hidden. - let placements = CustomizableUI.getWidgetsInArea(CustomizableUI.AREA_NAVBAR); - let lastVisible = null; - for (let widgetGroup of placements.reverse()) { - let widget = widgetGroup.forWindow(window); - if (widget && widget.node && !widget.node.hidden) { - lastVisible = widget.node; - break; - } - } - - if (!lastVisible) { - ok(false, "Apparently, there are no visible items in the nav-bar."); - } - - info("The last visible item in the nav-bar has ID: " + lastVisible.id); - - let hidden1 = createDummyXULButton(kHidden1Id, "You can't see me"); - let hidden2 = createDummyXULButton(kHidden2Id, "You can't see me either."); - hidden1.hidden = hidden2.hidden = true; - - // Make sure we have some hidden items at the end of the nav-bar. - navbar.insertItem(hidden1.id); - navbar.insertItem(hidden2.id); - - // Drag an item and drop it onto the nav-bar customization target, but - // not over a particular item. - yield startCustomizing(); - let downloadsButton = document.getElementById("downloads-button"); - simulateItemDrag(downloadsButton, navbar.customizationTarget); - - yield endCustomizing(); - - is(downloadsButton.previousSibling.id, lastVisible.id, - "The downloads button should be placed after the last visible item."); - - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js b/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js deleted file mode 100644 index b5479fcb7..000000000 --- a/browser/components/customizableui/test/browser_969427_recreate_destroyed_widget_after_reset.js +++ /dev/null @@ -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/. */ - -"use strict"; - -function getPlacementArea(id) { - let placement = CustomizableUI.getPlacementOfWidget(id); - return placement && placement.area; -} - -// Check that a destroyed widget recreated after a reset call goes to -// the navigation bar. -add_task(function() { - const kWidgetId = "test-recreate-after-reset"; - let spec = {id: kWidgetId, label: "Test re-create after reset.", - removable: true, defaultArea: CustomizableUI.AREA_NAVBAR}; - - CustomizableUI.createWidget(spec); - is(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR, - "widget is in the navigation bar"); - - CustomizableUI.destroyWidget(kWidgetId); - isnot(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR, - "widget removed from the navigation bar"); - - CustomizableUI.reset(); - - CustomizableUI.createWidget(spec); - is(getPlacementArea(kWidgetId), CustomizableUI.AREA_NAVBAR, - "widget recreated and added back to the nav bar"); - - CustomizableUI.destroyWidget(kWidgetId); -}); diff --git a/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js b/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js deleted file mode 100644 index 6f057a100..000000000 --- a/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js +++ /dev/null @@ -1,26 +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"; - - -// Adding the character encoding menu to the panel, exiting customize mode, -// and moving it to the nav-bar should have it enabled, not disabled. -add_task(function*() { - yield startCustomizing(); - CustomizableUI.addWidgetToArea("characterencoding-button", "PanelUI-contents"); - yield endCustomizing(); - yield PanelUI.show(); - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - CustomizableUI.addWidgetToArea("characterencoding-button", 'nav-bar'); - let button = document.getElementById("characterencoding-button"); - ok(!button.hasAttribute("disabled"), "Button shouldn't be disabled"); -}); - -add_task(function asyncCleanup() { - resetCustomization(); -}); - diff --git a/browser/components/customizableui/test/browser_970511_undo_restore_default.js b/browser/components/customizableui/test/browser_970511_undo_restore_default.js deleted file mode 100644 index e7b3ca674..000000000 --- a/browser/components/customizableui/test/browser_970511_undo_restore_default.js +++ /dev/null @@ -1,128 +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"; - -requestLongerTimeout(2); - -// Restoring default should reset theme and show an "undo" option which undoes the restoring operation. -add_task(function*() { - let homeButtonId = "home-button"; - CustomizableUI.removeWidgetFromArea(homeButtonId); - yield startCustomizing(); - ok(!CustomizableUI.inDefaultState, "Not in default state to begin with"); - is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette"); - let undoResetButton = document.getElementById("customization-undo-reset-button"); - is(undoResetButton.hidden, true, "The undo button is hidden before reset"); - - let themesButton = document.getElementById("customization-lwtheme-button"); - let popup = document.getElementById("customization-lwtheme-menu"); - let popupShownPromise = popupShown(popup); - EventUtils.synthesizeMouseAtCenter(themesButton, {}); - info("Clicked on themes button"); - yield popupShownPromise; - - let recommendedHeader = document.getElementById("customization-lwtheme-menu-recommended"); - let firstLWTheme = recommendedHeader.nextSibling; - let firstLWThemeId = firstLWTheme.theme.id; - let themeChangedPromise = promiseObserverNotified("lightweight-theme-changed"); - firstLWTheme.doCommand(); - info("Clicked on first theme"); - yield themeChangedPromise; - - is(LightweightThemeManager.currentTheme.id, firstLWThemeId, "Theme changed to first option"); - - yield gCustomizeMode.reset(); - - ok(CustomizableUI.inDefaultState, "In default state after reset"); - is(undoResetButton.hidden, false, "The undo button is visible after reset"); - is(LightweightThemeManager.currentTheme, null, "Theme reset to default"); - - yield gCustomizeMode.undoReset() - - is(LightweightThemeManager.currentTheme.id, firstLWThemeId, "Theme has been reset from default to original choice"); - ok(!CustomizableUI.inDefaultState, "Not in default state after undo-reset"); - is(undoResetButton.hidden, true, "The undo button is hidden after clicking on the undo button"); - is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette"); - - yield gCustomizeMode.reset(); -}); - -// Performing an action after a reset will hide the reset button. -add_task(function*() { - let homeButtonId = "home-button"; - CustomizableUI.removeWidgetFromArea(homeButtonId); - ok(!CustomizableUI.inDefaultState, "Not in default state to begin with"); - is(CustomizableUI.getPlacementOfWidget(homeButtonId), null, "Home button is in palette"); - let undoResetButton = document.getElementById("customization-undo-reset-button"); - is(undoResetButton.hidden, true, "The undo button is hidden before reset"); - - yield gCustomizeMode.reset(); - - ok(CustomizableUI.inDefaultState, "In default state after reset"); - is(undoResetButton.hidden, false, "The undo button is visible after reset"); - - CustomizableUI.addWidgetToArea(homeButtonId, CustomizableUI.AREA_PANEL); - is(undoResetButton.hidden, true, "The undo button is hidden after another change"); -}); - -// "Restore defaults", exiting customize, and re-entering shouldn't show the Undo button -add_task(function*() { - let undoResetButton = document.getElementById("customization-undo-reset-button"); - is(undoResetButton.hidden, true, "The undo button is hidden before a reset"); - ok(!CustomizableUI.inDefaultState, "The browser should not be in default state"); - yield gCustomizeMode.reset(); - - is(undoResetButton.hidden, false, "The undo button is visible after a reset"); - yield endCustomizing(); - yield startCustomizing(); - is(undoResetButton.hidden, true, "The undo reset button should be hidden after entering customization mode"); -}); - -// Bug 971626 - Restore Defaults should collapse the Title Bar -add_task(function*() { - if (Services.appinfo.OS != "WINNT" && - Services.appinfo.OS != "Darwin") { - return; - } - let prefName = "browser.tabs.drawInTitlebar"; - let defaultValue = Services.prefs.getBoolPref(prefName); - let restoreDefaultsButton = document.getElementById("customization-reset-button"); - let titleBarButton = document.getElementById("customization-titlebar-visibility-button"); - let undoResetButton = document.getElementById("customization-undo-reset-button"); - ok(CustomizableUI.inDefaultState, "Should be in default state at start of test"); - ok(restoreDefaultsButton.disabled, "Restore defaults button should be disabled when in default state"); - is(titleBarButton.hasAttribute("checked"), !defaultValue, "Title bar button should reflect pref value"); - is(undoResetButton.hidden, true, "Undo reset button should be hidden at start of test"); - - Services.prefs.setBoolPref(prefName, !defaultValue); - ok(!restoreDefaultsButton.disabled, "Restore defaults button should be enabled when pref changed"); - is(titleBarButton.hasAttribute("checked"), defaultValue, "Title bar button should reflect changed pref value"); - ok(!CustomizableUI.inDefaultState, "With titlebar flipped, no longer default"); - is(undoResetButton.hidden, true, "Undo reset button should be hidden after pref change"); - - yield gCustomizeMode.reset(); - ok(restoreDefaultsButton.disabled, "Restore defaults button should be disabled after reset"); - is(titleBarButton.hasAttribute("checked"), !defaultValue, "Title bar button should reflect default value after reset"); - is(Services.prefs.getBoolPref(prefName), defaultValue, "Reset should reset drawInTitlebar"); - ok(CustomizableUI.inDefaultState, "In default state after titlebar reset"); - is(undoResetButton.hidden, false, "Undo reset button should be visible after reset"); - ok(!undoResetButton.disabled, "Undo reset button should be enabled after reset"); - - yield gCustomizeMode.undoReset(); - ok(!restoreDefaultsButton.disabled, "Restore defaults button should be enabled after undo-reset"); - is(titleBarButton.hasAttribute("checked"), defaultValue, "Title bar button should reflect undo-reset value"); - ok(!CustomizableUI.inDefaultState, "No longer in default state after undo"); - is(Services.prefs.getBoolPref(prefName), !defaultValue, "Undo-reset goes back to previous pref value"); - is(undoResetButton.hidden, true, "Undo reset button should be hidden after undo-reset clicked"); - - Services.prefs.clearUserPref(prefName); - ok(CustomizableUI.inDefaultState, "In default state after pref cleared"); - is(undoResetButton.hidden, true, "Undo reset button should be hidden at end of test"); -}); - -add_task(function* asyncCleanup() { - yield gCustomizeMode.reset(); - yield endCustomizing(); -}); diff --git a/browser/components/customizableui/test/browser_972267_customizationchange_events.js b/browser/components/customizableui/test/browser_972267_customizationchange_events.js deleted file mode 100644 index b37dbe954..000000000 --- a/browser/components/customizableui/test/browser_972267_customizationchange_events.js +++ /dev/null @@ -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/. */ - -"use strict"; - -// Create a new window, then move the home button to the menu and check both windows have -// customizationchange events fire on the toolbox: -add_task(function*() { - let newWindow = yield openAndLoadWindow(); - let otherToolbox = newWindow.gNavToolbox; - - let handlerCalledCount = 0; - let handler = (ev) => { - handlerCalledCount++; - }; - - let homeButton = document.getElementById("home-button"); - - gNavToolbox.addEventListener("customizationchange", handler); - otherToolbox.addEventListener("customizationchange", handler); - - gCustomizeMode.addToPanel(homeButton); - - is(handlerCalledCount, 2, "Should be called for both windows."); - - // If the test is run in isolation and the panel has never been open, - // the button will be in the palette. Deal with this case: - if (homeButton.parentNode.id == "BrowserToolbarPalette") { - yield PanelUI.ensureReady(); - isnot(homeButton.parentNode.id, "BrowserToolbarPalette", "Home button should now be in panel"); - } - - handlerCalledCount = 0; - gCustomizeMode.addToToolbar(homeButton); - is(handlerCalledCount, 2, "Should be called for both windows."); - - gNavToolbox.removeEventListener("customizationchange", handler); - otherToolbox.removeEventListener("customizationchange", handler); - - yield promiseWindowClosed(newWindow); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_973641_button_addon.js b/browser/components/customizableui/test/browser_973641_button_addon.js deleted file mode 100755 index 796bf3d0e..000000000 --- a/browser/components/customizableui/test/browser_973641_button_addon.js +++ /dev/null @@ -1,71 +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 kButton = "test_button_for_addon"; -var initialLocation = gBrowser.currentURI.spec; - -add_task(function*() { - info("Check addon button functionality"); - - // create mocked addon button on the navigation bar - let widgetSpec = { - id: kButton, - type: 'button', - onClick: function() { - gBrowser.selectedTab = gBrowser.addTab("about:addons"); - } - }; - CustomizableUI.createWidget(widgetSpec); - CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_NAVBAR); - - // check the button's functionality in navigation bar - let addonButton = document.getElementById(kButton); - let navBar = document.getElementById("nav-bar"); - ok(addonButton, "Addon button exists"); - ok(navBar.contains(addonButton), "Addon button is in the navbar"); - yield checkButtonFunctionality(addonButton); - - resetTabs(); - - // move the add-on button in the Panel Menu - CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_PANEL); - ok(!navBar.contains(addonButton), "Addon button was removed from the browser bar"); - - // check the addon button's functionality in the Panel Menu - yield PanelUI.show(); - var panelMenu = document.getElementById("PanelUI-mainView"); - let addonButtonInPanel = panelMenu.getElementsByAttribute("id", kButton); - ok(panelMenu.contains(addonButton), "Addon button was added to the Panel Menu"); - yield checkButtonFunctionality(addonButtonInPanel[0]); -}); - -add_task(function* asyncCleanup() { - resetTabs(); - - // reset the UI to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The UI is in default state again."); - - // destroy the widget - CustomizableUI.destroyWidget(kButton); -}); - -function resetTabs() { - // close all opened tabs - while (gBrowser.tabs.length > 1) { - gBrowser.removeTab(gBrowser.selectedTab); - } - - // restore the initial tab - gBrowser.addTab(initialLocation); - gBrowser.removeTab(gBrowser.selectedTab); -} - -function* checkButtonFunctionality(aButton) { - aButton.click(); - yield waitForCondition(() => gBrowser.currentURI && - gBrowser.currentURI.spec == "about:addons"); -} diff --git a/browser/components/customizableui/test/browser_973932_addonbar_currentset.js b/browser/components/customizableui/test/browser_973932_addonbar_currentset.js deleted file mode 100644 index 66fa6ef47..000000000 --- a/browser/components/customizableui/test/browser_973932_addonbar_currentset.js +++ /dev/null @@ -1,30 +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"; - -var addonbarID = CustomizableUI.AREA_ADDONBAR; -var addonbar = document.getElementById(addonbarID); - -// Check that currentset is correctly updated after a reset: -add_task(function*() { - let placements = CustomizableUI.getWidgetIdsInArea(addonbarID); - is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements"); - ok(CustomizableUI.inDefaultState, "Should be in default state"); - info("Adding a spring to add-on bar shim"); - CustomizableUI.addWidgetToArea("spring", addonbarID, 1); - ok(addonbar.getElementsByTagName("toolbarspring").length, "There should be a spring in the toolbar"); - ok(!CustomizableUI.inDefaultState, "Should no longer be in default state"); - placements = CustomizableUI.getWidgetIdsInArea(addonbarID); - is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match placements after spring addition"); - - yield startCustomizing(); - yield gCustomizeMode.reset(); - ok(CustomizableUI.inDefaultState, "Should be in default state after reset"); - placements = CustomizableUI.getWidgetIdsInArea(addonbarID); - is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements after reset"); - ok(!addonbar.getElementsByTagName("toolbarspring").length, "There should be no spring in the toolbar"); - yield endCustomizing(); -}); - diff --git a/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js b/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js deleted file mode 100644 index 73fc7c1ff..000000000 --- a/browser/components/customizableui/test/browser_975719_customtoolbars_behaviour.js +++ /dev/null @@ -1,145 +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"; - -requestLongerTimeout(2); - -const kXULWidgetId = "a-test-button"; // we'll create a button with this ID. - -add_task(function setup() { - // create a XUL button and add it to the palette. - createDummyXULButton(kXULWidgetId, "test-button"); -}); - -add_task(function* customizeToolbarAndKeepIt() { - ok(gNavToolbox.toolbarset, "There should be a toolbarset"); - let toolbarID = "testAustralisCustomToolbar"; - gNavToolbox.appendCustomToolbar(toolbarID, ""); - let toolbarDOMID = getToolboxCustomToolbarId(toolbarID); - let toolbarElement = document.getElementById(toolbarDOMID); - ok(toolbarElement, "There should be a toolbar"); - if (!toolbarElement) { - ok(false, "No toolbar created, bailing out of the test."); - return; - } - is(toolbarElement.nextSibling, gNavToolbox.toolbarset, - "Toolbar should have been inserted in toolbox, before toolbarset element"); - let cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID); - is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR, - "CustomizableUI should know the area and think it's a toolbar"); - if (cuiAreaType != CustomizableUI.TYPE_TOOLBAR) { - ok(false, "Toolbar not registered successfully, bailing out of the test."); - toolbarElement.remove(); - return; - } - ok(!CustomizableUI.getWidgetIdsInArea(toolbarDOMID).length, "There should be no widgets in the area yet."); - CustomizableUI.addWidgetToArea("open-file-button", toolbarDOMID, 0); - ok(toolbarElement.hasChildNodes(), "Toolbar should now have a button."); - assertAreaPlacements(toolbarDOMID, ["open-file-button"]); - - gNavToolbox.toolbarset.setAttribute("toolbar1", toolbarID + ":open-file-button"); - document.persist(gNavToolbox.toolbarset.id, "toolbar1"); - - yield startCustomizing(); - // First, exit customize mode without doing anything, and verify the toolbar doesn't get removed. - yield endCustomizing(); - ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state, the toolbar should still be there."); - cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID); - is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR, - "CustomizableUI should still know the area and think it's a toolbar"); - ok(toolbarElement.parentNode, "Toolbar should still be in the DOM."); - ok(toolbarElement.hasChildNodes(), "Toolbar should still have items in it."); - assertAreaPlacements(toolbarDOMID, ["open-file-button"]); - - let newWindow = yield openAndLoadWindow({}, true); - is(newWindow.gNavToolbox.toolbarset.getAttribute("toolbar1"), - gNavToolbox.toolbarset.getAttribute("toolbar1"), - "Attribute should be the same in new window"); - yield promiseWindowClosed(newWindow); - - // Then customize again, and this time empty out the toolbar and verify it *does* get removed. - yield startCustomizing(); - let openFileButton = document.getElementById("open-file-button"); - let palette = document.getElementById("customization-palette"); - simulateItemDrag(openFileButton, palette); - ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state because there's still a non-collapsed toolbar."); - ok(!toolbarElement.hasChildNodes(), "Toolbar should have no more child nodes."); - - toolbarElement.collapsed = true; - ok(CustomizableUI.inDefaultState, "Should be in default state because there's now just a collapsed toolbar."); - toolbarElement.collapsed = false; - ok(!CustomizableUI.inDefaultState, "Shouldn't be in default state because there's a non-collapsed toolbar again."); - yield endCustomizing(); - ok(CustomizableUI.inDefaultState, "Should be in default state because the toolbar should have been removed."); - - newWindow = yield openAndLoadWindow({}, true); - ok(!newWindow.gNavToolbox.toolbarset.hasAttribute("toolbar1"), - "Attribute should be gone in new window"); - yield promiseWindowClosed(newWindow); - - ok(!toolbarElement.parentNode, "Toolbar should no longer be in the DOM."); - cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID); - is(cuiAreaType, null, "CustomizableUI should have forgotten all about the area"); -}); - -add_task(function* resetShouldDealWithCustomToolbars() { - ok(gNavToolbox.toolbarset, "There should be a toolbarset"); - let toolbarID = "testAustralisCustomToolbar"; - gNavToolbox.appendCustomToolbar(toolbarID, ""); - let toolbarDOMID = getToolboxCustomToolbarId(toolbarID); - let toolbarElement = document.getElementById(toolbarDOMID); - ok(toolbarElement, "There should be a toolbar"); - if (!toolbarElement) { - ok(false, "No toolbar created, bailing out of the test."); - return; - } - is(toolbarElement.nextSibling, gNavToolbox.toolbarset, - "Toolbar should have been inserted in toolbox, before toolbarset element"); - let cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID); - is(cuiAreaType, CustomizableUI.TYPE_TOOLBAR, - "CustomizableUI should know the area and think it's a toolbar"); - if (cuiAreaType != CustomizableUI.TYPE_TOOLBAR) { - ok(false, "Toolbar not registered successfully, bailing out of the test."); - toolbarElement.remove(); - return; - } - ok(!CustomizableUI.getWidgetIdsInArea(toolbarDOMID).length, "There should be no widgets in the area yet."); - CustomizableUI.addWidgetToArea(kXULWidgetId, toolbarDOMID, 0); - ok(toolbarElement.hasChildNodes(), "Toolbar should now have a button."); - assertAreaPlacements(toolbarDOMID, [kXULWidgetId]); - - gNavToolbox.toolbarset.setAttribute("toolbar2", `${toolbarID}:${kXULWidgetId}`); - document.persist(gNavToolbox.toolbarset.id, "toolbar2"); - - let newWindow = yield openAndLoadWindow({}, true); - is(newWindow.gNavToolbox.toolbarset.getAttribute("toolbar2"), - gNavToolbox.toolbarset.getAttribute("toolbar2"), - "Attribute should be the same in new window"); - yield promiseWindowClosed(newWindow); - - CustomizableUI.reset(); - - newWindow = yield openAndLoadWindow({}, true); - ok(!newWindow.gNavToolbox.toolbarset.hasAttribute("toolbar2"), - "Attribute should be gone in new window"); - yield promiseWindowClosed(newWindow); - - ok(CustomizableUI.inDefaultState, "Should be in default state after reset."); - let xulButton = document.getElementById(kXULWidgetId); - ok(!xulButton, "XUL button shouldn't be in the document anymore."); - ok(gNavToolbox.palette.querySelector(`#${kXULWidgetId}`), "XUL button should be in the palette"); - ok(!toolbarElement.hasChildNodes(), "Toolbar should have no more child nodes."); - ok(!toolbarElement.parentNode, "Toolbar should no longer be in the DOM."); - cuiAreaType = CustomizableUI.getAreaType(toolbarDOMID); - is(cuiAreaType, null, "CustomizableUI should have forgotten all about the area"); -}); - - -add_task(function*() { - let newWin = yield openAndLoadWindow({}, true); - ok(!newWin.gNavToolbox.toolbarset.hasAttribute("toolbar1"), "New window shouldn't have attribute toolbar1"); - ok(!newWin.gNavToolbox.toolbarset.hasAttribute("toolbar2"), "New window shouldn't have attribute toolbar2"); - yield promiseWindowClosed(newWin); -}); diff --git a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js b/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js deleted file mode 100644 index 3bfa8c25d..000000000 --- a/browser/components/customizableui/test/browser_976792_insertNodeInWindow.js +++ /dev/null @@ -1,414 +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 kToolbarName = "test-insertNodeInWindow-placements-toolbar"; -const kTestWidgetPrefix = "test-widget-for-insertNodeInWindow-placements-"; - - -/* -Tries to replicate the situation of having a placement list like this: - -exists-1,trying-to-insert-this,doesn't-exist,exists-2 -*/ -add_task(function*() { - let testWidgetExists = [true, false, false, true]; - let widgetIds = []; - for (let i = 0; i < testWidgetExists.length; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - if (testWidgetExists[i]) { - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - } - } - - let toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds); - assertAreaPlacements(kToolbarName, widgetIds); - - let btnId = kTestWidgetPrefix + 1; - let btn = createDummyXULButton(btnId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(btnId, window); - - is(btn.parentNode.id, kToolbarName, "New XUL widget should be placed inside new toolbar"); - - is(btn.previousSibling.id, toolbarNode.firstChild.id, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - btn.remove(); - removeCustomToolbars(); - yield resetCustomization(); -}); - - -/* -Tests nodes get placed inside the toolbar's overflow as expected. Replicates a -situation similar to: - -exists-1,exists-2,overflow-1,trying-to-insert-this,overflow-2 -*/ -add_task(function*() { - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - - let widgetIds = []; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - CustomizableUI.addWidgetToArea(id, "nav-bar"); - } - - for (let id of widgetIds) { - document.getElementById(id).style.minWidth = "200px"; - } - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - - let testWidgetId = kTestWidgetPrefix + 3; - - CustomizableUI.destroyWidget(testWidgetId); - - let btn = createDummyXULButton(testWidgetId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window); - - is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar"); - is(btn.previousSibling.id, kTestWidgetPrefix + 2, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - is(btn.nextSibling.id, kTestWidgetPrefix + 4, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName); - btn.remove(); - yield resetCustomization(); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); -}); - - -/* -Tests nodes get placed inside the toolbar's overflow as expected. Replicates a -placements situation similar to: - -exists-1,exists-2,overflow-1,doesn't-exist,trying-to-insert-this,overflow-2 -*/ -add_task(function*() { - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - - let widgetIds = []; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - CustomizableUI.addWidgetToArea(id, "nav-bar"); - } - - for (let id of widgetIds) { - document.getElementById(id).style.minWidth = "200px"; - } - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - - let testWidgetId = kTestWidgetPrefix + 3; - - CustomizableUI.destroyWidget(kTestWidgetPrefix + 2); - CustomizableUI.destroyWidget(testWidgetId); - - let btn = createDummyXULButton(testWidgetId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window); - - is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar"); - is(btn.previousSibling.id, kTestWidgetPrefix + 1, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - is(btn.nextSibling.id, kTestWidgetPrefix + 4, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName); - btn.remove(); - yield resetCustomization(); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); -}); - - -/* -Tests nodes get placed inside the toolbar's overflow as expected. Replicates a -placements situation similar to: - -exists-1,exists-2,overflow-1,doesn't-exist,trying-to-insert-this,doesn't-exist -*/ -add_task(function*() { - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - - let widgetIds = []; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - CustomizableUI.addWidgetToArea(id, "nav-bar"); - } - - for (let id of widgetIds) { - document.getElementById(id).style.minWidth = "200px"; - } - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - - let testWidgetId = kTestWidgetPrefix + 3; - - CustomizableUI.destroyWidget(kTestWidgetPrefix + 2); - CustomizableUI.destroyWidget(testWidgetId); - CustomizableUI.destroyWidget(kTestWidgetPrefix + 4); - - let btn = createDummyXULButton(testWidgetId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window); - - is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar"); - is(btn.previousSibling.id, kTestWidgetPrefix + 1, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - is(btn.nextSibling, null, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName); - btn.remove(); - yield resetCustomization(); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); -}); - - -/* -Tests nodes get placed inside the toolbar's overflow as expected. Replicates a -placements situation similar to: - -exists-1,exists-2,overflow-1,can't-overflow,trying-to-insert-this,overflow-2 -*/ -add_task(function*() { - let navbar = document.getElementById(CustomizableUI.AREA_NAVBAR); - - let widgetIds = []; - for (let i = 5; i >= 0; i--) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - CustomizableUI.addWidgetToArea(id, "nav-bar", 0); - } - - for (let i = 10; i < 15; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "insertNodeInWindow test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - CustomizableUI.addWidgetToArea(id, "nav-bar"); - } - - for (let id of widgetIds) { - document.getElementById(id).style.minWidth = "200px"; - } - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => navbar.hasAttribute("overflowing")); - - // Find last widget that doesn't allow overflowing - let nonOverflowing = navbar.customizationTarget.lastChild; - is(nonOverflowing.getAttribute("overflows"), "false", "Last child is expected to not allow overflowing"); - isnot(nonOverflowing.getAttribute("skipintoolbarset"), "true", "Last child is expected to not be skipintoolbarset"); - - let testWidgetId = kTestWidgetPrefix + 10; - CustomizableUI.destroyWidget(testWidgetId); - - let btn = createDummyXULButton(testWidgetId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(testWidgetId, window); - - is(btn.parentNode.id, navbar.overflowable._list.id, "New XUL widget should be placed inside overflow of toolbar"); - is(btn.nextSibling.id, kTestWidgetPrefix + 11, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - CustomizableUI.removeWidgetFromArea(btn.id, kToolbarName); - btn.remove(); - yield resetCustomization(); - yield waitForCondition(() => !navbar.hasAttribute("overflowing")); -}); - - -/* -Tests nodes get placed inside the toolbar's overflow as expected. Replicates a -placements situation similar to: - -exists-1,exists-2,overflow-1,trying-to-insert-this,can't-overflow,overflow-2 -*/ -add_task(function*() { - let widgetIds = []; - let missingId = 2; - let nonOverflowableId = 3; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - if (i != missingId) { - // Setting min-width to make the overflow state not depend on styling of the button and/or - // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { - node.style.minWidth = "200px"; - if (id == (kTestWidgetPrefix + nonOverflowableId)) { - node.setAttribute("overflows", false); - } - }}; - info("Creating: " + id); - CustomizableUI.createWidget(spec); - } - } - - let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds); - assertAreaPlacements(kToolbarName, widgetIds); - ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with."); - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => toolbarNode.hasAttribute("overflowing")); - ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - let btnId = kTestWidgetPrefix + missingId; - let btn = createDummyXULButton(btnId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(btnId, window); - - is(btn.parentNode.id, kToolbarName + "-overflow-list", "New XUL widget should be placed inside new toolbar's overflow"); - is(btn.previousSibling.id, kTestWidgetPrefix + 1, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - is(btn.nextSibling.id, kTestWidgetPrefix + 4, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing")); - - btn.remove(); - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - removeCustomToolbars(); - yield resetCustomization(); -}); - - -/* -Tests nodes do *not* get placed in the toolbar's overflow. Replicates a -plcements situation similar to: - -exists-1,trying-to-insert-this,exists-2,overflowed-1 -*/ -add_task(function*() { - let widgetIds = []; - let missingId = 1; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - if (i != missingId) { - // Setting min-width to make the overflow state not depend on styling of the button and/or - // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "100px"; }}; - info("Creating: " + id); - CustomizableUI.createWidget(spec); - } - } - - let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds); - assertAreaPlacements(kToolbarName, widgetIds); - ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with."); - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => toolbarNode.hasAttribute("overflowing")); - ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - let btnId = kTestWidgetPrefix + missingId; - let btn = createDummyXULButton(btnId, "test"); - CustomizableUI.ensureWidgetPlacedInWindow(btnId, window); - - is(btn.parentNode.id, kToolbarName + "-target", "New XUL widget should be placed inside new toolbar"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing")); - - btn.remove(); - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - removeCustomToolbars(); - yield resetCustomization(); -}); - - -/* -Tests inserting a node onto the end of an overflowing toolbar *doesn't* put it in -the overflow list when the widget disallows overflowing. ie: - -exists-1,exists-2,overflows-1,trying-to-insert-this - -Where trying-to-insert-this has overflows=false -*/ -add_task(function*() { - let widgetIds = []; - let missingId = 3; - for (let i = 0; i < 5; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - if (i != missingId) { - // Setting min-width to make the overflow state not depend on styling of the button and/or - // screen width - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i, - onCreated: function(node) { node.style.minWidth = "200px"; }}; - info("Creating: " + id); - CustomizableUI.createWidget(spec); - } - } - - let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds); - assertAreaPlacements(kToolbarName, widgetIds); - ok(!toolbarNode.hasAttribute("overflowing"), "Toolbar shouldn't overflow to start with."); - - let originalWindowWidth = window.outerWidth; - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => toolbarNode.hasAttribute("overflowing")); - ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - - let btnId = kTestWidgetPrefix + missingId; - let btn = createDummyXULButton(btnId, "test"); - btn.setAttribute("overflows", false); - CustomizableUI.ensureWidgetPlacedInWindow(btnId, window); - - is(btn.parentNode.id, kToolbarName + "-target", "New XUL widget should be placed inside new toolbar"); - is(btn.nextSibling, null, - "insertNodeInWindow should have placed new XUL widget in correct place in DOM according to placements"); - - window.resizeTo(originalWindowWidth, window.outerHeight); - yield waitForCondition(() => !toolbarNode.hasAttribute("overflowing")); - - btn.remove(); - widgetIds.forEach(id => CustomizableUI.destroyWidget(id)); - removeCustomToolbars(); - yield resetCustomization(); -}); - - -add_task(function* asyncCleanUp() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js b/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js deleted file mode 100644 index a653c2d51..000000000 --- a/browser/components/customizableui/test/browser_978084_dragEnd_after_move.js +++ /dev/null @@ -1,46 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var draggedItem; - -/** - * Check that customizing-movingItem gets removed on a drop when the item is moved. - */ - -// Drop on the palette -add_task(function*() { - draggedItem = document.createElement("toolbarbutton"); - draggedItem.id = "test-dragEnd-after-move1"; - draggedItem.setAttribute("label", "Test"); - draggedItem.setAttribute("removable", "true"); - let navbar = document.getElementById("nav-bar"); - navbar.customizationTarget.appendChild(draggedItem); - yield startCustomizing(); - simulateItemDrag(draggedItem, gCustomizeMode.visiblePalette); - is(document.documentElement.hasAttribute("customizing-movingItem"), false, - "Make sure customizing-movingItem is removed after dragging to the palette"); - yield endCustomizing(); -}); - -// Drop on a customization target itself -add_task(function*() { - draggedItem = document.createElement("toolbarbutton"); - draggedItem.id = "test-dragEnd-after-move2"; - draggedItem.setAttribute("label", "Test"); - draggedItem.setAttribute("removable", "true"); - let dest = createToolbarWithPlacements("test-dragEnd"); - let navbar = document.getElementById("nav-bar"); - navbar.customizationTarget.appendChild(draggedItem); - yield startCustomizing(); - simulateItemDrag(draggedItem, dest.customizationTarget); - is(document.documentElement.hasAttribute("customizing-movingItem"), false, - "Make sure customizing-movingItem is removed"); - yield endCustomizing(); -}); - -add_task(function* asyncCleanup() { - yield endCustomizing(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js b/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js deleted file mode 100644 index 15197ac86..000000000 --- a/browser/components/customizableui/test/browser_980155_add_overflow_toolbar.js +++ /dev/null @@ -1,51 +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 kToolbarName = "test-new-overflowable-toolbar"; -const kTestWidgetPrefix = "test-widget-for-overflowable-toolbar-"; - -add_task(function* addOverflowingToolbar() { - let originalWindowWidth = window.outerWidth; - - let widgetIds = []; - for (let i = 0; i < 10; i++) { - let id = kTestWidgetPrefix + i; - widgetIds.push(id); - let spec = {id: id, type: "button", removable: true, label: "test", tooltiptext: "" + i}; - CustomizableUI.createWidget(spec); - } - - let toolbarNode = createOverflowableToolbarWithPlacements(kToolbarName, widgetIds); - assertAreaPlacements(kToolbarName, widgetIds); - - for (let id of widgetIds) { - document.getElementById(id).style.minWidth = "200px"; - } - - isnot(toolbarNode.overflowable, null, "Toolbar should have overflowable controller"); - isnot(toolbarNode.customizationTarget, null, "Toolbar should have customization target"); - isnot(toolbarNode.customizationTarget, toolbarNode, "Customization target should not be toolbar node"); - - let oldChildCount = toolbarNode.customizationTarget.childElementCount; - let overflowableList = document.getElementById(kToolbarName + "-overflow-list"); - let oldOverflowCount = overflowableList.childElementCount; - - isnot(oldChildCount, 0, "Toolbar should have non-overflowing widgets"); - - window.resizeTo(400, window.outerHeight); - yield waitForCondition(() => toolbarNode.hasAttribute("overflowing")); - ok(toolbarNode.hasAttribute("overflowing"), "Should have an overflowing toolbar."); - ok(toolbarNode.customizationTarget.childElementCount < oldChildCount, "Should have fewer children."); - ok(overflowableList.childElementCount > oldOverflowCount, "Should have more overflowed widgets."); - - window.resizeTo(originalWindowWidth, window.outerHeight); -}); - - -add_task(function* asyncCleanup() { - removeCustomToolbars(); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_981305_separator_insertion.js b/browser/components/customizableui/test/browser_981305_separator_insertion.js deleted file mode 100644 index 8d4d86c2a..000000000 --- a/browser/components/customizableui/test/browser_981305_separator_insertion.js +++ /dev/null @@ -1,73 +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"; - -var tempElements = []; - -function insertTempItemsIntoMenu(parentMenu) { - // Last element is null to insert at the end: - let beforeEls = [parentMenu.firstChild, parentMenu.lastChild, null]; - for (let i = 0; i < beforeEls.length; i++) { - let sep = document.createElement("menuseparator"); - tempElements.push(sep); - parentMenu.insertBefore(sep, beforeEls[i]); - let menu = document.createElement("menu"); - tempElements.push(menu); - parentMenu.insertBefore(menu, beforeEls[i]); - // And another separator for good measure: - sep = document.createElement("menuseparator"); - tempElements.push(sep); - parentMenu.insertBefore(sep, beforeEls[i]); - } -} - -function checkSeparatorInsertion(menuId, buttonId, subviewId) { - return function*() { - info("Checking for duplicate separators in " + buttonId + " widget"); - let menu = document.getElementById(menuId); - insertTempItemsIntoMenu(menu); - - let placement = CustomizableUI.getPlacementOfWidget(buttonId); - let changedPlacement = false; - if (!placement || placement.area != CustomizableUI.AREA_PANEL) { - CustomizableUI.addWidgetToArea(buttonId, CustomizableUI.AREA_PANEL); - changedPlacement = true; - } - yield PanelUI.show(); - - let button = document.getElementById(buttonId); - button.click(); - - yield waitForCondition(() => !PanelUI.multiView.hasAttribute("transitioning")); - let subview = document.getElementById(subviewId); - ok(subview.firstChild, "Subview should have a kid"); - is(subview.firstChild.localName, "toolbarbutton", "There should be no separators to start with"); - - for (let kid of subview.children) { - if (kid.localName == "menuseparator") { - ok(kid.previousSibling && kid.previousSibling.localName != "menuseparator", - "Separators should never have another separator next to them, and should never be the first node."); - } - } - - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - - if (changedPlacement) { - CustomizableUI.reset(); - } - }; -} - -add_task(checkSeparatorInsertion("menuWebDeveloperPopup", "developer-button", "PanelUI-developerItems")); -add_task(checkSeparatorInsertion("viewSidebarMenu", "sidebar-button", "PanelUI-sidebarItems")); - -registerCleanupFunction(function() { - for (let el of tempElements) { - el.remove(); - } - tempElements = null; -}); diff --git a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js deleted file mode 100644 index 9a7227a47..000000000 --- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js +++ /dev/null @@ -1,93 +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 kWidgetId = 'test-981418-widget-onbeforecreated'; - -// Should be able to add broken view widget -add_task(function* testAddOnBeforeCreatedWidget() { - let viewShownDeferred = Promise.defer(); - let onBeforeCreatedCalled = false; - let widgetSpec = { - id: kWidgetId, - type: 'view', - viewId: kWidgetId + 'idontexistyet', - onBeforeCreated: function(doc) { - let view = doc.createElement("panelview"); - view.id = kWidgetId + 'idontexistyet'; - let label = doc.createElement("label"); - label.setAttribute("value", "Hello world"); - label.className = 'panel-subview-header'; - view.appendChild(label); - document.getElementById("PanelUI-multiView").appendChild(view); - onBeforeCreatedCalled = true; - }, - onViewShowing: function() { - viewShownDeferred.resolve(); - } - }; - - let noError = true; - try { - CustomizableUI.createWidget(widgetSpec); - CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_NAVBAR); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Should not throw an exception trying to add the widget."); - ok(onBeforeCreatedCalled, "onBeforeCreated should have been called"); - - let widgetNode = document.getElementById(kWidgetId); - ok(widgetNode, "Widget should exist"); - if (widgetNode) { - try { - widgetNode.click(); - - let tempPanel = document.getElementById("customizationui-widget-panel"); - let panelShownPromise = promisePanelElementShown(window, tempPanel); - - let shownTimeout = setTimeout(() => viewShownDeferred.reject("Panel not shown within 20s"), 20000); - yield viewShownDeferred.promise; - yield panelShownPromise; - clearTimeout(shownTimeout); - ok(true, "Found view shown"); - - let panelHiddenPromise = promisePanelElementHidden(window, tempPanel); - tempPanel.hidePopup(); - yield panelHiddenPromise; - - CustomizableUI.addWidgetToArea(kWidgetId, CustomizableUI.AREA_PANEL); - yield PanelUI.show(); - - viewShownDeferred = Promise.defer(); - widgetNode.click(); - - shownTimeout = setTimeout(() => viewShownDeferred.reject("Panel not shown within 20s"), 20000); - yield viewShownDeferred.promise; - clearTimeout(shownTimeout); - ok(true, "Found view shown"); - - let panelHidden = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidden; - } catch (ex) { - ok(false, "Unexpected exception (like a timeout for one of the yields) " + - "when testing view widget."); - } - } - - noError = true; - try { - CustomizableUI.destroyWidget(kWidgetId); - } catch (ex) { - Cu.reportError(ex); - noError = false; - } - ok(noError, "Should not throw an exception trying to remove the broken view widget."); -}); - -add_task(function* asyncCleanup() { - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js b/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js deleted file mode 100644 index e7f8d0cf4..000000000 --- a/browser/components/customizableui/test/browser_982656_restore_defaults_builtin_widgets.js +++ /dev/null @@ -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/. */ - -"use strict"; - -// Restoring default should not place addon widgets back in the toolbar -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Default state to begin"); - - const kWidgetId = "bug982656-add-on-widget-should-not-restore-to-default-area"; - let widgetSpec = { - id: kWidgetId, - defaultArea: CustomizableUI.AREA_NAVBAR - }; - CustomizableUI.createWidget(widgetSpec); - - ok(!CustomizableUI.inDefaultState, "Not in default state after widget added"); - is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, CustomizableUI.AREA_NAVBAR, "Widget should be in navbar"); - - yield resetCustomization(); - - ok(CustomizableUI.inDefaultState, "Back in default state after reset"); - is(CustomizableUI.getPlacementOfWidget(kWidgetId), null, "Widget now in palette"); - CustomizableUI.destroyWidget(kWidgetId); -}); - - -// resetCustomization shouldn't move 3rd party widgets out of custom toolbars -add_task(function*() { - const kToolbarId = "bug982656-toolbar-with-defaultset"; - const kWidgetId = "bug982656-add-on-widget-should-restore-to-default-area-when-area-is-not-builtin"; - ok(CustomizableUI.inDefaultState, "Everything should be in its default state."); - let toolbar = createToolbarWithPlacements(kToolbarId); - ok(CustomizableUI.areas.indexOf(kToolbarId) != -1, - "Toolbar has been registered."); - is(CustomizableUI.getAreaType(kToolbarId), CustomizableUI.TYPE_TOOLBAR, - "Area should be registered as toolbar"); - - let widgetSpec = { - id: kWidgetId, - defaultArea: kToolbarId - }; - CustomizableUI.createWidget(widgetSpec); - - ok(!CustomizableUI.inDefaultState, "No longer in default state after toolbar is registered and visible."); - is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, kToolbarId, "Widget should be in custom toolbar"); - - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "Back in default state after reset"); - is(CustomizableUI.getPlacementOfWidget(kWidgetId).area, kToolbarId, "Widget still in custom toolbar"); - ok(toolbar.collapsed, "Custom toolbar should be collapsed after reset"); - - toolbar.remove(); - CustomizableUI.destroyWidget(kWidgetId); - CustomizableUI.unregisterArea(kToolbarId); -}); diff --git a/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js b/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js deleted file mode 100644 index 42b346c10..000000000 --- a/browser/components/customizableui/test/browser_984455_bookmarks_items_reparenting.js +++ /dev/null @@ -1,267 +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"; - -var gNavBar = document.getElementById(CustomizableUI.AREA_NAVBAR); -var gOverflowList = document.getElementById(gNavBar.getAttribute("overflowtarget")); - -const kBookmarksButton = "bookmarks-menu-button"; -const kBookmarksItems = "personal-bookmarks"; -const kOriginalWindowWidth = window.outerWidth; -const kSmallWidth = 400; - -/** - * Helper function that opens the bookmarks menu, and returns a Promise that - * resolves as soon as the menu is ready for interaction. - */ -function bookmarksMenuPanelShown() { - let deferred = Promise.defer(); - let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup"); - let onTransitionEnd = (e) => { - if (e.target == bookmarksMenuPopup) { - bookmarksMenuPopup.removeEventListener("transitionend", onTransitionEnd); - deferred.resolve(); - } - } - bookmarksMenuPopup.addEventListener("transitionend", onTransitionEnd); - return deferred.promise; -} - -/** - * Checks that the placesContext menu is correctly attached to the - * controller of some view. Returns a Promise that resolves as soon - * as the context menu is closed. - * - * @param aItemWithContextMenu the item that we need to synthesize hte - * right click on in order to open the context menu. - */ -function checkPlacesContextMenu(aItemWithContextMenu) { - return Task.spawn(function* () { - let contextMenu = document.getElementById("placesContext"); - let newBookmarkItem = document.getElementById("placesContext_new:bookmark"); - info("Waiting for context menu on " + aItemWithContextMenu.id); - let shownPromise = popupShown(contextMenu); - EventUtils.synthesizeMouseAtCenter(aItemWithContextMenu, - {type: "contextmenu", button: 2}); - yield shownPromise; - - ok(!newBookmarkItem.hasAttribute("disabled"), - "New bookmark item shouldn't be disabled"); - - info("Closing context menu"); - yield closePopup(contextMenu); - }); -} - -/** - * Opens the bookmarks menu panel, and then opens each of the "special" - * submenus in that list. Then it checks that those submenu's context menus - * are properly hooked up to a controller. - */ -function checkSpecialContextMenus() { - return Task.spawn(function* () { - let bookmarksMenuButton = document.getElementById(kBookmarksButton); - let bookmarksMenuPopup = document.getElementById("BMB_bookmarksPopup"); - - const kSpecialItemIDs = { - "BMB_bookmarksToolbar": "BMB_bookmarksToolbarPopup", - "BMB_unsortedBookmarks": "BMB_unsortedBookmarksPopup", - }; - - // Open the bookmarks menu button context menus and ensure that - // they have the proper views attached. - let shownPromise = bookmarksMenuPanelShown(); - let dropmarker = document.getAnonymousElementByAttribute(bookmarksMenuButton, - "anonid", "dropmarker"); - EventUtils.synthesizeMouseAtCenter(dropmarker, {}); - info("Waiting for bookmarks menu popup to show after clicking dropmarker.") - yield shownPromise; - - for (let menuID in kSpecialItemIDs) { - let menuItem = document.getElementById(menuID); - let menuPopup = document.getElementById(kSpecialItemIDs[menuID]); - info("Waiting to open menu for " + menuID); - let shownPromise = popupShown(menuPopup); - menuPopup.openPopup(menuItem, null, 0, 0, false, false, null); - yield shownPromise; - - yield checkPlacesContextMenu(menuPopup); - info("Closing menu for " + menuID); - yield closePopup(menuPopup); - } - - info("Closing bookmarks menu"); - yield closePopup(bookmarksMenuPopup); - }); -} - -/** - * Closes a focused popup by simulating pressing the Escape key, - * and returns a Promise that resolves as soon as the popup is closed. - * - * @param aPopup the popup node to close. - */ -function closePopup(aPopup) { - let hiddenPromise = popupHidden(aPopup); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - return hiddenPromise; -} - -/** - * Helper function that checks that the context menu of the - * bookmark toolbar items chevron popup is correctly hooked up - * to the controller of a view. - */ -function checkBookmarksItemsChevronContextMenu() { - return Task.spawn(function*() { - let chevronPopup = document.getElementById("PlacesChevronPopup"); - let shownPromise = popupShown(chevronPopup); - let chevron = document.getElementById("PlacesChevron"); - EventUtils.synthesizeMouseAtCenter(chevron, {}); - info("Waiting for bookmark toolbar item chevron popup to show"); - yield shownPromise; - yield waitForCondition(() => { - for (let child of chevronPopup.children) { - if (child.style.visibility != "hidden") - return true; - } - return false; - }); - yield checkPlacesContextMenu(chevronPopup); - info("Waiting for bookmark toolbar item chevron popup to close"); - yield closePopup(chevronPopup); - }); -} - -/** - * Forces the window to a width that causes the nav-bar to overflow - * its contents. Returns a Promise that resolves as soon as the - * overflowable nav-bar is showing its chevron. - */ -function overflowEverything() { - info("Waiting for overflow"); - window.resizeTo(kSmallWidth, window.outerHeight); - return waitForCondition(() => gNavBar.hasAttribute("overflowing")); -} - -/** - * Returns the window to its original size from the start of the test, - * and returns a Promise that resolves when the nav-bar is no longer - * overflowing. - */ -function stopOverflowing() { - info("Waiting until we stop overflowing"); - window.resizeTo(kOriginalWindowWidth, window.outerHeight); - return waitForCondition(() => !gNavBar.hasAttribute("overflowing")); -} - -/** - * Checks that an item with ID aID is overflowing in the nav-bar. - * - * @param aID the ID of the node to check for overflowingness. - */ -function checkOverflowing(aID) { - ok(!gNavBar.querySelector("#" + aID), - "Item with ID " + aID + " should no longer be in the gNavBar"); - let item = gOverflowList.querySelector("#" + aID); - ok(item, "Item with ID " + aID + " should be overflowing"); - is(item.getAttribute("overflowedItem"), "true", - "Item with ID " + aID + " should have overflowedItem attribute"); -} - -/** - * Checks that an item with ID aID is not overflowing in the nav-bar. - * - * @param aID the ID of hte node to check for non-overflowingness. - */ -function checkNotOverflowing(aID) { - ok(!gOverflowList.querySelector("#" + aID), - "Item with ID " + aID + " should no longer be overflowing"); - let item = gNavBar.querySelector("#" + aID); - ok(item, "Item with ID " + aID + " should be in the nav bar"); - ok(!item.hasAttribute("overflowedItem"), - "Item with ID " + aID + " should not have overflowedItem attribute"); -} - -/** - * Test that overflowing the bookmarks menu button doesn't break the - * context menus for the Unsorted and Bookmarks Toolbar menu items. - */ -add_task(function* testOverflowingBookmarksButtonContextMenu() { - ok(!gNavBar.hasAttribute("overflowing"), "Should start with a non-overflowing toolbar."); - ok(CustomizableUI.inDefaultState, "Should start in default state."); - - // Open the Unsorted and Bookmarks Toolbar context menus and ensure - // that they have views attached. - yield checkSpecialContextMenus(); - - yield overflowEverything(); - checkOverflowing(kBookmarksButton); - - yield stopOverflowing(); - checkNotOverflowing(kBookmarksButton); - - yield checkSpecialContextMenus(); -}); - -/** - * Test that the bookmarks toolbar items context menu still works if moved - * to the menu from the overflow panel, and then back to the toolbar. - */ -add_task(function* testOverflowingBookmarksItemsContextMenu() { - info("Ensuring panel is ready."); - yield PanelUI.ensureReady(); - - let bookmarksToolbarItems = document.getElementById(kBookmarksItems); - gCustomizeMode.addToToolbar(bookmarksToolbarItems); - yield checkPlacesContextMenu(bookmarksToolbarItems); - - yield overflowEverything(); - checkOverflowing(kBookmarksItems) - - gCustomizeMode.addToPanel(bookmarksToolbarItems); - - yield stopOverflowing(); - - gCustomizeMode.addToToolbar(bookmarksToolbarItems); - yield checkPlacesContextMenu(bookmarksToolbarItems); -}); - -/** - * Test that overflowing the bookmarks toolbar items doesn't cause the - * context menu in the bookmarks toolbar items chevron to stop working. - */ -add_task(function* testOverflowingBookmarksItemsChevronContextMenu() { - // If it's not already there, let's move the bookmarks toolbar items to - // the nav-bar. - let bookmarksToolbarItems = document.getElementById(kBookmarksItems); - gCustomizeMode.addToToolbar(bookmarksToolbarItems); - - // We make the PlacesToolbarItems element be super tiny in order to force - // the bookmarks toolbar items into overflowing and making the chevron - // show itself. - let placesToolbarItems = document.getElementById("PlacesToolbarItems"); - let placesChevron = document.getElementById("PlacesChevron"); - placesToolbarItems.style.maxWidth = "10px"; - info("Waiting for chevron to no longer be collapsed"); - yield waitForCondition(() => !placesChevron.collapsed); - - yield checkBookmarksItemsChevronContextMenu(); - - yield overflowEverything(); - checkOverflowing(kBookmarksItems); - - yield stopOverflowing(); - checkNotOverflowing(kBookmarksItems); - - yield checkBookmarksItemsChevronContextMenu(); - - placesToolbarItems.style.removeProperty("max-width"); -}); - -add_task(function* asyncCleanup() { - window.resizeTo(kOriginalWindowWidth, window.outerHeight); - yield resetCustomization(); -}); diff --git a/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js b/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js deleted file mode 100644 index c341c2158..000000000 --- a/browser/components/customizableui/test/browser_985815_propagate_setToolbarVisibility.js +++ /dev/null @@ -1,45 +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"; - -add_task(function*() { - ok(CustomizableUI.inDefaultState, "Should start in default state."); - this.otherWin = yield openAndLoadWindow({private: true}, true); - yield startCustomizing(this.otherWin); - let resetButton = this.otherWin.document.getElementById("customization-reset-button"); - ok(resetButton.disabled, "Reset button should be disabled"); - - if (typeof CustomizableUI.setToolbarVisibility == "function") { - CustomizableUI.setToolbarVisibility("PersonalToolbar", true); - } else { - setToolbarVisibility(document.getElementById("PersonalToolbar"), true); - } - - let otherPersonalToolbar = this.otherWin.document.getElementById("PersonalToolbar"); - let personalToolbar = document.getElementById("PersonalToolbar"); - ok(!otherPersonalToolbar.collapsed, "Toolbar should be uncollapsed in private window"); - ok(!personalToolbar.collapsed, "Toolbar should be uncollapsed in normal window"); - ok(!resetButton.disabled, "Reset button should be enabled"); - - yield this.otherWin.gCustomizeMode.reset(); - - ok(otherPersonalToolbar.collapsed, "Toolbar should be collapsed in private window"); - ok(personalToolbar.collapsed, "Toolbar should be collapsed in normal window"); - ok(resetButton.disabled, "Reset button should be disabled"); - - yield endCustomizing(this.otherWin); - - yield promiseWindowClosed(this.otherWin); -}); - - -add_task(function* asyncCleanup() { - if (this.otherWin && !this.otherWin.closed) { - yield promiseWindowClosed(this.otherWin); - } - if (!CustomizableUI.inDefaultState) { - CustomizableUI.reset(); - } -}); diff --git a/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js b/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js deleted file mode 100644 index 6a4d0aab4..000000000 --- a/browser/components/customizableui/test/browser_987177_destroyWidget_xul.js +++ /dev/null @@ -1,33 +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 BUTTONID = "test-XUL-wrapper-destroyWidget"; - - -add_task(function() { - let btn = createDummyXULButton(BUTTONID, "XUL btn"); - gNavToolbox.palette.appendChild(btn); - let firstWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window); - ok(firstWrapper, "Should get a wrapper"); - ok(firstWrapper.node, "Node should be there on first wrapper."); - - btn.remove(); - CustomizableUI.destroyWidget(BUTTONID); - let secondWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window); - isnot(firstWrapper, secondWrapper, "Wrappers should be different after destroyWidget call."); - ok(!firstWrapper.node, "No node should be there on old wrapper."); - ok(!secondWrapper.node, "No node should be there on new wrapper."); - - btn = createDummyXULButton(BUTTONID, "XUL btn"); - gNavToolbox.palette.appendChild(btn); - let thirdWrapper = CustomizableUI.getWidget(BUTTONID).forWindow(window); - ok(thirdWrapper, "Should get a wrapper"); - is(secondWrapper, thirdWrapper, "Should get the second wrapper again."); - ok(firstWrapper.node, "Node should be there on old wrapper."); - ok(secondWrapper.node, "Node should be there on second wrapper."); - ok(thirdWrapper.node, "Node should be there on third wrapper."); -}); - diff --git a/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js b/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js deleted file mode 100644 index f838e204d..000000000 --- a/browser/components/customizableui/test/browser_987177_xul_wrapper_updating.js +++ /dev/null @@ -1,74 +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 BUTTONID = "test-XUL-wrapper-widget"; -add_task(function() { - let btn = createDummyXULButton(BUTTONID, "XUL btn"); - gNavToolbox.palette.appendChild(btn); - let groupWrapper = CustomizableUI.getWidget(BUTTONID); - ok(groupWrapper, "Should get a group wrapper"); - let singleWrapper = groupWrapper.forWindow(window); - ok(singleWrapper, "Should get a single wrapper"); - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR); - - let otherSingleWrapper = groupWrapper.forWindow(window); - is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after adding the node to the navbar."); - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - CustomizableUI.removeWidgetFromArea(BUTTONID); - - otherSingleWrapper = groupWrapper.forWindow(window); - isnot(singleWrapper, otherSingleWrapper, "Shouldn't get the same wrapper after removing it from the navbar."); - singleWrapper = otherSingleWrapper; - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - btn.remove(); - otherSingleWrapper = groupWrapper.forWindow(window); - is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after physically removing the node."); - is(singleWrapper.node, null, "Wrapper's node should be null now that it's left the DOM."); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, null, "That instance should be null."); - - btn = createDummyXULButton(BUTTONID, "XUL btn"); - gNavToolbox.palette.appendChild(btn); - otherSingleWrapper = groupWrapper.forWindow(window); - is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after readding the node."); - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - CustomizableUI.addWidgetToArea(BUTTONID, CustomizableUI.AREA_NAVBAR); - - otherSingleWrapper = groupWrapper.forWindow(window); - is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after adding the node to the navbar."); - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - CustomizableUI.removeWidgetFromArea(BUTTONID); - - otherSingleWrapper = groupWrapper.forWindow(window); - isnot(singleWrapper, otherSingleWrapper, "Shouldn't get the same wrapper after removing it from the navbar."); - singleWrapper = otherSingleWrapper; - is(singleWrapper.node, btn, "Node should be in the wrapper"); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, btn, "Button should be that instance."); - - btn.remove(); - otherSingleWrapper = groupWrapper.forWindow(window); - is(singleWrapper, otherSingleWrapper, "Should get the same wrapper after physically removing the node."); - is(singleWrapper.node, null, "Wrapper's node should be null now that it's left the DOM."); - is(groupWrapper.instances.length, 1, "There should be 1 instance on the group wrapper"); - is(groupWrapper.instances[0].node, null, "That instance should be null."); -}); diff --git a/browser/components/customizableui/test/browser_987185_syncButton.js b/browser/components/customizableui/test/browser_987185_syncButton.js deleted file mode 100755 index 988d738be..000000000 --- a/browser/components/customizableui/test/browser_987185_syncButton.js +++ /dev/null @@ -1,77 +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"; - -var syncService = {}; -Components.utils.import("resource://services-sync/service.js", syncService); - -var needsSetup; -var originalSync; -var service = syncService.Service; -var syncWasCalled = false; - -add_task(function* testSyncButtonFunctionality() { - info("Check Sync button functionality"); - storeInitialValues(); - mockFunctions(); - - // add the Sync button to the panel - CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL); - - // check the button's functionality - yield PanelUI.show(); - info("The panel menu was opened"); - - let syncButton = document.getElementById("sync-button"); - ok(syncButton, "The Sync button was added to the Panel Menu"); - // click the button - the panel should open. - syncButton.click(); - let syncPanel = document.getElementById("PanelUI-remotetabs"); - ok(syncPanel.getAttribute("current"), "Sync Panel is in view"); - - // Find and click the "setup" button. - let syncNowButton = document.getElementById("PanelUI-remotetabs-syncnow"); - syncNowButton.click(); - - info("The sync button was clicked"); - - yield waitForCondition(() => syncWasCalled); -}); - -add_task(function* asyncCleanup() { - // reset the panel UI to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The panel UI is in default state again."); - - if (isPanelUIOpen()) { - let panelHidePromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHidePromise; - } - - restoreValues(); -}); - -function mockFunctions() { - // mock needsSetup - gSyncUI._needsSetup = () => Promise.resolve(false); - - // mock service.errorHandler.syncAndReportErrors() - service.errorHandler.syncAndReportErrors = mocked_syncAndReportErrors; -} - -function mocked_syncAndReportErrors() { - syncWasCalled = true; -} - -function restoreValues() { - gSyncUI._needsSetup = needsSetup; - service.sync = originalSync; -} - -function storeInitialValues() { - needsSetup = gSyncUI._needsSetup; - originalSync = service.sync; -} diff --git a/browser/components/customizableui/test/browser_987492_window_api.js b/browser/components/customizableui/test/browser_987492_window_api.js deleted file mode 100644 index 1718303e1..000000000 --- a/browser/components/customizableui/test/browser_987492_window_api.js +++ /dev/null @@ -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"; - - -add_task(function* testOneWindow() { - let windows = []; - for (let win of CustomizableUI.windows) - windows.push(win); - is(windows.length, 1, "Should have one customizable window"); -}); - - -add_task(function* testOpenCloseWindow() { - let newWindow = null; - let openListener = { - onWindowOpened: function(window) { - newWindow = window; - } - } - CustomizableUI.addListener(openListener); - let win = yield openAndLoadWindow(null, true); - isnot(newWindow, null, "Should have gotten onWindowOpen event"); - is(newWindow, win, "onWindowOpen event should have received expected window"); - CustomizableUI.removeListener(openListener); - - let windows = []; - for (let win of CustomizableUI.windows) - windows.push(win); - is(windows.length, 2, "Should have two customizable windows"); - isnot(windows.indexOf(window), -1, "Current window should be in window collection."); - isnot(windows.indexOf(newWindow), -1, "New window should be in window collection."); - - let closedWindow = null; - let closeListener = { - onWindowClosed: function(window) { - closedWindow = window; - } - } - CustomizableUI.addListener(closeListener); - yield promiseWindowClosed(newWindow); - isnot(closedWindow, null, "Should have gotten onWindowClosed event") - is(newWindow, closedWindow, "Closed window should match previously opened window"); - CustomizableUI.removeListener(closeListener); - - windows = []; - for (let win of CustomizableUI.windows) - windows.push(win); - is(windows.length, 1, "Should have one customizable window"); - isnot(windows.indexOf(window), -1, "Current window should be in window collection."); - is(windows.indexOf(closedWindow), -1, "Closed window should not be in window collection."); -}); diff --git a/browser/components/customizableui/test/browser_987640_charEncoding.js b/browser/components/customizableui/test/browser_987640_charEncoding.js deleted file mode 100644 index dfe02f940..000000000 --- a/browser/components/customizableui/test/browser_987640_charEncoding.js +++ /dev/null @@ -1,60 +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://mochi.test:8888/browser/browser/components/customizableui/test/support/test_967000_charEncoding_page.html"; - -add_task(function*() { - info("Check Character Encoding panel functionality"); - - // add the Character Encoding button to the panel - CustomizableUI.addWidgetToArea("characterencoding-button", - CustomizableUI.AREA_PANEL); - - let newTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_PAGE, true, true); - - yield PanelUI.show(); - let charEncodingButton = document.getElementById("characterencoding-button"); - let characterEncodingView = document.getElementById("PanelUI-characterEncodingView"); - let subviewShownPromise = subviewShown(characterEncodingView); - charEncodingButton.click(); - yield subviewShownPromise; - - let checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']"); - let initialEncoding = checkedButtons[0]; - is(initialEncoding.getAttribute("label"), "Unicode", "The unicode encoding is initially selected"); - - // change the encoding - let encodings = characterEncodingView.querySelectorAll("toolbarbutton"); - let newEncoding = encodings[0].hasAttribute("checked") ? encodings[1] : encodings[0]; - let tabLoadPromise = promiseTabLoadEvent(gBrowser.selectedTab, TEST_PAGE); - newEncoding.click(); - yield tabLoadPromise; - - // check that the new encodng is applied - yield PanelUI.show(); - charEncodingButton.click(); - checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']"); - let selectedEncodingName = checkedButtons[0].getAttribute("label"); - ok(selectedEncodingName != "Unicode", "The encoding was changed to " + selectedEncodingName); - - // reset the initial encoding - yield PanelUI.show(); - charEncodingButton.click(); - tabLoadPromise = promiseTabLoadEvent(gBrowser.selectedTab, TEST_PAGE); - initialEncoding.click(); - yield tabLoadPromise; - yield PanelUI.show(); - charEncodingButton.click(); - checkedButtons = characterEncodingView.querySelectorAll("toolbarbutton[checked='true']"); - is(checkedButtons[0].getAttribute("label"), "Unicode", "The encoding was reset to Unicode"); - yield BrowserTestUtils.removeTab(newTab); -}); - -add_task(function* asyncCleanup() { - // reset the panel to the default state - yield resetCustomization(); - ok(CustomizableUI.inDefaultState, "The UI is in default state again."); -}); diff --git a/browser/components/customizableui/test/browser_988072_sidebar_events.js b/browser/components/customizableui/test/browser_988072_sidebar_events.js deleted file mode 100644 index 6791be67a..000000000 --- a/browser/components/customizableui/test/browser_988072_sidebar_events.js +++ /dev/null @@ -1,392 +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"; - -var gSidebarMenu = document.getElementById("viewSidebarMenu"); -var gTestSidebarItem = null; - -var EVENTS = { - click: 0, command: 0, - onclick: 0, oncommand: 0 -}; - -window.sawEvent = function(event, isattr) { - let type = (isattr ? "on" : "") + event.type - EVENTS[type]++; -}; - -registerCleanupFunction(() => { - delete window.sawEvent; - - // Ensure sidebar is hidden after each test: - if (!document.getElementById("sidebar-box").hidden) { - SidebarUI.hide(); - } -}); - -function checkExpectedEvents(expected) { - for (let type of Object.keys(EVENTS)) { - let count = (type in expected ? expected[type] : 0); - is(EVENTS[type], count, "Should have seen the right number of " + type + " events"); - EVENTS[type] = 0; - } -} - -function createSidebarItem() { - gTestSidebarItem = document.createElement("menuitem"); - gTestSidebarItem.id = "testsidebar"; - gTestSidebarItem.setAttribute("label", "Test Sidebar"); - gSidebarMenu.insertBefore(gTestSidebarItem, gSidebarMenu.firstChild); -} - -function addWidget() { - CustomizableUI.addWidgetToArea("sidebar-button", "nav-bar"); - PanelUI.disableSingleSubviewPanelAnimations(); -} - -function removeWidget() { - CustomizableUI.removeWidgetFromArea("sidebar-button"); - PanelUI.enableSingleSubviewPanelAnimations(); -} - -// Filters out the trailing menuseparators from the sidebar list -function getSidebarList() { - let sidebars = [...gSidebarMenu.children].filter(sidebar => { - if (sidebar.localName == "menuseparator") - return false; - if (sidebar.getAttribute("hidden") == "true") - return false; - return true; - }); - return sidebars; -} - -function compareElements(original, displayed) { - let attrs = ["label", "key", "disabled", "hidden", "origin", "image", "checked"]; - for (let attr of attrs) { - is(displayed.getAttribute(attr), original.getAttribute(attr), "Should have the same " + attr + " attribute"); - } -} - -function compareList(original, displayed) { - is(displayed.length, original.length, "Should have the same number of children"); - - for (let i = 0; i < Math.min(original.length, displayed.length); i++) { - compareElements(displayed[i], original[i]); - } -} - -var showSidebarPopup = Task.async(function*() { - let button = document.getElementById("sidebar-button"); - let subview = document.getElementById("PanelUI-sidebar"); - - let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown"); - - let subviewShownPromise = subviewShown(subview); - EventUtils.synthesizeMouseAtCenter(button, {}); - return Promise.all([subviewShownPromise, popupShownPromise]); -}); - -// Check the sidebar widget shows the default items -add_task(function*() { - addWidget(); - - yield showSidebarPopup(); - - let sidebars = getSidebarList(); - let displayed = [...document.getElementById("PanelUI-sidebarItems").children]; - compareList(sidebars, displayed); - - let subview = document.getElementById("PanelUI-sidebar"); - let subviewHiddenPromise = subviewHidden(subview); - document.getElementById("customizationui-widget-panel").hidePopup(); - yield subviewHiddenPromise; - - removeWidget(); -}); - -function add_sidebar_task(description, setup, teardown) { - add_task(function*() { - info(description); - createSidebarItem(); - addWidget(); - yield setup(); - - CustomizableUI.addWidgetToArea("sidebar-button", "nav-bar"); - - yield showSidebarPopup(); - - let sidebars = getSidebarList(); - let displayed = [...document.getElementById("PanelUI-sidebarItems").children]; - compareList(sidebars, displayed); - - is(displayed[0].label, "Test Sidebar", "Should have the right element at the top"); - let subview = document.getElementById("PanelUI-sidebar"); - let subviewHiddenPromise = subviewHidden(subview); - EventUtils.synthesizeMouseAtCenter(displayed[0], {}); - yield subviewHiddenPromise; - - yield teardown(); - gTestSidebarItem.remove(); - removeWidget(); - }); -} - -add_sidebar_task( - "Check that a sidebar that uses a command event listener works", -function*() { - gTestSidebarItem.addEventListener("command", window.sawEvent); -}, function*() { - checkExpectedEvents({ command: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses a click event listener works", -function*() { - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ click: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses both click and command event listeners works", -function*() { - gTestSidebarItem.addEventListener("command", window.sawEvent); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ command: 1, click: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses an oncommand attribute works", -function*() { - gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)"); -}, function*() { - checkExpectedEvents({ oncommand: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses an onclick attribute works", -function*() { - gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)"); -}, function*() { - checkExpectedEvents({ onclick: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses both onclick and oncommand attributes works", -function*() { - gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)"); - gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)"); -}, function*() { - checkExpectedEvents({ onclick: 1, oncommand: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses an onclick attribute and a command listener works", -function*() { - gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)"); - gTestSidebarItem.addEventListener("command", window.sawEvent); -}, function*() { - checkExpectedEvents({ onclick: 1, command: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses an oncommand attribute and a click listener works", -function*() { - gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)"); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ click: 1, oncommand: 1 }); -}); - -add_sidebar_task( - "A sidebar with both onclick attribute and click listener sees only one event :(", -function*() { - gTestSidebarItem.setAttribute("onclick", "window.sawEvent(event, true)"); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ onclick: 1 }); -}); - -add_sidebar_task( - "A sidebar with both oncommand attribute and command listener sees only one event :(", -function*() { - gTestSidebarItem.setAttribute("oncommand", "window.sawEvent(event, true)"); - gTestSidebarItem.addEventListener("command", window.sawEvent); -}, function*() { - checkExpectedEvents({ oncommand: 1 }); -}); - -add_sidebar_task( - "Check that a sidebar that uses a broadcaster with an oncommand attribute works", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); -}, function*() { - checkExpectedEvents({ oncommand: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar that uses a broadcaster with an onclick attribute works", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("onclick", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); -}, function*() { - checkExpectedEvents({ onclick: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar that uses a broadcaster with both onclick and oncommand attributes works", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("onclick", "window.sawEvent(event, true)"); - broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); -}, function*() { - checkExpectedEvents({ onclick: 1, oncommand: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar with a click listener and a broadcaster with an oncommand attribute works", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ click: 1, oncommand: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar with a command listener and a broadcaster with an onclick attribute works", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("onclick", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); - gTestSidebarItem.addEventListener("command", window.sawEvent); -}, function*() { - checkExpectedEvents({ onclick: 1, command: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar with a click listener and a broadcaster with an onclick " + - "attribute only sees one event :(", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("onclick", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ onclick: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar with a command listener and a broadcaster with an oncommand " + - "attribute only sees one event :(", -function*() { - let broadcaster = document.createElement("broadcaster"); - broadcaster.setAttribute("id", "testbroadcaster"); - broadcaster.setAttribute("oncommand", "window.sawEvent(event, true)"); - broadcaster.setAttribute("label", "Test Sidebar"); - document.getElementById("mainBroadcasterSet").appendChild(broadcaster); - - gTestSidebarItem.setAttribute("observes", "testbroadcaster"); - gTestSidebarItem.addEventListener("command", window.sawEvent); -}, function*() { - checkExpectedEvents({ oncommand: 1 }); - document.getElementById("testbroadcaster").remove(); -}); - -add_sidebar_task( - "Check that a sidebar that uses a command element with a command event listener works", -function*() { - let command = document.createElement("command"); - command.setAttribute("id", "testcommand"); - document.getElementById("mainCommandSet").appendChild(command); - command.addEventListener("command", window.sawEvent); - - gTestSidebarItem.setAttribute("command", "testcommand"); -}, function*() { - checkExpectedEvents({ command: 1 }); - document.getElementById("testcommand").remove(); -}); - -add_sidebar_task( - "Check that a sidebar that uses a command element with an oncommand attribute works", -function*() { - let command = document.createElement("command"); - command.setAttribute("id", "testcommand"); - command.setAttribute("oncommand", "window.sawEvent(event, true)"); - document.getElementById("mainCommandSet").appendChild(command); - - gTestSidebarItem.setAttribute("command", "testcommand"); -}, function*() { - checkExpectedEvents({ oncommand: 1 }); - document.getElementById("testcommand").remove(); -}); - -add_sidebar_task("Check that a sidebar that uses a command element with a " + - "command event listener and oncommand attribute works", -function*() { - let command = document.createElement("command"); - command.setAttribute("id", "testcommand"); - command.setAttribute("oncommand", "window.sawEvent(event, true)"); - document.getElementById("mainCommandSet").appendChild(command); - command.addEventListener("command", window.sawEvent); - - gTestSidebarItem.setAttribute("command", "testcommand"); -}, function*() { - checkExpectedEvents({ command: 1, oncommand: 1 }); - document.getElementById("testcommand").remove(); -}); - -add_sidebar_task( - "A sidebar with a command element will still see click events", -function*() { - let command = document.createElement("command"); - command.setAttribute("id", "testcommand"); - command.setAttribute("oncommand", "window.sawEvent(event, true)"); - document.getElementById("mainCommandSet").appendChild(command); - command.addEventListener("command", window.sawEvent); - - gTestSidebarItem.setAttribute("command", "testcommand"); - gTestSidebarItem.addEventListener("click", window.sawEvent); -}, function*() { - checkExpectedEvents({ click: 1, command: 1, oncommand: 1 }); - document.getElementById("testcommand").remove(); -}); diff --git a/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js b/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js deleted file mode 100644 index 2a1b01bf7..000000000 --- a/browser/components/customizableui/test/browser_989338_saved_placements_not_resaved.js +++ /dev/null @@ -1,56 +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 BUTTONID = "test-widget-saved-earlier"; -const AREAID = "test-area-saved-earlier"; - -var hadSavedState; -function test() { - // Hack our way into the module to fake a saved state that isn't there... - let backstagePass = Cu.import("resource:///modules/CustomizableUI.jsm", {}); - hadSavedState = backstagePass.gSavedState != null; - if (!hadSavedState) { - backstagePass.gSavedState = {placements: {}}; - } - backstagePass.gSavedState.placements[AREAID] = [BUTTONID]; - // Put bogus stuff in the saved state for the nav-bar, so as to check the current placements - // override this one... - backstagePass.gSavedState.placements[CustomizableUI.AREA_NAVBAR] = ["bogus-navbar-item"]; - - backstagePass.gDirty = true; - backstagePass.CustomizableUIInternal.saveState(); - - let newSavedState = JSON.parse(Services.prefs.getCharPref("browser.uiCustomization.state")); - let savedArea = Array.isArray(newSavedState.placements[AREAID]); - ok(savedArea, "Should have re-saved the state, even though the area isn't registered"); - - if (savedArea) { - placementArraysEqual(AREAID, newSavedState.placements[AREAID], [BUTTONID]); - } - ok(!backstagePass.gPlacements.has(AREAID), "Placements map shouldn't have been affected"); - - let savedNavbar = Array.isArray(newSavedState.placements[CustomizableUI.AREA_NAVBAR]); - ok(savedNavbar, "Should have saved nav-bar contents"); - if (savedNavbar) { - placementArraysEqual(CustomizableUI.AREA_NAVBAR, newSavedState.placements[CustomizableUI.AREA_NAVBAR], - CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR)); - } -} - -registerCleanupFunction(function() { - let backstagePass = Cu.import("resource:///modules/CustomizableUI.jsm", {}); - if (!hadSavedState) { - backstagePass.gSavedState = null; - } else { - let savedPlacements = backstagePass.gSavedState.placements; - delete savedPlacements[AREAID]; - let realNavBarPlacements = CustomizableUI.getWidgetIdsInArea(CustomizableUI.AREA_NAVBAR); - savedPlacements[CustomizableUI.AREA_NAVBAR] = realNavBarPlacements; - } - backstagePass.gDirty = true; - backstagePass.CustomizableUIInternal.saveState(); -}); - diff --git a/browser/components/customizableui/test/browser_989751_subviewbutton_class.js b/browser/components/customizableui/test/browser_989751_subviewbutton_class.js deleted file mode 100644 index 0d11324ed..000000000 --- a/browser/components/customizableui/test/browser_989751_subviewbutton_class.js +++ /dev/null @@ -1,62 +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 kCustomClass = "acustomclassnoonewilluse"; -var tempElement = null; - -function insertClassNameToMenuChildren(parentMenu) { - let el = parentMenu.querySelector("menuitem:first-of-type"); - el.classList.add(kCustomClass); - tempElement = el; -} - -function checkSubviewButtonClass(menuId, buttonId, subviewId) { - return function*() { - info("Checking for items without the subviewbutton class in " + buttonId + " widget"); - let menu = document.getElementById(menuId); - insertClassNameToMenuChildren(menu); - - let placement = CustomizableUI.getPlacementOfWidget(buttonId); - let changedPlacement = false; - if (!placement || placement.area != CustomizableUI.AREA_PANEL) { - CustomizableUI.addWidgetToArea(buttonId, CustomizableUI.AREA_PANEL); - changedPlacement = true; - } - yield PanelUI.show(); - - let button = document.getElementById(buttonId); - button.click(); - - yield waitForCondition(() => !PanelUI.multiView.hasAttribute("transitioning")); - let subview = document.getElementById(subviewId); - ok(subview.firstChild, "Subview should have a kid"); - let subviewchildren = subview.querySelectorAll("toolbarbutton"); - for (let i = 0; i < subviewchildren.length; i++) { - let item = subviewchildren[i]; - let itemReadable = "Item '" + item.label + "' (classes: " + item.className + ")"; - ok(item.classList.contains("subviewbutton"), itemReadable + " should have the subviewbutton class."); - if (i == 0) { - ok(item.classList.contains(kCustomClass), itemReadable + " should still have its own class, too."); - } - } - - let panelHiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield panelHiddenPromise; - - if (changedPlacement) { - CustomizableUI.reset(); - } - }; -} - -add_task(checkSubviewButtonClass("menuWebDeveloperPopup", "developer-button", "PanelUI-developerItems")); -add_task(checkSubviewButtonClass("viewSidebarMenu", "sidebar-button", "PanelUI-sidebarItems")); - -registerCleanupFunction(function() { - tempElement.classList.remove(kCustomClass) - tempElement = null; -}); diff --git a/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js b/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js deleted file mode 100644 index eb0a8c8ee..000000000 --- a/browser/components/customizableui/test/browser_992747_toggle_noncustomizable_toolbar.js +++ /dev/null @@ -1,26 +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 TOOLBARID = "test-noncustomizable-toolbar-for-toggling"; -function test() { - let tb = document.createElementNS(kNSXUL, "toolbar"); - tb.id = TOOLBARID; - gNavToolbox.appendChild(tb); - try { - CustomizableUI.setToolbarVisibility(TOOLBARID, false); - } catch (ex) { - ok(false, "Should not throw exceptions trying to set toolbar visibility."); - } - is(tb.getAttribute("collapsed"), "true", "Toolbar should be collapsed"); - try { - CustomizableUI.setToolbarVisibility(TOOLBARID, true); - } catch (ex) { - ok(false, "Should not throw exceptions trying to set toolbar visibility."); - } - is(tb.getAttribute("collapsed"), "false", "Toolbar should be uncollapsed"); - tb.remove(); -} - diff --git a/browser/components/customizableui/test/browser_993322_widget_notoolbar.js b/browser/components/customizableui/test/browser_993322_widget_notoolbar.js deleted file mode 100644 index 9264eb78a..000000000 --- a/browser/components/customizableui/test/browser_993322_widget_notoolbar.js +++ /dev/null @@ -1,36 +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 BUTTONID = "test-API-created-widget-toolbar-gone"; -const TOOLBARID = "test-API-created-extra-toolbar"; - -add_task(function*() { - let toolbar = createToolbarWithPlacements(TOOLBARID, []); - CustomizableUI.addWidgetToArea(BUTTONID, TOOLBARID); - is(CustomizableUI.getPlacementOfWidget(BUTTONID).area, TOOLBARID, "Should be on toolbar"); - is(toolbar.children.length, 0, "Toolbar has no kid"); - - CustomizableUI.unregisterArea(TOOLBARID); - CustomizableUI.createWidget({id: BUTTONID, label: "Test widget toolbar gone"}); - - let currentWidget = CustomizableUI.getWidget(BUTTONID); - - yield startCustomizing(); - let buttonNode = document.getElementById(BUTTONID); - ok(buttonNode, "Should find button in window"); - if (buttonNode) { - is(buttonNode.parentNode.localName, "toolbarpaletteitem", "Node should be wrapped"); - is(buttonNode.parentNode.getAttribute("place"), "palette", "Node should be in palette"); - is(buttonNode, gNavToolbox.palette.querySelector("#" + BUTTONID), "Node should really be in palette."); - } - is(currentWidget.forWindow(window).node, buttonNode, "Should have the same node for customize mode"); - yield endCustomizing(); - - CustomizableUI.destroyWidget(BUTTONID); - CustomizableUI.unregisterArea(TOOLBARID, true); - toolbar.remove(); - gAddedToolbars.clear(); -}); diff --git a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js b/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js deleted file mode 100644 index 4d292a929..000000000 --- a/browser/components/customizableui/test/browser_995164_registerArea_during_customize_mode.js +++ /dev/null @@ -1,149 +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 TOOLBARID = "test-toolbar-added-during-customize-mode"; - -// The ID of a button that is not placed (ie, is in the palette) by default -const kNonPlacedWidgetId = "open-file-button"; - -add_task(function*() { - yield startCustomizing(); - let toolbar = createToolbarWithPlacements(TOOLBARID, []); - CustomizableUI.addWidgetToArea(kNonPlacedWidgetId, TOOLBARID); - let button = document.getElementById(kNonPlacedWidgetId); - ok(button, "Button should exist."); - is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should be a wrapper."); - - simulateItemDrag(button, gNavToolbox.palette); - ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette"); - ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette."); - - button.scrollIntoView(); - simulateItemDrag(button, toolbar); - ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette"); - is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar"); - ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar."); - - yield endCustomizing(); - isnot(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should not be a wrapper outside customize mode."); - yield startCustomizing(); - - is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should be a wrapper back in customize mode."); - - simulateItemDrag(button, gNavToolbox.palette); - ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette"); - ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette."); - - ok(!CustomizableUI.inDefaultState, "Not in default state while toolbar is not collapsed yet."); - setToolbarVisibility(toolbar, false); - ok(CustomizableUI.inDefaultState, "In default state while toolbar is collapsed."); - - setToolbarVisibility(toolbar, true); - - info("Check that removing the area registration from within customize mode works"); - CustomizableUI.unregisterArea(TOOLBARID); - ok(CustomizableUI.inDefaultState, "Now that the toolbar is no longer registered, should be in default state."); - ok(!gCustomizeMode.areas.has(toolbar), "Toolbar shouldn't be known to customize mode."); - - CustomizableUI.registerArea(TOOLBARID, {legacy: true, defaultPlacements: []}); - CustomizableUI.registerToolbarNode(toolbar, []); - ok(!CustomizableUI.inDefaultState, "Now that the toolbar is registered again, should no longer be in default state."); - ok(gCustomizeMode.areas.has(toolbar), "Toolbar should be known to customize mode again."); - - button.scrollIntoView(); - simulateItemDrag(button, toolbar); - ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette"); - is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar"); - ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar."); - - let otherWin = yield openAndLoadWindow({}, true); - let otherTB = otherWin.document.createElementNS(kNSXUL, "toolbar"); - otherTB.id = TOOLBARID; - otherTB.setAttribute("customizable", "true"); - let wasInformedCorrectlyOfAreaAppearing = false; - let listener = { - onAreaNodeRegistered: function(aArea, aNode) { - if (aNode == otherTB) { - wasInformedCorrectlyOfAreaAppearing = true; - } - } - }; - CustomizableUI.addListener(listener); - otherWin.gNavToolbox.appendChild(otherTB); - ok(wasInformedCorrectlyOfAreaAppearing, "Should have been told area was registered."); - CustomizableUI.removeListener(listener); - - ok(otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is on other toolbar, too."); - - simulateItemDrag(button, gNavToolbox.palette); - ok(!CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved to the palette"); - ok(gNavToolbox.palette.querySelector(`#${kNonPlacedWidgetId}`), "Button really is in palette."); - ok(!otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is in palette in other window, too."); - - button.scrollIntoView(); - simulateItemDrag(button, toolbar); - ok(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId), "Button moved out of palette"); - is(CustomizableUI.getPlacementOfWidget(kNonPlacedWidgetId).area, TOOLBARID, "Button's back on toolbar"); - ok(toolbar.querySelector(`#${kNonPlacedWidgetId}`), "Button really is on toolbar."); - ok(otherTB.querySelector(`#${kNonPlacedWidgetId}`), "Button is on other toolbar, too."); - - let wasInformedCorrectlyOfAreaDisappearing = false; - // XXXgijs So we could be using promiseWindowClosed here. However, after - // repeated random oranges, I'm instead relying on onWindowClosed below to - // fire appropriately - it is linked to an unload event as well, and so - // reusing it prevents a potential race between unload handlers where the - // one from promiseWindowClosed could fire before the onWindowClosed - // (and therefore onAreaNodeRegistered) one, causing the test to fail. - let windowCloseDeferred = Promise.defer(); - listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { - if (aArea == TOOLBARID) { - is(aNode, otherTB, "Should be informed about other toolbar"); - is(aReason, CustomizableUI.REASON_WINDOW_CLOSED, "Reason should be correct."); - wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_WINDOW_CLOSED); - } - }, - onWindowClosed: function(aWindow) { - if (aWindow == otherWin) { - windowCloseDeferred.resolve(aWindow); - } else { - info("Other window was closed!"); - info("Other window title: " + (aWindow.document && aWindow.document.title)); - info("Our window title: " + (otherWin.document && otherWin.document.title)); - } - }, - }; - CustomizableUI.addListener(listener); - otherWin.close(); - let windowClosed = yield windowCloseDeferred.promise; - - is(windowClosed, otherWin, "Window should have sent onWindowClosed notification."); - ok(wasInformedCorrectlyOfAreaDisappearing, "Should be told about window closing."); - // Closing the other window should not be counted against this window's customize mode: - is(button.parentNode.localName, "toolbarpaletteitem", "Button's parent node should still be a wrapper."); - ok(gCustomizeMode.areas.has(toolbar), "Toolbar should still be a customizable area for this customize mode instance."); - - yield gCustomizeMode.reset(); - - yield endCustomizing(); - - CustomizableUI.removeListener(listener); - wasInformedCorrectlyOfAreaDisappearing = false; - listener = { - onAreaNodeUnregistered: function(aArea, aNode, aReason) { - if (aArea == TOOLBARID) { - is(aNode, toolbar, "Should be informed about this window's toolbar"); - is(aReason, CustomizableUI.REASON_AREA_UNREGISTERED, "Reason for final removal should be correct."); - wasInformedCorrectlyOfAreaDisappearing = (aReason === CustomizableUI.REASON_AREA_UNREGISTERED); - } - }, - } - CustomizableUI.addListener(listener); - removeCustomToolbars(); - ok(wasInformedCorrectlyOfAreaDisappearing, "Should be told about area being unregistered."); - CustomizableUI.removeListener(listener); - ok(CustomizableUI.inDefaultState, "Should be fine after exiting customize mode."); -}); diff --git a/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js b/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js deleted file mode 100644 index b9de5f687..000000000 --- a/browser/components/customizableui/test/browser_996364_registerArea_different_properties.js +++ /dev/null @@ -1,112 +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"; - -// Calling CustomizableUI.registerArea twice with no -// properties should not throw an exception. -add_task(function() { - try { - CustomizableUI.registerArea("area-996364", {}); - CustomizableUI.registerArea("area-996364", {}); - } catch (ex) { - ok(false, ex.message); - } - - CustomizableUI.unregisterArea("area-996364", true); -}); - -add_task(function() { - let exceptionThrown = false; - try { - CustomizableUI.registerArea("area-996364-2", {type: CustomizableUI.TYPE_TOOLBAR, defaultCollapsed: "false"}); - } catch (ex) { - exceptionThrown = true; - } - ok(exceptionThrown, "defaultCollapsed is not allowed as an external property"); - - // No need to unregister the area because registration fails. -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996364-3", {type: CustomizableUI.TYPE_TOOLBAR}); - CustomizableUI.registerArea("area-996364-3", {type: CustomizableUI.TYPE_MENU_PANEL}); - } catch (ex) { - exceptionThrown = ex; - } - ok(exceptionThrown, "Exception expected, an area cannot change types: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - - CustomizableUI.unregisterArea("area-996364-3", true); -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996364-4", {type: CustomizableUI.TYPE_MENU_PANEL}); - CustomizableUI.registerArea("area-996364-4", {type: CustomizableUI.TYPE_TOOLBAR}); - } catch (ex) { - exceptionThrown = ex; - } - ok(exceptionThrown, "Exception expected, an area cannot change types: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - - CustomizableUI.unregisterArea("area-996364-4", true); -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996899-1", { anchor: "PanelUI-menu-button", - type: CustomizableUI.TYPE_MENU_PANEL, - defaultPlacements: [] }); - CustomizableUI.registerArea("area-996899-1", { anchor: "home-button", - type: CustomizableUI.TYPE_MENU_PANEL, - defaultPlacements: [] }); - } catch (ex) { - exceptionThrown = ex; - } - ok(!exceptionThrown, "Changing anchors shouldn't throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - CustomizableUI.unregisterArea("area-996899-1", true); -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996899-2", { anchor: "PanelUI-menu-button", - type: CustomizableUI.TYPE_MENU_PANEL, - defaultPlacements: [] }); - CustomizableUI.registerArea("area-996899-2", { anchor: "PanelUI-menu-button", - type: CustomizableUI.TYPE_MENU_PANEL, - defaultPlacements: ["feed-button"] }); - } catch (ex) { - exceptionThrown = ex; - } - ok(!exceptionThrown, "Changing defaultPlacements shouldn't throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - CustomizableUI.unregisterArea("area-996899-2", true); -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996899-3", { legacy: true }); - CustomizableUI.registerArea("area-996899-3", { legacy: false }); - } catch (ex) { - exceptionThrown = ex; - } - ok(exceptionThrown, "Changing 'legacy' should throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - CustomizableUI.unregisterArea("area-996899-3", true); -}); - -add_task(function() { - let exceptionThrown; - try { - CustomizableUI.registerArea("area-996899-4", { overflowable: true }); - CustomizableUI.registerArea("area-996899-4", { overflowable: false }); - } catch (ex) { - exceptionThrown = ex; - } - ok(exceptionThrown, "Changing 'overflowable' should throw an exception: " + (exceptionThrown ? exceptionThrown : "[no exception]")); - CustomizableUI.unregisterArea("area-996899-4", true); -}); diff --git a/browser/components/customizableui/test/browser_996635_remove_non_widgets.js b/browser/components/customizableui/test/browser_996635_remove_non_widgets.js deleted file mode 100644 index 14a446eec..000000000 --- a/browser/components/customizableui/test/browser_996635_remove_non_widgets.js +++ /dev/null @@ -1,43 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -// NB: This is testing what happens if something that /isn't/ a customizable -// widget gets used in CustomizableUI APIs. Don't use this as an example of -// what should happen in a "normal" case or how you should use the API. -function test() { - // First create a button that isn't customizable, and add it in the nav-bar, - // but not in the customizable part of it (the customization target) but - // next to the main (hamburger) menu button. - const buttonID = "Test-non-widget-non-removable-button"; - let btn = document.createElement("toolbarbutton"); - btn.id = buttonID; - btn.label = "Hi"; - btn.setAttribute("style", "width: 20px; height: 20px; background-color: red"); - document.getElementById("nav-bar").appendChild(btn); - registerCleanupFunction(function() { - btn.remove(); - }); - - // Now try to add this non-customizable button to the tabstrip. This will - // update the internal bookkeeping (ie placements) information, but shouldn't - // move the node. - CustomizableUI.addWidgetToArea(buttonID, CustomizableUI.AREA_TABSTRIP); - let placement = CustomizableUI.getPlacementOfWidget(buttonID); - // Check our bookkeeping - ok(placement, "Button should be placed"); - is(placement && placement.area, CustomizableUI.AREA_TABSTRIP, "Should be placed on tabstrip."); - // Check we didn't move the node. - is(btn.parentNode && btn.parentNode.id, "nav-bar", "Actual button should still be on navbar."); - - // Now remove the node again. This should remove the bookkeeping, but again - // not affect the actual node. - CustomizableUI.removeWidgetFromArea(buttonID); - placement = CustomizableUI.getPlacementOfWidget(buttonID); - // Check our bookkeeping: - ok(!placement, "Button should no longer have a placement."); - // Check our node. - is(btn.parentNode && btn.parentNode.id, "nav-bar", "Actual button should still be on navbar."); -} - diff --git a/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js b/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js deleted file mode 100644 index 2c5f0c79c..000000000 --- a/browser/components/customizableui/test/browser_bootstrapped_custom_toolbar.js +++ /dev/null @@ -1,81 +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"; - -requestLongerTimeout(2); - -const kTestBarID = "testBar"; -const kWidgetID = "characterencoding-button"; - -function createTestBar(aLegacy) { - let testBar = document.createElement("toolbar"); - testBar.id = kTestBarID; - testBar.setAttribute("customizable", "true"); - CustomizableUI.registerArea(kTestBarID, { - type: CustomizableUI.TYPE_TOOLBAR, - legacy: aLegacy, - }); - gNavToolbox.appendChild(testBar); - return testBar; -} - -/** - * Helper function that does the following: - * - * 1) Creates a custom toolbar and registers it - * with CustomizableUI. Sets the legacy attribute - * of the object passed to registerArea to aLegacy. - * 2) Adds the widget with ID aWidgetID to that new - * toolbar. - * 3) Enters customize mode and makes sure that the - * widget is still in the right toolbar. - * 4) Exits customize mode, then removes and deregisters - * the custom toolbar. - * 5) Checks that the widget has no placement. - * 6) Re-adds and re-registers a custom toolbar with the same - * ID and options as the first one. - * 7) Enters customize mode and checks that the widget is - * properly back in the toolbar. - * 8) Exits customize mode, removes and de-registers the - * toolbar, and resets the toolbars to default. - */ -function checkRestoredPresence(aWidgetID, aLegacy) { - return Task.spawn(function* () { - let testBar = createTestBar(aLegacy); - CustomizableUI.addWidgetToArea(aWidgetID, kTestBarID); - let placement = CustomizableUI.getPlacementOfWidget(aWidgetID); - is(placement.area, kTestBarID, - "Expected " + aWidgetID + " to be in the test toolbar"); - - CustomizableUI.unregisterArea(testBar.id); - testBar.remove(); - - placement = CustomizableUI.getPlacementOfWidget(aWidgetID); - is(placement, null, "Expected " + aWidgetID + " to be in the palette"); - - testBar = createTestBar(aLegacy); - - yield startCustomizing(); - placement = CustomizableUI.getPlacementOfWidget(aWidgetID); - is(placement.area, kTestBarID, - "Expected " + aWidgetID + " to be in the test toolbar"); - yield endCustomizing(); - - CustomizableUI.unregisterArea(testBar.id); - testBar.remove(); - - yield resetCustomization(); - }); -} - -add_task(function* () { - yield checkRestoredPresence("downloads-button", false); - yield checkRestoredPresence("downloads-button", true); -}); - -add_task(function* () { - yield checkRestoredPresence("characterencoding-button", false); - yield checkRestoredPresence("characterencoding-button", true); -}); diff --git a/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js b/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js deleted file mode 100644 index 31dd42ad8..000000000 --- a/browser/components/customizableui/test/browser_check_tooltips_in_navbar.js +++ /dev/null @@ -1,14 +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"; - -add_task(function* check_tooltips_in_navbar() { - yield startCustomizing(); - let homeButtonWrapper = document.getElementById("wrapper-home-button"); - let homeButton = document.getElementById("home-button"); - is(homeButtonWrapper.getAttribute("tooltiptext"), homeButton.getAttribute("label"), "the wrapper's tooltip should match the button's label"); - ok(homeButtonWrapper.getAttribute("tooltiptext"), "the button should have tooltip text"); - yield endCustomizing(); -}); diff --git a/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js b/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js deleted file mode 100644 index 8e1950291..000000000 --- a/browser/components/customizableui/test/browser_customizemode_contextmenu_menubuttonstate.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; - -add_task(function*() { - ok(!PanelUI.menuButton.hasAttribute("open"), "Menu button should not be 'pressed' outside customize mode"); - yield startCustomizing(); - - is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode"); - - let contextMenu = document.getElementById("customizationPanelItemContextMenu"); - let shownPromise = popupShown(contextMenu); - let newWindowButton = document.getElementById("wrapper-new-window-button"); - EventUtils.synthesizeMouse(newWindowButton, 2, 2, {type: "contextmenu", button: 2}); - yield shownPromise; - is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode after opening a context menu"); - - let hiddenContextPromise = popupHidden(contextMenu); - contextMenu.hidePopup(); - yield hiddenContextPromise; - is(PanelUI.menuButton.getAttribute("open"), "true", "Menu button should be 'pressed' when in customize mode after hiding a context menu"); - yield endCustomizing(); - - ok(!PanelUI.menuButton.hasAttribute("open"), "Menu button should not be 'pressed' after ending customize mode"); -}); - diff --git a/browser/components/customizableui/test/browser_panel_toggle.js b/browser/components/customizableui/test/browser_panel_toggle.js deleted file mode 100644 index 4c286fb85..000000000 --- a/browser/components/customizableui/test/browser_panel_toggle.js +++ /dev/null @@ -1,43 +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 menu panel UI. - */ - -// Show and hide the menu panel programmatically without an event (like UITour.jsm would) -add_task(function*() { - let shownPromise = promisePanelShown(window); - PanelUI.show(); - yield shownPromise; - - is(PanelUI.panel.getAttribute("panelopen"), "true", "Check that panel has panelopen attribute"); - is(PanelUI.panel.state, "open", "Check that panel state is 'open'"); - - let hiddenPromise = promisePanelHidden(window); - PanelUI.hide(); - yield hiddenPromise; - - ok(!PanelUI.panel.hasAttribute("panelopen"), "Check that panel doesn't have the panelopen attribute"); - is(PanelUI.panel.state, "closed", "Check that panel state is 'closed'"); -}); - -// Toggle the menu panel open and closed -add_task(function*() { - let shownPromise = promisePanelShown(window); - PanelUI.toggle({type: "command"}); - yield shownPromise; - - is(PanelUI.panel.getAttribute("panelopen"), "true", "Check that panel has panelopen attribute"); - is(PanelUI.panel.state, "open", "Check that panel state is 'open'"); - - let hiddenPromise = promisePanelHidden(window); - PanelUI.toggle({type: "command"}); - yield hiddenPromise; - - ok(!PanelUI.panel.hasAttribute("panelopen"), "Check that panel doesn't have the panelopen attribute"); - is(PanelUI.panel.state, "closed", "Check that panel state is 'closed'"); -}); diff --git a/browser/components/customizableui/test/browser_switch_to_customize_mode.js b/browser/components/customizableui/test/browser_switch_to_customize_mode.js deleted file mode 100644 index 459ea7a1c..000000000 --- a/browser/components/customizableui/test/browser_switch_to_customize_mode.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; - -add_task(function*() { - yield startCustomizing(); - is(gBrowser.tabs.length, 2, "Should have 2 tabs"); - - let paletteKidCount = document.getElementById("customization-palette").childElementCount; - let nonCustomizingTab = gBrowser.tabContainer.querySelector("tab:not([customizemode=true])"); - let finishedCustomizing = BrowserTestUtils.waitForEvent(gNavToolbox, "aftercustomization"); - yield BrowserTestUtils.switchTab(gBrowser, nonCustomizingTab); - yield finishedCustomizing; - - let startedCount = 0; - let handler = e => startedCount++; - gNavToolbox.addEventListener("customizationstarting", handler); - yield startCustomizing(); - CustomizableUI.removeWidgetFromArea("home-button"); - yield gCustomizeMode.reset().catch(e => { - ok(false, "Threw an exception trying to reset after making modifications in customize mode: " + e); - }); - - let newKidCount = document.getElementById("customization-palette").childElementCount; - is(newKidCount, paletteKidCount, "Should have just as many items in the palette as before."); - yield endCustomizing(); - is(startedCount, 1, "Should have only started once"); - gNavToolbox.removeEventListener("customizationstarting", handler); - let customizableToolbars = document.querySelectorAll("toolbar[customizable=true]:not([autohide=true])"); - for (let toolbar of customizableToolbars) { - ok(!toolbar.hasAttribute("customizing"), "Toolbar " + toolbar.id + " is no longer customizing"); - } - let menuitem = document.getElementById("PanelUI-customize"); - isnot(menuitem.getAttribute("label"), menuitem.getAttribute("exitLabel"), "Should have exited successfully"); -}); - diff --git a/browser/components/customizableui/test/head.js b/browser/components/customizableui/test/head.js deleted file mode 100644 index 7b8d84e20..000000000 --- a/browser/components/customizableui/test/head.js +++ /dev/null @@ -1,499 +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"; - -// Avoid leaks by using tmp for imports... -var tmp = {}; -Cu.import("resource://gre/modules/Promise.jsm", tmp); -Cu.import("resource:///modules/CustomizableUI.jsm", tmp); -Cu.import("resource://gre/modules/AppConstants.jsm", tmp); -var {Promise, CustomizableUI, AppConstants} = tmp; - -var EventUtils = {}; -Services.scriptloader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - -Services.prefs.setBoolPref("browser.uiCustomization.skipSourceNodeCheck", true); -registerCleanupFunction(() => Services.prefs.clearUserPref("browser.uiCustomization.skipSourceNodeCheck")); - -// Remove temporary e10s related new window options in customize ui, -// they break a lot of tests. -CustomizableUI.destroyWidget("e10s-button"); -CustomizableUI.removeWidgetFromArea("e10s-button"); - -var {synthesizeDragStart, synthesizeDrop} = EventUtils; - -const kNSXUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; -const kTabEventFailureTimeoutInMs = 20000; - -function createDummyXULButton(id, label, win = window) { - let btn = document.createElementNS(kNSXUL, "toolbarbutton"); - btn.id = id; - btn.setAttribute("label", label || id); - btn.className = "toolbarbutton-1 chromeclass-toolbar-additional"; - win.gNavToolbox.palette.appendChild(btn); - return btn; -} - -var gAddedToolbars = new Set(); - -function createToolbarWithPlacements(id, placements = []) { - gAddedToolbars.add(id); - let tb = document.createElementNS(kNSXUL, "toolbar"); - tb.id = id; - tb.setAttribute("customizable", "true"); - CustomizableUI.registerArea(id, { - type: CustomizableUI.TYPE_TOOLBAR, - defaultPlacements: placements - }); - gNavToolbox.appendChild(tb); - return tb; -} - -function createOverflowableToolbarWithPlacements(id, placements) { - gAddedToolbars.add(id); - - let tb = document.createElementNS(kNSXUL, "toolbar"); - tb.id = id; - tb.setAttribute("customizationtarget", id + "-target"); - - let customizationtarget = document.createElementNS(kNSXUL, "hbox"); - customizationtarget.id = id + "-target"; - customizationtarget.setAttribute("flex", "1"); - tb.appendChild(customizationtarget); - - let overflowPanel = document.createElementNS(kNSXUL, "panel"); - overflowPanel.id = id + "-overflow"; - document.getElementById("mainPopupSet").appendChild(overflowPanel); - - let overflowList = document.createElementNS(kNSXUL, "vbox"); - overflowList.id = id + "-overflow-list"; - overflowPanel.appendChild(overflowList); - - let chevron = document.createElementNS(kNSXUL, "toolbarbutton"); - chevron.id = id + "-chevron"; - tb.appendChild(chevron); - - CustomizableUI.registerArea(id, { - type: CustomizableUI.TYPE_TOOLBAR, - defaultPlacements: placements, - overflowable: true, - }); - - tb.setAttribute("customizable", "true"); - tb.setAttribute("overflowable", "true"); - tb.setAttribute("overflowpanel", overflowPanel.id); - tb.setAttribute("overflowtarget", overflowList.id); - tb.setAttribute("overflowbutton", chevron.id); - - gNavToolbox.appendChild(tb); - return tb; -} - -function removeCustomToolbars() { - CustomizableUI.reset(); - for (let toolbarId of gAddedToolbars) { - CustomizableUI.unregisterArea(toolbarId, true); - let tb = document.getElementById(toolbarId); - if (tb.hasAttribute("overflowpanel")) { - let panel = document.getElementById(tb.getAttribute("overflowpanel")); - if (panel) - panel.remove(); - } - tb.remove(); - } - gAddedToolbars.clear(); -} - -function getToolboxCustomToolbarId(toolbarName) { - return "__customToolbar_" + toolbarName.replace(" ", "_"); -} - -function resetCustomization() { - return CustomizableUI.reset(); -} - -function isInDevEdition() { - return AppConstants.MOZ_DEV_EDITION; -} - -function removeDeveloperButtonIfDevEdition(areaPanelPlacements) { - if (isInDevEdition()) { - areaPanelPlacements.splice(areaPanelPlacements.indexOf("developer-button"), 1); - } -} - -function assertAreaPlacements(areaId, expectedPlacements) { - let actualPlacements = getAreaWidgetIds(areaId); - placementArraysEqual(areaId, actualPlacements, expectedPlacements); -} - -function placementArraysEqual(areaId, actualPlacements, expectedPlacements) { - is(actualPlacements.length, expectedPlacements.length, - "Area " + areaId + " should have " + expectedPlacements.length + " items."); - let minItems = Math.min(expectedPlacements.length, actualPlacements.length); - for (let i = 0; i < minItems; i++) { - if (typeof expectedPlacements[i] == "string") { - is(actualPlacements[i], expectedPlacements[i], - "Item " + i + " in " + areaId + " should match expectations."); - } else if (expectedPlacements[i] instanceof RegExp) { - ok(expectedPlacements[i].test(actualPlacements[i]), - "Item " + i + " (" + actualPlacements[i] + ") in " + - areaId + " should match " + expectedPlacements[i]); - } else { - ok(false, "Unknown type of expected placement passed to " + - " assertAreaPlacements. Is your test broken?"); - } - } -} - -function todoAssertAreaPlacements(areaId, expectedPlacements) { - let actualPlacements = getAreaWidgetIds(areaId); - let isPassing = actualPlacements.length == expectedPlacements.length; - let minItems = Math.min(expectedPlacements.length, actualPlacements.length); - for (let i = 0; i < minItems; i++) { - if (typeof expectedPlacements[i] == "string") { - isPassing = isPassing && actualPlacements[i] == expectedPlacements[i]; - } else if (expectedPlacements[i] instanceof RegExp) { - isPassing = isPassing && expectedPlacements[i].test(actualPlacements[i]); - } else { - ok(false, "Unknown type of expected placement passed to " + - " assertAreaPlacements. Is your test broken?"); - } - } - todo(isPassing, "The area placements for " + areaId + - " should equal the expected placements."); -} - -function getAreaWidgetIds(areaId) { - return CustomizableUI.getWidgetIdsInArea(areaId); -} - -function simulateItemDrag(aToDrag, aTarget) { - synthesizeDrop(aToDrag.parentNode, aTarget); -} - -function endCustomizing(aWindow=window) { - if (aWindow.document.documentElement.getAttribute("customizing") != "true") { - return true; - } - Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true); - let deferredEndCustomizing = Promise.defer(); - function onCustomizationEnds() { - Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false); - aWindow.gNavToolbox.removeEventListener("aftercustomization", onCustomizationEnds); - deferredEndCustomizing.resolve(); - } - aWindow.gNavToolbox.addEventListener("aftercustomization", onCustomizationEnds); - aWindow.gCustomizeMode.exit(); - - return deferredEndCustomizing.promise; -} - -function startCustomizing(aWindow=window) { - if (aWindow.document.documentElement.getAttribute("customizing") == "true") { - return null; - } - Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", true); - let deferred = Promise.defer(); - function onCustomizing() { - aWindow.gNavToolbox.removeEventListener("customizationready", onCustomizing); - Services.prefs.setBoolPref("browser.uiCustomization.disableAnimation", false); - deferred.resolve(); - } - aWindow.gNavToolbox.addEventListener("customizationready", onCustomizing); - aWindow.gCustomizeMode.enter(); - return deferred.promise; -} - -function promiseObserverNotified(aTopic) { - let deferred = Promise.defer(); - Services.obs.addObserver(function onNotification(aSubject, aTopic, aData) { - Services.obs.removeObserver(onNotification, aTopic); - deferred.resolve({subject: aSubject, data: aData}); - }, aTopic, false); - return deferred.promise; -} - -function openAndLoadWindow(aOptions, aWaitForDelayedStartup=false) { - let deferred = Promise.defer(); - let win = OpenBrowserWindow(aOptions); - if (aWaitForDelayedStartup) { - Services.obs.addObserver(function onDS(aSubject, aTopic, aData) { - if (aSubject != win) { - return; - } - Services.obs.removeObserver(onDS, "browser-delayed-startup-finished"); - deferred.resolve(win); - }, "browser-delayed-startup-finished", false); - - } else { - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad); - deferred.resolve(win); - }); - } - return deferred.promise; -} - -function promiseWindowClosed(win) { - let deferred = Promise.defer(); - win.addEventListener("unload", function onunload() { - win.removeEventListener("unload", onunload); - deferred.resolve(); - }); - win.close(); - return deferred.promise; -} - -function promisePanelShown(win) { - let panelEl = win.PanelUI.panel; - return promisePanelElementShown(win, panelEl); -} - -function promiseOverflowShown(win) { - let panelEl = win.document.getElementById("widget-overflow"); - return promisePanelElementShown(win, panelEl); -} - -function promisePanelElementShown(win, aPanel) { - let deferred = Promise.defer(); - let timeoutId = win.setTimeout(() => { - deferred.reject("Panel did not show within 20 seconds."); - }, 20000); - function onPanelOpen(e) { - aPanel.removeEventListener("popupshown", onPanelOpen); - win.clearTimeout(timeoutId); - deferred.resolve(); - } - aPanel.addEventListener("popupshown", onPanelOpen); - return deferred.promise; -} - -function promisePanelHidden(win) { - let panelEl = win.PanelUI.panel; - return promisePanelElementHidden(win, panelEl); -} - -function promiseOverflowHidden(win) { - let panelEl = document.getElementById("widget-overflow"); - return promisePanelElementHidden(win, panelEl); -} - -function promisePanelElementHidden(win, aPanel) { - let deferred = Promise.defer(); - let timeoutId = win.setTimeout(() => { - deferred.reject("Panel did not hide within 20 seconds."); - }, 20000); - function onPanelClose(e) { - aPanel.removeEventListener("popuphidden", onPanelClose); - win.clearTimeout(timeoutId); - deferred.resolve(); - } - aPanel.addEventListener("popuphidden", onPanelClose); - return deferred.promise; -} - -function isPanelUIOpen() { - return PanelUI.panel.state == "open" || PanelUI.panel.state == "showing"; -} - -function subviewShown(aSubview) { - let deferred = Promise.defer(); - let win = aSubview.ownerGlobal; - let timeoutId = win.setTimeout(() => { - deferred.reject("Subview (" + aSubview.id + ") did not show within 20 seconds."); - }, 20000); - function onViewShowing(e) { - aSubview.removeEventListener("ViewShowing", onViewShowing); - win.clearTimeout(timeoutId); - deferred.resolve(); - } - aSubview.addEventListener("ViewShowing", onViewShowing); - return deferred.promise; -} - -function subviewHidden(aSubview) { - let deferred = Promise.defer(); - let win = aSubview.ownerGlobal; - let timeoutId = win.setTimeout(() => { - deferred.reject("Subview (" + aSubview.id + ") did not hide within 20 seconds."); - }, 20000); - function onViewHiding(e) { - aSubview.removeEventListener("ViewHiding", onViewHiding); - win.clearTimeout(timeoutId); - deferred.resolve(); - } - aSubview.addEventListener("ViewHiding", onViewHiding); - return deferred.promise; -} - -function waitForCondition(aConditionFn, aMaxTries=50, aCheckInterval=100) { - function tryNow() { - tries++; - if (aConditionFn()) { - deferred.resolve(); - } else if (tries < aMaxTries) { - tryAgain(); - } else { - deferred.reject("Condition timed out: " + aConditionFn.toSource()); - } - } - function tryAgain() { - setTimeout(tryNow, aCheckInterval); - } - let deferred = Promise.defer(); - let tries = 0; - tryAgain(); - return deferred.promise; -} - -function waitFor(aTimeout=100) { - let deferred = Promise.defer(); - setTimeout(() => deferred.resolve(), aTimeout); - return deferred.promise; -} - -/** - * Starts a load in an existing tab and waits for it to finish (via some event). - * - * @param aTab The tab to load into. - * @param aUrl The url to load. - * @param aEventType The load event type to wait for. Defaults to "load". - * @return {Promise} resolved when the event is handled. - */ -function promiseTabLoadEvent(aTab, aURL) { - let browser = aTab.linkedBrowser; - - BrowserTestUtils.loadURI(browser, aURL); - return BrowserTestUtils.browserLoaded(browser); -} - -/** - * Navigate back or forward in tab history and wait for it to finish. - * - * @param aDirection Number to indicate to move backward or forward in history. - * @param aConditionFn Function that returns the result of an evaluated condition - * that needs to be `true` to resolve the promise. - * @return {Promise} resolved when navigation has finished. - */ -function promiseTabHistoryNavigation(aDirection = -1, aConditionFn) { - let deferred = Promise.defer(); - - let timeoutId = setTimeout(() => { - gBrowser.removeEventListener("pageshow", listener, true); - deferred.reject("Pageshow did not happen within " + kTabEventFailureTimeoutInMs + "ms"); - }, kTabEventFailureTimeoutInMs); - - function listener(event) { - gBrowser.removeEventListener("pageshow", listener, true); - clearTimeout(timeoutId); - - if (aConditionFn) { - waitForCondition(aConditionFn).then(() => deferred.resolve(), - aReason => deferred.reject(aReason)); - } else { - deferred.resolve(); - } - } - gBrowser.addEventListener("pageshow", listener, true); - - content.history.go(aDirection); - - return deferred.promise; -} - -/** - * Wait for an attribute on a node to change - * - * @param aNode Node on which the mutation is expected - * @param aAttribute The attribute we're interested in - * @param aFilterFn A function to check if the new value is what we want. - * @return {Promise} resolved when the requisite mutation shows up. - */ -function promiseAttributeMutation(aNode, aAttribute, aFilterFn) { - return new Promise((resolve, reject) => { - info("waiting for mutation of attribute '" + aAttribute + "'."); - let obs = new MutationObserver((mutations) => { - for (let mut of mutations) { - let attr = mut.attributeName; - let newValue = mut.target.getAttribute(attr); - if (aFilterFn(newValue)) { - ok(true, "mutation occurred: attribute '" + attr + "' changed to '" + newValue + "' from '" + mut.oldValue + "'."); - obs.disconnect(); - resolve(); - } else { - info("Ignoring mutation that produced value " + newValue + " because of filter."); - } - } - }); - obs.observe(aNode, {attributeFilter: [aAttribute]}); - }); -} - -function popupShown(aPopup) { - return promisePopupEvent(aPopup, "shown"); -} - -function popupHidden(aPopup) { - return promisePopupEvent(aPopup, "hidden"); -} - -/** - * Returns a Promise that resolves when aPopup fires an event of type - * aEventType. Times out and rejects after 20 seconds. - * - * @param aPopup the popup to monitor for events. - * @param aEventSuffix the _suffix_ for the popup event type to watch for. - * - * Example usage: - * let popupShownPromise = promisePopupEvent(somePopup, "shown"); - * // ... something that opens a popup - * yield popupShownPromise; - * - * let popupHiddenPromise = promisePopupEvent(somePopup, "hidden"); - * // ... something that hides a popup - * yield popupHiddenPromise; - */ -function promisePopupEvent(aPopup, aEventSuffix) { - let deferred = Promise.defer(); - let eventType = "popup" + aEventSuffix; - - function onPopupEvent(e) { - aPopup.removeEventListener(eventType, onPopupEvent); - deferred.resolve(); - } - - aPopup.addEventListener(eventType, onPopupEvent); - return deferred.promise; -} - -// This is a simpler version of the context menu check that -// exists in contextmenu_common.js. -function checkContextMenu(aContextMenu, aExpectedEntries, aWindow=window) { - let childNodes = [...aContextMenu.childNodes]; - // Ignore hidden nodes: - childNodes = childNodes.filter((n) => !n.hidden); - - for (let i = 0; i < childNodes.length; i++) { - let menuitem = childNodes[i]; - try { - if (aExpectedEntries[i][0] == "---") { - is(menuitem.localName, "menuseparator", "menuseparator expected"); - continue; - } - - let selector = aExpectedEntries[i][0]; - ok(menuitem.matches(selector), "menuitem should match " + selector + " selector"); - let commandValue = menuitem.getAttribute("command"); - let relatedCommand = commandValue ? aWindow.document.getElementById(commandValue) : null; - let menuItemDisabled = relatedCommand ? - relatedCommand.getAttribute("disabled") == "true" : - menuitem.getAttribute("disabled") == "true"; - is(menuItemDisabled, !aExpectedEntries[i][1], "disabled state for " + selector); - } catch (e) { - ok(false, "Exception when checking context menu: " + e); - } - } -} diff --git a/browser/components/customizableui/test/support/feeds_test_page.html b/browser/components/customizableui/test/support/feeds_test_page.html deleted file mode 100644 index be78e4dff..000000000 --- a/browser/components/customizableui/test/support/feeds_test_page.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<head> - <title>Feeds test page</title> - <link rel="alternate" type="application/rss+xml" href="test-feed.xml" title="Test feed"> -</head> - -<body> - This is a test page for feeds -</body> -</html> diff --git a/browser/components/customizableui/test/support/test-feed.xml b/browser/components/customizableui/test/support/test-feed.xml deleted file mode 100644 index 0e700b6d8..000000000 --- a/browser/components/customizableui/test/support/test-feed.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2010-08-22T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id> - - <entry> - - <title>Item</title> - <link href="http://example.org/first"/> - <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id> - <updated>2010-08-22T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/customizableui/test/support/test_967000_charEncoding_page.html b/browser/components/customizableui/test/support/test_967000_charEncoding_page.html deleted file mode 100644 index c8d35115c..000000000 --- a/browser/components/customizableui/test/support/test_967000_charEncoding_page.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE html>
-<html>
- <head>
- <meta charset="utf-8">
- <title>Test page</title>
- </head>
-
- <body>
- This is a test page
- </body>
-</html>
diff --git a/browser/components/dirprovider/tests/unit/.eslintrc.js b/browser/components/dirprovider/tests/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/dirprovider/tests/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/downloads/test/browser/.eslintrc.js b/browser/components/downloads/test/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/downloads/test/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/downloads/test/browser/browser.ini b/browser/components/downloads/test/browser/browser.ini deleted file mode 100644 index 76f026c78..000000000 --- a/browser/components/downloads/test/browser/browser.ini +++ /dev/null @@ -1,15 +0,0 @@ -[DEFAULT] -support-files = head.js - -[browser_basic_functionality.js] -[browser_first_download_panel.js] -skip-if = os == "linux" # Bug 949434 -[browser_overflow_anchor.js] -skip-if = os == "linux" # Bug 952422 -[browser_confirm_unblock_download.js] -[browser_iframe_gone_mid_download.js] -[browser_indicatorDrop.js] -[browser_libraryDrop.js] -[browser_downloads_panel_block.js] -[browser_downloads_panel_footer.js] -[browser_downloads_panel_height.js] diff --git a/browser/components/downloads/test/browser/browser_basic_functionality.js b/browser/components/downloads/test/browser/browser_basic_functionality.js deleted file mode 100644 index 564a344a7..000000000 --- a/browser/components/downloads/test/browser/browser_basic_functionality.js +++ /dev/null @@ -1,56 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -registerCleanupFunction(function*() { - yield task_resetState(); -}); - -/** - * Make sure the downloads panel can display items in the right order and - * contains the expected data. - */ -add_task(function* test_basic_functionality() { - // Display one of each download state. - const DownloadData = [ - { state: nsIDM.DOWNLOAD_NOTSTARTED }, - { state: nsIDM.DOWNLOAD_PAUSED }, - { state: nsIDM.DOWNLOAD_FINISHED }, - { state: nsIDM.DOWNLOAD_FAILED }, - { state: nsIDM.DOWNLOAD_CANCELED }, - ]; - - // Wait for focus first - yield promiseFocus(); - - // Ensure that state is reset in case previous tests didn't finish. - yield task_resetState(); - - // For testing purposes, show all the download items at once. - var originalCountLimit = DownloadsView.kItemCountLimit; - DownloadsView.kItemCountLimit = DownloadData.length; - registerCleanupFunction(function () { - DownloadsView.kItemCountLimit = originalCountLimit; - }); - - // Populate the downloads database with the data required by this test. - yield task_addDownloads(DownloadData); - - // Open the user interface and wait for data to be fully loaded. - yield task_openPanel(); - - // Test item data and count. This also tests the ordering of the display. - let richlistbox = document.getElementById("downloadsListBox"); - /* disabled for failing intermittently (bug 767828) - is(richlistbox.children.length, DownloadData.length, - "There is the correct number of richlistitems"); - */ - let itemCount = richlistbox.children.length; - for (let i = 0; i < itemCount; i++) { - let element = richlistbox.children[itemCount - i - 1]; - let download = DownloadsView.itemForElement(element).download; - is(DownloadsCommon.stateOfDownload(download), DownloadData[i].state, - "Download states match up"); - } -}); diff --git a/browser/components/downloads/test/browser/browser_confirm_unblock_download.js b/browser/components/downloads/test/browser/browser_confirm_unblock_download.js deleted file mode 100644 index 8ba37ba64..000000000 --- a/browser/components/downloads/test/browser/browser_confirm_unblock_download.js +++ /dev/null @@ -1,92 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -// Tests the dialog which allows the user to unblock a downloaded file. - -registerCleanupFunction(() => {}); - -function* assertDialogResult({ args, buttonToClick, expectedResult }) { - promiseAlertDialogOpen(buttonToClick); - is(yield DownloadsCommon.confirmUnblockDownload(args), expectedResult); -} - -/** - * Tests the "unblock" dialog, for each of the possible verdicts. - */ -add_task(function* test_unblock_dialog_unblock() { - for (let verdict of [Downloads.Error.BLOCK_VERDICT_MALWARE, - Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED, - Downloads.Error.BLOCK_VERDICT_UNCOMMON]) { - let args = { verdict, window, dialogType: "unblock" }; - - // Test both buttons. - yield assertDialogResult({ - args, - buttonToClick: "accept", - expectedResult: "unblock", - }); - yield assertDialogResult({ - args, - buttonToClick: "cancel", - expectedResult: "cancel", - }); - } -}); - -/** - * Tests the "chooseUnblock" dialog for potentially unwanted downloads. - */ -add_task(function* test_chooseUnblock_dialog() { - let args = { - verdict: Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED, - window, - dialogType: "chooseUnblock", - }; - - // Test each of the three buttons. - yield assertDialogResult({ - args, - buttonToClick: "accept", - expectedResult: "unblock", - }); - yield assertDialogResult({ - args, - buttonToClick: "cancel", - expectedResult: "cancel", - }); - yield assertDialogResult({ - args, - buttonToClick: "extra1", - expectedResult: "confirmBlock", - }); -}); - -/** - * Tests the "chooseOpen" dialog for uncommon downloads. - */ -add_task(function* test_chooseOpen_dialog() { - let args = { - verdict: Downloads.Error.BLOCK_VERDICT_UNCOMMON, - window, - dialogType: "chooseOpen", - }; - - // Test each of the three buttons. - yield assertDialogResult({ - args, - buttonToClick: "accept", - expectedResult: "open", - }); - yield assertDialogResult({ - args, - buttonToClick: "cancel", - expectedResult: "cancel", - }); - yield assertDialogResult({ - args, - buttonToClick: "extra1", - expectedResult: "confirmBlock", - }); -}); diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_block.js b/browser/components/downloads/test/browser/browser_downloads_panel_block.js deleted file mode 100644 index 05056e842..000000000 --- a/browser/components/downloads/test/browser/browser_downloads_panel_block.js +++ /dev/null @@ -1,183 +0,0 @@ -"use strict"; - -add_task(function* mainTest() { - yield task_resetState(); - - let verdicts = [ - Downloads.Error.BLOCK_VERDICT_UNCOMMON, - Downloads.Error.BLOCK_VERDICT_MALWARE, - Downloads.Error.BLOCK_VERDICT_POTENTIALLY_UNWANTED, - ]; - yield task_addDownloads(verdicts.map(v => makeDownload(v))); - - // Check that the richlistitem for each download is correct. - for (let i = 0; i < verdicts.length; i++) { - yield openPanel(); - - // The current item is always the first one in the listbox since each - // iteration of this loop removes the item at the end. - let item = DownloadsView.richListBox.firstChild; - - // Open the panel and click the item to show the subview. - EventUtils.sendMouseEvent({ type: "click" }, item); - yield promiseSubviewShown(true); - - // Items are listed in newest-to-oldest order, so e.g. the first item's - // verdict is the last element in the verdicts array. - Assert.ok(DownloadsBlockedSubview.subview.getAttribute("verdict"), - verdicts[verdicts.count - i - 1]); - - // Click the sliver of the main view that's still showing on the left to go - // back to it. - EventUtils.synthesizeMouse(DownloadsPanel.panel, 10, 10, {}, window); - yield promiseSubviewShown(false); - - // Show the subview again. - EventUtils.sendMouseEvent({ type: "click" }, item); - yield promiseSubviewShown(true); - - // Click the Open button. The download should be unblocked and then opened, - // i.e., unblockAndOpenDownload() should be called on the item. The panel - // should also be closed as a result, so wait for that too. - let unblockOpenPromise = promiseUnblockAndOpenDownloadCalled(item); - let hidePromise = promisePanelHidden(); - EventUtils.synthesizeMouse(DownloadsBlockedSubview.elements.openButton, - 10, 10, {}, window); - yield unblockOpenPromise; - yield hidePromise; - - window.focus(); - yield SimpleTest.promiseFocus(window); - - // Reopen the panel and show the subview again. - yield openPanel(); - - EventUtils.sendMouseEvent({ type: "click" }, item); - yield promiseSubviewShown(true); - - // Click the Remove button. The panel should close and the item should be - // removed from it. - EventUtils.synthesizeMouse(DownloadsBlockedSubview.elements.deleteButton, - 10, 10, {}, window); - yield promisePanelHidden(); - yield openPanel(); - - Assert.ok(!item.parentNode); - DownloadsPanel.hidePanel(); - yield promisePanelHidden(); - } - - yield task_resetState(); -}); - -function* openPanel() { - // This function is insane but something intermittently causes the panel to be - // closed as soon as it's opening on Linux ASAN. Maybe it would also happen - // on other build machines if the test ran often enough. Not only is the - // panel closed, it's closed while it's opening, leaving DownloadsPanel._state - // such that when you try to open the panel again, it thinks it's already - // open, but it's not. The result is that the test times out. - // - // What this does is call DownloadsPanel.showPanel over and over again until - // the panel is really open. There are a few wrinkles: - // - // (1) When panel.state is "open", check four more times (for a total of five) - // before returning to make the panel stays open. - // (2) If the panel is not open, check the _state. It should be either - // kStateUninitialized or kStateHidden. If it's not, then the panel is in the - // process of opening -- or maybe it's stuck in that process -- so reset the - // _state to kStateHidden. - // (3) If the _state is not kStateUninitialized or kStateHidden, then it may - // actually be properly opening and not stuck at all. To avoid always closing - // the panel while it's properly opening, use an exponential backoff mechanism - // for retries. - // - // If all that fails, then the test will time out, but it would have timed out - // anyway. - - yield promiseFocus(); - yield new Promise(resolve => { - let verifyCount = 5; - let backoff = 0; - let iBackoff = 0; - let interval = setInterval(() => { - if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") { - if (verifyCount > 0) { - verifyCount--; - } else { - clearInterval(interval); - resolve(); - } - } else { - if (iBackoff < backoff) { - // Keep backing off before trying again. - iBackoff++; - } else { - // Try (or retry) opening the panel. - verifyCount = 5; - backoff = Math.max(1, 2 * backoff); - iBackoff = 0; - if (DownloadsPanel._state != DownloadsPanel.kStateUninitialized) { - DownloadsPanel._state = DownloadsPanel.kStateHidden; - } - DownloadsPanel.showPanel(); - } - } - }, 100); - }); -} - -function promisePanelHidden() { - return new Promise(resolve => { - if (!DownloadsPanel.panel || DownloadsPanel.panel.state == "closed") { - resolve(); - return; - } - DownloadsPanel.panel.addEventListener("popuphidden", function onHidden() { - DownloadsPanel.panel.removeEventListener("popuphidden", onHidden); - setTimeout(resolve, 0); - }); - }); -} - -function makeDownload(verdict) { - return { - state: nsIDM.DOWNLOAD_DIRTY, - hasBlockedData: true, - errorObj: { - result: Components.results.NS_ERROR_FAILURE, - message: "Download blocked.", - becauseBlocked: true, - becauseBlockedByReputationCheck: true, - reputationCheckVerdict: verdict, - }, - }; -} - -function promiseSubviewShown(shown) { - // More terribleness, but I'm tired of fighting intermittent timeouts on try. - // Just poll for the subview and wait a second before resolving the promise. - return new Promise(resolve => { - let interval = setInterval(() => { - if (shown == DownloadsBlockedSubview.view.showingSubView && - !DownloadsBlockedSubview.view._transitioning) { - clearInterval(interval); - setTimeout(resolve, 1000); - return; - } - }, 0); - }); -} - -function promiseUnblockAndOpenDownloadCalled(item) { - return new Promise(resolve => { - let realFn = item._shell.unblockAndOpenDownload; - item._shell.unblockAndOpenDownload = () => { - item._shell.unblockAndOpenDownload = realFn; - resolve(); - // unblockAndOpenDownload returns a promise (that's resolved when the file - // is opened). - return Promise.resolve(); - }; - }); -} diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_footer.js b/browser/components/downloads/test/browser/browser_downloads_panel_footer.js deleted file mode 100644 index 4083dde98..000000000 --- a/browser/components/downloads/test/browser/browser_downloads_panel_footer.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; - -function *task_openDownloadsSubPanel() { - let downloadSubPanel = document.getElementById("downloadSubPanel"); - let popupShownPromise = BrowserTestUtils.waitForEvent(downloadSubPanel, "popupshown"); - - let downloadsDropmarker = document.getElementById("downloadsFooterDropmarker"); - EventUtils.synthesizeMouseAtCenter(downloadsDropmarker, {}, window); - - yield popupShownPromise; -} - -add_task(function* test_openDownloadsFolder() { - yield SpecialPowers.pushPrefEnv({"set": [["browser.download.showPanelDropmarker", true]]}); - yield task_openPanel(); - - yield task_openDownloadsSubPanel(); - - yield new Promise(resolve => { - sinon.stub(DownloadsCommon, "showDirectory", file => { - resolve(Downloads.getPreferredDownloadsDirectory().then(downloadsPath => { - is(file.path, downloadsPath, "Check the download folder path."); - })); - }); - - let itemOpenDownloadsFolder = - document.getElementById("downloadsDropdownItemOpenDownloadsFolder"); - EventUtils.synthesizeMouseAtCenter(itemOpenDownloadsFolder, {}, window); - }); - - yield task_resetState(); -}); - -add_task(function* test_clearList() { - const kTestCases = [{ - downloads: [ - { state: nsIDM.DOWNLOAD_NOTSTARTED }, - { state: nsIDM.DOWNLOAD_FINISHED }, - { state: nsIDM.DOWNLOAD_FAILED }, - { state: nsIDM.DOWNLOAD_CANCELED }, - ], - expectClearListShown: true, - expectedItemNumber: 0, - },{ - downloads: [ - { state: nsIDM.DOWNLOAD_NOTSTARTED }, - { state: nsIDM.DOWNLOAD_FINISHED }, - { state: nsIDM.DOWNLOAD_FAILED }, - { state: nsIDM.DOWNLOAD_PAUSED }, - { state: nsIDM.DOWNLOAD_CANCELED }, - ], - expectClearListShown: true, - expectedItemNumber: 1, - },{ - downloads: [ - { state: nsIDM.DOWNLOAD_PAUSED }, - ], - expectClearListShown: false, - expectedItemNumber: 1, - }]; - - for (let testCase of kTestCases) { - yield verify_clearList(testCase); - } -}); - -function *verify_clearList(testCase) { - let downloads = testCase.downloads; - yield task_addDownloads(downloads); - - yield task_openPanel(); - is(DownloadsView._downloads.length, downloads.length, - "Expect the number of download items"); - - yield task_openDownloadsSubPanel(); - - let itemClearList = document.getElementById("downloadsDropdownItemClearList"); - let itemNumberPromise = BrowserTestUtils.waitForCondition(() => { - return DownloadsView._downloads.length === testCase.expectedItemNumber; - }); - if (testCase.expectClearListShown) { - isnot("true", itemClearList.getAttribute("hidden"), - "Should show Clear Preview Panel button"); - EventUtils.synthesizeMouseAtCenter(itemClearList, {}, window); - } else { - is("true", itemClearList.getAttribute("hidden"), - "Should not show Clear Preview Panel button"); - } - - yield itemNumberPromise; - is(DownloadsView._downloads.length, testCase.expectedItemNumber, - "Download items remained."); - - yield task_resetState(); -} diff --git a/browser/components/downloads/test/browser/browser_downloads_panel_height.js b/browser/components/downloads/test/browser/browser_downloads_panel_height.js deleted file mode 100644 index 1638e4f0e..000000000 --- a/browser/components/downloads/test/browser/browser_downloads_panel_height.js +++ /dev/null @@ -1,29 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * This test exists because we use a <panelmultiview> element and it handles - * some of the height changes for us. We need to verify that the height is - * updated correctly if downloads are removed while the panel is hidden. - */ -add_task(function* test_height_reduced_after_removal() { - yield task_addDownloads([ - { state: nsIDM.DOWNLOAD_FINISHED }, - ]); - - yield task_openPanel(); - let panel = document.getElementById("downloadsPanel"); - let heightBeforeRemoval = panel.getBoundingClientRect().height; - - // We want to close the panel before we remove the download from the list. - DownloadsPanel.hidePanel(); - yield task_resetState(); - - yield task_openPanel(); - let heightAfterRemoval = panel.getBoundingClientRect().height; - Assert.greater(heightBeforeRemoval, heightAfterRemoval); - - yield task_resetState(); -}); diff --git a/browser/components/downloads/test/browser/browser_first_download_panel.js b/browser/components/downloads/test/browser/browser_first_download_panel.js deleted file mode 100644 index 2cd871360..000000000 --- a/browser/components/downloads/test/browser/browser_first_download_panel.js +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Make sure the downloads panel only opens automatically on the first - * download it notices. All subsequent downloads, even across sessions, should - * not open the panel automatically. - */ -add_task(function* test_first_download_panel() { - // Clear the download panel has shown preference first as this test is used to - // verify this preference's behaviour. - let oldPrefValue = Services.prefs.getBoolPref("browser.download.panel.shown"); - Services.prefs.setBoolPref("browser.download.panel.shown", false); - - registerCleanupFunction(function*() { - // Clean up when the test finishes. - yield task_resetState(); - - // Set the preference instead of clearing it afterwards to ensure the - // right value is used no matter what the default was. This ensures the - // panel doesn't appear and affect other tests. - Services.prefs.setBoolPref("browser.download.panel.shown", oldPrefValue); - }); - - // Ensure that state is reset in case previous tests didn't finish. - yield task_resetState(); - - // With this set to false, we should automatically open the panel the first - // time a download is started. - DownloadsCommon.getData(window).panelHasShownBefore = false; - - let promise = promisePanelOpened(); - DownloadsCommon.getData(window)._notifyDownloadEvent("start"); - yield promise; - - // If we got here, that means the panel opened. - DownloadsPanel.hidePanel(); - - ok(DownloadsCommon.getData(window).panelHasShownBefore, - "Should have recorded that the panel was opened on a download.") - - // Next, make sure that if we start another download, we don't open the - // panel automatically. - let originalOnPopupShown = DownloadsPanel.onPopupShown; - DownloadsPanel.onPopupShown = function () { - originalOnPopupShown.apply(this, arguments); - ok(false, "Should not have opened the downloads panel."); - }; - - DownloadsCommon.getData(window)._notifyDownloadEvent("start"); - - // Wait 2 seconds to ensure that the panel does not open. - yield new Promise(resolve => setTimeout(resolve, 2000)); - DownloadsPanel.onPopupShown = originalOnPopupShown; -}); diff --git a/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js b/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js deleted file mode 100644 index ebdd4f9af..000000000 --- a/browser/components/downloads/test/browser/browser_iframe_gone_mid_download.js +++ /dev/null @@ -1,62 +0,0 @@ -const SAVE_PER_SITE_PREF = "browser.download.lastDir.savePerSite"; - -function test_deleted_iframe(perSitePref, windowOptions={}) { - return function*() { - Services.prefs.setBoolPref(SAVE_PER_SITE_PREF, perSitePref); - let {DownloadLastDir} = Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}); - - let win = yield promiseOpenAndLoadWindow(windowOptions); - let tab = win.gBrowser.addTab(); - yield promiseTabLoadEvent(tab, "about:mozilla"); - - let doc = tab.linkedBrowser.contentDocument; - let iframe = doc.createElement("iframe"); - doc.body.appendChild(iframe); - - ok(iframe.contentWindow, "iframe should have a window"); - let gDownloadLastDir = new DownloadLastDir(iframe.contentWindow); - let cw = iframe.contentWindow; - let promiseIframeWindowGone = new Promise((resolve, reject) => { - Services.obs.addObserver(function obs(subject, topic) { - if (subject == cw) { - Services.obs.removeObserver(obs, topic); - resolve(); - } - }, "dom-window-destroyed", false); - }); - iframe.remove(); - yield promiseIframeWindowGone; - cw = null; - ok(!iframe.contentWindow, "Managed to destroy iframe"); - - let someDir = "blah"; - try { - someDir = yield new Promise((resolve, reject) => { - gDownloadLastDir.getFileAsync("http://www.mozilla.org/", function(dir) { - resolve(dir); - }); - }); - } catch (ex) { - ok(false, "Got an exception trying to get the directory where things should be saved."); - Cu.reportError(ex); - } - // NB: someDir can legitimately be null here when set, hence the 'blah' workaround: - isnot(someDir, "blah", "Should get a file even after the window was destroyed."); - - try { - gDownloadLastDir.setFile("http://www.mozilla.org/", null); - } catch (ex) { - ok(false, "Got an exception trying to set the directory where things should be saved."); - Cu.reportError(ex); - } - - yield promiseWindowClosed(win); - Services.prefs.clearUserPref(SAVE_PER_SITE_PREF); - }; -} - -add_task(test_deleted_iframe(false)); -add_task(test_deleted_iframe(false)); -add_task(test_deleted_iframe(true, {private: true})); -add_task(test_deleted_iframe(true, {private: true})); - diff --git a/browser/components/downloads/test/browser/browser_indicatorDrop.js b/browser/components/downloads/test/browser/browser_indicatorDrop.js deleted file mode 100644 index 368d85ccf..000000000 --- a/browser/components/downloads/test/browser/browser_indicatorDrop.js +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -XPCOMUtils.defineLazyModuleGetter(this, "HttpServer", - "resource://testing-common/httpd.js"); - -registerCleanupFunction(function*() { - yield task_resetState(); - yield task_clearHistory(); -}); - -add_task(function* test_indicatorDrop() { - let downloadButton = document.getElementById("downloads-button"); - ok(downloadButton, "download button present"); - - let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); - let EventUtils = {}; - scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - - function* task_drop(urls) { - let dragData = [[{type: "text/plain", data: urls.join("\n")}]]; - - let list = yield Downloads.getList(Downloads.ALL); - - let added = new Set(); - let succeeded = new Set(); - yield new Promise(function(resolve) { - let view = { - onDownloadAdded: function(download) { - added.add(download.source.url); - }, - onDownloadChanged: function(download) { - if (!added.has(download.source.url)) - return; - if (!download.succeeded) - return; - succeeded.add(download.source.url); - if (succeeded.size == urls.length) { - list.removeView(view).then(resolve); - } - } - }; - list.addView(view).then(function() { - EventUtils.synthesizeDrop(downloadButton, downloadButton, dragData, "link", window); - }); - }); - - for (let url of urls) { - ok(added.has(url), url + " is added to download"); - } - } - - // Ensure that state is reset in case previous tests didn't finish. - yield task_resetState(); - - yield setDownloadDir(); - - startServer(); - - yield* task_drop([httpUrl("file1.txt")]); - yield* task_drop([httpUrl("file1.txt"), - httpUrl("file2.txt"), - httpUrl("file3.txt")]); -}); diff --git a/browser/components/downloads/test/browser/browser_libraryDrop.js b/browser/components/downloads/test/browser/browser_libraryDrop.js deleted file mode 100644 index fa7df8a87..000000000 --- a/browser/components/downloads/test/browser/browser_libraryDrop.js +++ /dev/null @@ -1,72 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -XPCOMUtils.defineLazyModuleGetter(this, "HttpServer", - "resource://testing-common/httpd.js"); - -registerCleanupFunction(function*() { - yield task_resetState(); - yield task_clearHistory(); -}); - -add_task(function* test_indicatorDrop() { - let scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); - let EventUtils = {}; - scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - - function task_drop(win, urls) { - let dragData = [[{type: "text/plain", data: urls.join("\n")}]]; - - let listBox = win.document.getElementById("downloadsRichListBox"); - ok(listBox, "download list box present"); - - let list = yield Downloads.getList(Downloads.ALL); - - let added = new Set(); - let succeeded = new Set(); - yield new Promise(function(resolve) { - let view = { - onDownloadAdded: function(download) { - added.add(download.source.url); - }, - onDownloadChanged: function(download) { - if (!added.has(download.source.url)) - return; - if (!download.succeeded) - return; - succeeded.add(download.source.url); - if (succeeded.size == urls.length) { - list.removeView(view).then(resolve); - } - } - }; - list.addView(view).then(function() { - EventUtils.synthesizeDrop(listBox, listBox, dragData, "link", win); - }); - }); - - for (let url of urls) { - ok(added.has(url), url + " is added to download"); - } - } - - // Ensure that state is reset in case previous tests didn't finish. - yield task_resetState(); - - setDownloadDir(); - - startServer(); - - let win = yield openLibrary("Downloads"); - registerCleanupFunction(function() { - win.close(); - }); - - yield* task_drop(win, [httpUrl("file1.txt")]); - yield* task_drop(win, [httpUrl("file1.txt"), - httpUrl("file2.txt"), - httpUrl("file3.txt")]); -}); diff --git a/browser/components/downloads/test/browser/browser_overflow_anchor.js b/browser/components/downloads/test/browser/browser_overflow_anchor.js deleted file mode 100644 index a293a81cf..000000000 --- a/browser/components/downloads/test/browser/browser_overflow_anchor.js +++ /dev/null @@ -1,115 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -registerCleanupFunction(function*() { - // Clean up when the test finishes. - yield task_resetState(); -}); - -/** - * Make sure the downloads button and indicator overflows into the nav-bar - * chevron properly, and then when those buttons are clicked in the overflow - * panel that the downloads panel anchors to the chevron. - */ -add_task(function* test_overflow_anchor() { - // Ensure that state is reset in case previous tests didn't finish. - yield task_resetState(); - - // Record the original width of the window so we can put it back when - // this test finishes. - let oldWidth = window.outerWidth; - - // The downloads button should not be overflowed to begin with. - let button = CustomizableUI.getWidget("downloads-button") - .forWindow(window); - ok(!button.overflowed, "Downloads button should not be overflowed."); - - // Hack - we lock the size of the default flex-y items in the nav-bar, - // namely, the URL and search inputs. That way we can resize the - // window without worrying about them flexing. - const kFlexyItems = ["urlbar-container", "search-container"]; - registerCleanupFunction(() => unlockWidth(kFlexyItems)); - lockWidth(kFlexyItems); - - // Resize the window to half of its original size. That should - // be enough to overflow the downloads button. - window.resizeTo(oldWidth / 2, window.outerHeight); - yield waitForOverflowed(button, true); - - let promise = promisePanelOpened(); - button.node.doCommand(); - yield promise; - - let panel = DownloadsPanel.panel; - let chevron = document.getElementById("nav-bar-overflow-button"); - is(panel.anchorNode, chevron, "Panel should be anchored to the chevron."); - - DownloadsPanel.hidePanel(); - - // Unlock the widths on the flex-y items. - unlockWidth(kFlexyItems); - - // Put the window back to its original dimensions. - window.resizeTo(oldWidth, window.outerHeight); - - // The downloads button should eventually be un-overflowed. - yield waitForOverflowed(button, false); - - // Now try opening the panel again. - promise = promisePanelOpened(); - button.node.doCommand(); - yield promise; - - is(panel.anchorNode.id, "downloads-indicator-anchor"); - - DownloadsPanel.hidePanel(); -}); - -/** - * For some node IDs, finds the nodes and sets their min-width's to their - * current width, preventing them from flex-shrinking. - * - * @param aItemIDs an array of item IDs to set min-width on. - */ -function lockWidth(aItemIDs) { - for (let itemID of aItemIDs) { - let item = document.getElementById(itemID); - let curWidth = item.getBoundingClientRect().width + "px"; - item.style.minWidth = curWidth; - } -} - -/** - * Clears the min-width's set on a set of IDs by lockWidth. - * - * @param aItemIDs an array of ItemIDs to remove min-width on. - */ -function unlockWidth(aItemIDs) { - for (let itemID of aItemIDs) { - let item = document.getElementById(itemID); - item.style.minWidth = ""; - } -} - -/** - * Waits for a node to enter or exit the overflowed state. - * - * @param aItem the node to wait for. - * @param aIsOverflowed if we're waiting for the item to be overflowed. - */ -function waitForOverflowed(aItem, aIsOverflowed) { - let deferOverflow = Promise.defer(); - if (aItem.overflowed == aIsOverflowed) { - return deferOverflow.resolve(); - } - - let observer = new MutationObserver(function(aMutations) { - if (aItem.overflowed == aIsOverflowed) { - observer.disconnect(); - deferOverflow.resolve(); - } - }); - observer.observe(aItem.node, {attributes: true}); - - return deferOverflow.promise; -} diff --git a/browser/components/downloads/test/browser/head.js b/browser/components/downloads/test/browser/head.js deleted file mode 100644 index bcf703eb6..000000000 --- a/browser/components/downloads/test/browser/head.js +++ /dev/null @@ -1,300 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Provides infrastructure for automated download components tests. - */ - -//////////////////////////////////////////////////////////////////////////////// -//// Globals - -XPCOMUtils.defineLazyModuleGetter(this, "Downloads", - "resource://gre/modules/Downloads.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon", - "resource:///modules/DownloadsCommon.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Promise", - "resource://gre/modules/Promise.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Task", - "resource://gre/modules/Task.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", - "resource://gre/modules/PlacesUtils.jsm"); -const nsIDM = Ci.nsIDownloadManager; - -var gTestTargetFile = FileUtils.getFile("TmpD", ["dm-ui-test.file"]); -gTestTargetFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); - -// Load mocking/stubbing library, sinon -// docs: http://sinonjs.org/docs/ -Services.scriptloader.loadSubScript("resource://testing-common/sinon-1.16.1.js"); - -registerCleanupFunction(function () { - gTestTargetFile.remove(false); - - delete window.sinon; - delete window.setImmediate; - delete window.clearImmediate; -}); - -//////////////////////////////////////////////////////////////////////////////// -//// Asynchronous support subroutines - -function promiseOpenAndLoadWindow(aOptions) -{ - return new Promise((resolve, reject) => { - let win = OpenBrowserWindow(aOptions); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad); - resolve(win); - }); - }); -} - -/** - * Waits for a load (or custom) event to finish in a given tab. If provided - * load an uri into the tab. - * - * @param tab - * The tab to load into. - * @param [optional] url - * The url to load, or the current url. - * @param [optional] event - * The load event type to wait for. Defaults to "load". - * @return {Promise} resolved when the event is handled. - * @resolves to the received event - * @rejects if a valid load event is not received within a meaningful interval - */ -function promiseTabLoadEvent(tab, url, eventType="load") -{ - let deferred = Promise.defer(); - info("Wait tab event: " + eventType); - - function handle(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank" || - (url && event.target.location.href != url)) { - info("Skipping spurious '" + eventType + "'' event" + - " for " + event.target.location.href); - return; - } - // Remove reference to tab from the cleanup function: - realCleanup = () => {}; - tab.linkedBrowser.removeEventListener(eventType, handle, true); - info("Tab event received: " + eventType); - deferred.resolve(event); - } - - // Juggle a bit to avoid leaks: - let realCleanup = () => tab.linkedBrowser.removeEventListener(eventType, handle, true); - registerCleanupFunction(() => realCleanup()); - - tab.linkedBrowser.addEventListener(eventType, handle, true, true); - if (url) - tab.linkedBrowser.loadURI(url); - return deferred.promise; -} - -function promiseWindowClosed(win) -{ - let promise = new Promise((resolve, reject) => { - Services.obs.addObserver(function obs(subject, topic) { - if (subject == win) { - Services.obs.removeObserver(obs, topic); - resolve(); - } - }, "domwindowclosed", false); - }); - win.close(); - return promise; -} - - -function promiseFocus() -{ - let deferred = Promise.defer(); - waitForFocus(deferred.resolve); - return deferred.promise; -} - -function promisePanelOpened() -{ - let deferred = Promise.defer(); - - if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") { - return deferred.resolve(); - } - - // Hook to wait until the panel is shown. - let originalOnPopupShown = DownloadsPanel.onPopupShown; - DownloadsPanel.onPopupShown = function () { - DownloadsPanel.onPopupShown = originalOnPopupShown; - originalOnPopupShown.apply(this, arguments); - - // Defer to the next tick of the event loop so that we don't continue - // processing during the DOM event handler itself. - setTimeout(deferred.resolve, 0); - }; - - return deferred.promise; -} - -function* task_resetState() -{ - // Remove all downloads. - let publicList = yield Downloads.getList(Downloads.PUBLIC); - let downloads = yield publicList.getAll(); - for (let download of downloads) { - publicList.remove(download); - yield download.finalize(true); - } - - DownloadsPanel.hidePanel(); - - yield promiseFocus(); -} - -function* task_addDownloads(aItems) -{ - let startTimeMs = Date.now(); - - let publicList = yield Downloads.getList(Downloads.PUBLIC); - for (let item of aItems) { - let download = { - source: { - url: "http://www.example.com/test-download.txt", - }, - target: { - path: gTestTargetFile.path, - }, - succeeded: item.state == nsIDM.DOWNLOAD_FINISHED, - canceled: item.state == nsIDM.DOWNLOAD_CANCELED || - item.state == nsIDM.DOWNLOAD_PAUSED, - error: item.state == nsIDM.DOWNLOAD_FAILED ? new Error("Failed.") : null, - hasPartialData: item.state == nsIDM.DOWNLOAD_PAUSED, - hasBlockedData: item.hasBlockedData || false, - startTime: new Date(startTimeMs++), - }; - // `"errorObj" in download` must be false when there's no error. - if (item.errorObj) { - download.errorObj = item.errorObj; - } - yield publicList.add(yield Downloads.createDownload(download)); - } -} - -function* task_openPanel() -{ - yield promiseFocus(); - - let promise = promisePanelOpened(); - DownloadsPanel.showPanel(); - yield promise; -} - -function* setDownloadDir() { - let tmpDir = Services.dirsvc.get("TmpD", Ci.nsIFile); - tmpDir.append("testsavedir"); - if (!tmpDir.exists()) { - tmpDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0o755); - registerCleanupFunction(function () { - try { - tmpDir.remove(true); - } catch (e) { - // On Windows debug build this may fail. - } - }); - } - - yield new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": [ - ["browser.download.folderList", 2], - ["browser.download.dir", tmpDir, Ci.nsIFile], - ]}, resolve); - }); -} - - -let gHttpServer = null; -function startServer() { - gHttpServer = new HttpServer(); - gHttpServer.start(-1); - registerCleanupFunction(function*() { - yield new Promise(function(resolve) { - gHttpServer.stop(resolve); - }); - }); - - gHttpServer.registerPathHandler("/file1.txt", (request, response) => { - response.setStatusLine(null, 200, "OK"); - response.write("file1"); - response.processAsync(); - response.finish(); - }); - gHttpServer.registerPathHandler("/file2.txt", (request, response) => { - response.setStatusLine(null, 200, "OK"); - response.write("file2"); - response.processAsync(); - response.finish(); - }); - gHttpServer.registerPathHandler("/file3.txt", (request, response) => { - response.setStatusLine(null, 200, "OK"); - response.write("file3"); - response.processAsync(); - response.finish(); - }); -} - -function httpUrl(aFileName) { - return "http://localhost:" + gHttpServer.identity.primaryPort + "/" + - aFileName; -} - -function task_clearHistory() { - return new Promise(function(resolve) { - Services.obs.addObserver(function observeCH(aSubject, aTopic, aData) { - Services.obs.removeObserver(observeCH, PlacesUtils.TOPIC_EXPIRATION_FINISHED); - resolve(); - }, PlacesUtils.TOPIC_EXPIRATION_FINISHED, false); - PlacesUtils.history.clear(); - }); -} - -function openLibrary(aLeftPaneRoot) { - let library = window.openDialog("chrome://browser/content/places/places.xul", - "", "chrome,toolbar=yes,dialog=no,resizable", - aLeftPaneRoot); - - return new Promise(resolve => { - waitForFocus(resolve, library); - }); -} - -function promiseAlertDialogOpen(buttonAction) { - return new Promise(resolve => { - Services.ww.registerNotification(function onOpen(subj, topic, data) { - if (topic == "domwindowopened" && subj instanceof Ci.nsIDOMWindow) { - // The test listens for the "load" event which guarantees that the alert - // class has already been added (it is added when "DOMContentLoaded" is - // fired). - subj.addEventListener("load", function onLoad() { - subj.removeEventListener("load", onLoad); - if (subj.document.documentURI == - "chrome://global/content/commonDialog.xul") { - Services.ww.unregisterNotification(onOpen); - - let dialog = subj.document.getElementById("commonDialog"); - ok(dialog.classList.contains("alert-dialog"), - "The dialog element should contain an alert class."); - - let doc = subj.document.documentElement; - doc.getButton(buttonAction).click(); - resolve(); - } - }); - } - }); - }); -} diff --git a/browser/components/downloads/test/unit/.eslintrc.js b/browser/components/downloads/test/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/downloads/test/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/downloads/test/unit/head.js b/browser/components/downloads/test/unit/head.js deleted file mode 100644 index d7ce4d48a..000000000 --- a/browser/components/downloads/test/unit/head.js +++ /dev/null @@ -1,18 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Provides infrastructure for automated download components tests. - */ - -//////////////////////////////////////////////////////////////////////////////// -//// Globals - -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cu = Components.utils; -var Cr = Components.results; - -Cu.import("resource:///modules/DownloadsCommon.jsm"); diff --git a/browser/components/downloads/test/unit/test_DownloadsCommon.js b/browser/components/downloads/test/unit/test_DownloadsCommon.js deleted file mode 100644 index 46afbaef9..000000000 --- a/browser/components/downloads/test/unit/test_DownloadsCommon.js +++ /dev/null @@ -1,37 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests for the functions located directly in the "DownloadsCommon" object. - */ - -function testFormatTimeLeft(aSeconds, aExpectedValue, aExpectedUnitString) -{ - let expected = ""; - if (aExpectedValue) { - // Format the expected result based on the current language. - expected = DownloadsCommon.strings[aExpectedUnitString](aExpectedValue); - } - do_check_eq(DownloadsCommon.formatTimeLeft(aSeconds), expected); -} - -function run_test() -{ - testFormatTimeLeft( 0, "", ""); - testFormatTimeLeft( 1, "1", "shortTimeLeftSeconds"); - testFormatTimeLeft( 29, "29", "shortTimeLeftSeconds"); - testFormatTimeLeft( 30, "30", "shortTimeLeftSeconds"); - testFormatTimeLeft( 31, "1", "shortTimeLeftMinutes"); - testFormatTimeLeft( 60, "1", "shortTimeLeftMinutes"); - testFormatTimeLeft( 89, "1", "shortTimeLeftMinutes"); - testFormatTimeLeft( 90, "2", "shortTimeLeftMinutes"); - testFormatTimeLeft( 91, "2", "shortTimeLeftMinutes"); - testFormatTimeLeft( 3600, "1", "shortTimeLeftHours"); - testFormatTimeLeft( 86400, "24", "shortTimeLeftHours"); - testFormatTimeLeft( 169200, "47", "shortTimeLeftHours"); - testFormatTimeLeft( 172800, "2", "shortTimeLeftDays"); - testFormatTimeLeft(8553600, "99", "shortTimeLeftDays"); - testFormatTimeLeft(8640000, "99", "shortTimeLeftDays"); -} diff --git a/browser/components/downloads/test/unit/xpcshell.ini b/browser/components/downloads/test/unit/xpcshell.ini deleted file mode 100644 index f53a8cf89..000000000 --- a/browser/components/downloads/test/unit/xpcshell.ini +++ /dev/null @@ -1,7 +0,0 @@ -[DEFAULT] -head = head.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_DownloadsCommon.js] diff --git a/browser/components/extensions/test/browser/.eslintrc.js b/browser/components/extensions/test/browser/.eslintrc.js deleted file mode 100644 index 0e673ecb9..000000000 --- a/browser/components/extensions/test/browser/.eslintrc.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; - -module.exports = { // eslint-disable-line no-undef - "extends": "../../../../../testing/mochitest/browser.eslintrc.js", - - "env": { - "webextensions": true, - }, - - "globals": { - "NetUtil": true, - "XPCOMUtils": true, - "Task": true, - - // Browser window globals. - "PanelUI": false, - - // Test harness globals - "ExtensionTestUtils": false, - "TestUtils": false, - - "clickBrowserAction": true, - "clickPageAction": true, - "closeContextMenu": true, - "closeExtensionContextMenu": true, - "focusWindow": true, - "makeWidgetId": true, - "openContextMenu": true, - "openExtensionContextMenu": true, - "CustomizableUI": true, - }, - - "rules": { - "no-shadow": 0, - }, -}; diff --git a/browser/components/extensions/test/browser/browser.ini b/browser/components/extensions/test/browser/browser.ini deleted file mode 100644 index 1e894dcb5..000000000 --- a/browser/components/extensions/test/browser/browser.ini +++ /dev/null @@ -1,115 +0,0 @@ -[DEFAULT] -support-files = - head.js - head_pageAction.js - head_sessions.js - context.html - ctxmenu-image.png - context_tabs_onUpdated_page.html - context_tabs_onUpdated_iframe.html - file_popup_api_injection_a.html - file_popup_api_injection_b.html - file_iframe_document.html - file_iframe_document.sjs - file_bypass_cache.sjs - file_language_fr_en.html - file_language_ja.html - file_language_tlh.html - file_dummy.html - searchSuggestionEngine.xml - searchSuggestionEngine.sjs - ../../../../../toolkit/components/extensions/test/mochitest/head_webrequest.js -tags = webextensions - - -[browser_ext_browserAction_context.js] -[browser_ext_browserAction_disabled.js] -[browser_ext_browserAction_pageAction_icon.js] -[browser_ext_browserAction_pageAction_icon_permissions.js] -[browser_ext_browserAction_popup.js] -[browser_ext_browserAction_popup_resize.js] -[browser_ext_browserAction_simple.js] -[browser_ext_commands_execute_browser_action.js] -[browser_ext_commands_execute_page_action.js] -[browser_ext_commands_getAll.js] -[browser_ext_commands_onCommand.js] -[browser_ext_contentscript_connect.js] -[browser_ext_contextMenus.js] -[browser_ext_contextMenus_checkboxes.js] -[browser_ext_contextMenus_icons.js] -[browser_ext_contextMenus_onclick.js] -[browser_ext_contextMenus_radioGroups.js] -[browser_ext_contextMenus_uninstall.js] -[browser_ext_contextMenus_urlPatterns.js] -[browser_ext_currentWindow.js] -[browser_ext_getViews.js] -[browser_ext_incognito_popup.js] -[browser_ext_incognito_views.js] -[browser_ext_lastError.js] -[browser_ext_legacy_extension_context_contentscript.js] -[browser_ext_omnibox.js] -[browser_ext_optionsPage_privileges.js] -[browser_ext_pageAction_context.js] -[browser_ext_pageAction_popup.js] -[browser_ext_pageAction_popup_resize.js] -[browser_ext_pageAction_simple.js] -[browser_ext_pageAction_title.js] -[browser_ext_popup_api_injection.js] -[browser_ext_popup_background.js] -[browser_ext_popup_corners.js] -[browser_ext_popup_sendMessage.js] -[browser_ext_popup_shutdown.js] -[browser_ext_runtime_openOptionsPage.js] -[browser_ext_runtime_openOptionsPage_uninstall.js] -[browser_ext_runtime_setUninstallURL.js] -[browser_ext_sessions_getRecentlyClosed.js] -[browser_ext_sessions_getRecentlyClosed_private.js] -[browser_ext_sessions_getRecentlyClosed_tabs.js] -[browser_ext_sessions_restore.js] -[browser_ext_simple.js] -[browser_ext_tab_runtimeConnect.js] -[browser_ext_tabs_audio.js] -[browser_ext_tabs_captureVisibleTab.js] -[browser_ext_tabs_create.js] -[browser_ext_tabs_create_invalid_url.js] -[browser_ext_tabs_detectLanguage.js] -[browser_ext_tabs_duplicate.js] -[browser_ext_tabs_events.js] -[browser_ext_tabs_executeScript.js] -[browser_ext_tabs_executeScript_good.js] -[browser_ext_tabs_executeScript_bad.js] -[browser_ext_tabs_executeScript_runAt.js] -[browser_ext_tabs_getCurrent.js] -[browser_ext_tabs_insertCSS.js] -[browser_ext_tabs_removeCSS.js] -[browser_ext_tabs_move.js] -[browser_ext_tabs_move_window.js] -[browser_ext_tabs_move_window_multiple.js] -[browser_ext_tabs_move_window_pinned.js] -[browser_ext_tabs_onHighlighted.js] -[browser_ext_tabs_onUpdated.js] -[browser_ext_tabs_query.js] -[browser_ext_tabs_reload.js] -[browser_ext_tabs_reload_bypass_cache.js] -[browser_ext_tabs_sendMessage.js] -[browser_ext_tabs_cookieStoreId.js] -[browser_ext_tabs_update.js] -[browser_ext_tabs_zoom.js] -[browser_ext_tabs_update_url.js] -[browser_ext_topwindowid.js] -[browser_ext_webNavigation_frameId0.js] -[browser_ext_webNavigation_getFrames.js] -[browser_ext_webNavigation_urlbar_transitions.js] -[browser_ext_webRequest.js] -[browser_ext_windows.js] -[browser_ext_windows_allowScriptsToClose.js] -[browser_ext_windows_create.js] -tags = fullscreen -[browser_ext_windows_create_params.js] -[browser_ext_windows_create_tabId.js] -[browser_ext_windows_create_url.js] -[browser_ext_windows_events.js] -[browser_ext_windows_size.js] -skip-if = os == 'mac' # Fails when windows are randomly opened in fullscreen mode -[browser_ext_windows_update.js] -tags = fullscreen diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_context.js b/browser/components/extensions/test/browser/browser_ext_browserAction_context.js deleted file mode 100644 index 8a26dbb3c..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_context.js +++ /dev/null @@ -1,398 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* runTests(options) { - async function background(getTests) { - async function checkDetails(expecting, tabId) { - let title = await browser.browserAction.getTitle({tabId}); - browser.test.assertEq(expecting.title, title, - "expected value from getTitle"); - - let popup = await browser.browserAction.getPopup({tabId}); - browser.test.assertEq(expecting.popup, popup, - "expected value from getPopup"); - - let badge = await browser.browserAction.getBadgeText({tabId}); - browser.test.assertEq(expecting.badge, badge, - "expected value from getBadge"); - - let badgeBackgroundColor = await browser.browserAction.getBadgeBackgroundColor({tabId}); - browser.test.assertEq(String(expecting.badgeBackgroundColor), - String(badgeBackgroundColor), - "expected value from getBadgeBackgroundColor"); - } - - let expectDefaults = expecting => { - return checkDetails(expecting); - }; - - let tabs = []; - let tests = getTests(tabs, expectDefaults); - - { - let tabId = 0xdeadbeef; - let calls = [ - () => browser.browserAction.enable(tabId), - () => browser.browserAction.disable(tabId), - () => browser.browserAction.setTitle({tabId, title: "foo"}), - () => browser.browserAction.setIcon({tabId, path: "foo.png"}), - () => browser.browserAction.setPopup({tabId, popup: "foo.html"}), - () => browser.browserAction.setBadgeText({tabId, text: "foo"}), - () => browser.browserAction.setBadgeBackgroundColor({tabId, color: [0xff, 0, 0, 0xff]}), - ]; - - for (let call of calls) { - await browser.test.assertRejects( - new Promise(resolve => resolve(call())), - RegExp(`Invalid tab ID: ${tabId}`), - "Expected invalid tab ID error"); - } - } - - // Runs the next test in the `tests` array, checks the results, - // and passes control back to the outer test scope. - function nextTest() { - let test = tests.shift(); - - test(async expecting => { - // Check that the API returns the expected values, and then - // run the next test. - let tabs = await browser.tabs.query({active: true, currentWindow: true}); - await checkDetails(expecting, tabs[0].id); - - // Check that the actual icon has the expected values, then - // run the next test. - browser.test.sendMessage("nextTest", expecting, tests.length); - }); - } - - browser.test.onMessage.addListener((msg) => { - if (msg != "runNextTest") { - browser.test.fail("Expecting 'runNextTest' message"); - } - - nextTest(); - }); - - browser.tabs.query({active: true, currentWindow: true}, resultTabs => { - tabs[0] = resultTabs[0].id; - - nextTest(); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: options.manifest, - - files: options.files || {}, - - background: `(${background})(${options.getTests})`, - }); - - let browserActionId; - function checkDetails(details) { - if (!browserActionId) { - browserActionId = `${makeWidgetId(extension.id)}-browser-action`; - } - - let button = document.getElementById(browserActionId); - - ok(button, "button exists"); - - let title = details.title || options.manifest.name; - - is(getListStyleImage(button), details.icon, "icon URL is correct"); - is(button.getAttribute("tooltiptext"), title, "image title is correct"); - is(button.getAttribute("label"), title, "image label is correct"); - is(button.getAttribute("badge"), details.badge, "badge text is correct"); - is(button.getAttribute("disabled") == "true", Boolean(details.disabled), "disabled state is correct"); - - if (details.badge && details.badgeBackgroundColor) { - let badge = button.ownerDocument.getAnonymousElementByAttribute( - button, "class", "toolbarbutton-badge"); - - let badgeColor = window.getComputedStyle(badge).backgroundColor; - let color = details.badgeBackgroundColor; - let expectedColor = `rgb(${color[0]}, ${color[1]}, ${color[2]})`; - - is(badgeColor, expectedColor, "badge color is correct"); - } - - - // TODO: Popup URL. - } - - let awaitFinish = new Promise(resolve => { - extension.onMessage("nextTest", (expecting, testsRemaining) => { - checkDetails(expecting); - - if (testsRemaining) { - extension.sendMessage("runNextTest"); - } else { - resolve(); - } - }); - }); - - yield extension.startup(); - - yield awaitFinish; - - yield extension.unload(); -} - -add_task(function* testTabSwitchContext() { - yield runTests({ - manifest: { - "browser_action": { - "default_icon": "default.png", - "default_popup": "__MSG_popup__", - "default_title": "Default __MSG_title__", - }, - - "default_locale": "en", - - "permissions": ["tabs"], - }, - - "files": { - "_locales/en/messages.json": { - "popup": { - "message": "default.html", - "description": "Popup", - }, - - "title": { - "message": "Title", - "description": "Title", - }, - }, - - "default.png": imageBuffer, - "default-2.png": imageBuffer, - "1.png": imageBuffer, - "2.png": imageBuffer, - }, - - getTests(tabs, expectDefaults) { - const DEFAULT_BADGE_COLOR = [0xd9, 0, 0, 255]; - - let details = [ - {"icon": browser.runtime.getURL("default.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default Title", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR}, - {"icon": browser.runtime.getURL("1.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default Title", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR}, - {"icon": browser.runtime.getURL("2.png"), - "popup": browser.runtime.getURL("2.html"), - "title": "Title 2", - "badge": "2", - "badgeBackgroundColor": [0xff, 0, 0, 0xff], - "disabled": true}, - {"icon": browser.runtime.getURL("1.png"), - "popup": browser.runtime.getURL("default-2.html"), - "title": "Default Title 2", - "badge": "d2", - "badgeBackgroundColor": [0, 0xff, 0, 0xff], - "disabled": true}, - {"icon": browser.runtime.getURL("1.png"), - "popup": browser.runtime.getURL("default-2.html"), - "title": "Default Title 2", - "badge": "d2", - "badgeBackgroundColor": [0, 0xff, 0, 0xff], - "disabled": false}, - {"icon": browser.runtime.getURL("default-2.png"), - "popup": browser.runtime.getURL("default-2.html"), - "title": "Default Title 2", - "badge": "d2", - "badgeBackgroundColor": [0, 0xff, 0, 0xff]}, - ]; - - return [ - async expect => { - browser.test.log("Initial state, expect default properties."); - - await expectDefaults(details[0]); - expect(details[0]); - }, - async expect => { - browser.test.log("Change the icon in the current tab. Expect default properties excluding the icon."); - browser.browserAction.setIcon({tabId: tabs[0], path: "1.png"}); - - await expectDefaults(details[0]); - expect(details[1]); - }, - async expect => { - browser.test.log("Create a new tab. Expect default properties."); - let tab = await browser.tabs.create({active: true, url: "about:blank?0"}); - tabs.push(tab.id); - - await expectDefaults(details[0]); - expect(details[0]); - }, - async expect => { - browser.test.log("Change properties. Expect new properties."); - let tabId = tabs[1]; - browser.browserAction.setIcon({tabId, path: "2.png"}); - browser.browserAction.setPopup({tabId, popup: "2.html"}); - browser.browserAction.setTitle({tabId, title: "Title 2"}); - browser.browserAction.setBadgeText({tabId, text: "2"}); - browser.browserAction.setBadgeBackgroundColor({tabId, color: "#ff0000"}); - browser.browserAction.disable(tabId); - - await expectDefaults(details[0]); - expect(details[2]); - }, - expect => { - browser.test.log("Navigate to a new page. Expect no changes."); - - // TODO: This listener should not be necessary, but the |tabs.update| - // callback currently fires too early in e10s windows. - browser.tabs.onUpdated.addListener(function listener(tabId, changed) { - if (tabId == tabs[1] && changed.url) { - browser.tabs.onUpdated.removeListener(listener); - expect(details[2]); - } - }); - - browser.tabs.update(tabs[1], {url: "about:blank?1"}); - }, - async expect => { - browser.test.log("Switch back to the first tab. Expect previously set properties."); - await browser.tabs.update(tabs[0], {active: true}); - expect(details[1]); - }, - async expect => { - browser.test.log("Change default values, expect those changes reflected."); - browser.browserAction.setIcon({path: "default-2.png"}); - browser.browserAction.setPopup({popup: "default-2.html"}); - browser.browserAction.setTitle({title: "Default Title 2"}); - browser.browserAction.setBadgeText({text: "d2"}); - browser.browserAction.setBadgeBackgroundColor({color: [0, 0xff, 0, 0xff]}); - browser.browserAction.disable(); - - await expectDefaults(details[3]); - expect(details[3]); - }, - async expect => { - browser.test.log("Re-enable by default. Expect enabled."); - browser.browserAction.enable(); - - await expectDefaults(details[4]); - expect(details[4]); - }, - async expect => { - browser.test.log("Switch back to tab 2. Expect former value, unaffected by changes to defaults in previous step."); - await browser.tabs.update(tabs[1], {active: true}); - - await expectDefaults(details[3]); - expect(details[2]); - }, - async expect => { - browser.test.log("Delete tab, switch back to tab 1. Expect previous results again."); - await browser.tabs.remove(tabs[1]); - expect(details[4]); - }, - async expect => { - browser.test.log("Create a new tab. Expect new default properties."); - let tab = await browser.tabs.create({active: true, url: "about:blank?2"}); - tabs.push(tab.id); - expect(details[5]); - }, - async expect => { - browser.test.log("Delete tab."); - await browser.tabs.remove(tabs[2]); - expect(details[4]); - }, - ]; - }, - }); -}); - -add_task(function* testDefaultTitle() { - yield runTests({ - manifest: { - "name": "Foo Extension", - - "browser_action": { - "default_icon": "icon.png", - }, - - "permissions": ["tabs"], - }, - - files: { - "icon.png": imageBuffer, - }, - - getTests(tabs, expectDefaults) { - const DEFAULT_BADGE_COLOR = [0xd9, 0, 0, 255]; - - let details = [ - {"title": "Foo Extension", - "popup": "", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR, - "icon": browser.runtime.getURL("icon.png")}, - {"title": "Foo Title", - "popup": "", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR, - "icon": browser.runtime.getURL("icon.png")}, - {"title": "Bar Title", - "popup": "", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR, - "icon": browser.runtime.getURL("icon.png")}, - {"title": "", - "popup": "", - "badge": "", - "badgeBackgroundColor": DEFAULT_BADGE_COLOR, - "icon": browser.runtime.getURL("icon.png")}, - ]; - - return [ - async expect => { - browser.test.log("Initial state. Expect extension title as default title."); - - await expectDefaults(details[0]); - expect(details[0]); - }, - async expect => { - browser.test.log("Change the title. Expect new title."); - browser.browserAction.setTitle({tabId: tabs[0], title: "Foo Title"}); - - await expectDefaults(details[0]); - expect(details[1]); - }, - async expect => { - browser.test.log("Change the default. Expect same properties."); - browser.browserAction.setTitle({title: "Bar Title"}); - - await expectDefaults(details[2]); - expect(details[1]); - }, - async expect => { - browser.test.log("Clear the title. Expect new default title."); - browser.browserAction.setTitle({tabId: tabs[0], title: ""}); - - await expectDefaults(details[2]); - expect(details[2]); - }, - async expect => { - browser.test.log("Set default title to null string. Expect null string from API, extension title in UI."); - browser.browserAction.setTitle({title: ""}); - - await expectDefaults(details[3]); - expect(details[3]); - }, - ]; - }, - }); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js b/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js deleted file mode 100644 index c0b9c1a1d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_disabled.js +++ /dev/null @@ -1,68 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testDisabled() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": {}, - }, - - background: function() { - let clicked = false; - - browser.browserAction.onClicked.addListener(() => { - browser.test.log("Got click event"); - clicked = true; - }); - - browser.test.onMessage.addListener((msg, expectClick) => { - if (msg == "enable") { - browser.test.log("enable browserAction"); - browser.browserAction.enable(); - } else if (msg == "disable") { - browser.test.log("disable browserAction"); - browser.browserAction.disable(); - } else if (msg == "check-clicked") { - browser.test.assertEq(expectClick, clicked, "got click event?"); - clicked = false; - } else { - browser.test.fail("Unexpected message"); - } - - browser.test.sendMessage("next-test"); - }); - - browser.test.sendMessage("ready"); - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - yield clickBrowserAction(extension); - yield new Promise(resolve => setTimeout(resolve, 0)); - - extension.sendMessage("check-clicked", true); - yield extension.awaitMessage("next-test"); - - extension.sendMessage("disable"); - yield extension.awaitMessage("next-test"); - - yield clickBrowserAction(extension); - yield new Promise(resolve => setTimeout(resolve, 0)); - - extension.sendMessage("check-clicked", false); - yield extension.awaitMessage("next-test"); - - extension.sendMessage("enable"); - yield extension.awaitMessage("next-test"); - - yield clickBrowserAction(extension); - yield new Promise(resolve => setTimeout(resolve, 0)); - - extension.sendMessage("check-clicked", true); - yield extension.awaitMessage("next-test"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js b/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js deleted file mode 100644 index 9665d6832..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon.js +++ /dev/null @@ -1,321 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -// Test that various combinations of icon details specs, for both paths -// and ImageData objects, result in the correct image being displayed in -// all display resolutions. -add_task(function* testDetailsObjects() { - function background() { - function getImageData(color) { - let canvas = document.createElement("canvas"); - canvas.width = 2; - canvas.height = 2; - let canvasContext = canvas.getContext("2d"); - - canvasContext.clearRect(0, 0, canvas.width, canvas.height); - canvasContext.fillStyle = color; - canvasContext.fillRect(0, 0, 1, 1); - - return { - url: canvas.toDataURL("image/png"), - imageData: canvasContext.getImageData(0, 0, canvas.width, canvas.height), - }; - } - - let imageData = { - red: getImageData("red"), - green: getImageData("green"), - }; - - /* eslint-disable comma-dangle, indent */ - let iconDetails = [ - // Only paths. - {details: {"path": "a.png"}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a.png")}}, - {details: {"path": "/a.png"}, - resolutions: { - "1": browser.runtime.getURL("a.png"), - "2": browser.runtime.getURL("a.png")}}, - {details: {"path": {"19": "a.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a.png")}}, - {details: {"path": {"38": "a.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a.png")}}, - {details: {"path": {"19": "a.png", "38": "a-x2.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a-x2.png")}}, - - // Test that CSS strings are escaped properly. - {details: {"path": 'a.png#" \\'}, - resolutions: { - "1": browser.runtime.getURL("data/a.png#%22%20%5C"), - "2": browser.runtime.getURL("data/a.png#%22%20%5C")}}, - - // Only ImageData objects. - {details: {"imageData": imageData.red.imageData}, - resolutions: { - "1": imageData.red.url, - "2": imageData.red.url}}, - {details: {"imageData": {"19": imageData.red.imageData}}, - resolutions: { - "1": imageData.red.url, - "2": imageData.red.url}}, - {details: {"imageData": {"38": imageData.red.imageData}}, - resolutions: { - "1": imageData.red.url, - "2": imageData.red.url}}, - {details: {"imageData": { - "19": imageData.red.imageData, - "38": imageData.green.imageData}}, - resolutions: { - "1": imageData.red.url, - "2": imageData.green.url}}, - - // Mixed path and imageData objects. - // - // The behavior is currently undefined if both |path| and - // |imageData| specify icons of the same size. - {details: { - "path": {"19": "a.png"}, - "imageData": {"38": imageData.red.imageData}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": imageData.red.url}}, - {details: { - "path": {"38": "a.png"}, - "imageData": {"19": imageData.red.imageData}}, - resolutions: { - "1": imageData.red.url, - "2": browser.runtime.getURL("data/a.png")}}, - - // A path or ImageData object by itself is treated as a 19px icon. - {details: { - "path": "a.png", - "imageData": {"38": imageData.red.imageData}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": imageData.red.url}}, - {details: { - "path": {"38": "a.png"}, - "imageData": imageData.red.imageData}, - resolutions: { - "1": imageData.red.url, - "2": browser.runtime.getURL("data/a.png")}}, - - // Various resolutions - {details: {"path": {"18": "a.png", "36": "a-x2.png"}}, - legacy: true, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a-x2.png")}}, - {details: {"path": {"16": "a.png", "30": "a-x2.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/a.png"), - "2": browser.runtime.getURL("data/a-x2.png")}}, - {details: {"path": {"16": "16.png", "100": "100.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/16.png"), - "2": browser.runtime.getURL("data/100.png")}}, - {details: {"path": {"2": "2.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/2.png"), - "2": browser.runtime.getURL("data/2.png")}}, - {details: {"path": { - "16": "16.svg", - "18": "18.svg"}}, - resolutions: { - "1": browser.runtime.getURL("data/16.svg"), - "2": browser.runtime.getURL("data/18.svg")}}, - {details: {"path": { - "6": "6.png", - "18": "18.png", - "36": "36.png", - "48": "48.png", - "128": "128.png"}}, - legacy: true, - resolutions: { - "1": browser.runtime.getURL("data/18.png"), - "2": browser.runtime.getURL("data/36.png")}, - menuResolutions: { - "1": browser.runtime.getURL("data/36.png"), - "2": browser.runtime.getURL("data/128.png")}}, - {details: {"path": { - "16": "16.png", - "18": "18.png", - "32": "32.png", - "48": "48.png", - "64": "64.png", - "128": "128.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/16.png"), - "2": browser.runtime.getURL("data/32.png")}, - menuResolutions: { - "1": browser.runtime.getURL("data/32.png"), - "2": browser.runtime.getURL("data/64.png")}}, - {details: {"path": { - "18": "18.png", - "32": "32.png", - "48": "48.png", - "128": "128.png"}}, - resolutions: { - "1": browser.runtime.getURL("data/32.png"), - "2": browser.runtime.getURL("data/32.png")}}, - ]; - - // Allow serializing ImageData objects for logging. - ImageData.prototype.toJSON = () => "<ImageData>"; - - let tabId; - - browser.test.onMessage.addListener((msg, test) => { - if (msg != "setIcon") { - browser.test.fail("expecting 'setIcon' message"); - } - - let details = iconDetails[test.index]; - - let detailString = JSON.stringify(details); - browser.test.log(`Setting browerAction/pageAction to ${detailString} expecting URLs ${JSON.stringify(details.resolutions)}`); - - Promise.all([ - browser.browserAction.setIcon(Object.assign({tabId}, details.details)), - browser.pageAction.setIcon(Object.assign({tabId}, details.details)), - ]).then(() => { - browser.test.sendMessage("iconSet"); - }); - }); - - // Generate a list of tests and resolutions to send back to the test - // context. - // - // This process is a bit convoluted, because the outer test context needs - // to handle checking the button nodes and changing the screen resolution, - // but it can't pass us icon definitions with ImageData objects. This - // shouldn't be a problem, since structured clones should handle ImageData - // objects without issue. Unfortunately, |cloneInto| implements a slightly - // different algorithm than we use in web APIs, and does not handle them - // correctly. - let tests = []; - for (let [idx, icon] of iconDetails.entries()) { - tests.push({ - index: idx, - legacy: !!icon.legacy, - menuResolutions: icon.menuResolutions, - resolutions: icon.resolutions, - }); - } - - // Sort by resolution, so we don't needlessly switch back and forth - // between each test. - tests.sort(test => test.resolution); - - browser.tabs.query({active: true, currentWindow: true}, tabs => { - tabId = tabs[0].id; - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("ready", tests); - }); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": {}, - "page_action": {}, - "background": { - "page": "data/background.html", - } - }, - - files: { - "data/background.html": `<script src="background.js"></script>`, - "data/background.js": background, - - "data/16.svg": imageBuffer, - "data/18.svg": imageBuffer, - - "data/16.png": imageBuffer, - "data/18.png": imageBuffer, - "data/32.png": imageBuffer, - "data/36.png": imageBuffer, - "data/48.png": imageBuffer, - "data/64.png": imageBuffer, - "data/128.png": imageBuffer, - - "a.png": imageBuffer, - "data/2.png": imageBuffer, - "data/100.png": imageBuffer, - "data/a.png": imageBuffer, - "data/a-x2.png": imageBuffer, - }, - }); - - const RESOLUTION_PREF = "layout.css.devPixelsPerPx"; - - yield extension.startup(); - - let pageActionId = `${makeWidgetId(extension.id)}-page-action`; - let browserActionWidget = getBrowserActionWidget(extension); - - let tests = yield extension.awaitMessage("ready"); - for (let test of tests) { - extension.sendMessage("setIcon", test); - yield extension.awaitMessage("iconSet"); - - let browserActionButton = browserActionWidget.forWindow(window).node; - let pageActionImage = document.getElementById(pageActionId); - - - // Test icon sizes in the toolbar/urlbar. - for (let resolution of Object.keys(test.resolutions)) { - yield SpecialPowers.pushPrefEnv({set: [[RESOLUTION_PREF, resolution]]}); - - is(window.devicePixelRatio, +resolution, "window has the required resolution"); - - let imageURL = test.resolutions[resolution]; - is(getListStyleImage(browserActionButton), imageURL, `browser action has the correct image at ${resolution}x resolution`); - is(getListStyleImage(pageActionImage), imageURL, `page action has the correct image at ${resolution}x resolution`); - - let isLegacy = browserActionButton.classList.contains("toolbarbutton-legacy-addon"); - is(isLegacy, test.legacy, "Legacy class should be present?"); - - yield SpecialPowers.popPrefEnv(); - } - - if (!test.menuResolutions) { - continue; - } - - - // Test icon sizes in the menu panel. - CustomizableUI.addWidgetToArea(browserActionWidget.id, - CustomizableUI.AREA_PANEL); - - yield showBrowserAction(extension); - browserActionButton = browserActionWidget.forWindow(window).node; - - for (let resolution of Object.keys(test.menuResolutions)) { - yield SpecialPowers.pushPrefEnv({set: [[RESOLUTION_PREF, resolution]]}); - - is(window.devicePixelRatio, +resolution, "window has the required resolution"); - - let imageURL = test.menuResolutions[resolution]; - is(getListStyleImage(browserActionButton), imageURL, `browser action has the correct menu image at ${resolution}x resolution`); - - yield SpecialPowers.popPrefEnv(); - } - - yield closeBrowserAction(extension); - - CustomizableUI.addWidgetToArea(browserActionWidget.id, - CustomizableUI.AREA_NAVBAR); - } - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js b/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js deleted file mode 100644 index 110746cae..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_pageAction_icon_permissions.js +++ /dev/null @@ -1,210 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -// Test that an error is thrown when providing invalid icon sizes -add_task(function* testInvalidIconSizes() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": {}, - "page_action": {}, - }, - - background: function() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - let tabId = tabs[0].id; - - let promises = []; - for (let api of ["pageAction", "browserAction"]) { - // helper function to run setIcon and check if it fails - let assertSetIconThrows = function(detail, error, message) { - detail.tabId = tabId; - promises.push( - browser.test.assertRejects( - browser[api].setIcon(detail), - /must be an integer/, - "setIcon with invalid icon size")); - }; - - let imageData = new ImageData(1, 1); - - // test invalid icon size inputs - for (let type of ["path", "imageData"]) { - let img = type == "imageData" ? imageData : "test.png"; - - assertSetIconThrows({[type]: {"abcdef": img}}); - assertSetIconThrows({[type]: {"48px": img}}); - assertSetIconThrows({[type]: {"20.5": img}}); - assertSetIconThrows({[type]: {"5.0": img}}); - assertSetIconThrows({[type]: {"-300": img}}); - assertSetIconThrows({[type]: {"abc": img, "5": img}}); - } - - assertSetIconThrows({imageData: {"abcdef": imageData}, path: {"5": "test.png"}}); - assertSetIconThrows({path: {"abcdef": "test.png"}, imageData: {"5": imageData}}); - } - - Promise.all(promises).then(() => { - browser.test.notifyPass("setIcon with invalid icon size"); - }); - }); - }, - }); - - yield Promise.all([extension.startup(), extension.awaitFinish("setIcon with invalid icon size")]); - - yield extension.unload(); -}); - - -// Test that default icon details in the manifest.json file are handled -// correctly. -add_task(function* testDefaultDetails() { - // TODO: Test localized variants. - let icons = [ - "foo/bar.png", - "/foo/bar.png", - {"19": "foo/bar.png"}, - {"38": "foo/bar.png"}, - ]; - - if (window.devicePixelRatio > 1) { - icons.push({"19": "baz/quux.png", "38": "foo/bar.png"}); - } else { - icons.push({"19": "foo/bar.png", "38": "baz/quux@2x.png"}); - } - - let expectedURL = new RegExp(String.raw`^moz-extension://[^/]+/foo/bar\.png$`); - - for (let icon of icons) { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": {"default_icon": icon}, - "page_action": {"default_icon": icon}, - }, - - background: function() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - let tabId = tabs[0].id; - - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("ready"); - }); - }); - }, - - files: { - "foo/bar.png": imageBuffer, - "baz/quux.png": imageBuffer, - "baz/quux@2x.png": imageBuffer, - }, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("ready")]); - - let browserActionId = makeWidgetId(extension.id) + "-browser-action"; - let pageActionId = makeWidgetId(extension.id) + "-page-action"; - - let browserActionButton = document.getElementById(browserActionId); - let image = getListStyleImage(browserActionButton); - - ok(expectedURL.test(image), `browser action image ${image} matches ${expectedURL}`); - - let pageActionImage = document.getElementById(pageActionId); - image = getListStyleImage(pageActionImage); - - ok(expectedURL.test(image), `page action image ${image} matches ${expectedURL}`); - - yield extension.unload(); - - let node = document.getElementById(pageActionId); - is(node, null, "pageAction image removed from document"); - } -}); - - -// Check that attempts to load a privileged URL as an icon image fail. -add_task(function* testSecureURLsDenied() { - // Test URLs passed to setIcon. - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": {}, - "page_action": {}, - }, - - background: function() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - let tabId = tabs[0].id; - - let urls = ["chrome://browser/content/browser.xul", - "javascript:true"]; - - let promises = []; - for (let url of urls) { - for (let api of ["pageAction", "browserAction"]) { - promises.push( - browser.test.assertRejects( - browser[api].setIcon({tabId, path: url}), - /Illegal URL/, - `Load of '${url}' should fail.`)); - } - } - - Promise.all(promises).then(() => { - browser.test.notifyPass("setIcon security tests"); - }); - }); - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("setIcon security tests"); - yield extension.unload(); -}); - - -add_task(function* testSecureManifestURLsDenied() { - // Test URLs included in the manifest. - - let urls = ["chrome://browser/content/browser.xul", - "javascript:true"]; - - let apis = ["browser_action", "page_action"]; - - for (let url of urls) { - for (let api of apis) { - info(`TEST ${api} icon url: ${url}`); - - let matchURLForbidden = url => ({ - message: new RegExp(`match the format "strictRelativeUrl"`), - }); - - let messages = [matchURLForbidden(url)]; - - let waitForConsole = new Promise(resolve => { - // Not necessary in browser-chrome tests, but monitorConsole gripes - // if we don't call it. - SimpleTest.waitForExplicitFinish(); - - SimpleTest.monitorConsole(resolve, messages); - }); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - [api]: { - "default_icon": url, - }, - }, - }); - - yield Assert.rejects(extension.startup(), - null, - "Manifest rejected"); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; - } - } -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js b/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js deleted file mode 100644 index 9f04b3c11..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js +++ /dev/null @@ -1,413 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function getBrowserAction(extension) { - const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let ext = GlobalManager.extensionMap.get(extension.id); - return browserActionFor(ext); -} - -let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>${url}</body></html>`; - -function* testInArea(area) { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "background": { - "page": "data/background.html", - }, - "browser_action": { - "default_popup": "popup-a.html", - "browser_style": true, - }, - }, - - files: { - "popup-a.html": scriptPage("popup-a.js"), - "popup-a.js": function() { - window.onload = () => { - let color = window.getComputedStyle(document.body).color; - browser.test.assertEq("rgb(34, 36, 38)", color); - browser.runtime.sendMessage("from-popup-a"); - }; - browser.runtime.onMessage.addListener(msg => { - if (msg == "close-popup-using-window.close") { - window.close(); - } - }); - }, - - "data/popup-b.html": scriptPage("popup-b.js"), - "data/popup-b.js": function() { - window.onload = () => { - browser.runtime.sendMessage("from-popup-b"); - }; - }, - - "data/popup-c.html": scriptPage("popup-c.js"), - "data/popup-c.js": function() { - // Close the popup before the document is fully-loaded to make sure that - // we handle this case sanely. - browser.runtime.sendMessage("from-popup-c"); - window.close(); - }, - - "data/background.html": scriptPage("background.js"), - - "data/background.js": function() { - let sendClick; - let tests = [ - () => { - browser.test.log(`Click browser action, expect popup "a".`); - sendClick({expectEvent: false, expectPopup: "a"}); - }, - () => { - browser.test.log(`Click browser action again, expect popup "a".`); - sendClick({expectEvent: false, expectPopup: "a"}); - }, - () => { - browser.test.log(`Call triggerAction, expect popup "a" again. Leave popup open.`); - sendClick({expectEvent: false, expectPopup: "a", closePopup: false}, "trigger-action"); - }, - () => { - browser.test.log(`Call triggerAction again. Expect remaining popup closed.`); - sendClick({expectEvent: false, expectPopup: null}, "trigger-action"); - browser.test.sendMessage("next-test", {waitUntilClosed: true}); - }, - () => { - browser.test.log(`Call triggerAction again. Expect popup "a" again.`); - sendClick({expectEvent: false, expectPopup: "a"}, "trigger-action"); - }, - () => { - browser.test.log(`Set popup to "c" and click browser action. Expect popup "c".`); - browser.browserAction.setPopup({popup: "popup-c.html"}); - sendClick({expectEvent: false, expectPopup: "c", closePopup: false}); - }, - () => { - browser.test.log(`Set popup to "b" and click browser action. Expect popup "b".`); - browser.browserAction.setPopup({popup: "popup-b.html"}); - sendClick({expectEvent: false, expectPopup: "b"}); - }, - () => { - browser.test.log(`Click browser action again, expect popup "b".`); - sendClick({expectEvent: false, expectPopup: "b"}); - }, - () => { - browser.test.log(`Clear popup URL. Click browser action. Expect click event.`); - browser.browserAction.setPopup({popup: ""}); - sendClick({expectEvent: true, expectPopup: null}); - }, - () => { - browser.test.log(`Click browser action again. Expect another click event.`); - sendClick({expectEvent: true, expectPopup: null}); - }, - () => { - browser.test.log(`Call triggerAction. Expect click event.`); - sendClick({expectEvent: true, expectPopup: null}, "trigger-action"); - }, - () => { - browser.test.log(`Set popup to "a" and click browser action. Expect popup "a", and leave open.`); - browser.browserAction.setPopup({popup: "/popup-a.html"}); - sendClick({expectEvent: false, expectPopup: "a", closePopup: false}); - }, - () => { - browser.test.log(`Tell popup "a" to call window.close(). Expect popup closed.`); - browser.test.sendMessage("next-test", {closePopupUsingWindow: true}); - }, - ]; - - let expect = {}; - sendClick = ({expectEvent, expectPopup, runNextTest, waitUntilClosed, closePopup}, message = "send-click") => { - if (closePopup == undefined) { - closePopup = true; - } - - expect = {event: expectEvent, popup: expectPopup, runNextTest, waitUntilClosed, closePopup}; - browser.test.sendMessage(message); - }; - - browser.runtime.onMessage.addListener(msg => { - if (msg == "close-popup-using-window.close") { - return; - } else if (expect.popup) { - browser.test.assertEq(msg, `from-popup-${expect.popup}`, - "expected popup opened"); - } else { - browser.test.fail(`unexpected popup: ${msg}`); - } - - expect.popup = null; - browser.test.sendMessage("next-test", expect); - }); - - browser.browserAction.onClicked.addListener(() => { - if (expect.event) { - browser.test.succeed("expected click event received"); - } else { - browser.test.fail("unexpected click event"); - } - - expect.event = false; - browser.test.sendMessage("next-test", expect); - }); - - browser.test.onMessage.addListener((msg) => { - if (msg == "close-popup-using-window.close") { - browser.runtime.sendMessage("close-popup-using-window.close"); - return; - } - - if (msg != "next-test") { - browser.test.fail("Expecting 'next-test' message"); - } - - if (tests.length) { - let test = tests.shift(); - test(); - } else { - browser.test.notifyPass("browseraction-tests-done"); - } - }); - - browser.test.sendMessage("next-test"); - }, - }, - }); - - extension.onMessage("send-click", () => { - clickBrowserAction(extension); - }); - - extension.onMessage("trigger-action", () => { - getBrowserAction(extension).triggerAction(window); - }); - - let widget; - extension.onMessage("next-test", Task.async(function* (expecting = {}) { - if (!widget) { - widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, area); - } - if (expecting.waitUntilClosed) { - let panel = getBrowserActionPopup(extension); - if (panel && panel.state != "closed") { - yield promisePopupHidden(panel); - } - } else if (expecting.closePopupUsingWindow) { - let panel = getBrowserActionPopup(extension); - ok(panel, "Expect panel to exist"); - yield promisePopupShown(panel); - - extension.sendMessage("close-popup-using-window.close"); - - yield promisePopupHidden(panel); - ok(true, "Panel is closed"); - } else if (expecting.closePopup) { - yield closeBrowserAction(extension); - } - - extension.sendMessage("next-test"); - })); - - yield Promise.all([extension.startup(), extension.awaitFinish("browseraction-tests-done")]); - - yield extension.unload(); - - let view = document.getElementById(widget.viewId); - is(view, null, "browserAction view removed from document"); -} - -add_task(function* testBrowserActionInToolbar() { - yield testInArea(CustomizableUI.AREA_NAVBAR); -}); - -add_task(function* testBrowserActionInPanel() { - yield testInArea(CustomizableUI.AREA_PANEL); -}); - -add_task(function* testBrowserActionClickCanceled() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - "permissions": ["activeTab"], - }, - - files: { - "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head></html>`, - }, - }); - - yield extension.startup(); - - const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let ext = GlobalManager.extensionMap.get(extension.id); - let browserAction = browserActionFor(ext); - - let widget = getBrowserActionWidget(extension).forWindow(window); - let tab = window.gBrowser.selectedTab; - - // Test canceled click. - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window); - - isnot(browserAction.pendingPopup, null, "Have pending popup"); - is(browserAction.pendingPopup.window, window, "Have pending popup for the correct window"); - - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - is(browserAction.tabToRevokeDuringClearPopup, tab, "Tab to revoke was saved"); - is(browserAction.tabManager.hasActiveTabPermission(tab), true, "Active tab was granted permission"); - - EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mouseup", button: 0}, window); - - is(browserAction.pendingPopup, null, "Pending popup was cleared"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - is(browserAction.tabToRevokeDuringClearPopup, null, "Tab to revoke was removed"); - is(browserAction.tabManager.hasActiveTabPermission(tab), false, "Permission was revoked from tab"); - - // Test completed click. - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window); - - isnot(browserAction.pendingPopup, null, "Have pending popup"); - is(browserAction.pendingPopup.window, window, "Have pending popup for the correct window"); - - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - // We need to do these tests during the mouseup event cycle, since the click - // and command events will be dispatched immediately after mouseup, and void - // the results. - let mouseUpPromise = BrowserTestUtils.waitForEvent(widget.node, "mouseup", false, event => { - isnot(browserAction.pendingPopup, null, "Pending popup was not cleared"); - isnot(browserAction.pendingPopupTimeout, null, "Have a pending popup timeout"); - return true; - }); - - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, window); - - yield mouseUpPromise; - - is(browserAction.pendingPopup, null, "Pending popup was cleared"); - is(browserAction.pendingPopupTimeout, null, "Pending popup timeout was cleared"); - - yield promisePopupShown(getBrowserActionPopup(extension)); - yield closeBrowserAction(extension); - - yield extension.unload(); -}); - -add_task(function* testBrowserActionDisabled() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - }, - - background() { - browser.browserAction.disable(); - }, - - files: { - "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>`, - "popup.js"() { - browser.test.fail("Should not get here"); - }, - }, - }); - - yield extension.startup(); - - const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let ext = GlobalManager.extensionMap.get(extension.id); - let browserAction = browserActionFor(ext); - - let widget = getBrowserActionWidget(extension).forWindow(window); - - // Test canceled click. - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window); - - is(browserAction.pendingPopup, null, "Have no pending popup"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - EventUtils.synthesizeMouseAtCenter(document.documentElement, {type: "mouseup", button: 0}, window); - - is(browserAction.pendingPopup, null, "Have no pending popup"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - - // Test completed click. - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, window); - - is(browserAction.pendingPopup, null, "Have no pending popup"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - // We need to do these tests during the mouseup event cycle, since the click - // and command events will be dispatched immediately after mouseup, and void - // the results. - let mouseUpPromise = BrowserTestUtils.waitForEvent(widget.node, "mouseup", false, event => { - is(browserAction.pendingPopup, null, "Have no pending popup"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - return true; - }); - - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, window); - - yield mouseUpPromise; - - is(browserAction.pendingPopup, null, "Have no pending popup"); - is(browserAction.pendingPopupTimeout, null, "Have no pending popup timeout"); - - // Give the popup a chance to load and trigger a failure, if it was - // erroneously opened. - yield new Promise(resolve => setTimeout(resolve, 250)); - - yield extension.unload(); -}); - -add_task(function* testBrowserActionTabPopulation() { - // Note: This test relates to https://bugzilla.mozilla.org/show_bug.cgi?id=1310019 - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - "permissions": ["activeTab"], - }, - - files: { - "popup.html": scriptPage("popup.js"), - "popup.js": function() { - browser.tabs.query({active: true, currentWindow: true}).then(tabs => { - browser.test.assertEq("mochitest index /", - tabs[0].title, - "Tab has the expected title on first click"); - browser.test.sendMessage("tabTitle"); - }); - }, - }, - }); - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "http://example.com/"); - yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - - yield extension.startup(); - - let widget = getBrowserActionWidget(extension).forWindow(win); - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mousedown", button: 0}, win); - - yield extension.awaitMessage("tabTitle"); - - EventUtils.synthesizeMouseAtCenter(widget.node, {type: "mouseup", button: 0}, win); - - yield extension.unload(); - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js b/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js deleted file mode 100644 index 6c19b17f1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_popup_resize.js +++ /dev/null @@ -1,304 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* openPanel(extension, win = window, awaitLoad = false) { - clickBrowserAction(extension, win); - - return yield awaitExtensionPanel(extension, win, awaitLoad); -} - -add_task(function* testBrowserActionPopupResize() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - }, - - files: { - "popup.html": '<!DOCTYPE html><html><head><meta charset="utf-8"></head></html>', - }, - }); - - yield extension.startup(); - - let browser = yield openPanel(extension); - - function* checkSize(expected) { - let dims = yield promiseContentDimensions(browser); - - is(dims.window.innerHeight, expected, `Panel window should be ${expected}px tall`); - is(dims.body.clientHeight, dims.body.scrollHeight, - "Panel body should be tall enough to fit its contents"); - - // Tolerate if it is 1px too wide, as that may happen with the current resizing method. - ok(Math.abs(dims.window.innerWidth - expected) <= 1, `Panel window should be ${expected}px wide`); - is(dims.body.clientWidth, dims.body.scrollWidth, - "Panel body should be wide enough to fit its contents"); - } - - /* eslint-disable mozilla/no-cpows-in-tests */ - function setSize(size) { - content.document.body.style.height = `${size}px`; - content.document.body.style.width = `${size}px`; - } - /* eslint-enable mozilla/no-cpows-in-tests */ - - let sizes = [ - 200, - 400, - 300, - ]; - - for (let size of sizes) { - yield alterContent(browser, setSize, size); - yield checkSize(size); - } - - yield closeBrowserAction(extension); - yield extension.unload(); -}); - -function* testPopupSize(standardsMode, browserWin = window, arrowSide = "top") { - let docType = standardsMode ? "<!DOCTYPE html>" : ""; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - }, - - files: { - "popup.html": `${docType} - <html> - <head> - <meta charset="utf-8"> - <style type="text/css"> - body > span { - display: inline-block; - width: 10px; - height: 150px; - border: 2px solid black; - } - .big > span { - width: 300px; - height: 100px; - } - .bigger > span { - width: 150px; - height: 150px; - } - .huge > span { - height: ${2 * screen.height}px; - } - </style> - </head> - <body> - <span></span> - <span></span> - <span></span> - <span></span> - </body> - </html>`, - }, - }); - - yield extension.startup(); - - /* eslint-disable mozilla/no-cpows-in-tests */ - - if (arrowSide == "top") { - // Test the standalone panel for a toolbar button. - let browser = yield openPanel(extension, browserWin, true); - - let dims = yield promiseContentDimensions(browser); - - is(dims.isStandards, standardsMode, "Document has the expected compat mode"); - - let {innerWidth, innerHeight} = dims.window; - - dims = yield alterContent(browser, () => { - content.document.body.classList.add("bigger"); - }); - - let win = dims.window; - is(win.innerHeight, innerHeight, "Window height should not change"); - ok(win.innerWidth > innerWidth, `Window width should increase (${win.innerWidth} > ${innerWidth})`); - - - dims = yield alterContent(browser, () => { - content.document.body.classList.remove("bigger"); - }); - - win = dims.window; - is(win.innerHeight, innerHeight, "Window height should not change"); - - // The getContentSize calculation is not always reliable to single-pixel - // precision. - ok(Math.abs(win.innerWidth - innerWidth) <= 1, - `Window width should return to approximately its original value (${win.innerWidth} ~= ${innerWidth})`); - - yield closeBrowserAction(extension, browserWin); - } - - - // Test the PanelUI panel for a menu panel button. - let widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL); - - let browser = yield openPanel(extension, browserWin); - - let {panel} = browserWin.PanelUI; - let origPanelRect = panel.getBoundingClientRect(); - - // Check that the panel is still positioned as expected. - let checkPanelPosition = () => { - is(panel.getAttribute("side"), arrowSide, "Panel arrow is positioned as expected"); - - let panelRect = panel.getBoundingClientRect(); - if (arrowSide == "top") { - ok(panelRect.top, origPanelRect.top, "Panel has not moved downwards"); - ok(panelRect.bottom >= origPanelRect.bottom, `Panel has not shrunk from original size (${panelRect.bottom} >= ${origPanelRect.bottom})`); - - let screenBottom = browserWin.screen.availTop + browserWin.screen.availHeight; - let panelBottom = browserWin.mozInnerScreenY + panelRect.bottom; - ok(panelBottom <= screenBottom, `Bottom of popup should be on-screen. (${panelBottom} <= ${screenBottom})`); - } else { - ok(panelRect.bottom, origPanelRect.bottom, "Panel has not moved upwards"); - ok(panelRect.top <= origPanelRect.top, `Panel has not shrunk from original size (${panelRect.top} <= ${origPanelRect.top})`); - - let panelTop = browserWin.mozInnerScreenY + panelRect.top; - ok(panelTop >= browserWin.screen.availTop, `Top of popup should be on-screen. (${panelTop} >= ${browserWin.screen.availTop})`); - } - }; - - yield awaitBrowserLoaded(browser); - - // Wait long enough to make sure the initial resize debouncing timer has - // expired. - yield new Promise(resolve => setTimeout(resolve, 100)); - - let dims = yield promiseContentDimensions(browser); - - is(dims.isStandards, standardsMode, "Document has the expected compat mode"); - - // If the browser's preferred height is smaller than the initial height of the - // panel, then it will still take up the full available vertical space. Even - // so, we need to check that we've gotten the preferred height calculation - // correct, so check that explicitly. - let getHeight = () => parseFloat(browser.style.height); - - let {innerWidth, innerHeight} = dims.window; - let height = getHeight(); - - - let setClass = className => { - content.document.body.className = className; - }; - - info("Increase body children's width. " + - "Expect them to wrap, and the frame to grow vertically rather than widen."); - - dims = yield alterContent(browser, setClass, "big"); - let win = dims.window; - - ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`); - - is(win.innerWidth, innerWidth, "Window width should not change"); - ok(win.innerHeight >= innerHeight, `Window height should increase (${win.innerHeight} >= ${innerHeight})`); - is(win.scrollMaxY, 0, "Document should not be vertically scrollable"); - - checkPanelPosition(); - - - info("Increase body children's width and height. " + - "Expect them to wrap, and the frame to grow vertically rather than widen."); - - dims = yield alterContent(browser, setClass, "bigger"); - win = dims.window; - - ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`); - - is(win.innerWidth, innerWidth, "Window width should not change"); - ok(win.innerHeight >= innerHeight, `Window height should increase (${win.innerHeight} >= ${innerHeight})`); - is(win.scrollMaxY, 0, "Document should not be vertically scrollable"); - - checkPanelPosition(); - - - info("Increase body height beyond the height of the screen. " + - "Expect the panel to grow to accommodate, but not larger than the height of the screen."); - - dims = yield alterContent(browser, setClass, "huge"); - win = dims.window; - - ok(getHeight() > height, `Browser height should increase (${getHeight()} > ${height})`); - - is(win.innerWidth, innerWidth, "Window width should not change"); - ok(win.innerHeight > innerHeight, `Window height should increase (${win.innerHeight} > ${innerHeight})`); - ok(win.innerHeight < screen.height, `Window height be less than the screen height (${win.innerHeight} < ${screen.height})`); - ok(win.scrollMaxY > 0, `Document should be vertically scrollable (${win.scrollMaxY} > 0)`); - - checkPanelPosition(); - - - info("Restore original styling. Expect original dimensions."); - dims = yield alterContent(browser, setClass, ""); - win = dims.window; - - is(getHeight(), height, "Browser height should return to its original value"); - - is(win.innerWidth, innerWidth, "Window width should not change"); - is(win.innerHeight, innerHeight, "Window height should return to its original value"); - is(win.scrollMaxY, 0, "Document should not be vertically scrollable"); - - checkPanelPosition(); - - yield closeBrowserAction(extension, browserWin); - - yield extension.unload(); -} - -add_task(function* testBrowserActionMenuResizeStandards() { - yield testPopupSize(true); -}); - -add_task(function* testBrowserActionMenuResizeQuirks() { - yield testPopupSize(false); -}); - -// Test that we still make reasonable maximum size calculations when the window -// is close enough to the bottom of the screen that the menu panel opens above, -// rather than below, its button. -add_task(function* testBrowserActionMenuResizeBottomArrow() { - const WIDTH = 800; - const HEIGHT = 300; - - let left = screen.availLeft + screen.availWidth - WIDTH; - let top = screen.availTop + screen.availHeight - HEIGHT; - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - - win.resizeTo(WIDTH, HEIGHT); - - // Sometimes we run into problems on Linux with resizing being asynchronous - // and window managers not allowing us to move the window so that any part of - // it is off-screen, so we need to try more than once. - for (let i = 0; i < 20; i++) { - win.moveTo(left, top); - - if (win.screenX == left && win.screenY == top) { - break; - } - - yield new Promise(resolve => setTimeout(resolve, 100)); - } - - yield testPopupSize(true, win, "bottom"); - - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js b/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js deleted file mode 100644 index e83010958..000000000 --- a/browser/components/extensions/test/browser/browser_ext_browserAction_simple.js +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "unrecognized_property": "with-a-random-value", - }, - }, - - files: { - "popup.html": ` - <!DOCTYPE html> - <html><body> - <script src="popup.js"></script> - </body></html> - `, - - "popup.js": function() { - window.onload = () => { - browser.runtime.sendMessage("from-popup"); - }; - }, - }, - - background: function() { - browser.runtime.onMessage.addListener(msg => { - browser.test.assertEq(msg, "from-popup", "correct message received"); - browser.test.sendMessage("popup"); - }); - }, - }); - - SimpleTest.waitForExplicitFinish(); - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{ - message: /Reading manifest: Error processing browser_action.unrecognized_property: An unexpected property was found/, - }]); - }); - - yield extension.startup(); - - // Do this a few times to make sure the pop-up is reloaded each time. - for (let i = 0; i < 3; i++) { - clickBrowserAction(extension); - - yield extension.awaitMessage("popup"); - - closeBrowserAction(extension); - } - - yield extension.unload(); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js b/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js deleted file mode 100644 index f97a735d4..000000000 --- a/browser/components/extensions/test/browser/browser_ext_commands_execute_browser_action.js +++ /dev/null @@ -1,113 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* testExecuteBrowserActionWithOptions(options = {}) { - let extensionOptions = {}; - - extensionOptions.manifest = { - "commands": { - "_execute_browser_action": { - "suggested_key": { - "default": "Alt+Shift+J", - }, - }, - }, - "browser_action": { - "browser_style": true, - }, - }; - - if (options.withPopup) { - extensionOptions.manifest.browser_action.default_popup = "popup.html"; - - extensionOptions.files = { - "popup.html": ` - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - <script src="popup.js"></script> - </head> - </html> - `, - - "popup.js": function() { - browser.runtime.sendMessage("from-browser-action-popup"); - }, - }; - } - - extensionOptions.background = () => { - browser.test.onMessage.addListener((message, withPopup) => { - browser.commands.onCommand.addListener((commandName) => { - if (commandName == "_execute_browser_action") { - browser.test.fail("The onCommand listener should never fire for _execute_browser_action."); - } - }); - - browser.browserAction.onClicked.addListener(() => { - if (withPopup) { - browser.test.fail("The onClick listener should never fire if the browserAction has a popup."); - browser.test.notifyFail("execute-browser-action-on-clicked-fired"); - } else { - browser.test.notifyPass("execute-browser-action-on-clicked-fired"); - } - }); - - browser.runtime.onMessage.addListener(msg => { - if (msg == "from-browser-action-popup") { - browser.test.notifyPass("execute-browser-action-popup-opened"); - } - }); - - browser.test.sendMessage("send-keys"); - }); - }; - - let extension = ExtensionTestUtils.loadExtension(extensionOptions); - - extension.onMessage("send-keys", () => { - EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true}); - }); - - yield extension.startup(); - - if (options.inArea) { - let widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, options.inArea); - } - - extension.sendMessage("withPopup", options.withPopup); - - if (options.withPopup) { - yield extension.awaitFinish("execute-browser-action-popup-opened"); - yield closeBrowserAction(extension); - } else { - yield extension.awaitFinish("execute-browser-action-on-clicked-fired"); - } - yield extension.unload(); -} - -add_task(function* test_execute_browser_action_with_popup() { - yield testExecuteBrowserActionWithOptions({ - withPopup: true, - }); -}); - -add_task(function* test_execute_browser_action_without_popup() { - yield testExecuteBrowserActionWithOptions(); -}); - -add_task(function* test_execute_browser_action_in_hamburger_menu_with_popup() { - yield testExecuteBrowserActionWithOptions({ - withPopup: true, - inArea: CustomizableUI.AREA_PANEL, - }); -}); - -add_task(function* test_execute_browser_action_in_hamburger_menu_without_popup() { - yield testExecuteBrowserActionWithOptions({ - inArea: CustomizableUI.AREA_PANEL, - }); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js b/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js deleted file mode 100644 index 83684493e..000000000 --- a/browser/components/extensions/test/browser/browser_ext_commands_execute_page_action.js +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* test_execute_page_action_without_popup() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "commands": { - "_execute_page_action": { - "suggested_key": { - "default": "Alt+Shift+J", - }, - }, - "send-keys-command": { - "suggested_key": { - "default": "Alt+Shift+3", - }, - }, - }, - "page_action": {}, - }, - - background: function() { - let isShown = false; - - browser.commands.onCommand.addListener((commandName) => { - if (commandName == "_execute_page_action") { - browser.test.fail(`The onCommand listener should never fire for ${commandName}.`); - } else if (commandName == "send-keys-command") { - if (!isShown) { - isShown = true; - browser.tabs.query({currentWindow: true, active: true}, tabs => { - tabs.forEach(tab => { - browser.pageAction.show(tab.id); - }); - browser.test.sendMessage("send-keys"); - }); - } - } - }); - - browser.pageAction.onClicked.addListener(() => { - browser.test.assertTrue(isShown, "The onClicked event should fire if the page action is shown."); - browser.test.notifyPass("page-action-without-popup"); - }); - - browser.test.sendMessage("send-keys"); - }, - }); - - extension.onMessage("send-keys", () => { - EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true}); - EventUtils.synthesizeKey("3", {altKey: true, shiftKey: true}); - }); - - yield extension.startup(); - yield extension.awaitFinish("page-action-without-popup"); - yield extension.unload(); -}); - -add_task(function* test_execute_page_action_with_popup() { - let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>Test Popup</body></html>`; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "commands": { - "_execute_page_action": { - "suggested_key": { - "default": "Alt+Shift+J", - }, - }, - "send-keys-command": { - "suggested_key": { - "default": "Alt+Shift+3", - }, - }, - }, - "page_action": { - "default_popup": "popup.html", - }, - }, - - files: { - "popup.html": scriptPage("popup.js"), - "popup.js": function() { - browser.runtime.sendMessage("popup-opened"); - }, - }, - - background: function() { - let isShown = false; - - browser.commands.onCommand.addListener((message) => { - if (message == "_execute_page_action") { - browser.test.fail(`The onCommand listener should never fire for ${message}.`); - } - - if (message == "send-keys-command") { - if (!isShown) { - isShown = true; - browser.tabs.query({currentWindow: true, active: true}, tabs => { - tabs.forEach(tab => { - browser.pageAction.show(tab.id); - }); - browser.test.sendMessage("send-keys"); - }); - } - } - }); - - browser.pageAction.onClicked.addListener(() => { - browser.test.fail(`The onClicked listener should never fire when the pageAction has a popup.`); - }); - - browser.runtime.onMessage.addListener(msg => { - browser.test.assertEq(msg, "popup-opened", "expected popup opened"); - browser.test.assertTrue(isShown, "The onClicked event should fire if the page action is shown."); - browser.test.notifyPass("page-action-with-popup"); - }); - - browser.test.sendMessage("send-keys"); - }, - }); - - extension.onMessage("send-keys", () => { - EventUtils.synthesizeKey("j", {altKey: true, shiftKey: true}); - EventUtils.synthesizeKey("3", {altKey: true, shiftKey: true}); - }); - - yield extension.startup(); - yield extension.awaitFinish("page-action-with-popup"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_commands_getAll.js b/browser/components/extensions/test/browser/browser_ext_commands_getAll.js deleted file mode 100644 index 5885e8aee..000000000 --- a/browser/components/extensions/test/browser/browser_ext_commands_getAll.js +++ /dev/null @@ -1,81 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -var {AppConstants} = Cu.import("resource://gre/modules/AppConstants.jsm"); - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "name": "Commands Extension", - "commands": { - "with-desciption": { - "suggested_key": { - "default": "Ctrl+Shift+Y", - }, - "description": "should have a description", - }, - "without-description": { - "suggested_key": { - "default": "Ctrl+Shift+D", - }, - }, - "with-platform-info": { - "suggested_key": { - "mac": "Ctrl+Shift+M", - "linux": "Ctrl+Shift+L", - "windows": "Ctrl+Shift+W", - "android": "Ctrl+Shift+A", - }, - }, - }, - }, - - background: function() { - browser.test.onMessage.addListener((message, additionalScope) => { - browser.commands.getAll((commands) => { - let errorMessage = "getAll should return an array of commands"; - browser.test.assertEq(commands.length, 3, errorMessage); - - let command = commands.find(c => c.name == "with-desciption"); - - errorMessage = "The description should match what is provided in the manifest"; - browser.test.assertEq("should have a description", command.description, errorMessage); - - errorMessage = "The shortcut should match the default shortcut provided in the manifest"; - browser.test.assertEq("Ctrl+Shift+Y", command.shortcut, errorMessage); - - command = commands.find(c => c.name == "without-description"); - - errorMessage = "The description should be empty when it is not provided"; - browser.test.assertEq(null, command.description, errorMessage); - - errorMessage = "The shortcut should match the default shortcut provided in the manifest"; - browser.test.assertEq("Ctrl+Shift+D", command.shortcut, errorMessage); - - let platformKeys = { - macosx: "M", - linux: "L", - win: "W", - android: "A", - }; - - command = commands.find(c => c.name == "with-platform-info"); - let platformKey = platformKeys[additionalScope.platform]; - let shortcut = `Ctrl+Shift+${platformKey}`; - errorMessage = `The shortcut should match the one provided in the manifest for OS='${additionalScope.platform}'`; - browser.test.assertEq(shortcut, command.shortcut, errorMessage); - - browser.test.notifyPass("commands"); - }); - }); - browser.test.sendMessage("ready"); - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - extension.sendMessage("additional-scope", {platform: AppConstants.platform}); - yield extension.awaitFinish("commands"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js b/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js deleted file mode 100644 index dd959dcec..000000000 --- a/browser/components/extensions/test/browser/browser_ext_commands_onCommand.js +++ /dev/null @@ -1,229 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -Cu.import("resource://gre/modules/AppConstants.jsm"); - -add_task(function* test_user_defined_commands() { - const testCommands = [ - // Ctrl Shortcuts - { - name: "toggle-ctrl-a", - shortcut: "Ctrl+A", - key: "A", - modifiers: { - accelKey: true, - }, - }, - { - name: "toggle-ctrl-up", - shortcut: "Ctrl+Up", - key: "VK_UP", - modifiers: { - accelKey: true, - }, - }, - // Alt Shortcuts - { - name: "toggle-alt-a", - shortcut: "Alt+A", - key: "A", - modifiers: { - altKey: true, - }, - }, - { - name: "toggle-alt-down", - shortcut: "Alt+Down", - key: "VK_DOWN", - modifiers: { - altKey: true, - }, - }, - // Mac Shortcuts - { - name: "toggle-command-shift-page-up", - shortcutMac: "Command+Shift+PageUp", - key: "VK_PAGE_UP", - modifiers: { - accelKey: true, - shiftKey: true, - }, - }, - { - name: "toggle-mac-control-shift+period", - shortcut: "Ctrl+Shift+Period", - shortcutMac: "MacCtrl+Shift+Period", - key: "VK_PERIOD", - modifiers: { - ctrlKey: true, - shiftKey: true, - }, - }, - // Ctrl+Shift Shortcuts - { - name: "toggle-ctrl-shift-left", - shortcut: "Ctrl+Shift+Left", - key: "VK_LEFT", - modifiers: { - accelKey: true, - shiftKey: true, - }, - }, - // Alt+Shift Shortcuts - { - name: "toggle-alt-shift-1", - shortcut: "Alt+Shift+1", - key: "1", - modifiers: { - altKey: true, - shiftKey: true, - }, - }, - { - name: "toggle-alt-shift-a", - shortcut: "Alt+Shift+A", - key: "A", - modifiers: { - altKey: true, - shiftKey: true, - }, - }, - { - name: "toggle-alt-shift-right", - shortcut: "Alt+Shift+Right", - key: "VK_RIGHT", - modifiers: { - altKey: true, - shiftKey: true, - }, - }, - // Misc Shortcuts - { - name: "valid-command-with-unrecognized-property-name", - shortcut: "Alt+Shift+3", - key: "3", - modifiers: { - altKey: true, - shiftKey: true, - }, - unrecognized_property: "with-a-random-value", - }, - { - name: "spaces-in-shortcut-name", - shortcut: " Alt + Shift + 2 ", - key: "2", - modifiers: { - altKey: true, - shiftKey: true, - }, - }, - ]; - - // Create a window before the extension is loaded. - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.loadURI(win1.gBrowser.selectedBrowser, "about:robots"); - yield BrowserTestUtils.browserLoaded(win1.gBrowser.selectedBrowser); - - let commands = {}; - let isMac = AppConstants.platform == "macosx"; - let totalMacOnlyCommands = 0; - - for (let testCommand of testCommands) { - let command = { - suggested_key: {}, - }; - - if (testCommand.shortcut) { - command.suggested_key.default = testCommand.shortcut; - } - - if (testCommand.shortcutMac) { - command.suggested_key.mac = testCommand.shortcutMac; - } - - if (testCommand.shortcutMac && !testCommand.shortcut) { - totalMacOnlyCommands++; - } - - if (testCommand.unrecognized_property) { - command.unrecognized_property = testCommand.unrecognized_property; - } - - commands[testCommand.name] = command; - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "commands": commands, - }, - - background: function() { - browser.commands.onCommand.addListener(commandName => { - browser.test.sendMessage("oncommand", commandName); - }); - browser.test.sendMessage("ready"); - }, - }); - - SimpleTest.waitForExplicitFinish(); - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{ - message: /Reading manifest: Error processing commands.*.unrecognized_property: An unexpected property was found/, - }]); - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - function* runTest(window) { - for (let testCommand of testCommands) { - if (testCommand.shortcutMac && !testCommand.shortcut && !isMac) { - continue; - } - EventUtils.synthesizeKey(testCommand.key, testCommand.modifiers, window); - let message = yield extension.awaitMessage("oncommand"); - is(message, testCommand.name, `Expected onCommand listener to fire with the correct name: ${testCommand.name}`); - } - } - - // Create another window after the extension is loaded. - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.loadURI(win2.gBrowser.selectedBrowser, "about:robots"); - yield BrowserTestUtils.browserLoaded(win2.gBrowser.selectedBrowser); - - let totalTestCommands = Object.keys(testCommands).length; - let expectedCommandsRegistered = isMac ? totalTestCommands : totalTestCommands - totalMacOnlyCommands; - - // Confirm the keysets have been added to both windows. - let keysetID = `ext-keyset-id-${makeWidgetId(extension.id)}`; - let keyset = win1.document.getElementById(keysetID); - ok(keyset != null, "Expected keyset to exist"); - is(keyset.childNodes.length, expectedCommandsRegistered, "Expected keyset to have the correct number of children"); - - keyset = win2.document.getElementById(keysetID); - ok(keyset != null, "Expected keyset to exist"); - is(keyset.childNodes.length, expectedCommandsRegistered, "Expected keyset to have the correct number of children"); - - // Confirm that the commands are registered to both windows. - yield focusWindow(win1); - yield runTest(win1); - - yield focusWindow(win2); - yield runTest(win2); - - yield extension.unload(); - - // Confirm that the keysets have been removed from both windows after the extension is unloaded. - keyset = win1.document.getElementById(keysetID); - is(keyset, null, "Expected keyset to be removed from the window"); - - keyset = win2.document.getElementById(keysetID); - is(keyset, null, "Expected keyset to be removed from the window"); - - yield BrowserTestUtils.closeWindow(win1); - yield BrowserTestUtils.closeWindow(win2); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js b/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js deleted file mode 100644 index 8b2d9badf..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contentscript_connect.js +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/"], - }, - - background: function() { - let ports_received = 0; - let port_messages_received = 0; - - browser.runtime.onConnect.addListener((port) => { - browser.test.assertTrue(!!port, "port1 received"); - - ports_received++; - browser.test.assertEq(1, ports_received, "1 port received"); - - port.onMessage.addListener((msg, msgPort) => { - browser.test.assertEq("port message", msg, "listener1 port message received"); - browser.test.assertEq(port, msgPort, "onMessage should receive port as second argument"); - - port_messages_received++; - browser.test.assertEq(1, port_messages_received, "1 port message received"); - }); - }); - browser.runtime.onConnect.addListener((port) => { - browser.test.assertTrue(!!port, "port2 received"); - - ports_received++; - browser.test.assertEq(2, ports_received, "2 ports received"); - - port.onMessage.addListener((msg, msgPort) => { - browser.test.assertEq("port message", msg, "listener2 port message received"); - browser.test.assertEq(port, msgPort, "onMessage should receive port as second argument"); - - port_messages_received++; - browser.test.assertEq(2, port_messages_received, "2 port messages received"); - - browser.test.notifyPass("contentscript_connect.pass"); - }); - }); - - browser.tabs.executeScript({file: "script.js"}).catch(e => { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("contentscript_connect.pass"); - }); - }, - - files: { - "script.js": function() { - let port = browser.runtime.connect(); - port.postMessage("port message"); - }, - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contentscript_connect.pass"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus.js b/browser/components/extensions/test/browser/browser_ext_contextMenus.js deleted file mode 100644 index fa1483b20..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus.js +++ /dev/null @@ -1,342 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -const PAGE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: function() { - browser.contextMenus.create({ - id: "clickme-image", - title: "Click me!", - contexts: ["image"], - }); - browser.contextMenus.create({ - id: "clickme-page", - title: "Click me!", - contexts: ["page"], - }); - browser.test.notifyPass(); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish(); - - let contentAreaContextMenu = yield openContextMenu("#img1"); - let item = contentAreaContextMenu.getElementsByAttribute("label", "Click me!"); - is(item.length, 1, "contextMenu item for image was found"); - yield closeContextMenu(); - - contentAreaContextMenu = yield openContextMenu("body"); - item = contentAreaContextMenu.getElementsByAttribute("label", "Click me!"); - is(item.length, 1, "contextMenu item for page was found"); - yield closeContextMenu(); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); -}); - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: async function() { - // A generic onclick callback function. - function genericOnClick(info, tab) { - browser.test.sendMessage("onclick", {info, tab}); - } - - browser.contextMenus.onClicked.addListener((info, tab) => { - browser.test.sendMessage("browser.contextMenus.onClicked", {info, tab}); - }); - - browser.contextMenus.create({ - contexts: ["all"], - type: "separator", - }); - - let contexts = ["page", "selection", "image", "editable"]; - for (let i = 0; i < contexts.length; i++) { - let context = contexts[i]; - let title = context; - browser.contextMenus.create({ - title: title, - contexts: [context], - id: "ext-" + context, - onclick: genericOnClick, - }); - if (context == "selection") { - browser.contextMenus.update("ext-selection", { - title: "selection is: '%s'", - onclick: (info, tab) => { - browser.contextMenus.removeAll(); - genericOnClick(info, tab); - }, - }); - } - } - - let parent = browser.contextMenus.create({ - title: "parent", - }); - browser.contextMenus.create({ - title: "child1", - parentId: parent, - onclick: genericOnClick, - }); - let child2 = browser.contextMenus.create({ - title: "child2", - parentId: parent, - onclick: genericOnClick, - }); - - let parentToDel = browser.contextMenus.create({ - title: "parentToDel", - }); - browser.contextMenus.create({ - title: "child1", - parentId: parentToDel, - onclick: genericOnClick, - }); - browser.contextMenus.create({ - title: "child2", - parentId: parentToDel, - onclick: genericOnClick, - }); - browser.contextMenus.remove(parentToDel); - - browser.contextMenus.create({ - title: "Without onclick property", - id: "ext-without-onclick", - }); - - await browser.test.assertRejects( - browser.contextMenus.update(parent, {parentId: child2}), - /cannot be an ancestor/, - "Should not be able to reparent an item as descendent of itself"); - - browser.test.notifyPass("contextmenus"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contextmenus"); - - let expectedClickInfo = { - menuItemId: "ext-image", - mediaType: "image", - srcUrl: "http://mochi.test:8888/browser/browser/components/extensions/test/browser/ctxmenu-image.png", - pageUrl: PAGE, - editable: false, - }; - - function checkClickInfo(result) { - for (let i of Object.keys(expectedClickInfo)) { - is(result.info[i], expectedClickInfo[i], - "click info " + i + " expected to be: " + expectedClickInfo[i] + " but was: " + result.info[i]); - } - is(expectedClickInfo.pageSrc, result.tab.url, "click info page source is the right tab"); - } - - let extensionMenuRoot = yield openExtensionContextMenu(); - - // Check some menu items - let items = extensionMenuRoot.getElementsByAttribute("label", "image"); - is(items.length, 1, "contextMenu item for image was found (context=image)"); - let image = items[0]; - - items = extensionMenuRoot.getElementsByAttribute("label", "selection-edited"); - is(items.length, 0, "contextMenu item for selection was not found (context=image)"); - - items = extensionMenuRoot.getElementsByAttribute("label", "parentToDel"); - is(items.length, 0, "contextMenu item for removed parent was not found (context=image)"); - - items = extensionMenuRoot.getElementsByAttribute("label", "parent"); - is(items.length, 1, "contextMenu item for parent was found (context=image)"); - - is(items[0].childNodes[0].childNodes.length, 2, "child items for parent were found (context=image)"); - - // Click on ext-image item and check the click results - yield closeExtensionContextMenu(image); - - let result = yield extension.awaitMessage("onclick"); - checkClickInfo(result); - result = yield extension.awaitMessage("browser.contextMenus.onClicked"); - checkClickInfo(result); - - - // Test "editable" context and OnClick data property. - extensionMenuRoot = yield openExtensionContextMenu("#edit-me"); - - // Check some menu items. - items = extensionMenuRoot.getElementsByAttribute("label", "editable"); - is(items.length, 1, "contextMenu item for text input element was found (context=editable)"); - let editable = items[0]; - - // Click on ext-editable item and check the click results. - yield closeExtensionContextMenu(editable); - - expectedClickInfo = { - menuItemId: "ext-editable", - pageUrl: PAGE, - editable: true, - }; - - result = yield extension.awaitMessage("onclick"); - checkClickInfo(result); - result = yield extension.awaitMessage("browser.contextMenus.onClicked"); - checkClickInfo(result); - - - // Select some text - yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* (arg) { - let doc = content.document; - let range = doc.createRange(); - let selection = content.getSelection(); - selection.removeAllRanges(); - let textNode = doc.getElementById("img1").previousSibling; - range.setStart(textNode, 0); - range.setEnd(textNode, 100); - selection.addRange(range); - }); - - // Bring up context menu again - extensionMenuRoot = yield openExtensionContextMenu(); - - // Check some menu items - items = extensionMenuRoot.getElementsByAttribute("label", "Without onclick property"); - is(items.length, 1, "contextMenu item was found (context=page)"); - - yield closeExtensionContextMenu(items[0]); - - expectedClickInfo = { - menuItemId: "ext-without-onclick", - pageUrl: PAGE, - }; - - result = yield extension.awaitMessage("browser.contextMenus.onClicked"); - checkClickInfo(result); - - // Bring up context menu again - extensionMenuRoot = yield openExtensionContextMenu(); - - // Check some menu items - items = extensionMenuRoot.getElementsByAttribute("label", "selection is: 'just some text 123456789012345678901234567890...'"); - is(items.length, 1, "contextMenu item for selection was found (context=selection)"); - let selectionItem = items[0]; - - items = extensionMenuRoot.getElementsByAttribute("label", "selection"); - is(items.length, 0, "contextMenu item label update worked (context=selection)"); - - yield closeExtensionContextMenu(selectionItem); - - expectedClickInfo = { - menuItemId: "ext-selection", - pageUrl: PAGE, - selectionText: "just some text 1234567890123456789012345678901234567890123456789012345678901234567890123456789012", - }; - - result = yield extension.awaitMessage("onclick"); - checkClickInfo(result); - result = yield extension.awaitMessage("browser.contextMenus.onClicked"); - checkClickInfo(result); - - let contentAreaContextMenu = yield openContextMenu("#img1"); - items = contentAreaContextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - is(items.length, 0, "top level item was not found (after removeAll()"); - yield closeContextMenu(); - - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); - -add_task(function* testRemoveAllWithTwoExtensions() { - const tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE); - const manifest = {permissions: ["contextMenus"]}; - - const first = ExtensionTestUtils.loadExtension({manifest, background() { - browser.contextMenus.create({title: "alpha", contexts: ["all"]}); - - browser.contextMenus.onClicked.addListener(() => { - browser.contextMenus.removeAll(); - }); - browser.test.onMessage.addListener(msg => { - if (msg == "ping") { - browser.test.sendMessage("pong-alpha"); - return; - } - browser.contextMenus.create({title: "gamma", contexts: ["all"]}); - }); - }}); - - const second = ExtensionTestUtils.loadExtension({manifest, background() { - browser.contextMenus.create({title: "beta", contexts: ["all"]}); - - browser.contextMenus.onClicked.addListener(() => { - browser.contextMenus.removeAll(); - }); - - browser.test.onMessage.addListener(() => { - browser.test.sendMessage("pong-beta"); - }); - }}); - - yield first.startup(); - yield second.startup(); - - function* confirmMenuItems(...items) { - // Round-trip to extension to make sure that the context menu state has been - // updated by the async contextMenus.create / contextMenus.removeAll calls. - first.sendMessage("ping"); - second.sendMessage("ping"); - yield first.awaitMessage("pong-alpha"); - yield second.awaitMessage("pong-beta"); - - const menu = yield openContextMenu(); - for (const id of ["alpha", "beta", "gamma"]) { - const expected = items.includes(id); - const found = menu.getElementsByAttribute("label", id); - is(found.length, expected, `menu item ${id} ${expected ? "" : "not "}found`); - } - // Return the first menu item, we need to click it. - return menu.getElementsByAttribute("label", items[0])[0]; - } - - // Confirm alpha, beta exist; click alpha to remove it. - const alpha = yield confirmMenuItems("alpha", "beta"); - yield closeExtensionContextMenu(alpha); - - // Confirm only beta exists. - yield confirmMenuItems("beta"); - yield closeContextMenu(); - - // Create gamma, confirm, click. - first.sendMessage("create"); - const beta = yield confirmMenuItems("beta", "gamma"); - yield closeExtensionContextMenu(beta); - - // Confirm only gamma is left. - yield confirmMenuItems("gamma"); - yield closeContextMenu(); - - yield first.unload(); - yield second.unload(); - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js deleted file mode 100644 index a3fa9d32c..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_checkboxes.js +++ /dev/null @@ -1,96 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: function() { - // Report onClickData info back. - browser.contextMenus.onClicked.addListener(info => { - browser.test.sendMessage("contextmenus-click", info); - }); - - browser.contextMenus.create({ - title: "Checkbox", - type: "checkbox", - }); - - browser.contextMenus.create({ - type: "separator", - }); - - browser.contextMenus.create({ - title: "Checkbox", - type: "checkbox", - checked: true, - }); - - browser.contextMenus.create({ - title: "Checkbox", - type: "checkbox", - }); - - browser.test.notifyPass("contextmenus-checkboxes"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-checkboxes"); - - function confirmCheckboxStates(extensionMenuRoot, expectedStates) { - let checkboxItems = extensionMenuRoot.getElementsByAttribute("type", "checkbox"); - - is(checkboxItems.length, 3, "there should be 3 checkbox items in the context menu"); - - is(checkboxItems[0].hasAttribute("checked"), expectedStates[0], `checkbox item 1 has state (checked=${expectedStates[0]})`); - is(checkboxItems[1].hasAttribute("checked"), expectedStates[1], `checkbox item 2 has state (checked=${expectedStates[1]})`); - is(checkboxItems[2].hasAttribute("checked"), expectedStates[2], `checkbox item 3 has state (checked=${expectedStates[2]})`); - - return extensionMenuRoot.getElementsByAttribute("type", "checkbox"); - } - - function confirmOnClickData(onClickData, id, was, checked) { - is(onClickData.wasChecked, was, `checkbox item ${id} was ${was ? "" : "not "}checked before the click`); - is(onClickData.checked, checked, `checkbox item ${id} is ${checked ? "" : "not "}checked after the click`); - } - - let extensionMenuRoot = yield openExtensionContextMenu(); - let items = confirmCheckboxStates(extensionMenuRoot, [false, true, false]); - yield closeExtensionContextMenu(items[0]); - - let result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 1, false, true); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmCheckboxStates(extensionMenuRoot, [true, true, false]); - yield closeExtensionContextMenu(items[2]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 3, false, true); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmCheckboxStates(extensionMenuRoot, [true, true, true]); - yield closeExtensionContextMenu(items[0]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 1, true, false); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmCheckboxStates(extensionMenuRoot, [false, true, true]); - yield closeExtensionContextMenu(items[2]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 3, true, false); - - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js deleted file mode 100644 index a3d31bd19..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_icons.js +++ /dev/null @@ -1,76 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - let encodedImageData = "iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAC4klEQVRYhdWXLWzbQBSADQtDAwsHC1tUhUxqfL67lk2tdn+OJg0ODU0rLByqgqINBY6tmlbn7LMTJ5FaFVVBk1G0oUGjG2jT2Y7jxmmcbU/6iJ+f36fz+e5sGP9riCGm9hB37RG+scd4Yo/wsDXCZyIE2xuXsce4bY+wXkAsQtzYmExrfFgvkJkRbkzo1ehoxx5iXcgI/9iYUGt8WH9MqDXEcmNChmEYrRCf2SHWeYgQx3x0tLNRIeKQLTtEFyJEep4NTuhk8BC+yMrwEE3+iozo42d8gK7FAOkMsRiiN8QhW2ttSK5QTfRRV4QoymVeJMvPvDp7gCZigD613MN6yRFA3SWarow9QB9LCfG+NeF9qCtjAKOSQjCqVKhfVsiHEQ+grgx/lRGqUihAc1uL8EFD+KCRO+GrF4J61phcoRoPoEzkYhZYpykh5sMb7kOdIeY+jHKur4QI4Feh4AFX1nVeLxrAvQchGsBz5ls6wa2QdwcvIcE2863bTH79KOvsz/uUYJsp+J0pSzNlDckVqqVGUAF+n6uS7txcOl6wot4JVy70ufDLy4pWLUQVPE81pRI0mGe9oxLMHSeohHvMs/STUNaUK6vDPCvOyxMFDx4achehRDJmHnydnkPww5OFfLxrGIZBFDyYl4LpMzlTQFIP6AQx86w2UeYBccFpJrcKv5L9eGDtUAU6RIELqsB74uynjy/UBRF1gS5BTFxwQT1wTiXoUg9MH7m/3NZRRoi5IJytUbMgzv4Wc832+oQkiKgEehmyMkkpKsFkQV11QsRJL5rJYBLItQgRaUZEmnoZXsomz3vGiWw+I9KMF9SVFOqZEemZekli1jN3U/UOqhHHvC6oWWGElhfSpGdOk6+O9prdwvtLj5BjRsQxdRnot+Zeifpy/2/0stktKTRNLmbk0mwXyl8253fyojj+8rxOHNAhjjm5n0/5OOCGOKBzkrMO0Z75lvSAzKlrF32Z/3z8BqLAn+yMV7VhAAAAAElFTkSuQmCC"; - let decodedImageData = atob(encodedImageData); - const IMAGE_ARRAYBUFFER = Uint8Array.from(decodedImageData, byte => byte.charCodeAt(0)).buffer; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - "icons": { - "18": "extension.png", - }, - }, - - files: { - "extension.png": IMAGE_ARRAYBUFFER, - }, - - background: function() { - let menuitemId = browser.contextMenus.create({ - title: "child-to-delete", - onclick: () => { - browser.contextMenus.remove(menuitemId); - }, - }); - - browser.contextMenus.create({ - title: "child", - }); - - browser.test.onMessage.addListener(() => { - browser.test.sendMessage("pong"); - }); - browser.test.notifyPass("contextmenus-icons"); - }, - }); - - let confirmContextMenuIcon = (rootElement) => { - let expectedURL = new RegExp(String.raw`^moz-extension://[^/]+/extension\.png$`); - let imageUrl = rootElement.getAttribute("image"); - ok(expectedURL.test(imageUrl), "The context menu should display the extension icon next to the root element"); - }; - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-icons"); - - let extensionMenu = yield openExtensionContextMenu(); - - let contextMenu = document.getElementById("contentAreaContextMenu"); - let topLevelMenuItem = contextMenu.getElementsByAttribute("ext-type", "top-level-menu")[0]; - confirmContextMenuIcon(topLevelMenuItem); - - let childToDelete = extensionMenu.getElementsByAttribute("label", "child-to-delete")[0]; - yield closeExtensionContextMenu(childToDelete); - // Now perform a roundtrip to the extension process to make sure that the - // click event has had a chance to fire. - extension.sendMessage("ping"); - yield extension.awaitMessage("pong"); - - yield openExtensionContextMenu(); - - contextMenu = document.getElementById("contentAreaContextMenu"); - topLevelMenuItem = contextMenu.getElementsByAttribute("label", "child")[0]; - - confirmContextMenuIcon(topLevelMenuItem); - yield closeContextMenu(); - - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js deleted file mode 100644 index 96453863d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_onclick.js +++ /dev/null @@ -1,196 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -// Loaded both as a background script and a tab page. -function testScript() { - let page = location.pathname.includes("tab.html") ? "tab" : "background"; - let clickCounts = { - old: 0, - new: 0, - }; - browser.contextMenus.onClicked.addListener(() => { - // Async to give other onclick handlers a chance to fire. - setTimeout(() => { - browser.test.sendMessage("onClicked-fired", page); - }); - }); - browser.test.onMessage.addListener((toPage, msg) => { - if (toPage !== page) { - return; - } - browser.test.log(`Received ${msg} for ${toPage}`); - if (msg == "get-click-counts") { - browser.test.sendMessage("click-counts", clickCounts); - } else if (msg == "clear-click-counts") { - clickCounts.old = clickCounts.new = 0; - browser.test.sendMessage("next"); - } else if (msg == "create-with-onclick") { - browser.contextMenus.create({ - id: "iden", - title: "tifier", - onclick() { - ++clickCounts.old; - browser.test.log(`onclick fired for original onclick property in ${page}`); - }, - }, () => browser.test.sendMessage("next")); - } else if (msg == "create-without-onclick") { - browser.contextMenus.create({ - id: "iden", - title: "tifier", - }, () => browser.test.sendMessage("next")); - } else if (msg == "update-without-onclick") { - browser.contextMenus.update("iden", { - enabled: true, // Already enabled, so this does nothing. - }, () => browser.test.sendMessage("next")); - } else if (msg == "update-with-onclick") { - browser.contextMenus.update("iden", { - onclick() { - ++clickCounts.new; - browser.test.log(`onclick fired for updated onclick property in ${page}`); - }, - }, () => browser.test.sendMessage("next")); - } else if (msg == "remove") { - browser.contextMenus.remove("iden", () => browser.test.sendMessage("next")); - } else if (msg == "removeAll") { - browser.contextMenus.removeAll(() => browser.test.sendMessage("next")); - } - }); - - if (page == "background") { - browser.test.log("Opening tab.html"); - browser.tabs.create({ - url: "tab.html", - active: false, // To not interfere with the context menu tests. - }); - } else { - // Sanity check - the pages must be in the same process. - let pages = browser.extension.getViews(); - browser.test.assertTrue(pages.includes(window), - "Expected this tab to be an extension view"); - pages = pages.filter(w => w !== window); - browser.test.assertEq(pages[0], browser.extension.getBackgroundPage(), - "Expected the other page to be a background page"); - browser.test.sendMessage("tab.html ready"); - } -} - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - background: testScript, - files: { - "tab.html": `<!DOCTYPE html><meta charset="utf-8"><script src="tab.js"></script>`, - "tab.js": testScript, - }, - }); - yield extension.startup(); - yield extension.awaitMessage("tab.html ready"); - - function* clickContextMenu() { - // Using openContextMenu instead of openExtensionContextMenu because the - // test extension has only one context menu item. - let extensionMenuRoot = yield openContextMenu(); - let items = extensionMenuRoot.getElementsByAttribute("label", "tifier"); - is(items.length, 1, "Expected one context menu item"); - yield closeExtensionContextMenu(items[0]); - // One of them is "tab", the other is "background". - info(`onClicked from: ${yield extension.awaitMessage("onClicked-fired")}`); - info(`onClicked from: ${yield extension.awaitMessage("onClicked-fired")}`); - } - - function* getCounts(page) { - extension.sendMessage(page, "get-click-counts"); - return yield extension.awaitMessage("click-counts"); - } - function* resetCounts() { - extension.sendMessage("tab", "clear-click-counts"); - extension.sendMessage("background", "clear-click-counts"); - yield extension.awaitMessage("next"); - yield extension.awaitMessage("next"); - } - - // During this test, at most one "onclick" attribute is expected at any time. - for (let pageOne of ["background", "tab"]) { - for (let pageTwo of ["background", "tab"]) { - info(`Testing with menu created by ${pageOne} and updated by ${pageTwo}`); - extension.sendMessage(pageOne, "create-with-onclick"); - yield extension.awaitMessage("next"); - - // Test that update without onclick attribute does not clear the existing - // onclick handler. - extension.sendMessage(pageTwo, "update-without-onclick"); - yield extension.awaitMessage("next"); - yield clickContextMenu(); - let clickCounts = yield getCounts(pageOne); - is(clickCounts.old, 1, `Original onclick should still be present in ${pageOne}`); - is(clickCounts.new, 0, `Not expecting any new handlers in ${pageOne}`); - if (pageOne !== pageTwo) { - clickCounts = yield getCounts(pageTwo); - is(clickCounts.old, 0, `Not expecting any handlers in ${pageTwo}`); - is(clickCounts.new, 0, `Not expecting any new handlers in ${pageTwo}`); - } - yield resetCounts(); - - // Test that update with onclick handler in a different page clears the - // existing handler and activates the new onclick handler. - extension.sendMessage(pageTwo, "update-with-onclick"); - yield extension.awaitMessage("next"); - yield clickContextMenu(); - clickCounts = yield getCounts(pageOne); - is(clickCounts.old, 0, `Original onclick should be gone from ${pageOne}`); - if (pageOne !== pageTwo) { - is(clickCounts.new, 0, `Still not expecting new handlers in ${pageOne}`); - } - clickCounts = yield getCounts(pageTwo); - if (pageOne !== pageTwo) { - is(clickCounts.old, 0, `Not expecting an old onclick in ${pageTwo}`); - } - is(clickCounts.new, 1, `New onclick should be triggered in ${pageTwo}`); - yield resetCounts(); - - // Test that updating the handler (different again from the last `update` - // call, but the same as the `create` call) clears the existing handler - // and activates the new onclick handler. - extension.sendMessage(pageOne, "update-with-onclick"); - yield extension.awaitMessage("next"); - yield clickContextMenu(); - clickCounts = yield getCounts(pageOne); - is(clickCounts.new, 1, `onclick should be triggered in ${pageOne}`); - if (pageOne !== pageTwo) { - clickCounts = yield getCounts(pageTwo); - is(clickCounts.new, 0, `onclick should be gone from ${pageTwo}`); - } - yield resetCounts(); - - // Test that removing the context menu and recreating it with the same ID - // (in a different context) does not leave behind any onclick handlers. - extension.sendMessage(pageTwo, "remove"); - yield extension.awaitMessage("next"); - extension.sendMessage(pageTwo, "create-without-onclick"); - yield extension.awaitMessage("next"); - yield clickContextMenu(); - clickCounts = yield getCounts(pageOne); - is(clickCounts.new, 0, `Did not expect any click handlers in ${pageOne}`); - if (pageOne !== pageTwo) { - clickCounts = yield getCounts(pageTwo); - is(clickCounts.new, 0, `Did not expect any click handlers in ${pageTwo}`); - } - yield resetCounts(); - - // Remove context menu for the next iteration of the test. And just to get - // more coverage, let's use removeAll instead of remove. - extension.sendMessage(pageOne, "removeAll"); - yield extension.awaitMessage("next"); - } - } - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js deleted file mode 100644 index 3c5fa584b..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_radioGroups.js +++ /dev/null @@ -1,100 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: function() { - // Report onClickData info back. - browser.contextMenus.onClicked.addListener(info => { - browser.test.sendMessage("contextmenus-click", info); - }); - - browser.contextMenus.create({ - title: "radio-group-1", - type: "radio", - checked: true, - }); - - browser.contextMenus.create({ - type: "separator", - }); - - browser.contextMenus.create({ - title: "radio-group-2", - type: "radio", - }); - - browser.contextMenus.create({ - title: "radio-group-2", - type: "radio", - }); - - browser.test.notifyPass("contextmenus-radio-groups"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-radio-groups"); - - function confirmRadioGroupStates(extensionMenuRoot, expectedStates) { - let radioItems = extensionMenuRoot.getElementsByAttribute("type", "radio"); - let radioGroup1 = extensionMenuRoot.getElementsByAttribute("label", "radio-group-1"); - let radioGroup2 = extensionMenuRoot.getElementsByAttribute("label", "radio-group-2"); - - is(radioItems.length, 3, "there should be 3 radio items in the context menu"); - is(radioGroup1.length, 1, "the first radio group should only have 1 radio item"); - is(radioGroup2.length, 2, "the second radio group should only have 2 radio items"); - - is(radioGroup1[0].hasAttribute("checked"), expectedStates[0], `radio item 1 has state (checked=${expectedStates[0]})`); - is(radioGroup2[0].hasAttribute("checked"), expectedStates[1], `radio item 2 has state (checked=${expectedStates[1]})`); - is(radioGroup2[1].hasAttribute("checked"), expectedStates[2], `radio item 3 has state (checked=${expectedStates[2]})`); - - return extensionMenuRoot.getElementsByAttribute("type", "radio"); - } - - function confirmOnClickData(onClickData, id, was, checked) { - is(onClickData.wasChecked, was, `radio item ${id} was ${was ? "" : "not "}checked before the click`); - is(onClickData.checked, checked, `radio item ${id} is ${checked ? "" : "not "}checked after the click`); - } - - let extensionMenuRoot = yield openExtensionContextMenu(); - let items = confirmRadioGroupStates(extensionMenuRoot, [true, false, false]); - yield closeExtensionContextMenu(items[1]); - - let result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 2, false, true); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmRadioGroupStates(extensionMenuRoot, [true, true, false]); - yield closeExtensionContextMenu(items[2]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 3, false, true); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmRadioGroupStates(extensionMenuRoot, [true, false, true]); - yield closeExtensionContextMenu(items[0]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 1, true, true); - - extensionMenuRoot = yield openExtensionContextMenu(); - items = confirmRadioGroupStates(extensionMenuRoot, [true, false, true]); - yield closeExtensionContextMenu(items[0]); - - result = yield extension.awaitMessage("contextmenus-click"); - confirmOnClickData(result, 1, true, true); - - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js deleted file mode 100644 index fdf06d656..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_uninstall.js +++ /dev/null @@ -1,84 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - // Install an extension. - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: function() { - browser.contextMenus.create({title: "a"}); - browser.contextMenus.create({title: "b"}); - browser.test.notifyPass("contextmenus-icons"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-icons"); - - // Open the context menu. - let contextMenu = yield openContextMenu("#img1"); - - // Confirm that the extension menu item exists. - let topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - is(topLevelExtensionMenuItems.length, 1, "the top level extension menu item exists"); - - yield closeContextMenu(); - - // Uninstall the extension. - yield extension.unload(); - - // Open the context menu. - contextMenu = yield openContextMenu("#img1"); - - // Confirm that the extension menu item has been removed. - topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - is(topLevelExtensionMenuItems.length, 0, "no top level extension menu items should exist"); - - yield closeContextMenu(); - - // Install a new extension. - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - background: function() { - browser.contextMenus.create({title: "c"}); - browser.contextMenus.create({title: "d"}); - browser.test.notifyPass("contextmenus-uninstall-second-extension"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-uninstall-second-extension"); - - // Open the context menu. - contextMenu = yield openContextMenu("#img1"); - - // Confirm that only the new extension menu item is in the context menu. - topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - is(topLevelExtensionMenuItems.length, 1, "only one top level extension menu item should exist"); - - // Close the context menu. - yield closeContextMenu(); - - // Uninstall the extension. - yield extension.unload(); - - // Open the context menu. - contextMenu = yield openContextMenu("#img1"); - - // Confirm that no extension menu items exist. - topLevelExtensionMenuItems = contextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - is(topLevelExtensionMenuItems.length, 0, "no top level extension menu items should exist"); - - yield closeContextMenu(); - - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js b/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js deleted file mode 100644 index 7849b8778..000000000 --- a/browser/components/extensions/test/browser/browser_ext_contextMenus_urlPatterns.js +++ /dev/null @@ -1,254 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, - "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context.html"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["contextMenus"], - }, - - background: function() { - // Test menu items using targetUrlPatterns. - browser.contextMenus.create({ - title: "targetUrlPatterns-patternMatches-contextAll", - targetUrlPatterns: ["*://*/*ctxmenu-image.png", "*://*/*some-link"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "targetUrlPatterns-patternMatches-contextImage", - targetUrlPatterns: ["*://*/*ctxmenu-image.png"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "targetUrlPatterns-patternMatches-contextLink", - targetUrlPatterns: ["*://*/*some-link"], - contexts: ["link"], - }); - - browser.contextMenus.create({ - title: "targetUrlPatterns-patternDoesNotMatch-contextAll", - targetUrlPatterns: ["*://*/does-not-match"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "targetUrlPatterns-patternDoesNotMatch-contextImage", - targetUrlPatterns: ["*://*/does-not-match"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "targetUrlPatterns-patternDoesNotMatch-contextLink", - targetUrlPatterns: ["*://*/does-not-match"], - contexts: ["link"], - }); - - // Test menu items using documentUrlPatterns. - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-contextAll", - documentUrlPatterns: ["*://*/*context.html"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-contextImage", - documentUrlPatterns: ["*://*/*context.html", "http://*/url-that-does-not-match"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-contextLink", - documentUrlPatterns: ["*://*/*context.html", "*://*/does-not-match"], - contexts: ["link"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-contextAll", - documentUrlPatterns: ["*://*/does-not-match"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-contextImage", - documentUrlPatterns: ["*://*/does-not-match"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-contextLink", - documentUrlPatterns: ["*://*/does-not-match"], - contexts: ["link"], - }); - - // Test menu items using both targetUrlPatterns and documentUrlPatterns. - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll", - documentUrlPatterns: ["*://*/*context.html"], - targetUrlPatterns: ["*://*/*ctxmenu-image.png"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll", - documentUrlPatterns: ["*://does-not-match"], - targetUrlPatterns: ["*://*/*ctxmenu-image.png"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll", - documentUrlPatterns: ["*://*/*context.html"], - targetUrlPatterns: ["*://does-not-match"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll", - documentUrlPatterns: ["*://does-not-match"], - targetUrlPatterns: ["*://does-not-match"], - contexts: ["all"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage", - documentUrlPatterns: ["*://*/*context.html"], - targetUrlPatterns: ["*://*/*ctxmenu-image.png"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage", - documentUrlPatterns: ["*://does-not-match"], - targetUrlPatterns: ["*://*/*ctxmenu-image.png"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage", - documentUrlPatterns: ["*://*/*context.html"], - targetUrlPatterns: ["*://does-not-match"], - contexts: ["image"], - }); - - browser.contextMenus.create({ - title: "documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage", - documentUrlPatterns: ["*://does-not-match"], - targetUrlPatterns: ["*://does-not-match"], - contexts: ["image"], - }); - - browser.test.notifyPass("contextmenus-urlPatterns"); - }, - }); - - function* confirmContextMenuItems(menu, expected) { - for (let [label, shouldShow] of expected) { - let items = menu.getElementsByAttribute("label", label); - if (shouldShow) { - is(items.length, 1, `The menu item for label ${label} was correctly shown`); - } else { - is(items.length, 0, `The menu item for label ${label} was correctly not shown`); - } - } - } - - yield extension.startup(); - yield extension.awaitFinish("contextmenus-urlPatterns"); - - let extensionContextMenu = yield openExtensionContextMenu("#img1"); - let expected = [ - ["targetUrlPatterns-patternMatches-contextAll", true], - ["targetUrlPatterns-patternMatches-contextImage", true], - ["targetUrlPatterns-patternMatches-contextLink", false], - ["targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["targetUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-contextAll", true], - ["documentUrlPatterns-patternMatches-contextImage", true], - ["documentUrlPatterns-patternMatches-contextLink", false], - ["documentUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll", true], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage", true], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ]; - yield confirmContextMenuItems(extensionContextMenu, expected); - yield closeContextMenu(); - - let contextMenu = yield openContextMenu("body"); - expected = [ - ["targetUrlPatterns-patternMatches-contextAll", false], - ["targetUrlPatterns-patternMatches-contextImage", false], - ["targetUrlPatterns-patternMatches-contextLink", false], - ["targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["targetUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-contextAll", true], - ["documentUrlPatterns-patternMatches-contextImage", false], - ["documentUrlPatterns-patternMatches-contextLink", false], - ["documentUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextAll", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternMatches-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternMatches-contextImage", false], - ["documentUrlPatterns-patternMatches-targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ]; - yield confirmContextMenuItems(contextMenu, expected); - yield closeContextMenu(); - - contextMenu = yield openContextMenu("#link1"); - expected = [ - ["targetUrlPatterns-patternMatches-contextAll", true], - ["targetUrlPatterns-patternMatches-contextImage", false], - ["targetUrlPatterns-patternMatches-contextLink", true], - ["targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["targetUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-contextAll", true], - ["documentUrlPatterns-patternMatches-contextImage", false], - ["documentUrlPatterns-patternMatches-contextLink", true], - ["documentUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-contextLink", false], - ]; - yield confirmContextMenuItems(contextMenu, expected); - yield closeContextMenu(); - - contextMenu = yield openContextMenu("#img-wrapped-in-link"); - expected = [ - ["targetUrlPatterns-patternMatches-contextAll", true], - ["targetUrlPatterns-patternMatches-contextImage", true], - ["targetUrlPatterns-patternMatches-contextLink", true], - ["targetUrlPatterns-patternDoesNotMatch-contextAll", false], - ["targetUrlPatterns-patternDoesNotMatch-contextImage", false], - ["targetUrlPatterns-patternDoesNotMatch-contextLink", false], - ["documentUrlPatterns-patternMatches-contextAll", true], - ["documentUrlPatterns-patternMatches-contextImage", true], - ["documentUrlPatterns-patternMatches-contextLink", true], - ["documentUrlPatterns-patternDoesNotMatch-contextAll", false], - ["documentUrlPatterns-patternDoesNotMatch-contextImage", false], - ["documentUrlPatterns-patternDoesNotMatch-contextLink", false], - ]; - yield confirmContextMenuItems(contextMenu, expected); - yield closeContextMenu(); - - yield extension.unload(); - yield BrowserTestUtils.removeTab(tab1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_currentWindow.js b/browser/components/extensions/test/browser/browser_ext_currentWindow.js deleted file mode 100644 index 11660bf4d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_currentWindow.js +++ /dev/null @@ -1,149 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function genericChecker() { - let kind = "background"; - let path = window.location.pathname; - if (path.includes("/popup.html")) { - kind = "popup"; - } else if (path.includes("/page.html")) { - kind = "page"; - } - - browser.test.onMessage.addListener((msg, ...args) => { - if (msg == kind + "-check-current1") { - browser.tabs.query({ - currentWindow: true, - }, function(tabs) { - browser.test.sendMessage("result", tabs[0].windowId); - }); - } else if (msg == kind + "-check-current2") { - browser.tabs.query({ - windowId: browser.windows.WINDOW_ID_CURRENT, - }, function(tabs) { - browser.test.sendMessage("result", tabs[0].windowId); - }); - } else if (msg == kind + "-check-current3") { - browser.windows.getCurrent(function(window) { - browser.test.sendMessage("result", window.id); - }); - } else if (msg == kind + "-open-page") { - browser.tabs.create({windowId: args[0], url: browser.runtime.getURL("page.html")}); - } else if (msg == kind + "-close-page") { - browser.tabs.query({ - windowId: args[0], - }, tabs => { - let tab = tabs.find(tab => tab.url.includes("/page.html")); - browser.tabs.remove(tab.id, () => { - browser.test.sendMessage("closed"); - }); - }); - } - }); - browser.test.sendMessage(kind + "-ready"); -} - -add_task(function* () { - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - - yield focusWindow(win2); - - yield BrowserTestUtils.loadURI(win1.gBrowser.selectedBrowser, "about:robots"); - yield BrowserTestUtils.browserLoaded(win1.gBrowser.selectedBrowser); - - yield BrowserTestUtils.loadURI(win2.gBrowser.selectedBrowser, "about:config"); - yield BrowserTestUtils.browserLoaded(win2.gBrowser.selectedBrowser); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "browser_action": { - "default_popup": "popup.html", - }, - }, - - files: { - "page.html": ` - <!DOCTYPE html> - <html><body> - <script src="page.js"></script> - </body></html> - `, - - "page.js": genericChecker, - - "popup.html": ` - <!DOCTYPE html> - <html><body> - <script src="popup.js"></script> - </body></html> - `, - - "popup.js": genericChecker, - }, - - background: genericChecker, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]); - - let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let winId1 = WindowManager.getId(win1); - let winId2 = WindowManager.getId(win2); - - function* checkWindow(kind, winId, name) { - extension.sendMessage(kind + "-check-current1"); - is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 1) [${kind}]`); - extension.sendMessage(kind + "-check-current2"); - is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 2) [${kind}]`); - extension.sendMessage(kind + "-check-current3"); - is((yield extension.awaitMessage("result")), winId, `${name} is on top (check 3) [${kind}]`); - } - - yield focusWindow(win1); - yield checkWindow("background", winId1, "win1"); - yield focusWindow(win2); - yield checkWindow("background", winId2, "win2"); - - function* triggerPopup(win, callback) { - yield clickBrowserAction(extension, win); - yield awaitExtensionPanel(extension, win); - - yield extension.awaitMessage("popup-ready"); - - yield callback(); - - closeBrowserAction(extension, win); - } - - // Set focus to some other window. - yield focusWindow(window); - - yield triggerPopup(win1, function* () { - yield checkWindow("popup", winId1, "win1"); - }); - - yield triggerPopup(win2, function* () { - yield checkWindow("popup", winId2, "win2"); - }); - - function* triggerPage(winId, name) { - extension.sendMessage("background-open-page", winId); - yield extension.awaitMessage("page-ready"); - yield checkWindow("page", winId, name); - extension.sendMessage("background-close-page", winId); - yield extension.awaitMessage("closed"); - } - - yield triggerPage(winId1, "win1"); - yield triggerPage(winId2, "win2"); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(win1); - yield BrowserTestUtils.closeWindow(win2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_getViews.js b/browser/components/extensions/test/browser/browser_ext_getViews.js deleted file mode 100644 index 684e19ac5..000000000 --- a/browser/components/extensions/test/browser/browser_ext_getViews.js +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function genericChecker() { - let kind = "background"; - let path = window.location.pathname; - if (path.indexOf("popup") != -1) { - kind = "popup"; - } else if (path.indexOf("tab") != -1) { - kind = "tab"; - } - window.kind = kind; - - browser.test.onMessage.addListener((msg, ...args) => { - if (msg == kind + "-check-views") { - let windowId = args[0]; - let counts = { - "background": 0, - "tab": 0, - "popup": 0, - "kind": 0, - "window": 0, - }; - if (Number.isInteger(windowId)) { - counts.window = browser.extension.getViews({windowId: windowId}).length; - } - if (kind !== "background") { - counts.kind = browser.extension.getViews({type: kind}).length; - } - let views = browser.extension.getViews(); - let background; - for (let i = 0; i < views.length; i++) { - let view = views[i]; - browser.test.assertTrue(view.kind in counts, "view type is valid"); - counts[view.kind]++; - if (view.kind == "background") { - browser.test.assertTrue(view === browser.extension.getBackgroundPage(), - "background page is correct"); - background = view; - } - } - if (background) { - browser.runtime.getBackgroundPage().then(view => { - browser.test.assertEq(background, view, "runtime.getBackgroundPage() is correct"); - browser.test.sendMessage("counts", counts); - }); - } else { - browser.test.sendMessage("counts", counts); - } - } else if (msg == kind + "-open-tab") { - browser.tabs.create({windowId: args[0], url: browser.runtime.getURL("tab.html")}); - } else if (msg == kind + "-close-tab") { - browser.tabs.query({ - windowId: args[0], - }, tabs => { - let tab = tabs.find(tab => tab.url.indexOf("tab.html") != -1); - browser.tabs.remove(tab.id, () => { - browser.test.sendMessage("closed"); - }); - }); - } - }); - browser.test.sendMessage(kind + "-ready"); -} - -add_task(function* () { - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "browser_action": { - "default_popup": "popup.html", - }, - }, - - files: { - "tab.html": ` - <!DOCTYPE html> - <html><body> - <script src="tab.js"></script> - </body></html> - `, - - "tab.js": genericChecker, - - "popup.html": ` - <!DOCTYPE html> - <html><body> - <script src="popup.js"></script> - </body></html> - `, - - "popup.js": genericChecker, - }, - - background: genericChecker, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]); - - info("started"); - - let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let winId1 = WindowManager.getId(win1); - let winId2 = WindowManager.getId(win2); - - function* openTab(winId) { - extension.sendMessage("background-open-tab", winId); - yield extension.awaitMessage("tab-ready"); - } - - function* checkViews(kind, tabCount, popupCount, kindCount, windowId = undefined, windowCount = 0) { - extension.sendMessage(kind + "-check-views", windowId); - let counts = yield extension.awaitMessage("counts"); - is(counts.background, 1, "background count correct"); - is(counts.tab, tabCount, "tab count correct"); - is(counts.popup, popupCount, "popup count correct"); - is(counts.kind, kindCount, "count for type correct"); - is(counts.window, windowCount, "count for window correct"); - } - - yield checkViews("background", 0, 0, 0); - - yield openTab(winId1); - - yield checkViews("background", 1, 0, 0, winId1, 1); - yield checkViews("tab", 1, 0, 1); - - yield openTab(winId2); - - yield checkViews("background", 2, 0, 0, winId2, 1); - - function* triggerPopup(win, callback) { - yield clickBrowserAction(extension, win); - yield awaitExtensionPanel(extension, win); - - yield extension.awaitMessage("popup-ready"); - - yield callback(); - - closeBrowserAction(extension, win); - } - - // The popup occasionally closes prematurely if we open it immediately here. - // I'm not sure what causes it to close (it's something internal, and seems to - // be focus-related, but it's not caused by JS calling hidePopup), but even a - // short timeout seems to consistently fix it. - yield new Promise(resolve => win1.setTimeout(resolve, 10)); - - yield triggerPopup(win1, function* () { - yield checkViews("background", 2, 1, 0, winId1, 2); - yield checkViews("popup", 2, 1, 1); - }); - - yield triggerPopup(win2, function* () { - yield checkViews("background", 2, 1, 0, winId2, 2); - yield checkViews("popup", 2, 1, 1); - }); - - info("checking counts after popups"); - - yield checkViews("background", 2, 0, 0, winId1, 1); - - info("closing one tab"); - - extension.sendMessage("background-close-tab", winId1); - yield extension.awaitMessage("closed"); - - info("one tab closed, one remains"); - - yield checkViews("background", 1, 0, 0); - - info("opening win1 popup"); - - yield triggerPopup(win1, function* () { - yield checkViews("background", 1, 1, 0); - yield checkViews("tab", 1, 1, 1); - yield checkViews("popup", 1, 1, 1); - }); - - info("opening win2 popup"); - - yield triggerPopup(win2, function* () { - yield checkViews("background", 1, 1, 0); - yield checkViews("tab", 1, 1, 1); - yield checkViews("popup", 1, 1, 1); - }); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(win1); - yield BrowserTestUtils.closeWindow(win2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_incognito_popup.js b/browser/components/extensions/test/browser/browser_ext_incognito_popup.js deleted file mode 100644 index 174b2179d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_incognito_popup.js +++ /dev/null @@ -1,108 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testIncognitoPopup() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - "browser_action": { - "default_popup": "popup.html", - }, - "page_action": { - "default_popup": "popup.html", - }, - }, - - background: async function() { - let resolveMessage; - browser.runtime.onMessage.addListener(msg => { - if (resolveMessage && msg.message == "popup-details") { - resolveMessage(msg); - } - }); - - let awaitPopup = windowId => { - return new Promise(resolve => { - resolveMessage = resolve; - }).then(msg => { - browser.test.assertEq(windowId, msg.windowId, "Got popup message from correct window"); - return msg; - }); - }; - - let testWindow = async window => { - let [tab] = await browser.tabs.query({active: true, windowId: window.id}); - - await browser.pageAction.show(tab.id); - browser.test.sendMessage("click-pageAction"); - - let msg = await awaitPopup(window.id); - browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in pageAction popup"); - - browser.test.sendMessage("click-browserAction"); - - msg = await awaitPopup(window.id); - browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup"); - }; - - const URL = "http://example.com/incognito"; - let windowReady = new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab) { - if (changed.status == "complete" && tab.url == URL) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - - try { - { - let window = await browser.windows.getCurrent(); - - await testWindow(window); - } - - { - let window = await browser.windows.create({incognito: true, url: URL}); - await windowReady; - - await testWindow(window); - - await browser.windows.remove(window.id); - } - - browser.test.notifyPass("incognito"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("incognito"); - } - }, - - files: { - "popup.html": '<html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>', - - "popup.js": async function() { - let win = await browser.windows.getCurrent(); - browser.runtime.sendMessage({ - message: "popup-details", - windowId: win.id, - incognito: browser.extension.inIncognitoContext, - }); - window.close(); - }, - }, - }); - - extension.onMessage("click-browserAction", () => { - clickBrowserAction(extension, Services.wm.getMostRecentWindow("navigator:browser")); - }); - - extension.onMessage("click-pageAction", () => { - clickPageAction(extension, Services.wm.getMostRecentWindow("navigator:browser")); - }); - - yield extension.startup(); - yield extension.awaitFinish("incognito"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_incognito_views.js b/browser/components/extensions/test/browser/browser_ext_incognito_views.js deleted file mode 100644 index 4865b2d4f..000000000 --- a/browser/components/extensions/test/browser/browser_ext_incognito_views.js +++ /dev/null @@ -1,121 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testIncognitoViews() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - "browser_action": { - "default_popup": "popup.html", - }, - }, - - background: async function() { - window.isBackgroundPage = true; - - let resolveMessage; - browser.runtime.onMessage.addListener(msg => { - if (resolveMessage && msg.message == "popup-details") { - resolveMessage(msg); - } - }); - - let awaitPopup = windowId => { - return new Promise(resolve => { - resolveMessage = resolve; - }).then(msg => { - browser.test.assertEq(windowId, msg.windowId, "Got popup message from correct window"); - return msg; - }); - }; - - let testWindow = async window => { - browser.test.sendMessage("click-browserAction"); - - let msg = await awaitPopup(window.id); - browser.test.assertEq(window.incognito, msg.incognito, "Correct incognito status in browserAction popup"); - }; - - const URL = "http://example.com/incognito"; - let windowReady = new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab) { - if (changed.status == "complete" && tab.url == URL) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - - try { - { - let window = await browser.windows.getCurrent(); - - await testWindow(window); - } - - { - let window = await browser.windows.create({incognito: true, url: URL}); - await windowReady; - - await testWindow(window); - - await browser.windows.remove(window.id); - } - - browser.test.notifyPass("incognito-views"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("incognito-views"); - } - }, - - files: { - "popup.html": '<html><head><meta charset="utf-8"><script src="popup.js"></script></head></html>', - - "popup.js": async function() { - let views = browser.extension.getViews(); - - if (browser.extension.inIncognitoContext) { - let bgPage = browser.extension.getBackgroundPage(); - browser.test.assertEq(null, bgPage, "Should not be able to access background page in incognito context"); - - bgPage = await browser.runtime.getBackgroundPage(); - browser.test.assertEq(null, bgPage, "Should not be able to access background page in incognito context"); - - browser.test.assertEq(1, views.length, "Should only see one view in incognito popup"); - browser.test.assertEq(window, views[0], "This window should be the only view"); - } else { - let bgPage = browser.extension.getBackgroundPage(); - browser.test.assertEq(true, bgPage.isBackgroundPage, - "Should be able to access background page in non-incognito context"); - - bgPage = await browser.runtime.getBackgroundPage(); - browser.test.assertEq(true, bgPage.isBackgroundPage, - "Should be able to access background page in non-incognito context"); - - browser.test.assertEq(2, views.length, "Should only two views in non-incognito popup"); - browser.test.assertEq(bgPage, views[0], "The background page should be the first view"); - browser.test.assertEq(window, views[1], "This window should be the second view"); - } - - let win = await browser.windows.getCurrent(); - browser.runtime.sendMessage({ - message: "popup-details", - windowId: win.id, - incognito: browser.extension.inIncognitoContext, - }); - - window.close(); - }, - }, - }); - - extension.onMessage("click-browserAction", () => { - clickBrowserAction(extension, Services.wm.getMostRecentWindow("navigator:browser")); - }); - - yield extension.startup(); - yield extension.awaitFinish("incognito-views"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_lastError.js b/browser/components/extensions/test/browser/browser_ext_lastError.js deleted file mode 100644 index 499e709aa..000000000 --- a/browser/components/extensions/test/browser/browser_ext_lastError.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; - -function* sendMessage(options) { - function background(options) { - browser.runtime.sendMessage(result => { - browser.test.assertEq(undefined, result, "Argument value"); - if (options.checkLastError) { - let lastError = browser[options.checkLastError].lastError; - browser.test.assertEq("runtime.sendMessage's message argument is missing", - lastError && lastError.message, - "lastError value"); - } - browser.test.sendMessage("done"); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: `(${background})(${JSON.stringify(options)})`, - }); - - yield extension.startup(); - - yield extension.awaitMessage("done"); - - yield extension.unload(); -} - -add_task(function* testLastError() { - // Not necessary in browser-chrome tests, but monitorConsole gripes - // if we don't call it. - SimpleTest.waitForExplicitFinish(); - - // Check that we have no unexpected console messages when lastError is - // checked. - for (let api of ["extension", "runtime"]) { - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{message: /message argument is missing/, forbid: true}]); - }); - - yield sendMessage({checkLastError: api}); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; - } - - // Check that we do have a console message when lastError is not checked. - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{message: /Unchecked lastError value: Error: runtime.sendMessage's message argument is missing/}]); - }); - - yield sendMessage({}); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js b/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js deleted file mode 100644 index 01557a745..000000000 --- a/browser/components/extensions/test/browser/browser_ext_legacy_extension_context_contentscript.js +++ /dev/null @@ -1,173 +0,0 @@ -"use strict"; - -const { - LegacyExtensionContext, -} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {}); - -function promiseAddonStartup(extension) { - const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - return new Promise((resolve) => { - let listener = (evt, extensionInstance) => { - Management.off("startup", listener); - resolve(extensionInstance); - }; - Management.on("startup", listener); - }); -} - -/** - * This test case ensures that the LegacyExtensionContext can receive a connection - * from a content script and that the received port contains the expected sender - * tab info. - */ -add_task(function* test_legacy_extension_context_contentscript_connection() { - function backgroundScript() { - // Extract the assigned uuid from the background page url and send it - // in a test message. - let uuid = window.location.hostname; - - browser.test.onMessage.addListener(async msg => { - if (msg == "open-test-tab") { - let tab = await browser.tabs.create({url: "http://example.com/"}); - browser.test.sendMessage("get-expected-sender-info", - {uuid, tab}); - } else if (msg == "close-current-tab") { - try { - let [tab] = await browser.tabs.query({active: true}); - await browser.tabs.remove(tab.id); - browser.test.sendMessage("current-tab-closed", true); - } catch (e) { - browser.test.sendMessage("current-tab-closed", false); - } - } - }); - - browser.test.sendMessage("ready"); - } - - function contentScript() { - browser.runtime.sendMessage("webextension -> legacy_extension message", (reply) => { - browser.test.assertEq("legacy_extension -> webextension reply", reply, - "Got the expected reply from the LegacyExtensionContext"); - browser.test.sendMessage("got-reply-message"); - }); - - let port = browser.runtime.connect(); - - port.onMessage.addListener(msg => { - browser.test.assertEq("legacy_extension -> webextension port message", msg, - "Got the expected message from the LegacyExtensionContext"); - port.postMessage("webextension -> legacy_extension port message"); - }); - } - - let extensionData = { - background: `new ${backgroundScript}`, - manifest: { - content_scripts: [ - { - matches: ["http://example.com/*"], - js: ["content-script.js"], - }, - ], - }, - files: { - "content-script.js": `new ${contentScript}`, - }, - }; - - let extension = ExtensionTestUtils.loadExtension(extensionData); - - let waitForExtensionReady = extension.awaitMessage("ready"); - - let waitForExtensionInstance = promiseAddonStartup(extension); - - extension.startup(); - - let extensionInstance = yield waitForExtensionInstance; - - // Connect to the target extension.id as an external context - // using the given custom sender info. - let legacyContext = new LegacyExtensionContext(extensionInstance); - - let waitConnectPort = new Promise(resolve => { - let {browser} = legacyContext.api; - browser.runtime.onConnect.addListener(port => { - resolve(port); - }); - }); - - let waitMessage = new Promise(resolve => { - let {browser} = legacyContext.api; - browser.runtime.onMessage.addListener((singleMsg, msgSender, sendReply) => { - sendReply("legacy_extension -> webextension reply"); - resolve({singleMsg, msgSender}); - }); - }); - - is(legacyContext.envType, "legacy_extension", - "LegacyExtensionContext instance has the expected type"); - - ok(legacyContext.api, "Got the API object"); - - yield waitForExtensionReady; - - extension.sendMessage("open-test-tab"); - - let {uuid, tab} = yield extension.awaitMessage("get-expected-sender-info"); - - let {singleMsg, msgSender} = yield waitMessage; - is(singleMsg, "webextension -> legacy_extension message", - "Got the expected message"); - ok(msgSender, "Got a message sender object"); - - is(msgSender.id, uuid, "The sender has the expected id property"); - is(msgSender.url, "http://example.com/", "The sender has the expected url property"); - ok(msgSender.tab, "The sender has a tab property"); - is(msgSender.tab.id, tab.id, "The port sender has the expected tab.id"); - - // Wait confirmation that the reply has been received. - yield extension.awaitMessage("got-reply-message"); - - let port = yield waitConnectPort; - - ok(port, "Got the Port API object"); - ok(port.sender, "The port has a sender property"); - - is(port.sender.id, uuid, "The port sender has an id property"); - is(port.sender.url, "http://example.com/", "The port sender has the expected url property"); - ok(port.sender.tab, "The port sender has a tab property"); - is(port.sender.tab.id, tab.id, "The port sender has the expected tab.id"); - - let waitPortMessage = new Promise(resolve => { - port.onMessage.addListener((msg) => { - resolve(msg); - }); - }); - - port.postMessage("legacy_extension -> webextension port message"); - - let msg = yield waitPortMessage; - - is(msg, "webextension -> legacy_extension port message", - "LegacyExtensionContext received the expected message from the webextension"); - - let waitForDisconnect = new Promise(resolve => { - port.onDisconnect.addListener(resolve); - }); - - let waitForTestDone = extension.awaitMessage("current-tab-closed"); - - extension.sendMessage("close-current-tab"); - - yield waitForDisconnect; - - info("Got the disconnect event on tab closed"); - - let success = yield waitForTestDone; - - ok(success, "Test completed successfully"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_omnibox.js b/browser/components/extensions/test/browser/browser_ext_omnibox.js deleted file mode 100644 index 98d3573c5..000000000 --- a/browser/components/extensions/test/browser/browser_ext_omnibox.js +++ /dev/null @@ -1,286 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* setup() { - const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches"; - Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, false); - - registerCleanupFunction(() => { - Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF); - }); -} - -add_task(function* () { - let keyword = "test"; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "omnibox": { - "keyword": keyword, - }, - }, - - background: function() { - browser.omnibox.onInputStarted.addListener(() => { - browser.test.sendMessage("on-input-started-fired"); - }); - - let synchronous = true; - let suggestions = null; - let suggestCallback = null; - - browser.omnibox.onInputChanged.addListener((text, suggest) => { - if (synchronous && suggestions) { - suggest(suggestions); - } else { - suggestCallback = suggest; - } - browser.test.sendMessage("on-input-changed-fired", {text}); - }); - - browser.omnibox.onInputCancelled.addListener(() => { - browser.test.sendMessage("on-input-cancelled-fired"); - }); - - browser.omnibox.onInputEntered.addListener((text, disposition) => { - browser.test.sendMessage("on-input-entered-fired", {text, disposition}); - }); - - browser.test.onMessage.addListener((msg, data) => { - switch (msg) { - case "set-suggestions": - suggestions = data.suggestions; - browser.test.sendMessage("suggestions-set"); - break; - case "set-default-suggestion": - browser.omnibox.setDefaultSuggestion(data.suggestion); - browser.test.sendMessage("default-suggestion-set"); - break; - case "set-synchronous": - synchronous = data.synchronous; - break; - case "test-multiple-suggest-calls": - suggestions.forEach(suggestion => suggestCallback([suggestion])); - browser.test.sendMessage("test-ready"); - break; - case "test-suggestions-after-delay": - Promise.resolve().then(() => { - suggestCallback(suggestions); - browser.test.sendMessage("test-ready"); - }); - break; - } - }); - }, - }); - - function* expectEvent(event, expected = {}) { - let actual = yield extension.awaitMessage(event); - if (expected.text) { - is(actual.text, expected.text, - `Expected "${event}" to have fired with text: "${expected.text}".`); - } - if (expected.disposition) { - is(actual.disposition, expected.disposition, - `Expected "${event}" to have fired with disposition: "${expected.disposition}".`); - } - } - - function* startInputSession() { - gURLBar.focus(); - gURLBar.value = keyword; - EventUtils.synthesizeKey(" ", {}); - yield expectEvent("on-input-started-fired"); - EventUtils.synthesizeKey("t", {}); - yield expectEvent("on-input-changed-fired", {text: "t"}); - return "t"; - } - - function* testInputEvents() { - gURLBar.focus(); - - // Start an input session by typing in <keyword><space>. - for (let letter of keyword) { - EventUtils.synthesizeKey(letter, {}); - } - EventUtils.synthesizeKey(" ", {}); - yield expectEvent("on-input-started-fired"); - - // We should expect input changed events now that the keyword is active. - EventUtils.synthesizeKey("b", {}); - yield expectEvent("on-input-changed-fired", {text: "b"}); - - EventUtils.synthesizeKey("c", {}); - yield expectEvent("on-input-changed-fired", {text: "bc"}); - - EventUtils.synthesizeKey("VK_BACK_SPACE", {}); - yield expectEvent("on-input-changed-fired", {text: "b"}); - - // Even though the input is <keyword><space> We should not expect an - // input started event to fire since the keyword is active. - EventUtils.synthesizeKey("VK_BACK_SPACE", {}); - yield expectEvent("on-input-changed-fired", {text: ""}); - - // Make the keyword inactive by hitting backspace. - EventUtils.synthesizeKey("VK_BACK_SPACE", {}); - yield expectEvent("on-input-cancelled-fired"); - - // Activate the keyword by typing a space. - // Expect onInputStarted to fire. - EventUtils.synthesizeKey(" ", {}); - yield expectEvent("on-input-started-fired"); - - // onInputChanged should fire even if a space is entered. - EventUtils.synthesizeKey(" ", {}); - yield expectEvent("on-input-changed-fired", {text: " "}); - - // The active session should cancel if the input blurs. - gURLBar.blur(); - yield expectEvent("on-input-cancelled-fired"); - } - - function* testHeuristicResult(expectedText, setDefaultSuggestion) { - if (setDefaultSuggestion) { - extension.sendMessage("set-default-suggestion", { - suggestion: { - description: expectedText, - }, - }); - yield extension.awaitMessage("default-suggestion-set"); - } - - let text = yield startInputSession(); - - let item = gURLBar.popup.richlistbox.children[0]; - - is(item.getAttribute("title"), expectedText, - `Expected heuristic result to have title: "${expectedText}".`); - - is(item.getAttribute("displayurl"), `${keyword} ${text}`, - `Expected heuristic result to have displayurl: "${keyword} ${text}".`); - - EventUtils.synthesizeMouseAtCenter(item, {}); - - yield expectEvent("on-input-entered-fired", { - text, - disposition: "currentTab", - }); - } - - function* testDisposition(suggestionIndex, expectedDisposition, expectedText) { - yield startInputSession(); - - // Select the suggestion. - for (let i = 0; i < suggestionIndex; i++) { - EventUtils.synthesizeKey("VK_DOWN", {}); - } - - let item = gURLBar.popup.richlistbox.children[suggestionIndex]; - if (expectedDisposition == "currentTab") { - EventUtils.synthesizeMouseAtCenter(item, {}); - } else if (expectedDisposition == "newForegroundTab") { - EventUtils.synthesizeMouseAtCenter(item, {accelKey: true}); - } else if (expectedDisposition == "newBackgroundTab") { - EventUtils.synthesizeMouseAtCenter(item, {shiftKey: true, accelKey: true}); - } - - yield expectEvent("on-input-entered-fired", { - text: expectedText, - disposition: expectedDisposition, - }); - } - - function* testSuggestions(info) { - extension.sendMessage("set-synchronous", {synchronous: false}); - - function expectSuggestion({content, description}, index) { - let item = gURLBar.popup.richlistbox.children[index + 1]; // Skip the heuristic result. - - ok(!!item, "Expected item to exist"); - is(item.getAttribute("title"), description, - `Expected suggestion to have title: "${description}".`); - - is(item.getAttribute("displayurl"), `${keyword} ${content}`, - `Expected suggestion to have displayurl: "${keyword} ${content}".`); - } - - let text = yield startInputSession(); - - extension.sendMessage(info.test); - yield extension.awaitMessage("test-ready"); - - info.suggestions.forEach(expectSuggestion); - - EventUtils.synthesizeMouseAtCenter(gURLBar.popup.richlistbox.children[0], {}); - yield expectEvent("on-input-entered-fired", { - text, - disposition: "currentTab", - }); - } - - yield setup(); - yield extension.startup(); - - yield testInputEvents(); - - // Test the heuristic result with default suggestions. - yield testHeuristicResult("Generated extension", false /* setDefaultSuggestion */); - yield testHeuristicResult("hello world", true /* setDefaultSuggestion */); - yield testHeuristicResult("foo bar", true /* setDefaultSuggestion */); - - let suggestions = [ - {content: "a", description: "select a"}, - {content: "b", description: "select b"}, - {content: "c", description: "select c"}, - ]; - - extension.sendMessage("set-suggestions", {suggestions}); - yield extension.awaitMessage("suggestions-set"); - - // Test each suggestion and search disposition. - yield testDisposition(1, "currentTab", suggestions[0].content); - yield testDisposition(2, "newForegroundTab", suggestions[1].content); - yield testDisposition(3, "newBackgroundTab", suggestions[2].content); - - extension.sendMessage("set-suggestions", {suggestions}); - yield extension.awaitMessage("suggestions-set"); - - // Test adding suggestions asynchronously. - yield testSuggestions({ - test: "test-multiple-suggest-calls", - skipHeuristic: true, - suggestions, - }); - yield testSuggestions({ - test: "test-suggestions-after-delay", - skipHeuristic: true, - suggestions, - }); - - // Start monitoring the console. - SimpleTest.waitForExplicitFinish(); - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{ - message: new RegExp(`The keyword provided is already registered: "${keyword}"`), - }]); - }); - - // Try registering another extension with the same keyword - let extension2 = ExtensionTestUtils.loadExtension({ - manifest: { - "omnibox": { - "keyword": keyword, - }, - }, - }); - - yield extension2.startup(); - - // Stop monitoring the console and confirm the correct errors are logged. - SimpleTest.endMonitorConsole(); - yield waitForConsole; - - yield extension2.unload(); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js b/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js deleted file mode 100644 index 3e7342dd1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_optionsPage_privileges.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* test_tab_options_privileges() { - function backgroundScript() { - browser.runtime.onMessage.addListener(({msgName, tabId}) => { - if (msgName == "removeTabId") { - browser.tabs.remove(tabId).then(() => { - browser.test.notifyPass("options-ui-privileges"); - }).catch(error => { - browser.test.log(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("options-ui-privileges"); - }); - } - }); - browser.runtime.openOptionsPage(); - } - - async function optionsScript() { - try { - let [tab] = await browser.tabs.query({url: "http://example.com/"}); - browser.test.assertEq("http://example.com/", tab.url, "Got the expect tab"); - - tab = await browser.tabs.getCurrent(); - browser.runtime.sendMessage({msgName: "removeTabId", tabId: tab.id}); - } catch (error) { - browser.test.log(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("options-ui-privileges"); - } - } - - const ID = "options_privileges@tests.mozilla.org"; - let extension = ExtensionTestUtils.loadExtension({ - useAddonManager: "temporary", - - manifest: { - applications: {gecko: {id: ID}}, - "permissions": ["tabs"], - "options_ui": { - "page": "options.html", - }, - }, - files: { - "options.html": `<!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - <script src="options.js" type="text/javascript"></script> - </head> - </html>`, - "options.js": optionsScript, - }, - background: backgroundScript, - }); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - yield extension.startup(); - - yield extension.awaitFinish("options-ui-privileges"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_context.js b/browser/components/extensions/test/browser/browser_ext_pageAction_context.js deleted file mode 100644 index 2c2a4cd2f..000000000 --- a/browser/components/extensions/test/browser/browser_ext_pageAction_context.js +++ /dev/null @@ -1,178 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* global runTests */ - -Services.scriptloader.loadSubScript(new URL("head_pageAction.js", gTestPath).href, - this); - -add_task(function* testTabSwitchContext() { - yield runTests({ - manifest: { - "name": "Foo Extension", - - "page_action": { - "default_icon": "default.png", - "default_popup": "__MSG_popup__", - "default_title": "Default __MSG_title__ \u263a", - }, - - "default_locale": "en", - - "permissions": ["tabs"], - }, - - "files": { - "_locales/en/messages.json": { - "popup": { - "message": "default.html", - "description": "Popup", - }, - - "title": { - "message": "Title", - "description": "Title", - }, - }, - - "_locales/es_ES/messages.json": { - "popup": { - "message": "default.html", - "description": "Popup", - }, - - "title": { - "message": "T\u00edtulo", - "description": "Title", - }, - }, - - "default.png": imageBuffer, - "1.png": imageBuffer, - "2.png": imageBuffer, - }, - - getTests(tabs) { - let details = [ - {"icon": browser.runtime.getURL("default.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default T\u00edtulo \u263a"}, - {"icon": browser.runtime.getURL("1.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default T\u00edtulo \u263a"}, - {"icon": browser.runtime.getURL("2.png"), - "popup": browser.runtime.getURL("2.html"), - "title": "Title 2"}, - {"icon": browser.runtime.getURL("2.png"), - "popup": browser.runtime.getURL("2.html"), - "title": "Default T\u00edtulo \u263a"}, - ]; - - let promiseTabLoad = details => { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changed) { - if (tabId == details.id && changed.url == details.url) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - }; - - return [ - expect => { - browser.test.log("Initial state. No icon visible."); - expect(null); - }, - async expect => { - browser.test.log("Show the icon on the first tab, expect default properties."); - await browser.pageAction.show(tabs[0]); - expect(details[0]); - }, - expect => { - browser.test.log("Change the icon. Expect default properties excluding the icon."); - browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"}); - expect(details[1]); - }, - async expect => { - browser.test.log("Create a new tab. No icon visible."); - let tab = await browser.tabs.create({active: true, url: "about:blank?0"}); - tabs.push(tab.id); - expect(null); - }, - expect => { - browser.test.log("Await tab load. No icon visible."); - expect(null); - }, - async expect => { - browser.test.log("Change properties. Expect new properties."); - let tabId = tabs[1]; - await browser.pageAction.show(tabId); - - browser.pageAction.setIcon({tabId, path: "2.png"}); - browser.pageAction.setPopup({tabId, popup: "2.html"}); - browser.pageAction.setTitle({tabId, title: "Title 2"}); - - expect(details[2]); - }, - async expect => { - browser.test.log("Change the hash. Expect same properties."); - - let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"}); - browser.tabs.update(tabs[1], {url: "about:blank?0#ref"}); - await promise; - - expect(details[2]); - }, - expect => { - browser.test.log("Clear the title. Expect default title."); - browser.pageAction.setTitle({tabId: tabs[1], title: ""}); - - expect(details[3]); - }, - async expect => { - browser.test.log("Navigate to a new page. Expect icon hidden."); - - // TODO: This listener should not be necessary, but the |tabs.update| - // callback currently fires too early in e10s windows. - let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"}); - - browser.tabs.update(tabs[1], {url: "about:blank?1"}); - - await promise; - expect(null); - }, - async expect => { - browser.test.log("Show the icon. Expect default properties again."); - - await browser.pageAction.show(tabs[1]); - expect(details[0]); - }, - async expect => { - browser.test.log("Switch back to the first tab. Expect previously set properties."); - await browser.tabs.update(tabs[0], {active: true}); - expect(details[1]); - }, - async expect => { - browser.test.log("Hide the icon on tab 2. Switch back, expect hidden."); - await browser.pageAction.hide(tabs[1]); - - await browser.tabs.update(tabs[1], {active: true}); - expect(null); - }, - async expect => { - browser.test.log("Switch back to tab 1. Expect previous results again."); - await browser.tabs.remove(tabs[1]); - expect(details[1]); - }, - async expect => { - browser.test.log("Hide the icon. Expect hidden."); - - await browser.pageAction.hide(tabs[0]); - expect(null); - }, - ]; - }, - }); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js b/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js deleted file mode 100644 index 83defdd68..000000000 --- a/browser/components/extensions/test/browser/browser_ext_pageAction_popup.js +++ /dev/null @@ -1,238 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testPageActionPopup() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head></html>`; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "background": { - "page": "data/background.html", - }, - "page_action": { - "default_popup": "popup-a.html", - }, - }, - - files: { - "popup-a.html": scriptPage("popup-a.js"), - "popup-a.js": function() { - window.onload = () => { - let background = window.getComputedStyle(document.body).backgroundColor; - browser.test.assertEq("transparent", background); - browser.runtime.sendMessage("from-popup-a"); - }; - browser.runtime.onMessage.addListener(msg => { - if (msg == "close-popup") { - window.close(); - } - }); - }, - - "data/popup-b.html": scriptPage("popup-b.js"), - "data/popup-b.js": function() { - browser.runtime.sendMessage("from-popup-b"); - }, - - "data/background.html": scriptPage("background.js"), - - "data/background.js": async function() { - let tabId; - - let sendClick; - let tests = [ - () => { - sendClick({expectEvent: false, expectPopup: "a"}); - }, - () => { - sendClick({expectEvent: false, expectPopup: "a"}); - }, - () => { - browser.pageAction.setPopup({tabId, popup: "popup-b.html"}); - sendClick({expectEvent: false, expectPopup: "b"}); - }, - () => { - sendClick({expectEvent: false, expectPopup: "b"}); - }, - () => { - browser.pageAction.setPopup({tabId, popup: ""}); - sendClick({expectEvent: true, expectPopup: null}); - }, - () => { - sendClick({expectEvent: true, expectPopup: null}); - }, - () => { - browser.pageAction.setPopup({tabId, popup: "/popup-a.html"}); - sendClick({expectEvent: false, expectPopup: "a", runNextTest: true}); - }, - () => { - browser.test.sendMessage("next-test", {expectClosed: true}); - }, - () => { - sendClick({expectEvent: false, expectPopup: "a", runNextTest: true}); - }, - () => { - browser.test.sendMessage("next-test", {closeOnTabSwitch: true}); - }, - ]; - - let expect = {}; - sendClick = ({expectEvent, expectPopup, runNextTest}) => { - expect = {event: expectEvent, popup: expectPopup, runNextTest}; - browser.test.sendMessage("send-click"); - }; - - browser.runtime.onMessage.addListener(msg => { - if (msg == "close-popup") { - return; - } else if (expect.popup) { - browser.test.assertEq(msg, `from-popup-${expect.popup}`, - "expected popup opened"); - } else { - browser.test.fail(`unexpected popup: ${msg}`); - } - - expect.popup = null; - if (expect.runNextTest) { - expect.runNextTest = false; - tests.shift()(); - } else { - browser.test.sendMessage("next-test"); - } - }); - - browser.pageAction.onClicked.addListener(() => { - if (expect.event) { - browser.test.succeed("expected click event received"); - } else { - browser.test.fail("unexpected click event"); - } - - expect.event = false; - browser.test.sendMessage("next-test"); - }); - - browser.test.onMessage.addListener(msg => { - if (msg == "close-popup") { - browser.runtime.sendMessage("close-popup"); - return; - } - - if (msg != "next-test") { - browser.test.fail("Expecting 'next-test' message"); - } - - if (tests.length) { - let test = tests.shift(); - test(); - } else { - browser.test.notifyPass("pageaction-tests-done"); - } - }); - - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - tabId = tab.id; - - await browser.pageAction.show(tabId); - browser.test.sendMessage("next-test"); - }, - }, - }); - - extension.onMessage("send-click", () => { - clickPageAction(extension); - }); - - let pageActionId, panelId; - extension.onMessage("next-test", Task.async(function* (expecting = {}) { - pageActionId = `${makeWidgetId(extension.id)}-page-action`; - panelId = `${makeWidgetId(extension.id)}-panel`; - let panel = document.getElementById(panelId); - if (expecting.expectClosed) { - ok(panel, "Expect panel to exist"); - yield promisePopupShown(panel); - - extension.sendMessage("close-popup"); - - yield promisePopupHidden(panel); - ok(true, `Panel is closed`); - } else if (expecting.closeOnTabSwitch) { - ok(panel, "Expect panel to exist"); - yield promisePopupShown(panel); - - let oldTab = gBrowser.selectedTab; - ok(oldTab != gBrowser.tabs[0], "Should have an inactive tab to switch to"); - - let hiddenPromise = promisePopupHidden(panel); - - gBrowser.selectedTab = gBrowser.tabs[0]; - yield hiddenPromise; - info("Panel closed"); - - gBrowser.selectedTab = oldTab; - } else if (panel) { - yield promisePopupShown(panel); - panel.hidePopup(); - } - - if (panel) { - panel = document.getElementById(panelId); - is(panel, null, "panel successfully removed from document after hiding"); - } - - extension.sendMessage("next-test"); - })); - - - yield extension.startup(); - yield extension.awaitFinish("pageaction-tests-done"); - - yield extension.unload(); - - let node = document.getElementById(pageActionId); - is(node, null, "pageAction image removed from document"); - - let panel = document.getElementById(panelId); - is(panel, null, "pageAction panel removed from document"); - - yield BrowserTestUtils.removeTab(tab); -}); - - -add_task(function* testPageActionSecurity() { - const URL = "chrome://browser/content/browser.xul"; - - let apis = ["browser_action", "page_action"]; - - for (let api of apis) { - info(`TEST ${api} icon url: ${URL}`); - - let messages = [/Access to restricted URI denied/]; - - let waitForConsole = new Promise(resolve => { - // Not necessary in browser-chrome tests, but monitorConsole gripes - // if we don't call it. - SimpleTest.waitForExplicitFinish(); - - SimpleTest.monitorConsole(resolve, messages); - }); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - [api]: {"default_popup": URL}, - }, - }); - - yield Assert.rejects(extension.startup(), - null, - "Manifest rejected"); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; - } -}); - -add_task(forceGC); diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js b/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js deleted file mode 100644 index 98c4c3488..000000000 --- a/browser/components/extensions/test/browser/browser_ext_pageAction_popup_resize.js +++ /dev/null @@ -1,169 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -let delay = ms => new Promise(resolve => { - setTimeout(resolve, ms); -}); - -add_task(function* testPageActionPopupResize() { - let browser; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "page_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - }, - background: function() { - /* global browser */ - browser.tabs.query({active: true, currentWindow: true}, tabs => { - const tabId = tabs[0].id; - - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("action-shown"); - }); - }); - }, - - files: { - "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><div></div></body></html>`, - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("action-shown"); - - clickPageAction(extension, window); - - browser = yield awaitExtensionPanel(extension); - - function* checkSize(expected) { - let dims = yield promiseContentDimensions(browser); - let {body, root} = dims; - - is(dims.window.innerHeight, expected, `Panel window should be ${expected}px tall`); - is(body.clientHeight, body.scrollHeight, - "Panel body should be tall enough to fit its contents"); - is(root.clientHeight, root.scrollHeight, - "Panel root should be tall enough to fit its contents"); - - // Tolerate if it is 1px too wide, as that may happen with the current resizing method. - ok(Math.abs(dims.window.innerWidth - expected) <= 1, `Panel window should be ${expected}px wide`); - is(body.clientWidth, body.scrollWidth, - "Panel body should be wide enough to fit its contents"); - } - - /* eslint-disable mozilla/no-cpows-in-tests */ - function setSize(size) { - let elem = content.document.body.firstChild; - elem.style.height = `${size}px`; - elem.style.width = `${size}px`; - } - /* eslint-enable mozilla/no-cpows-in-tests */ - - let sizes = [ - 200, - 400, - 300, - ]; - - for (let size of sizes) { - yield alterContent(browser, setSize, size); - yield checkSize(size); - } - - yield alterContent(browser, setSize, 1400); - - let dims = yield promiseContentDimensions(browser); - let {body, root} = dims; - - if (AppConstants.platform == "win") { - while (dims.window.innerWidth < 800) { - yield delay(50); - dims = yield promiseContentDimensions(browser); - } - } - - is(dims.window.innerWidth, 800, "Panel window width"); - ok(body.clientWidth <= 800, `Panel body width ${body.clientWidth} is less than 800`); - is(body.scrollWidth, 1400, "Panel body scroll width"); - - is(dims.window.innerHeight, 600, "Panel window height"); - ok(root.clientHeight <= 600, `Panel root height (${root.clientHeight}px) is less than 600px`); - is(root.scrollHeight, 1400, "Panel root scroll height"); - - yield extension.unload(); -}); - -add_task(function* testPageActionPopupReflow() { - let browser; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "page_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - }, - background: function() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - const tabId = tabs[0].id; - - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("action-shown"); - }); - }); - }, - - files: { - "popup.html": `<!DOCTYPE html><html><head><meta charset="utf-8"></head> - <body> - The quick mauve fox jumps over the opalescent toad, with its glowing - eyes, and its vantablack mouth, and its bottomless chasm where you - would hope to find a heart, that looks straight into the deepest - pits of hell. The fox shivers, and cowers, and tries to run, but - the toad is utterly without pity. It turns, ever so slightly... - </body> - </html>`, - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("action-shown"); - - clickPageAction(extension, window); - - browser = yield awaitExtensionPanel(extension); - - /* eslint-disable mozilla/no-cpows-in-tests */ - function setSize(size) { - content.document.body.style.fontSize = `${size}px`; - } - /* eslint-enable mozilla/no-cpows-in-tests */ - - let dims = yield alterContent(browser, setSize, 18); - - if (AppConstants.platform == "win") { - while (dims.window.innerWidth < 800) { - yield delay(50); - dims = yield promiseContentDimensions(browser); - } - } - - is(dims.window.innerWidth, 800, "Panel window should be 800px wide"); - is(dims.body.clientWidth, 800, "Panel body should be 800px wide"); - is(dims.body.clientWidth, dims.body.scrollWidth, - "Panel body should be wide enough to fit its contents"); - - ok(dims.window.innerHeight > 36, - `Panel window height (${dims.window.innerHeight}px) should be taller than two lines of text.`); - - is(dims.body.clientHeight, dims.body.scrollHeight, - "Panel body should be tall enough to fit its contents"); - is(dims.root.clientHeight, dims.root.scrollHeight, - "Panel root should be tall enough to fit its contents"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js b/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js deleted file mode 100644 index d1d173801..000000000 --- a/browser/components/extensions/test/browser/browser_ext_pageAction_simple.js +++ /dev/null @@ -1,60 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "page_action": { - "default_popup": "popup.html", - "unrecognized_property": "with-a-random-value", - }, - }, - - files: { - "popup.html": ` - <!DOCTYPE html> - <html><body> - <script src="popup.js"></script> - </body></html> - `, - - "popup.js": function() { - browser.runtime.sendMessage("from-popup"); - }, - }, - - background: function() { - browser.runtime.onMessage.addListener(msg => { - browser.test.assertEq(msg, "from-popup", "correct message received"); - browser.test.sendMessage("popup"); - }); - browser.tabs.query({active: true, currentWindow: true}, tabs => { - let tabId = tabs[0].id; - - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("page-action-shown"); - }); - }); - }, - }); - - SimpleTest.waitForExplicitFinish(); - let waitForConsole = new Promise(resolve => { - SimpleTest.monitorConsole(resolve, [{ - message: /Reading manifest: Error processing page_action.unrecognized_property: An unexpected property was found/, - }]); - }); - - yield extension.startup(); - yield extension.awaitMessage("page-action-shown"); - - clickPageAction(extension); - - yield extension.awaitMessage("popup"); - - yield extension.unload(); - - SimpleTest.endMonitorConsole(); - yield waitForConsole; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_pageAction_title.js b/browser/components/extensions/test/browser/browser_ext_pageAction_title.js deleted file mode 100644 index 793cd4499..000000000 --- a/browser/components/extensions/test/browser/browser_ext_pageAction_title.js +++ /dev/null @@ -1,226 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* global runTests */ - -Services.scriptloader.loadSubScript(new URL("head_pageAction.js", gTestPath).href, - this); - -add_task(function* testTabSwitchContext() { - yield runTests({ - manifest: { - "name": "Foo Extension", - - "page_action": { - "default_icon": "default.png", - "default_popup": "__MSG_popup__", - "default_title": "Default __MSG_title__ \u263a", - }, - - "default_locale": "en", - - "permissions": ["tabs"], - }, - - "files": { - "_locales/en/messages.json": { - "popup": { - "message": "default.html", - "description": "Popup", - }, - - "title": { - "message": "Title", - "description": "Title", - }, - }, - - "_locales/es_ES/messages.json": { - "popup": { - "message": "default.html", - "description": "Popup", - }, - - "title": { - "message": "T\u00edtulo", - "description": "Title", - }, - }, - - "default.png": imageBuffer, - "1.png": imageBuffer, - "2.png": imageBuffer, - }, - - getTests(tabs) { - let details = [ - {"icon": browser.runtime.getURL("default.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default T\u00edtulo \u263a"}, - {"icon": browser.runtime.getURL("1.png"), - "popup": browser.runtime.getURL("default.html"), - "title": "Default T\u00edtulo \u263a"}, - {"icon": browser.runtime.getURL("2.png"), - "popup": browser.runtime.getURL("2.html"), - "title": "Title 2"}, - {"icon": browser.runtime.getURL("2.png"), - "popup": browser.runtime.getURL("2.html"), - "title": "Default T\u00edtulo \u263a"}, - ]; - - let promiseTabLoad = details => { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changed) { - if (tabId == details.id && changed.url == details.url) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - }; - return [ - expect => { - browser.test.log("Initial state. No icon visible."); - expect(null); - }, - async expect => { - browser.test.log("Show the icon on the first tab, expect default properties."); - await browser.pageAction.show(tabs[0]); - expect(details[0]); - }, - expect => { - browser.test.log("Change the icon. Expect default properties excluding the icon."); - browser.pageAction.setIcon({tabId: tabs[0], path: "1.png"}); - expect(details[1]); - }, - async expect => { - browser.test.log("Create a new tab. No icon visible."); - let tab = await browser.tabs.create({active: true, url: "about:blank?0"}); - tabs.push(tab.id); - expect(null); - }, - expect => { - browser.test.log("Await tab load. No icon visible."); - expect(null); - }, - async expect => { - browser.test.log("Change properties. Expect new properties."); - let tabId = tabs[1]; - - await browser.pageAction.show(tabId); - browser.pageAction.setIcon({tabId, path: "2.png"}); - browser.pageAction.setPopup({tabId, popup: "2.html"}); - browser.pageAction.setTitle({tabId, title: "Title 2"}); - - expect(details[2]); - }, - async expect => { - browser.test.log("Change the hash. Expect same properties."); - - let promise = promiseTabLoad({id: tabs[1], url: "about:blank?0#ref"}); - - browser.tabs.update(tabs[1], {url: "about:blank?0#ref"}); - - await promise; - expect(details[2]); - }, - expect => { - browser.test.log("Clear the title. Expect default title."); - browser.pageAction.setTitle({tabId: tabs[1], title: ""}); - - expect(details[3]); - }, - async expect => { - browser.test.log("Navigate to a new page. Expect icon hidden."); - - // TODO: This listener should not be necessary, but the |tabs.update| - // callback currently fires too early in e10s windows. - let promise = promiseTabLoad({id: tabs[1], url: "about:blank?1"}); - - browser.tabs.update(tabs[1], {url: "about:blank?1"}); - - await promise; - expect(null); - }, - async expect => { - browser.test.log("Show the icon. Expect default properties again."); - await browser.pageAction.show(tabs[1]); - expect(details[0]); - }, - async expect => { - browser.test.log("Switch back to the first tab. Expect previously set properties."); - await browser.tabs.update(tabs[0], {active: true}); - expect(details[1]); - }, - async expect => { - browser.test.log("Hide the icon on tab 2. Switch back, expect hidden."); - await browser.pageAction.hide(tabs[1]); - await browser.tabs.update(tabs[1], {active: true}); - expect(null); - }, - async expect => { - browser.test.log("Switch back to tab 1. Expect previous results again."); - await browser.tabs.remove(tabs[1]); - expect(details[1]); - }, - async expect => { - browser.test.log("Hide the icon. Expect hidden."); - await browser.pageAction.hide(tabs[0]); - expect(null); - }, - ]; - }, - }); -}); - -add_task(function* testDefaultTitle() { - yield runTests({ - manifest: { - "name": "Foo Extension", - - "page_action": { - "default_icon": "icon.png", - }, - - "permissions": ["tabs"], - }, - - files: { - "icon.png": imageBuffer, - }, - - getTests(tabs) { - let details = [ - {"title": "Foo Extension", - "popup": "", - "icon": browser.runtime.getURL("icon.png")}, - {"title": "Foo Title", - "popup": "", - "icon": browser.runtime.getURL("icon.png")}, - ]; - - return [ - expect => { - browser.test.log("Initial state. No icon visible."); - expect(null); - }, - async expect => { - browser.test.log("Show the icon on the first tab, expect extension title as default title."); - await browser.pageAction.show(tabs[0]); - expect(details[0]); - }, - expect => { - browser.test.log("Change the title. Expect new title."); - browser.pageAction.setTitle({tabId: tabs[0], title: "Foo Title"}); - expect(details[1]); - }, - expect => { - browser.test.log("Clear the title. Expect extension title."); - browser.pageAction.setTitle({tabId: tabs[0], title: ""}); - expect(details[0]); - }, - ]; - }, - }); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js b/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js deleted file mode 100644 index 6f8a541a9..000000000 --- a/browser/components/extensions/test/browser/browser_ext_popup_api_injection.js +++ /dev/null @@ -1,101 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testPageActionPopup() { - const BASE = "http://example.com/browser/browser/components/extensions/test/browser"; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": `${BASE}/file_popup_api_injection_a.html`, - }, - "page_action": { - "default_popup": `${BASE}/file_popup_api_injection_b.html`, - }, - }, - - files: { - "popup-a.html": `<html><head><meta charset="utf-8"> - <script type="application/javascript" src="popup-a.js"></script></head></html>`, - "popup-a.js": 'browser.test.sendMessage("from-popup-a");', - - "popup-b.html": `<html><head><meta charset="utf-8"> - <script type="application/javascript" src="popup-b.js"></script></head></html>`, - "popup-b.js": 'browser.test.sendMessage("from-popup-b");', - }, - - background: function() { - let tabId; - browser.tabs.query({active: true, currentWindow: true}, tabs => { - tabId = tabs[0].id; - browser.pageAction.show(tabId).then(() => { - browser.test.sendMessage("ready"); - }); - }); - - browser.test.onMessage.addListener(() => { - browser.browserAction.setPopup({popup: "/popup-a.html"}); - browser.pageAction.setPopup({tabId, popup: "popup-b.html"}); - - browser.test.sendMessage("ok"); - }); - }, - }); - - let promiseConsoleMessage = pattern => new Promise(resolve => { - Services.console.registerListener(function listener(msg) { - if (pattern.test(msg.message)) { - resolve(msg.message); - Services.console.unregisterListener(listener); - } - }); - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - - // Check that unprivileged documents don't get the API. - // BrowserAction: - let awaitMessage = promiseConsoleMessage(/WebExt Privilege Escalation: BrowserAction/); - SimpleTest.expectUncaughtException(); - yield clickBrowserAction(extension); - yield promisePopupShown(getBrowserActionPopup(extension)); - - let message = yield awaitMessage; - ok(message.includes("WebExt Privilege Escalation: BrowserAction: typeof(browser) = undefined"), - `No BrowserAction API injection`); - - yield closeBrowserAction(extension); - - // PageAction - awaitMessage = promiseConsoleMessage(/WebExt Privilege Escalation: PageAction/); - SimpleTest.expectUncaughtException(); - yield clickPageAction(extension); - - message = yield awaitMessage; - ok(message.includes("WebExt Privilege Escalation: PageAction: typeof(browser) = undefined"), - `No PageAction API injection: ${message}`); - - yield closePageAction(extension); - - SimpleTest.expectUncaughtException(false); - - - // Check that privileged documents *do* get the API. - extension.sendMessage("next"); - yield extension.awaitMessage("ok"); - - - yield clickBrowserAction(extension); - yield extension.awaitMessage("from-popup-a"); - yield promisePopupShown(getBrowserActionPopup(extension)); - yield closeBrowserAction(extension); - - yield clickPageAction(extension); - yield extension.awaitMessage("from-popup-b"); - yield closePageAction(extension); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_popup_background.js b/browser/components/extensions/test/browser/browser_ext_popup_background.js deleted file mode 100644 index 8b310c674..000000000 --- a/browser/components/extensions/test/browser/browser_ext_popup_background.js +++ /dev/null @@ -1,133 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testPopupBackground() { - let extension = ExtensionTestUtils.loadExtension({ - background() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - browser.pageAction.show(tabs[0].id); - }); - }, - - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - - "page_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - }, - - files: { - "popup.html": `<!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - <body style="width: 100px; height: 100px; background-color: green;"> - </body> - </html>`, - }, - }); - - yield extension.startup(); - - function* testPanel(browser, standAlone) { - let panel = getPanelForNode(browser); - let arrowContent = document.getAnonymousElementByAttribute(panel, "class", "panel-arrowcontent"); - let arrow = document.getAnonymousElementByAttribute(panel, "anonid", "arrow"); - - let borderColor = getComputedStyle(arrowContent).borderTopColor; - - let checkArrow = (background = null) => { - let image = getComputedStyle(arrow).listStyleImage; - - if (background == null || !standAlone) { - ok(image.startsWith('url("chrome://'), `We should have the built-in background image (got: ${image})`); - return; - } - - if (AppConstants.platform == "mac") { - // Panels have a drop shadow rather than a border on OS-X, so we extend - // the background color through the border area instead. - borderColor = background; - } - - image = decodeURIComponent(image); - let borderIndex = image.indexOf(`fill="${borderColor}"`); - let backgroundIndex = image.lastIndexOf(`fill="${background}"`); - - ok(borderIndex >= 0, `Have border fill (index=${borderIndex})`); - ok(backgroundIndex >= 0, `Have background fill (index=${backgroundIndex})`); - is(getComputedStyle(arrowContent).backgroundColor, background, "Arrow content should have correct background"); - isnot(borderIndex, backgroundIndex, "Border and background fills are separate elements"); - }; - - function getBackground(browser) { - return ContentTask.spawn(browser, null, function* () { - return content.getComputedStyle(content.document.body) - .backgroundColor; - }); - } - - /* eslint-disable mozilla/no-cpows-in-tests */ - let setBackground = color => { - content.document.body.style.backgroundColor = color; - }; - /* eslint-enable mozilla/no-cpows-in-tests */ - - yield new Promise(resolve => setTimeout(resolve, 100)); - - info("Test that initial background color is applied"); - - checkArrow(yield getBackground(browser)); - - info("Test that dynamically-changed background color is applied"); - - yield alterContent(browser, setBackground, "black"); - - checkArrow(yield getBackground(browser)); - - info("Test that non-opaque background color results in default styling"); - - yield alterContent(browser, setBackground, "rgba(1, 2, 3, .9)"); - - checkArrow(null); - } - - { - info("Test stand-alone browserAction popup"); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser, true); - yield closeBrowserAction(extension); - } - - { - info("Test menu panel browserAction popup"); - - let widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser, false); - yield closeBrowserAction(extension); - } - - { - info("Test pageAction popup"); - - clickPageAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser, true); - yield closePageAction(extension); - } - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_popup_corners.js b/browser/components/extensions/test/browser/browser_ext_popup_corners.js deleted file mode 100644 index 52985ee46..000000000 --- a/browser/components/extensions/test/browser/browser_ext_popup_corners.js +++ /dev/null @@ -1,98 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testPopupBorderRadius() { - let extension = ExtensionTestUtils.loadExtension({ - background() { - browser.tabs.query({active: true, currentWindow: true}, tabs => { - browser.pageAction.show(tabs[0].id); - }); - }, - - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - - "page_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - }, - - files: { - "popup.html": `<!DOCTYPE html> - <html> - <head><meta charset="utf-8"></head> - <body style="width: 100px; height: 100px;"></body> - </html>`, - }, - }); - - yield extension.startup(); - - function* testPanel(browser, standAlone = true) { - let panel = getPanelForNode(browser); - let arrowContent = document.getAnonymousElementByAttribute(panel, "class", "panel-arrowcontent"); - - let panelStyle = getComputedStyle(arrowContent); - - let viewNode = browser.parentNode === panel ? browser : browser.parentNode; - let viewStyle = getComputedStyle(viewNode); - - let props = ["borderTopLeftRadius", "borderTopRightRadius", - "borderBottomRightRadius", "borderBottomLeftRadius"]; - - /* eslint-disable mozilla/no-cpows-in-tests */ - let bodyStyle = yield ContentTask.spawn(browser, props, function* (props) { - let bodyStyle = content.getComputedStyle(content.document.body); - - return new Map(props.map(prop => [prop, bodyStyle[prop]])); - }); - /* eslint-enable mozilla/no-cpows-in-tests */ - - for (let prop of props) { - if (standAlone) { - is(viewStyle[prop], panelStyle[prop], `Panel and view ${prop} should be the same`); - is(bodyStyle.get(prop), panelStyle[prop], `Panel and body ${prop} should be the same`); - } else { - is(viewStyle[prop], "0px", `View node ${prop} should be 0px`); - is(bodyStyle.get(prop), "0px", `Body node ${prop} should be 0px`); - } - } - } - - { - info("Test stand-alone browserAction popup"); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser); - yield closeBrowserAction(extension); - } - - { - info("Test menu panel browserAction popup"); - - let widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser, false); - yield closeBrowserAction(extension); - } - - { - info("Test pageAction popup"); - - clickPageAction(extension); - let browser = yield awaitExtensionPanel(extension); - yield testPanel(browser); - yield closePageAction(extension); - } - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js b/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js deleted file mode 100644 index 472ee7bbd..000000000 --- a/browser/components/extensions/test/browser/browser_ext_popup_sendMessage.js +++ /dev/null @@ -1,93 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* test_popup_sendMessage_reply() { - let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>${url}</body></html>`; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - - "page_action": { - "default_popup": "popup.html", - "browser_style": true, - }, - }, - - files: { - "popup.html": scriptPage("popup.js"), - "popup.js": async function() { - browser.runtime.onMessage.addListener(async msg => { - if (msg == "popup-ping") { - return Promise.resolve("popup-pong"); - } - }); - - let response = await browser.runtime.sendMessage("background-ping"); - browser.test.sendMessage("background-ping-response", response); - }, - }, - - async background() { - browser.runtime.onMessage.addListener(async msg => { - if (msg == "background-ping") { - let response = await browser.runtime.sendMessage("popup-ping"); - - browser.test.sendMessage("popup-ping-response", response); - - await new Promise(resolve => { - // Wait long enough that we're relatively sure the docShells have - // been swapped. Note that this value is fairly arbitrary. The load - // event that triggers the swap should happen almost immediately - // after the message is sent. The extra quarter of a second gives us - // enough leeway that we can expect to respond after the swap in the - // vast majority of cases. - setTimeout(resolve, 250); - }); - - return "background-pong"; - } - }); - - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - - await browser.pageAction.show(tab.id); - - browser.test.sendMessage("page-action-ready"); - }, - }); - - yield extension.startup(); - - { - clickBrowserAction(extension); - - let pong = yield extension.awaitMessage("background-ping-response"); - is(pong, "background-pong", "Got pong"); - - pong = yield extension.awaitMessage("popup-ping-response"); - is(pong, "popup-pong", "Got pong"); - - yield closeBrowserAction(extension); - } - - yield extension.awaitMessage("page-action-ready"); - - { - clickPageAction(extension); - - let pong = yield extension.awaitMessage("background-ping-response"); - is(pong, "background-pong", "Got pong"); - - pong = yield extension.awaitMessage("popup-ping-response"); - is(pong, "popup-pong", "Got pong"); - - yield closePageAction(extension); - } - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js b/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js deleted file mode 100644 index 66d37e857..000000000 --- a/browser/components/extensions/test/browser/browser_ext_popup_shutdown.js +++ /dev/null @@ -1,77 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -let getExtension = () => { - return ExtensionTestUtils.loadExtension({ - background: async function() { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - await browser.pageAction.show(tab.id); - browser.test.sendMessage("pageAction ready"); - }, - - manifest: { - "browser_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - - "page_action": { - "default_popup": "popup.html", - "browser_style": false, - }, - }, - - files: { - "popup.html": `<!DOCTYPE html> - <html><head><meta charset="utf-8"></head></html>`, - }, - }); -}; - -add_task(function* testStandaloneBrowserAction() { - info("Test stand-alone browserAction popup"); - - let extension = getExtension(); - yield extension.startup(); - yield extension.awaitMessage("pageAction ready"); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - let panel = getPanelForNode(browser); - - yield extension.unload(); - - is(panel.parentNode, null, "Panel should be removed from the document"); -}); - -add_task(function* testMenuPanelBrowserAction() { - let extension = getExtension(); - yield extension.startup(); - yield extension.awaitMessage("pageAction ready"); - - let widget = getBrowserActionWidget(extension); - CustomizableUI.addWidgetToArea(widget.id, CustomizableUI.AREA_PANEL); - - clickBrowserAction(extension); - let browser = yield awaitExtensionPanel(extension); - let panel = getPanelForNode(browser); - - yield extension.unload(); - - is(panel.state, "closed", "Panel should be closed"); -}); - -add_task(function* testPageAction() { - let extension = getExtension(); - yield extension.startup(); - yield extension.awaitMessage("pageAction ready"); - - clickPageAction(extension); - let browser = yield awaitExtensionPanel(extension); - let panel = getPanelForNode(browser); - - yield extension.unload(); - - is(panel.parentNode, null, "Panel should be removed from the document"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js b/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js deleted file mode 100644 index 1631ececa..000000000 --- a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage.js +++ /dev/null @@ -1,276 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -requestLongerTimeout(2); - -function add_tasks(task) { - add_task(task.bind(null, {embedded: false})); - - add_task(task.bind(null, {embedded: true})); -} - -function* loadExtension(options) { - let extension = ExtensionTestUtils.loadExtension({ - useAddonManager: "temporary", - - embedded: options.embedded, - - manifest: Object.assign({ - "permissions": ["tabs"], - }, options.manifest), - - files: { - "options.html": `<!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - <script src="options.js" type="text/javascript"></script> - </head> - </html>`, - - "options.js": function() { - window.iAmOption = true; - browser.runtime.sendMessage("options.html"); - browser.runtime.onMessage.addListener((msg, sender, respond) => { - if (msg == "ping") { - respond("pong"); - } - }); - }, - }, - - background: options.background, - }); - - yield extension.startup(); - - return extension; -} - -add_tasks(function* test_inline_options(extraOptions) { - info(`Test options opened inline (${JSON.stringify(extraOptions)})`); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - let extension = yield loadExtension(Object.assign({}, extraOptions, { - manifest: { - applications: {gecko: {id: "inline_options@tests.mozilla.org"}}, - "options_ui": { - "page": "options.html", - }, - }, - - background: async function() { - let _optionsPromise; - let awaitOptions = () => { - browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already"); - - return new Promise(resolve => { - _optionsPromise = {resolve}; - }); - }; - - browser.runtime.onMessage.addListener((msg, sender) => { - if (msg == "options.html") { - if (_optionsPromise) { - _optionsPromise.resolve(sender.tab); - _optionsPromise = null; - } else { - browser.test.fail("Saw unexpected options page load"); - } - } - }); - - try { - let [firstTab] = await browser.tabs.query({currentWindow: true, active: true}); - - browser.test.log("Open options page. Expect fresh load."); - - let [, optionsTab] = await Promise.all([ - browser.runtime.openOptionsPage(), - awaitOptions(), - ]); - - browser.test.assertEq("about:addons", optionsTab.url, "Tab contains AddonManager"); - browser.test.assertTrue(optionsTab.active, "Tab is active"); - browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab"); - - browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup"); - browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab"); - browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches"); - - let views = browser.extension.getViews(); - browser.test.assertEq(2, views.length, "Expected the options page and the background page"); - browser.test.assertTrue(views.includes(window), "One of the views is the background page"); - browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page"); - - browser.test.log("Switch tabs."); - await browser.tabs.update(firstTab.id, {active: true}); - - browser.test.log("Open options page again. Expect tab re-selected, no new load."); - - await browser.runtime.openOptionsPage(); - let [tab] = await browser.tabs.query({currentWindow: true, active: true}); - - browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab"); - browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager"); - - browser.test.log("Ping options page."); - let pong = await browser.runtime.sendMessage("ping"); - browser.test.assertEq("pong", pong, "Got pong."); - - browser.test.log("Remove options tab."); - await browser.tabs.remove(optionsTab.id); - - browser.test.log("Open options page again. Expect fresh load."); - [, tab] = await Promise.all([ - browser.runtime.openOptionsPage(), - awaitOptions(), - ]); - browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager"); - browser.test.assertTrue(tab.active, "Tab is active"); - browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab"); - - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("options-ui"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("options-ui"); - } - }, - })); - - yield extension.awaitFinish("options-ui"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); - -add_tasks(function* test_tab_options(extraOptions) { - info(`Test options opened in a tab (${JSON.stringify(extraOptions)})`); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - let extension = yield loadExtension(Object.assign({}, extraOptions, { - manifest: { - applications: {gecko: {id: "tab_options@tests.mozilla.org"}}, - "options_ui": { - "page": "options.html", - "open_in_tab": true, - }, - }, - - background: async function() { - let _optionsPromise; - let awaitOptions = () => { - browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already"); - - return new Promise(resolve => { - _optionsPromise = {resolve}; - }); - }; - - browser.runtime.onMessage.addListener((msg, sender) => { - if (msg == "options.html") { - if (_optionsPromise) { - _optionsPromise.resolve(sender.tab); - _optionsPromise = null; - } else { - browser.test.fail("Saw unexpected options page load"); - } - } - }); - - let optionsURL = browser.extension.getURL("options.html"); - - try { - let [firstTab] = await browser.tabs.query({currentWindow: true, active: true}); - - browser.test.log("Open options page. Expect fresh load."); - let [, optionsTab] = await Promise.all([ - browser.runtime.openOptionsPage(), - awaitOptions(), - ]); - browser.test.assertEq(optionsURL, optionsTab.url, "Tab contains options.html"); - browser.test.assertTrue(optionsTab.active, "Tab is active"); - browser.test.assertTrue(optionsTab.id != firstTab.id, "Tab is a new tab"); - - browser.test.assertEq(0, browser.extension.getViews({type: "popup"}).length, "viewType is not popup"); - browser.test.assertEq(1, browser.extension.getViews({type: "tab"}).length, "viewType is tab"); - browser.test.assertEq(1, browser.extension.getViews({windowId: optionsTab.windowId}).length, "windowId matches"); - - let views = browser.extension.getViews(); - browser.test.assertEq(2, views.length, "Expected the options page and the background page"); - browser.test.assertTrue(views.includes(window), "One of the views is the background page"); - browser.test.assertTrue(views.some(w => w.iAmOption), "One of the views is the options page"); - - browser.test.log("Switch tabs."); - await browser.tabs.update(firstTab.id, {active: true}); - - browser.test.log("Open options page again. Expect tab re-selected, no new load."); - - await browser.runtime.openOptionsPage(); - let [tab] = await browser.tabs.query({currentWindow: true, active: true}); - - browser.test.assertEq(optionsTab.id, tab.id, "Tab is the same as the previous options tab"); - browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html"); - - // Unfortunately, we can't currently do this, since onMessage doesn't - // currently support responses when there are multiple listeners. - // - // browser.test.log("Ping options page."); - // return new Promise(resolve => browser.runtime.sendMessage("ping", resolve)); - - browser.test.log("Remove options tab."); - await browser.tabs.remove(optionsTab.id); - - browser.test.log("Open options page again. Expect fresh load."); - [, tab] = await Promise.all([ - browser.runtime.openOptionsPage(), - awaitOptions(), - ]); - browser.test.assertEq(optionsURL, tab.url, "Tab contains options.html"); - browser.test.assertTrue(tab.active, "Tab is active"); - browser.test.assertTrue(tab.id != optionsTab.id, "Tab is a new tab"); - - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("options-ui-tab"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("options-ui-tab"); - } - }, - })); - - yield extension.awaitFinish("options-ui-tab"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); - -add_tasks(function* test_options_no_manifest(extraOptions) { - info(`Test with no manifest key (${JSON.stringify(extraOptions)})`); - - let extension = yield loadExtension(Object.assign({}, extraOptions, { - manifest: { - applications: {gecko: {id: "no_options@tests.mozilla.org"}}, - }, - - async background() { - browser.test.log("Try to open options page when not specified in the manifest."); - - await browser.test.assertRejects( - browser.runtime.openOptionsPage(), - /No `options_ui` declared/, - "Expected error from openOptionsPage()"); - - browser.test.notifyPass("options-no-manifest"); - }, - })); - - yield extension.awaitFinish("options-no-manifest"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js b/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js deleted file mode 100644 index 0c123b70e..000000000 --- a/browser/components/extensions/test/browser/browser_ext_runtime_openOptionsPage_uninstall.js +++ /dev/null @@ -1,101 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* loadExtension(options) { - let extension = ExtensionTestUtils.loadExtension({ - useAddonManager: "temporary", - - manifest: Object.assign({ - "permissions": ["tabs"], - }, options.manifest), - - files: { - "options.html": `<!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - <script src="options.js" type="text/javascript"></script> - </head> - </html>`, - - "options.js": function() { - browser.runtime.sendMessage("options.html"); - browser.runtime.onMessage.addListener((msg, sender, respond) => { - if (msg == "ping") { - respond("pong"); - } - }); - }, - }, - - background: options.background, - }); - - yield extension.startup(); - - return extension; -} - -add_task(function* test_inline_options_uninstall() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - let extension = yield loadExtension({ - manifest: { - applications: {gecko: {id: "inline_options_uninstall@tests.mozilla.org"}}, - "options_ui": { - "page": "options.html", - }, - }, - - background: async function() { - let _optionsPromise; - let awaitOptions = () => { - browser.test.assertFalse(_optionsPromise, "Should not be awaiting options already"); - - return new Promise(resolve => { - _optionsPromise = {resolve}; - }); - }; - - browser.runtime.onMessage.addListener((msg, sender) => { - if (msg == "options.html") { - if (_optionsPromise) { - _optionsPromise.resolve(sender.tab); - _optionsPromise = null; - } else { - browser.test.fail("Saw unexpected options page load"); - } - } - }); - - try { - let [firstTab] = await browser.tabs.query({currentWindow: true, active: true}); - - browser.test.log("Open options page. Expect fresh load."); - let [, tab] = await Promise.all([ - browser.runtime.openOptionsPage(), - awaitOptions(), - ]); - - browser.test.assertEq("about:addons", tab.url, "Tab contains AddonManager"); - browser.test.assertTrue(tab.active, "Tab is active"); - browser.test.assertTrue(tab.id != firstTab.id, "Tab is a new tab"); - - browser.test.sendMessage("options-ui-open"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - } - }, - }); - - yield extension.awaitMessage("options-ui-open"); - yield extension.unload(); - - is(gBrowser.selectedBrowser.currentURI.spec, "about:addons", - "Add-on manager tab should still be open"); - - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js b/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js deleted file mode 100644 index 1c7ef4969..000000000 --- a/browser/components/extensions/test/browser/browser_ext_runtime_setUninstallURL.js +++ /dev/null @@ -1,94 +0,0 @@ -"use strict"; - -let {AddonManager} = Components.utils.import("resource://gre/modules/AddonManager.jsm", {}); -let {Extension} = Components.utils.import("resource://gre/modules/Extension.jsm", {}); - -function* makeAndInstallXPI(id, backgroundScript, loadedURL) { - let xpi = Extension.generateXPI({ - manifest: {applications: {gecko: {id}}}, - background: backgroundScript, - }); - SimpleTest.registerCleanupFunction(function cleanupXPI() { - Services.obs.notifyObservers(xpi, "flush-cache-entry", null); - xpi.remove(false); - }); - - let loadPromise = BrowserTestUtils.waitForNewTab(gBrowser, loadedURL); - - - info(`installing ${xpi.path}`); - let addon = yield AddonManager.installTemporaryAddon(xpi); - info("installed"); - - // A WebExtension is started asynchronously, we have our test extension - // open a new tab to signal that the background script has executed. - let loadTab = yield loadPromise; - yield BrowserTestUtils.removeTab(loadTab); - - return addon; -} - - -add_task(function* test_setuninstallurl_badargs() { - async function background() { - await browser.test.assertRejects( - browser.runtime.setUninstallURL("this is not a url"), - /Invalid URL/, - "setUninstallURL with an invalid URL should fail"); - - await browser.test.assertRejects( - browser.runtime.setUninstallURL("file:///etc/passwd"), - /must have the scheme http or https/, - "setUninstallURL with an illegal URL should fail"); - - browser.test.notifyPass("setUninstallURL bad params"); - } - - let extension = ExtensionTestUtils.loadExtension({ - background, - }); - yield extension.startup(); - yield extension.awaitFinish(); - yield extension.unload(); -}); - -// Test the documented behavior of setUninstallURL() that passing an -// empty string is equivalent to not setting an uninstall URL -// (i.e., no new tab is opened upon uninstall) -add_task(function* test_setuninstall_empty_url() { - async function backgroundScript() { - await browser.runtime.setUninstallURL(""); - browser.tabs.create({url: "http://example.com/addon_loaded"}); - } - - let addon = yield makeAndInstallXPI("test_uinstallurl2@tests.mozilla.org", - backgroundScript, - "http://example.com/addon_loaded"); - - addon.uninstall(true); - info("uninstalled"); - - // no need to explicitly check for the absence of a new tab, - // BrowserTestUtils will eventually complain if one is opened. -}); - -add_task(function* test_setuninstallurl() { - async function backgroundScript() { - await browser.runtime.setUninstallURL("http://example.com/addon_uninstalled"); - browser.tabs.create({url: "http://example.com/addon_loaded"}); - } - - let addon = yield makeAndInstallXPI("test_uinstallurl@tests.mozilla.org", - backgroundScript, - "http://example.com/addon_loaded"); - - // look for a new tab with the uninstall url. - let uninstallPromise = BrowserTestUtils.waitForNewTab(gBrowser, "http://example.com/addon_uninstalled"); - - addon.uninstall(true); - info("uninstalled"); - - let uninstalledTab = yield uninstallPromise; - isnot(uninstalledTab, null, "opened tab with uninstall url"); - yield BrowserTestUtils.removeTab(uninstalledTab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js deleted file mode 100644 index 413f7bde6..000000000 --- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed.js +++ /dev/null @@ -1,97 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* globals recordInitialTimestamps, onlyNewItemsFilter, checkRecentlyClosed */ - -requestLongerTimeout(2); - -Services.scriptloader.loadSubScript(new URL("head_sessions.js", gTestPath).href, - this); - -add_task(function* test_sessions_get_recently_closed() { - function* openAndCloseWindow(url = "http://example.com", tabUrls) { - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, url); - yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - if (tabUrls) { - for (let url of tabUrls) { - yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url); - } - } - yield BrowserTestUtils.closeWindow(win); - } - - function background() { - Promise.all([ - browser.sessions.getRecentlyClosed(), - browser.tabs.query({active: true, currentWindow: true}), - ]).then(([recentlyClosed, tabs]) => { - browser.test.sendMessage("initialData", {recentlyClosed, currentWindowId: tabs[0].windowId}); - }); - - browser.test.onMessage.addListener((msg, filter) => { - if (msg == "check-sessions") { - browser.sessions.getRecentlyClosed(filter).then(recentlyClosed => { - browser.test.sendMessage("recentlyClosed", recentlyClosed); - }); - } - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["sessions", "tabs"], - }, - background, - }); - - // Open and close a window that will be ignored, to prove that we are removing previous entries - yield openAndCloseWindow(); - - yield extension.startup(); - - let {recentlyClosed, currentWindowId} = yield extension.awaitMessage("initialData"); - recordInitialTimestamps(recentlyClosed.map(item => item.lastModified)); - - yield openAndCloseWindow(); - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 1, currentWindowId); - - yield openAndCloseWindow("about:config", ["about:robots", "about:mozilla"]); - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - // Check for multiple tabs in most recently closed window - is(recentlyClosed[0].window.tabs.length, 3, "most recently closed window has the expected number of tabs"); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com"); - yield BrowserTestUtils.removeTab(tab); - - tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com"); - yield BrowserTestUtils.removeTab(tab); - - yield openAndCloseWindow(); - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - let finalResult = recentlyClosed.filter(onlyNewItemsFilter); - checkRecentlyClosed(finalResult, 5, currentWindowId); - - isnot(finalResult[0].window, undefined, "first item is a window"); - is(finalResult[0].tab, undefined, "first item is not a tab"); - isnot(finalResult[1].tab, undefined, "second item is a tab"); - is(finalResult[1].window, undefined, "second item is not a window"); - isnot(finalResult[2].tab, undefined, "third item is a tab"); - is(finalResult[2].window, undefined, "third item is not a window"); - isnot(finalResult[3].window, undefined, "fourth item is a window"); - is(finalResult[3].tab, undefined, "fourth item is not a tab"); - isnot(finalResult[4].window, undefined, "fifth item is a window"); - is(finalResult[4].tab, undefined, "fifth item is not a tab"); - - // test with filter - extension.sendMessage("check-sessions", {maxResults: 2}); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 2, currentWindowId); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js deleted file mode 100644 index 217c8e130..000000000 --- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_private.js +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* globals recordInitialTimestamps, onlyNewItemsFilter, checkRecentlyClosed */ - -SimpleTest.requestCompleteLog(); - -Services.scriptloader.loadSubScript(new URL("head_sessions.js", gTestPath).href, - this); - -add_task(function* test_sessions_get_recently_closed_private() { - function background() { - browser.test.onMessage.addListener((msg, filter) => { - if (msg == "check-sessions") { - browser.sessions.getRecentlyClosed(filter).then(recentlyClosed => { - browser.test.sendMessage("recentlyClosed", recentlyClosed); - }); - } - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["sessions", "tabs"], - }, - background, - }); - - // Open a private browsing window. - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - - yield extension.startup(); - - let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - let privateWinId = WindowManager.getId(privateWin); - - extension.sendMessage("check-sessions"); - let recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - recordInitialTimestamps(recentlyClosed.map(item => item.lastModified)); - - // Open and close two tabs in the private window - let tab = yield BrowserTestUtils.openNewForegroundTab(privateWin.gBrowser, "http://example.com"); - yield BrowserTestUtils.removeTab(tab); - - tab = yield BrowserTestUtils.openNewForegroundTab(privateWin.gBrowser, "http://example.com"); - yield BrowserTestUtils.removeTab(tab); - - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - checkRecentlyClosed(recentlyClosed.filter(onlyNewItemsFilter), 2, privateWinId, true); - - // Close the private window. - yield BrowserTestUtils.closeWindow(privateWin); - - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - is(recentlyClosed.filter(onlyNewItemsFilter).length, 0, "the closed private window info was not found in recently closed data"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js b/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js deleted file mode 100644 index ae0daff9a..000000000 --- a/browser/components/extensions/test/browser/browser_ext_sessions_getRecentlyClosed_tabs.js +++ /dev/null @@ -1,96 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function expectedTabInfo(tab, window) { - let browser = tab.linkedBrowser; - return { - url: browser.currentURI.spec, - title: browser.contentTitle, - favIconUrl: window.gBrowser.getIcon(tab), - }; -} - -function checkTabInfo(expected, actual) { - for (let prop in expected) { - is(actual[prop], expected[prop], `Expected value found for ${prop} of tab object.`); - } -} - -add_task(async function test_sessions_get_recently_closed_tabs() { - async function background() { - browser.test.onMessage.addListener(async msg => { - if (msg == "check-sessions") { - let recentlyClosed = await browser.sessions.getRecentlyClosed(); - browser.test.sendMessage("recentlyClosed", recentlyClosed); - } - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["sessions", "tabs"], - }, - background, - }); - - let win = await BrowserTestUtils.openNewBrowserWindow(); - await BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "about:addons"); - await BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - let expectedTabs = []; - let tab = win.gBrowser.selectedTab; - expectedTabs.push(expectedTabInfo(tab, win)); - - for (let url of ["about:robots", "about:mozilla"]) { - tab = await BrowserTestUtils.openNewForegroundTab(win.gBrowser, url); - expectedTabs.push(expectedTabInfo(tab, win)); - } - - await extension.startup(); - - // Test with a closed tab. - await BrowserTestUtils.removeTab(tab); - - extension.sendMessage("check-sessions"); - let recentlyClosed = await extension.awaitMessage("recentlyClosed"); - let tabInfo = recentlyClosed[0].tab; - let expectedTab = expectedTabs.pop(); - checkTabInfo(expectedTab, tabInfo); - - // Test with a closed window containing tabs. - await BrowserTestUtils.closeWindow(win); - - extension.sendMessage("check-sessions"); - recentlyClosed = await extension.awaitMessage("recentlyClosed"); - let tabInfos = recentlyClosed[0].window.tabs; - is(tabInfos.length, 2, "Expected number of tabs in closed window."); - for (let x = 0; x < tabInfos.length; x++) { - checkTabInfo(expectedTabs[x], tabInfos[x]); - } - - await extension.unload(); - - // Test without tabs permission. - extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["sessions"], - }, - background, - }); - - await extension.startup(); - - extension.sendMessage("check-sessions"); - recentlyClosed = await extension.awaitMessage("recentlyClosed"); - tabInfos = recentlyClosed[0].window.tabs; - is(tabInfos.length, 2, "Expected number of tabs in closed window."); - for (let tabInfo of tabInfos) { - for (let prop in expectedTabs[0]) { - is(undefined, - tabInfo[prop], - `${prop} of tab object is undefined without tabs permission.`); - } - } - - await extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_sessions_restore.js b/browser/components/extensions/test/browser/browser_ext_sessions_restore.js deleted file mode 100644 index 6f1c6cf9a..000000000 --- a/browser/components/extensions/test/browser/browser_ext_sessions_restore.js +++ /dev/null @@ -1,134 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -SimpleTest.requestCompleteLog(); - -XPCOMUtils.defineLazyModuleGetter(this, "SessionStore", - "resource:///modules/sessionstore/SessionStore.jsm"); - -add_task(function* test_sessions_restore() { - function background() { - browser.test.onMessage.addListener((msg, data) => { - if (msg == "check-sessions") { - browser.sessions.getRecentlyClosed().then(recentlyClosed => { - browser.test.sendMessage("recentlyClosed", recentlyClosed); - }); - } else if (msg == "restore") { - browser.sessions.restore(data).then(sessions => { - browser.test.sendMessage("restored", sessions); - }); - } else if (msg == "restore-reject") { - browser.sessions.restore("not-a-valid-session-id").then( - sessions => { - browser.test.fail("restore rejected with an invalid sessionId"); - }, - error => { - browser.test.assertTrue( - error.message.includes("Could not restore object using sessionId not-a-valid-session-id.")); - browser.test.sendMessage("restore-rejected"); - } - ); - } - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["sessions", "tabs"], - }, - background, - }); - - yield extension.startup(); - - let {Management: {global: {WindowManager, TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - function checkLocalTab(tab, expectedUrl) { - let realTab = TabManager.getTab(tab.id); - let tabState = JSON.parse(SessionStore.getTabState(realTab)); - is(tabState.entries[0].url, expectedUrl, "restored tab has the expected url"); - } - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.loadURI(win.gBrowser.selectedBrowser, "about:config"); - yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - for (let url of ["about:robots", "about:mozilla"]) { - yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url); - } - yield BrowserTestUtils.closeWindow(win); - - extension.sendMessage("check-sessions"); - let recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - - // Check that our expected window is the most recently closed. - is(recentlyClosed[0].window.tabs.length, 3, "most recently closed window has the expected number of tabs"); - - // Restore the window. - extension.sendMessage("restore"); - let restored = yield extension.awaitMessage("restored"); - - is(restored.length, 1, "restore returned the expected number of sessions"); - is(restored[0].window.tabs.length, 3, "restore returned a window with the expected number of tabs"); - checkLocalTab(restored[0].window.tabs[0], "about:config"); - checkLocalTab(restored[0].window.tabs[1], "about:robots"); - checkLocalTab(restored[0].window.tabs[2], "about:mozilla"); - - // Close the window again. - let window = WindowManager.getWindow(restored[0].window.id); - yield BrowserTestUtils.closeWindow(window); - - // Restore the window using the sessionId. - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - extension.sendMessage("restore", recentlyClosed[0].window.sessionId); - restored = yield extension.awaitMessage("restored"); - - is(restored.length, 1, "restore returned the expected number of sessions"); - is(restored[0].window.tabs.length, 3, "restore returned a window with the expected number of tabs"); - checkLocalTab(restored[0].window.tabs[0], "about:config"); - checkLocalTab(restored[0].window.tabs[1], "about:robots"); - checkLocalTab(restored[0].window.tabs[2], "about:mozilla"); - - // Close the window again. - window = WindowManager.getWindow(restored[0].window.id); - yield BrowserTestUtils.closeWindow(window); - - // Open and close a tab. - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots"); - yield BrowserTestUtils.removeTab(tab); - - // Restore the most recently closed item. - extension.sendMessage("restore"); - restored = yield extension.awaitMessage("restored"); - - is(restored.length, 1, "restore returned the expected number of sessions"); - tab = restored[0].tab; - ok(tab, "restore returned a tab"); - checkLocalTab(tab, "about:robots"); - - // Close the tab again. - let realTab = TabManager.getTab(tab.id); - yield BrowserTestUtils.removeTab(realTab); - - // Restore the tab using the sessionId. - extension.sendMessage("check-sessions"); - recentlyClosed = yield extension.awaitMessage("recentlyClosed"); - extension.sendMessage("restore", recentlyClosed[0].tab.sessionId); - restored = yield extension.awaitMessage("restored"); - - is(restored.length, 1, "restore returned the expected number of sessions"); - tab = restored[0].tab; - ok(tab, "restore returned a tab"); - checkLocalTab(tab, "about:robots"); - - // Close the tab again. - realTab = TabManager.getTab(tab.id); - yield BrowserTestUtils.removeTab(realTab); - - // Try to restore something with an invalid sessionId. - extension.sendMessage("restore-reject"); - restored = yield extension.awaitMessage("restore-rejected"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_simple.js b/browser/components/extensions/test/browser/browser_ext_simple.js deleted file mode 100644 index ffa00c9db..000000000 --- a/browser/components/extensions/test/browser/browser_ext_simple.js +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* test_simple() { - let extensionData = { - manifest: { - "name": "Simple extension test", - "version": "1.0", - "manifest_version": 2, - "description": "", - }, - }; - - let extension = ExtensionTestUtils.loadExtension(extensionData); - info("load complete"); - yield extension.startup(); - info("startup complete"); - yield extension.unload(); - info("extension unloaded successfully"); -}); - -add_task(function* test_background() { - function backgroundScript() { - browser.test.log("running background script"); - - browser.test.onMessage.addListener((x, y) => { - browser.test.assertEq(x, 10, "x is 10"); - browser.test.assertEq(y, 20, "y is 20"); - - browser.test.notifyPass("background test passed"); - }); - - browser.test.sendMessage("running", 1); - } - - let extensionData = { - background: "(" + backgroundScript.toString() + ")()", - manifest: { - "name": "Simple extension test", - "version": "1.0", - "manifest_version": 2, - "description": "", - }, - }; - - let extension = ExtensionTestUtils.loadExtension(extensionData); - info("load complete"); - let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]); - is(x, 1, "got correct value from extension"); - info("startup complete"); - extension.sendMessage(10, 20); - yield extension.awaitFinish(); - info("test complete"); - yield extension.unload(); - info("extension unloaded successfully"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js b/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js deleted file mode 100644 index a5541a002..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tab_runtimeConnect.js +++ /dev/null @@ -1,74 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - let messages_received = []; - - let tabId; - - browser.runtime.onConnect.addListener((port) => { - browser.test.assertTrue(!!port, "tab to background port received"); - browser.test.assertEq("tab-connection-name", port.name, "port name should be defined and equal to connectInfo.name"); - browser.test.assertTrue(!!port.sender.tab, "port.sender.tab should be defined"); - browser.test.assertEq(tabId, port.sender.tab.id, "port.sender.tab.id should be equal to the expected tabId"); - - port.onMessage.addListener((msg) => { - messages_received.push(msg); - - if (messages_received.length == 1) { - browser.test.assertEq("tab to background port message", msg, "'tab to background' port message received"); - port.postMessage("background to tab port message"); - } - - if (messages_received.length == 2) { - browser.test.assertTrue(!!msg.tabReceived, "'background to tab' reply port message received"); - browser.test.assertEq("background to tab port message", msg.tabReceived, "reply port content contains the message received"); - - browser.test.notifyPass("tabRuntimeConnect.pass"); - } - }); - }); - - browser.tabs.create({url: "tab.html"}, - (tab) => { tabId = tab.id; }); - }, - - files: { - "tab.js": function() { - let port = browser.runtime.connect({name: "tab-connection-name"}); - port.postMessage("tab to background port message"); - port.onMessage.addListener((msg) => { - port.postMessage({tabReceived: msg}); - }); - }, - "tab.html": ` - <!DOCTYPE html> - <html> - <head> - <title>test tab extension page</title> - <meta charset="utf-8"> - <script src="tab.js" async></script> - </head> - <body> - <h1>test tab extension page</h1> - </body> - </html> - `, - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabRuntimeConnect.pass"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_audio.js b/browser/components/extensions/test/browser/browser_ext_tabs_audio.js deleted file mode 100644 index f9f6956d4..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_audio.js +++ /dev/null @@ -1,203 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank?1"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank?2"); - - gBrowser.selectedTab = tab1; - - async function background() { - function promiseUpdated(tabId, attr) { - return new Promise(resolve => { - let onUpdated = (tabId_, changeInfo, tab) => { - if (tabId == tabId_ && attr in changeInfo) { - browser.tabs.onUpdated.removeListener(onUpdated); - - resolve({changeInfo, tab}); - } - }; - browser.tabs.onUpdated.addListener(onUpdated); - }); - } - - let deferred = {}; - browser.test.onMessage.addListener((message, tabId, result) => { - if (message == "change-tab-done" && deferred[tabId]) { - deferred[tabId].resolve(result); - } - }); - - function changeTab(tabId, attr, on) { - return new Promise((resolve, reject) => { - deferred[tabId] = {resolve, reject}; - browser.test.sendMessage("change-tab", tabId, attr, on); - }); - } - - - try { - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - browser.test.assertEq(tabs.length, 3, "We have three tabs"); - - for (let tab of tabs) { - // Note: We want to check that these are actual boolean values, not - // just that they evaluate as false. - browser.test.assertEq(false, tab.mutedInfo.muted, "Tab is not muted"); - browser.test.assertEq(undefined, tab.mutedInfo.reason, "Tab has no muted info reason"); - browser.test.assertEq(false, tab.audible, "Tab is not audible"); - } - - let windowId = tabs[0].windowId; - let tabIds = [tabs[1].id, tabs[2].id]; - - browser.test.log("Test initial queries for muted and audible return no tabs"); - let silent = await browser.tabs.query({windowId, audible: false}); - let audible = await browser.tabs.query({windowId, audible: true}); - let muted = await browser.tabs.query({windowId, muted: true}); - let nonMuted = await browser.tabs.query({windowId, muted: false}); - - browser.test.assertEq(3, silent.length, "Three silent tabs"); - browser.test.assertEq(0, audible.length, "No audible tabs"); - - browser.test.assertEq(0, muted.length, "No muted tabs"); - browser.test.assertEq(3, nonMuted.length, "Three non-muted tabs"); - - browser.test.log("Toggle muted and audible externally on one tab each, and check results"); - [muted, audible] = await Promise.all([ - promiseUpdated(tabIds[0], "mutedInfo"), - promiseUpdated(tabIds[1], "audible"), - changeTab(tabIds[0], "muted", true), - changeTab(tabIds[1], "audible", true), - ]); - - for (let obj of [muted.changeInfo, muted.tab]) { - browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted"); - browser.test.assertEq("user", obj.mutedInfo.reason, "Tab was muted by the user"); - } - - browser.test.assertEq(true, audible.changeInfo.audible, "Tab audible state changed"); - browser.test.assertEq(true, audible.tab.audible, "Tab is audible"); - - browser.test.log("Re-check queries. Expect one audible and one muted tab"); - silent = await browser.tabs.query({windowId, audible: false}); - audible = await browser.tabs.query({windowId, audible: true}); - muted = await browser.tabs.query({windowId, muted: true}); - nonMuted = await browser.tabs.query({windowId, muted: false}); - - browser.test.assertEq(2, silent.length, "Two silent tabs"); - browser.test.assertEq(1, audible.length, "One audible tab"); - - browser.test.assertEq(1, muted.length, "One muted tab"); - browser.test.assertEq(2, nonMuted.length, "Two non-muted tabs"); - - browser.test.assertEq(true, muted[0].mutedInfo.muted, "Tab is muted"); - browser.test.assertEq("user", muted[0].mutedInfo.reason, "Tab was muted by the user"); - - browser.test.assertEq(true, audible[0].audible, "Tab is audible"); - - browser.test.log("Toggle muted internally on two tabs, and check results"); - [nonMuted, muted] = await Promise.all([ - promiseUpdated(tabIds[0], "mutedInfo"), - promiseUpdated(tabIds[1], "mutedInfo"), - browser.tabs.update(tabIds[0], {muted: false}), - browser.tabs.update(tabIds[1], {muted: true}), - ]); - - for (let obj of [nonMuted.changeInfo, nonMuted.tab]) { - browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted"); - } - for (let obj of [muted.changeInfo, muted.tab]) { - browser.test.assertEq(true, obj.mutedInfo.muted, "Tab is muted"); - } - - for (let obj of [nonMuted.changeInfo, nonMuted.tab, muted.changeInfo, muted.tab]) { - browser.test.assertEq("extension", obj.mutedInfo.reason, "Mute state changed by extension"); - - // FIXME: browser.runtime.id is currently broken. - browser.test.assertEq(browser.i18n.getMessage("@@extension_id"), - obj.mutedInfo.extensionId, - "Mute state changed by extension"); - } - - browser.test.log("Test that mutedInfo is preserved by sessionstore"); - let tab = await changeTab(tabIds[1], "duplicate").then(browser.tabs.get); - - browser.test.assertEq(true, tab.mutedInfo.muted, "Tab is muted"); - - browser.test.assertEq("extension", tab.mutedInfo.reason, "Mute state changed by extension"); - - // FIXME: browser.runtime.id is currently broken. - browser.test.assertEq(browser.i18n.getMessage("@@extension_id"), - tab.mutedInfo.extensionId, - "Mute state changed by extension"); - - browser.test.log("Unmute externally, and check results"); - [nonMuted] = await Promise.all([ - promiseUpdated(tabIds[1], "mutedInfo"), - changeTab(tabIds[1], "muted", false), - browser.tabs.remove(tab.id), - ]); - - for (let obj of [nonMuted.changeInfo, nonMuted.tab]) { - browser.test.assertEq(false, obj.mutedInfo.muted, "Tab is not muted"); - browser.test.assertEq("user", obj.mutedInfo.reason, "Mute state changed by user"); - } - - browser.test.notifyPass("tab-audio"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("tab-audio"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - extension.onMessage("change-tab", (tabId, attr, on) => { - let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let tab = TabManager.getTab(tabId); - - if (attr == "muted") { - // Ideally we'd simulate a click on the tab audio icon for this, but the - // handler relies on CSS :hover states, which are complicated and fragile - // to simulate. - if (tab.muted != on) { - tab.toggleMuteAudio(); - } - } else if (attr == "audible") { - let browser = tab.linkedBrowser; - if (on) { - browser.audioPlaybackStarted(); - } else { - browser.audioPlaybackStopped(); - } - } else if (attr == "duplicate") { - // This is a bit of a hack. It won't be necessary once we have - // `tabs.duplicate`. - let newTab = gBrowser.duplicateTab(tab); - BrowserTestUtils.waitForEvent(newTab, "SSTabRestored", () => true).then(() => { - extension.sendMessage("change-tab-done", tabId, TabManager.getId(newTab)); - }); - return; - } - - extension.sendMessage("change-tab-done", tabId); - }); - - yield extension.startup(); - - yield extension.awaitFinish("tab-audio"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js b/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js deleted file mode 100644 index 1491a19ab..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_captureVisibleTab.js +++ /dev/null @@ -1,155 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* runTest(options) { - options.neutral = [0xaa, 0xaa, 0xaa]; - - let html = ` - <!DOCTYPE html> - <html lang="en"> - <head><meta charset="UTF-8"></head> - <body style="background-color: rgb(${options.color})"> - <!-- Fill most of the image with a neutral color to test edge-to-edge scaling. --> - <div style="position: absolute; - left: 2px; - right: 2px; - top: 2px; - bottom: 2px; - background: rgb(${options.neutral});"></div> - </body> - </html> - `; - - let url = `data:text/html,${encodeURIComponent(html)}`; - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, true); - - tab.linkedBrowser.fullZoom = options.fullZoom; - - async function background(options) { - browser.test.log(`Test color ${options.color} at fullZoom=${options.fullZoom}`); - - try { - let [tab] = await browser.tabs.query({currentWindow: true, active: true}); - - let [jpeg, png, ...pngs] = await Promise.all([ - browser.tabs.captureVisibleTab(tab.windowId, {format: "jpeg", quality: 95}), - browser.tabs.captureVisibleTab(tab.windowId, {format: "png", quality: 95}), - browser.tabs.captureVisibleTab(tab.windowId, {quality: 95}), - browser.tabs.captureVisibleTab(tab.windowId), - ]); - - browser.test.assertTrue(pngs.every(url => url == png), "All PNGs are identical"); - - browser.test.assertTrue(jpeg.startsWith("data:image/jpeg;base64,"), "jpeg is JPEG"); - browser.test.assertTrue(png.startsWith("data:image/png;base64,"), "png is PNG"); - - let promises = [jpeg, png].map(url => new Promise(resolve => { - let img = new Image(); - img.src = url; - img.onload = () => resolve(img); - })); - - [jpeg, png] = await Promise.all(promises); - let tabDims = `${tab.width}\u00d7${tab.height}`; - - let images = {jpeg, png}; - for (let format of Object.keys(images)) { - let img = images[format]; - - let dims = `${img.width}\u00d7${img.height}`; - browser.test.assertEq(tabDims, dims, `${format} dimensions are correct`); - - let canvas = document.createElement("canvas"); - canvas.width = img.width; - canvas.height = img.height; - canvas.mozOpaque = true; - - let ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0); - - // Check the colors of the first and last pixels of the image, to make - // sure we capture the entire frame, and scale it correctly. - let coords = [ - {x: 0, y: 0, - color: options.color}, - {x: img.width - 1, - y: img.height - 1, - color: options.color}, - {x: img.width / 2 | 0, - y: img.height / 2 | 0, - color: options.neutral}, - ]; - - for (let {x, y, color} of coords) { - let imageData = ctx.getImageData(x, y, 1, 1).data; - - if (format == "png") { - browser.test.assertEq(`rgba(${color},255)`, `rgba(${[...imageData]})`, `${format} image color is correct at (${x}, ${y})`); - } else { - // Allow for some deviation in JPEG version due to lossy compression. - const SLOP = 3; - - browser.test.log(`Testing ${format} image color at (${x}, ${y}), have rgba(${[...imageData]}), expecting approx. rgba(${color},255)`); - - browser.test.assertTrue(Math.abs(color[0] - imageData[0]) <= SLOP, `${format} image color.red is correct at (${x}, ${y})`); - browser.test.assertTrue(Math.abs(color[1] - imageData[1]) <= SLOP, `${format} image color.green is correct at (${x}, ${y})`); - browser.test.assertTrue(Math.abs(color[2] - imageData[2]) <= SLOP, `${format} image color.blue is correct at (${x}, ${y})`); - browser.test.assertEq(255, imageData[3], `${format} image color.alpha is correct at (${x}, ${y})`); - } - } - } - - browser.test.notifyPass("captureVisibleTab"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("captureVisibleTab"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["<all_urls>"], - }, - - background: `(${background})(${JSON.stringify(options)})`, - }); - - yield extension.startup(); - - yield extension.awaitFinish("captureVisibleTab"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -} - -add_task(function* testCaptureVisibleTab() { - yield runTest({color: [0, 0, 0], fullZoom: 1}); - - yield runTest({color: [0, 0, 0], fullZoom: 2}); - - yield runTest({color: [0, 0, 0], fullZoom: 0.5}); - - yield runTest({color: [255, 255, 255], fullZoom: 1}); -}); - -add_task(function* testCaptureVisibleTabPermissions() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background() { - browser.test.assertFalse("captureVisibleTab" in browser.tabs, - 'Extension without "<all_tabs>" permission should not have access to captureVisibleTab'); - browser.test.notifyPass("captureVisibleTabPermissions"); - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("captureVisibleTabPermissions"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js b/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js deleted file mode 100644 index dc0647e3c..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_cookieStoreId.js +++ /dev/null @@ -1,156 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* setup() { - // make sure userContext is enabled. - return SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true], - ]}); -}); - -add_task(function* () { - info("Start testing tabs.create with cookieStoreId"); - - let testCases = [ - // No private window - {privateTab: false, cookieStoreId: null, success: true, expectedCookieStoreId: "firefox-default"}, - {privateTab: false, cookieStoreId: "firefox-default", success: true, expectedCookieStoreId: "firefox-default"}, - {privateTab: false, cookieStoreId: "firefox-container-1", success: true, expectedCookieStoreId: "firefox-container-1"}, - {privateTab: false, cookieStoreId: "firefox-container-2", success: true, expectedCookieStoreId: "firefox-container-2"}, - {privateTab: false, cookieStoreId: "firefox-container-42", failure: "exist"}, - {privateTab: false, cookieStoreId: "firefox-private", failure: "defaultToPrivate"}, - {privateTab: false, cookieStoreId: "wow", failure: "illegal"}, - - // Private window - {privateTab: true, cookieStoreId: null, success: true, expectedCookieStoreId: "firefox-private"}, - {privateTab: true, cookieStoreId: "firefox-private", success: true, expectedCookieStoreId: "firefox-private"}, - {privateTab: true, cookieStoreId: "firefox-default", failure: "privateToDefault"}, - {privateTab: true, cookieStoreId: "firefox-container-1", failure: "privateToDefault"}, - {privateTab: true, cookieStoreId: "wow", failure: "illegal"}, - ]; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs", "cookies"], - }, - - background: function() { - function testTab(data, tab) { - browser.test.assertTrue(data.success, "we want a success"); - browser.test.assertTrue(!!tab, "we have a tab"); - browser.test.assertEq(data.expectedCookieStoreId, tab.cookieStoreId, "tab should have the correct cookieStoreId"); - } - - async function runTest(data) { - try { - // Tab Creation - let tab; - try { - tab = await browser.tabs.create({ - windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId, - cookieStoreId: data.cookieStoreId, - }); - - browser.test.assertTrue(!data.failure, "we want a success"); - } catch (error) { - browser.test.assertTrue(!!data.failure, "we want a failure"); - - if (data.failure == "illegal") { - browser.test.assertTrue(/Illegal cookieStoreId/.test(error.message), - "runtime.lastError should report the expected error message"); - } else if (data.failure == "defaultToPrivate") { - browser.test.assertTrue("Illegal to set private cookieStorageId in a non private window", - error.message, - "runtime.lastError should report the expected error message"); - } else if (data.failure == "privateToDefault") { - browser.test.assertTrue("Illegal to set non private cookieStorageId in a private window", - error.message, - "runtime.lastError should report the expected error message"); - } else if (data.failure == "exist") { - browser.test.assertTrue(/No cookie store exists/.test(error.message), - "runtime.lastError should report the expected error message"); - } else { - browser.test.fail("The test is broken"); - } - - browser.test.sendMessage("test-done"); - return; - } - - // Tests for tab creation - testTab(data, tab); - - { - // Tests for tab querying - let [tab] = await browser.tabs.query({ - windowId: data.privateTab ? this.privateWindowId : this.defaultWindowId, - cookieStoreId: data.cookieStoreId, - }); - - browser.test.assertTrue(tab != undefined, "Tab found!"); - testTab(data, tab); - } - - let stores = await browser.cookies.getAllCookieStores(); - - let store = stores.find(store => store.id === tab.cookieStoreId); - browser.test.assertTrue(!!store, "We have a store for this tab."); - - await browser.tabs.remove(tab.id); - - browser.test.sendMessage("test-done"); - } catch (e) { - browser.test.fail("An exception has been thrown"); - } - } - - async function initialize() { - let win = await browser.windows.create({incognito: true}); - this.privateWindowId = win.id; - - win = await browser.windows.create({incognito: false}); - this.defaultWindowId = win.id; - - browser.test.sendMessage("ready"); - } - - async function shutdown() { - await browser.windows.remove(this.privateWindowId); - await browser.windows.remove(this.defaultWindowId); - browser.test.sendMessage("gone"); - } - - // Waiting for messages - browser.test.onMessage.addListener((msg, data) => { - if (msg == "be-ready") { - initialize(); - } else if (msg == "test") { - runTest(data); - } else { - browser.test.assertTrue("finish", msg, "Shutting down"); - shutdown(); - } - }); - }, - }); - - yield extension.startup(); - - info("Tests must be ready..."); - extension.sendMessage("be-ready"); - yield extension.awaitMessage("ready"); - info("Tests are ready to run!"); - - for (let test of testCases) { - info(`test tab.create with cookieStoreId: "${test.cookieStoreId}"`); - extension.sendMessage("test", test); - yield extension.awaitMessage("test-done"); - } - - info("Waiting for shutting down..."); - extension.sendMessage("finish"); - yield extension.awaitMessage("gone"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_create.js b/browser/components/extensions/test/browser/browser_ext_tabs_create.js deleted file mode 100644 index 8bc5a68a2..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_create.js +++ /dev/null @@ -1,166 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots"); - gBrowser.selectedTab = tab; - - // TODO: Multiple windows. - - // Using pre-loaded new tab pages interferes with onUpdated events. - // It probably shouldn't. - SpecialPowers.setBoolPref("browser.newtab.preload", false); - registerCleanupFunction(() => { - SpecialPowers.clearUserPref("browser.newtab.preload"); - }); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "background": {"page": "bg/background.html"}, - }, - - files: { - "bg/blank.html": `<html><head><meta charset="utf-8"></head></html>`, - - "bg/background.html": `<html><head> - <meta charset="utf-8"> - <script src="background.js"></script> - </head></html>`, - - "bg/background.js": function() { - let activeTab; - let activeWindow; - - function runTests() { - const DEFAULTS = { - index: 2, - windowId: activeWindow, - active: true, - pinned: false, - url: "about:newtab", - }; - - let tests = [ - { - create: {url: "http://example.com/"}, - result: {url: "http://example.com/"}, - }, - { - create: {url: "blank.html"}, - result: {url: browser.runtime.getURL("bg/blank.html")}, - }, - { - create: {}, - result: {url: "about:newtab"}, - }, - { - create: {active: false}, - result: {active: false}, - }, - { - create: {active: true}, - result: {active: true}, - }, - { - create: {pinned: true}, - result: {pinned: true, index: 0}, - }, - { - create: {pinned: true, active: true}, - result: {pinned: true, active: true, index: 0}, - }, - { - create: {pinned: true, active: false}, - result: {pinned: true, active: false, index: 0}, - }, - { - create: {index: 1}, - result: {index: 1}, - }, - { - create: {index: 1, active: false}, - result: {index: 1, active: false}, - }, - { - create: {windowId: activeWindow}, - result: {windowId: activeWindow}, - }, - ]; - - async function nextTest() { - if (!tests.length) { - browser.test.notifyPass("tabs.create"); - return; - } - - let test = tests.shift(); - let expected = Object.assign({}, DEFAULTS, test.result); - - browser.test.log(`Testing tabs.create(${JSON.stringify(test.create)}), expecting ${JSON.stringify(test.result)}`); - - let updatedPromise = new Promise(resolve => { - let onUpdated = (changedTabId, changed) => { - if (changed.url) { - browser.tabs.onUpdated.removeListener(onUpdated); - resolve({tabId: changedTabId, url: changed.url}); - } - }; - browser.tabs.onUpdated.addListener(onUpdated); - }); - - let createdPromise = new Promise(resolve => { - let onCreated = tab => { - browser.test.assertTrue("id" in tab, `Expected tabs.onCreated callback to receive tab object`); - resolve(); - }; - browser.tabs.onCreated.addListener(onCreated); - }); - - let [tab] = await Promise.all([ - browser.tabs.create(test.create), - createdPromise, - ]); - let tabId = tab.id; - - for (let key of Object.keys(expected)) { - if (key === "url") { - // FIXME: This doesn't get updated until later in the load cycle. - continue; - } - - browser.test.assertEq(expected[key], tab[key], `Expected value for tab.${key}`); - } - - let updated = await updatedPromise; - browser.test.assertEq(tabId, updated.tabId, `Expected value for tab.id`); - browser.test.assertEq(expected.url, updated.url, `Expected value for tab.url`); - - await browser.tabs.remove(tabId); - await browser.tabs.update(activeTab, {active: true}); - - nextTest(); - } - - nextTest(); - } - - browser.tabs.query({active: true, currentWindow: true}, tabs => { - activeTab = tabs[0].id; - activeWindow = tabs[0].windowId; - - runTests(); - }); - }, - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.create"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); - diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js b/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js deleted file mode 100644 index 49938bf22..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_create_invalid_url.js +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* testTabsCreateInvalidURL(tabsCreateURL) { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.test.sendMessage("ready"); - browser.test.onMessage.addListener((msg, tabsCreateURL) => { - browser.tabs.create({url: tabsCreateURL}, (tab) => { - browser.test.assertEq(undefined, tab, "on error tab should be undefined"); - browser.test.assertTrue(/Illegal URL/.test(browser.runtime.lastError.message), - "runtime.lastError should report the expected error message"); - - // Remove the opened tab is any. - if (tab) { - browser.tabs.remove(tab.id); - } - browser.test.sendMessage("done"); - }); - }); - }, - }); - - yield extension.startup(); - - yield extension.awaitMessage("ready"); - - info(`test tab.create on invalid URL "${tabsCreateURL}"`); - - extension.sendMessage("start", tabsCreateURL); - yield extension.awaitMessage("done"); - - yield extension.unload(); -} - -add_task(function* () { - info("Start testing tabs.create on invalid URLs"); - - let dataURLPage = `data:text/html, - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - <body> - <h1>data url page</h1> - </body> - </html>`; - - let testCases = [ - {tabsCreateURL: "about:addons"}, - {tabsCreateURL: "javascript:console.log('tabs.update execute javascript')"}, - {tabsCreateURL: dataURLPage}, - ]; - - for (let {tabsCreateURL} of testCases) { - yield* testTabsCreateInvalidURL(tabsCreateURL); - } - - info("done"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js b/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js deleted file mode 100644 index f28606001..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_detectLanguage.js +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testDetectLanguage() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: async function() { - const BASE_PATH = "browser/browser/components/extensions/test/browser"; - - function loadTab(url) { - return browser.tabs.create({url}); - } - - try { - let tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_ja.html`); - let lang = await browser.tabs.detectLanguage(tab.id); - browser.test.assertEq("ja", lang, "Japanese document should be detected as Japanese"); - await browser.tabs.remove(tab.id); - - tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_fr_en.html`); - lang = await browser.tabs.detectLanguage(tab.id); - browser.test.assertEq("fr", lang, "French/English document should be detected as primarily French"); - await browser.tabs.remove(tab.id); - - tab = await loadTab(`http://example.co.jp/${BASE_PATH}/file_language_tlh.html`); - lang = await browser.tabs.detectLanguage(tab.id); - browser.test.assertEq("und", lang, "Klingon document should not be detected, should return 'und'"); - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("detectLanguage"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("detectLanguage"); - } - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("detectLanguage"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js b/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js deleted file mode 100644 index c4b0ffd2d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_duplicate.js +++ /dev/null @@ -1,146 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testDuplicateTab() { - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - lastFocusedWindow: true, - }, function(tabs) { - let source = tabs[1]; - // By moving it 0, we check that the new tab is created next - // to the existing one. - browser.tabs.move(source.id, {index: 0}, () => { - browser.tabs.duplicate(source.id, (tab) => { - browser.test.assertEq("http://example.net/", tab.url); - // Should be the second tab, next to the one duplicated. - browser.test.assertEq(1, tab.index); - // Should be selected by default. - browser.test.assertTrue(tab.selected); - browser.test.notifyPass("tabs.duplicate"); - }); - }); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.duplicate"); - yield extension.unload(); - - while (gBrowser.tabs[0].linkedBrowser.currentURI.spec === "http://example.net/") { - yield BrowserTestUtils.removeTab(gBrowser.tabs[0]); - } -}); - -add_task(function* testDuplicateTabLazily() { - async function background() { - let tabLoadComplete = new Promise(resolve => { - browser.test.onMessage.addListener((message, tabId, result) => { - if (message == "duplicate-tab-done") { - resolve(tabId); - } - }); - }); - - function awaitLoad(tabId) { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) { - if (tabId == tabId_ && changed.status == "complete") { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - } - - try { - let url = "http://example.com/browser/browser/components/extensions/test/browser/file_dummy.html"; - let tab = await browser.tabs.create({url}); - let startTabId = tab.id; - - await awaitLoad(startTabId); - browser.test.sendMessage("duplicate-tab", startTabId); - - let unloadedTabId = await tabLoadComplete; - let loadedtab = await browser.tabs.get(startTabId); - browser.test.assertEq("Dummy test page", loadedtab.title, "Title should be returned for loaded pages"); - browser.test.assertEq("complete", loadedtab.status, "Tab status should be complete for loaded pages"); - - let unloadedtab = await browser.tabs.get(unloadedTabId); - browser.test.assertEq("Dummy test page", unloadedtab.title, "Title should be returned after page has been unloaded"); - - await browser.tabs.remove([tab.id, unloadedTabId]); - browser.test.notifyPass("tabs.hasCorrectTabTitle"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("tabs.hasCorrectTabTitle"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - extension.onMessage("duplicate-tab", tabId => { - let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let tab = TabManager.getTab(tabId); - // This is a bit of a hack to load a tab in the background. - let newTab = gBrowser.duplicateTab(tab, false); - - BrowserTestUtils.waitForEvent(newTab, "SSTabRestored", () => true).then(() => { - extension.sendMessage("duplicate-tab-done", TabManager.getId(newTab)); - }); - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.hasCorrectTabTitle"); - yield extension.unload(); -}); - -add_task(function* testDuplicatePinnedTab() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - gBrowser.pinTab(tab); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - lastFocusedWindow: true, - }, function(tabs) { - // Duplicate the pinned tab, example.net. - browser.tabs.duplicate(tabs[0].id, (tab) => { - browser.test.assertEq("http://example.net/", tab.url); - // Should be the second tab, next to the one duplicated. - browser.test.assertEq(1, tab.index); - // Should be pinned. - browser.test.assertTrue(tab.pinned); - browser.test.notifyPass("tabs.duplicate.pinned"); - }); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.duplicate.pinned"); - yield extension.unload(); - - while (gBrowser.tabs[0].linkedBrowser.currentURI.spec === "http://example.net/") { - yield BrowserTestUtils.removeTab(gBrowser.tabs[0]); - } -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_events.js b/browser/components/extensions/test/browser/browser_ext_tabs_events.js deleted file mode 100644 index 75dea40fd..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_events.js +++ /dev/null @@ -1,280 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testTabEvents() { - async function background() { - let events = []; - browser.tabs.onCreated.addListener(tab => { - events.push({type: "onCreated", tab}); - }); - - browser.tabs.onAttached.addListener((tabId, info) => { - events.push(Object.assign({type: "onAttached", tabId}, info)); - }); - - browser.tabs.onDetached.addListener((tabId, info) => { - events.push(Object.assign({type: "onDetached", tabId}, info)); - }); - - browser.tabs.onRemoved.addListener((tabId, info) => { - events.push(Object.assign({type: "onRemoved", tabId}, info)); - }); - - browser.tabs.onMoved.addListener((tabId, info) => { - events.push(Object.assign({type: "onMoved", tabId}, info)); - }); - - async function expectEvents(names) { - browser.test.log(`Expecting events: ${names.join(", ")}`); - - await new Promise(resolve => setTimeout(resolve, 0)); - - browser.test.assertEq(names.length, events.length, "Got expected number of events"); - for (let [i, name] of names.entries()) { - browser.test.assertEq(name, i in events && events[i].type, - `Got expected ${name} event`); - } - return events.splice(0); - } - - try { - browser.test.log("Create second browser window"); - - let windows = await Promise.all([ - browser.windows.getCurrent(), - browser.windows.create({url: "about:blank"}), - ]); - - let windowId = windows[0].id; - let otherWindowId = windows[1].id; - - let [created] = await expectEvents(["onCreated"]); - let initialTab = created.tab; - - - browser.test.log("Create tab in window 1"); - let tab = await browser.tabs.create({windowId, index: 0, url: "about:blank"}); - let oldIndex = tab.index; - browser.test.assertEq(0, oldIndex, "Tab has the expected index"); - - [created] = await expectEvents(["onCreated"]); - browser.test.assertEq(tab.id, created.tab.id, "Got expected tab ID"); - browser.test.assertEq(oldIndex, created.tab.index, "Got expected tab index"); - - - browser.test.log("Move tab to window 2"); - await browser.tabs.move([tab.id], {windowId: otherWindowId, index: 0}); - - let [detached, attached] = await expectEvents(["onDetached", "onAttached"]); - browser.test.assertEq(oldIndex, detached.oldPosition, "Expected old index"); - browser.test.assertEq(windowId, detached.oldWindowId, "Expected old window ID"); - - browser.test.assertEq(0, attached.newPosition, "Expected new index"); - browser.test.assertEq(otherWindowId, attached.newWindowId, "Expected new window ID"); - - - browser.test.log("Move tab within the same window"); - let [moved] = await browser.tabs.move([tab.id], {index: 1}); - browser.test.assertEq(1, moved.index, "Expected new index"); - - [moved] = await expectEvents(["onMoved"]); - browser.test.assertEq(tab.id, moved.tabId, "Expected tab ID"); - browser.test.assertEq(0, moved.fromIndex, "Expected old index"); - browser.test.assertEq(1, moved.toIndex, "Expected new index"); - browser.test.assertEq(otherWindowId, moved.windowId, "Expected window ID"); - - - browser.test.log("Remove tab"); - await browser.tabs.remove(tab.id); - let [removed] = await expectEvents(["onRemoved"]); - - browser.test.assertEq(tab.id, removed.tabId, "Expected removed tab ID"); - browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID"); - // Note: We want to test for the actual boolean value false here. - browser.test.assertEq(false, removed.isWindowClosing, "Expected isWindowClosing value"); - - - browser.test.log("Close second window"); - await browser.windows.remove(otherWindowId); - [removed] = await expectEvents(["onRemoved"]); - browser.test.assertEq(initialTab.id, removed.tabId, "Expected removed tab ID"); - browser.test.assertEq(otherWindowId, removed.windowId, "Expected removed tab window ID"); - browser.test.assertEq(true, removed.isWindowClosing, "Expected isWindowClosing value"); - - - browser.test.log("Create additional tab in window 1"); - tab = await browser.tabs.create({windowId, url: "about:blank"}); - await expectEvents(["onCreated"]); - - - browser.test.log("Create a new window, adopting the new tab"); - // We have to explicitly wait for the event here, since its timing is - // not predictable. - let promiseAttached = new Promise(resolve => { - browser.tabs.onAttached.addListener(function listener(tabId) { - browser.tabs.onAttached.removeListener(listener); - resolve(); - }); - }); - - let [window] = await Promise.all([ - browser.windows.create({tabId: tab.id}), - promiseAttached, - ]); - - [detached, attached] = await expectEvents(["onDetached", "onAttached"]); - - browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID"); - - browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID"); - browser.test.assertEq(0, attached.newPosition, "Expected onAttached new index"); - browser.test.assertEq(window.id, attached.newWindowId, - "Expected onAttached new window id"); - - browser.test.log("Close the new window"); - await browser.windows.remove(window.id); - - browser.test.notifyPass("tabs-events"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("tabs-events"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs-events"); - yield extension.unload(); -}); - -add_task(function* testTabEventsSize() { - function background() { - function sendSizeMessages(tab, type) { - browser.test.sendMessage(`${type}-dims`, {width: tab.width, height: tab.height}); - } - - browser.tabs.onCreated.addListener(tab => { - sendSizeMessages(tab, "on-created"); - }); - - browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { - if (changeInfo.status == "complete") { - sendSizeMessages(tab, "on-updated"); - } - }); - - browser.test.onMessage.addListener(async (msg, arg) => { - if (msg === "create-tab") { - let tab = await browser.tabs.create({url: "http://example.com/"}); - sendSizeMessages(tab, "create"); - browser.test.sendMessage("created-tab-id", tab.id); - } else if (msg === "update-tab") { - let tab = await browser.tabs.update(arg, {url: "http://example.org/"}); - sendSizeMessages(tab, "update"); - } else if (msg === "remove-tab") { - browser.tabs.remove(arg); - browser.test.sendMessage("tab-removed"); - } - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - background, - }); - - const RESOLUTION_PREF = "layout.css.devPixelsPerPx"; - registerCleanupFunction(() => { - SpecialPowers.clearUserPref(RESOLUTION_PREF); - }); - - function checkDimensions(dims, type) { - is(dims.width, gBrowser.selectedBrowser.clientWidth, `tab from ${type} reports expected width`); - is(dims.height, gBrowser.selectedBrowser.clientHeight, `tab from ${type} reports expected height`); - } - - yield Promise.all([extension.startup(), extension.awaitMessage("ready")]); - - for (let resolution of [2, 1]) { - SpecialPowers.setCharPref(RESOLUTION_PREF, String(resolution)); - is(window.devicePixelRatio, resolution, "window has the required resolution"); - - extension.sendMessage("create-tab"); - let tabId = yield extension.awaitMessage("created-tab-id"); - - checkDimensions(yield extension.awaitMessage("create-dims"), "create"); - checkDimensions(yield extension.awaitMessage("on-created-dims"), "onCreated"); - checkDimensions(yield extension.awaitMessage("on-updated-dims"), "onUpdated"); - - extension.sendMessage("update-tab", tabId); - - checkDimensions(yield extension.awaitMessage("update-dims"), "update"); - checkDimensions(yield extension.awaitMessage("on-updated-dims"), "onUpdated"); - - extension.sendMessage("remove-tab", tabId); - yield extension.awaitMessage("tab-removed"); - } - - yield extension.unload(); - SpecialPowers.clearUserPref(RESOLUTION_PREF); -}); - -add_task(function* testTabRemovalEvent() { - async function background() { - function awaitLoad(tabId) { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) { - if (tabId == tabId_ && changed.status == "complete") { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - } - - chrome.tabs.onRemoved.addListener((tabId, info) => { - browser.test.log("Make sure the removed tab is not available in the tabs.query callback."); - chrome.tabs.query({}, tabs => { - for (let tab of tabs) { - browser.test.assertTrue(tab.id != tabId, "Tab query should not include removed tabId"); - } - browser.test.notifyPass("tabs-events"); - }); - }); - - try { - let url = "http://example.com/browser/browser/components/extensions/test/browser/context.html"; - let tab = await browser.tabs.create({url: url}); - await awaitLoad(tab.id); - - await browser.tabs.remove(tab.id); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("tabs-events"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs-events"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js deleted file mode 100644 index 5a15f2e39..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript.js +++ /dev/null @@ -1,234 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testExecuteScript() { - let {MessageChannel} = Cu.import("resource://gre/modules/MessageChannel.jsm", {}); - - function countMM(messageManagerMap) { - let count = 0; - // List of permanent message managers in the main process. We should not - // count them in the test because MessageChannel unsubscribes when the - // message manager closes, which never happens to these, of course. - let globalMMs = [ - Services.mm, - Services.ppmm, - Services.ppmm.getChildAt(0), - ]; - for (let mm of messageManagerMap.keys()) { - // Sanity check: mm is a message manager. - try { - mm.QueryInterface(Ci.nsIMessageSender); - } catch (e) { - mm.QueryInterface(Ci.nsIMessageBroadcaster); - } - if (!globalMMs.includes(mm)) { - ++count; - } - } - return count; - } - - let messageManagersSize = countMM(MessageChannel.messageManagers); - let responseManagersSize = countMM(MessageChannel.responseManagers); - - const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/"; - const URL = BASE + "file_iframe_document.html"; - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL, true); - - async function background() { - try { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - let frames = await browser.webNavigation.getAllFrames({tabId: tab.id}); - - browser.test.log(`FRAMES: ${frames[1].frameId} ${JSON.stringify(frames)}\n`); - await Promise.all([ - browser.tabs.executeScript({ - code: "42", - }).then(result => { - browser.test.assertEq(1, result.length, "Expected one callback result"); - browser.test.assertEq(42, result[0], "Expected callback result"); - }), - - browser.tabs.executeScript({ - file: "script.js", - code: "42", - }).then(result => { - browser.test.fail("Expected not to be able to execute a script with both file and code"); - }, error => { - browser.test.assertTrue(/a 'code' or a 'file' property, but not both/.test(error.message), - "Got expected error"); - }), - - browser.tabs.executeScript({ - file: "script.js", - }).then(result => { - browser.test.assertEq(1, result.length, "Expected one callback result"); - browser.test.assertEq(undefined, result[0], "Expected callback result"); - }), - - browser.tabs.executeScript({ - file: "script2.js", - }).then(result => { - browser.test.assertEq(1, result.length, "Expected one callback result"); - browser.test.assertEq(27, result[0], "Expected callback result"); - }), - - browser.tabs.executeScript({ - code: "location.href;", - allFrames: true, - }).then(result => { - browser.test.assertTrue(Array.isArray(result), "Result is an array"); - - browser.test.assertEq(2, result.length, "Result has correct length"); - - browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "First result is correct"); - browser.test.assertEq("http://mochi.test:8888/", result[1], "Second result is correct"); - }), - - browser.tabs.executeScript({ - code: "location.href;", - runAt: "document_end", - }).then(result => { - browser.test.assertEq(1, result.length, "Expected callback result"); - browser.test.assertEq("string", typeof result[0], "Result is a string"); - - browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "Result is correct"); - }), - - browser.tabs.executeScript({ - code: "window", - }).then(result => { - browser.test.fail("Expected error when returning non-structured-clonable object"); - }, error => { - browser.test.assertEq("Script returned non-structured-clonable data", - error.message, "Got expected error"); - }), - - browser.tabs.executeScript({ - code: "Promise.resolve(window)", - }).then(result => { - browser.test.fail("Expected error when returning non-structured-clonable object"); - }, error => { - browser.test.assertEq("Script returned non-structured-clonable data", - error.message, "Got expected error"); - }), - - browser.tabs.executeScript({ - frameId: Number.MAX_SAFE_INTEGER, - code: "42", - }).then(result => { - browser.test.fail("Expected error when specifying invalid frame ID"); - }, error => { - let details = { - frame_id: Number.MAX_SAFE_INTEGER, - matchesHost: ["http://mochi.test/", "http://example.com/"], - }; - browser.test.assertEq(`No window matching ${JSON.stringify(details)}`, - error.message, "Got expected error"); - }), - - browser.tabs.create({url: "http://example.net/", active: false}).then(async tab => { - await browser.tabs.executeScript(tab.id, { - code: "42", - }).then(result => { - browser.test.fail("Expected error when trying to execute on invalid domain"); - }, error => { - let details = { - matchesHost: ["http://mochi.test/", "http://example.com/"], - }; - browser.test.assertEq(`No window matching ${JSON.stringify(details)}`, - error.message, "Got expected error"); - }); - - await browser.tabs.remove(tab.id); - }), - - browser.tabs.executeScript({ - code: "Promise.resolve(42)", - }).then(result => { - browser.test.assertEq(42, result[0], "Got expected promise resolution value as result"); - }), - - browser.tabs.executeScript({ - code: "location.href;", - runAt: "document_end", - allFrames: true, - }).then(result => { - browser.test.assertTrue(Array.isArray(result), "Result is an array"); - - browser.test.assertEq(2, result.length, "Result has correct length"); - - browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), "First result is correct"); - browser.test.assertEq("http://mochi.test:8888/", result[1], "Second result is correct"); - }), - - browser.tabs.executeScript({ - code: "location.href;", - frameId: frames[0].frameId, - }).then(result => { - browser.test.assertEq(1, result.length, "Expected one result"); - browser.test.assertTrue(/\/file_iframe_document\.html$/.test(result[0]), `Result for frameId[0] is correct: ${result[0]}`); - }), - - browser.tabs.executeScript({ - code: "location.href;", - frameId: frames[1].frameId, - }).then(result => { - browser.test.assertEq(1, result.length, "Expected one result"); - browser.test.assertEq("http://mochi.test:8888/", result[0], "Result for frameId[1] is correct"); - }), - - browser.tabs.create({url: "http://example.com/"}).then(async tab => { - let result = await browser.tabs.executeScript(tab.id, {code: "location.href"}); - - browser.test.assertEq("http://example.com/", result[0], "Script executed correctly in new tab"); - - await browser.tabs.remove(tab.id); - }), - - new Promise(resolve => { - browser.runtime.onMessage.addListener(message => { - browser.test.assertEq("script ran", message, "Expected runtime message"); - resolve(); - }); - }), - ]); - - browser.test.notifyPass("executeScript"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("executeScript"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/", "http://example.com/", "webNavigation"], - }, - - background, - - files: { - "script.js": function() { - browser.runtime.sendMessage("script ran"); - }, - - "script2.js": "27", - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("executeScript"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); - - // Make sure that we're not holding on to references to closed message - // managers. - is(countMM(MessageChannel.messageManagers), messageManagersSize, "Message manager count"); - is(countMM(MessageChannel.responseManagers), responseManagersSize, "Response manager count"); - is(MessageChannel.pendingResponses.size, 0, "Pending response count"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js deleted file mode 100644 index d11354ead..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_bad.js +++ /dev/null @@ -1,217 +0,0 @@ -"use strict"; - -// This is a pretty terrible hack, but it's the best we can do until we -// support |executeScript| callbacks and |lastError|. -function* testHasNoPermission(params) { - let contentSetup = params.contentSetup || (() => Promise.resolve()); - - async function background(contentSetup) { - browser.runtime.onMessage.addListener((msg, sender) => { - browser.test.assertEq(msg, "second script ran", "second script ran"); - browser.test.notifyPass("executeScript"); - }); - - browser.test.onMessage.addListener(msg => { - browser.test.assertEq(msg, "execute-script"); - - browser.tabs.query({currentWindow: true}, tabs => { - browser.tabs.executeScript({ - file: "script.js", - }); - - // Execute a script we know we have permissions for in the - // second tab, in the hopes that it will execute after the - // first one. This has intermittent failure written all over - // it, but it's just about the best we can do until we - // support callbacks for executeScript. - browser.tabs.executeScript(tabs[1].id, { - file: "second-script.js", - }); - }); - }); - - await contentSetup(); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: params.manifest, - - background: `(${background})(${contentSetup})`, - - files: { - "script.js": function() { - browser.runtime.sendMessage("first script ran"); - }, - - "second-script.js": function() { - browser.runtime.sendMessage("second script ran"); - }, - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - if (params.setup) { - yield params.setup(extension); - } - - extension.sendMessage("execute-script"); - - yield extension.awaitFinish("executeScript"); - yield extension.unload(); -} - -add_task(function* testBadPermissions() { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/"); - - info("Test no special permissions"); - yield testHasNoPermission({ - manifest: {"permissions": ["http://example.com/"]}, - }); - - info("Test tabs permissions"); - yield testHasNoPermission({ - manifest: {"permissions": ["http://example.com/", "tabs"]}, - }); - - info("Test no special permissions, commands, key press"); - yield testHasNoPermission({ - manifest: { - "permissions": ["http://example.com/"], - "commands": { - "test-tabs-executeScript": { - "suggested_key": { - "default": "Alt+Shift+K", - }, - }, - }, - }, - contentSetup() { - browser.commands.onCommand.addListener(function(command) { - if (command == "test-tabs-executeScript") { - browser.test.sendMessage("tabs-command-key-pressed"); - } - }); - return Promise.resolve(); - }, - setup: function* (extension) { - yield EventUtils.synthesizeKey("k", {altKey: true, shiftKey: true}); - yield extension.awaitMessage("tabs-command-key-pressed"); - }, - }); - - info("Test active tab, commands, no key press"); - yield testHasNoPermission({ - manifest: { - "permissions": ["http://example.com/", "activeTab"], - "commands": { - "test-tabs-executeScript": { - "suggested_key": { - "default": "Alt+Shift+K", - }, - }, - }, - }, - }); - - info("Test active tab, browser action, no click"); - yield testHasNoPermission({ - manifest: { - "permissions": ["http://example.com/", "activeTab"], - "browser_action": {}, - }, - }); - - info("Test active tab, page action, no click"); - yield testHasNoPermission({ - manifest: { - "permissions": ["http://example.com/", "activeTab"], - "page_action": {}, - }, - async contentSetup() { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - await browser.pageAction.show(tab.id); - }, - }); - - yield BrowserTestUtils.removeTab(tab2); - yield BrowserTestUtils.removeTab(tab1); -}); - -add_task(function* testBadURL() { - async function background() { - let promises = [ - new Promise(resolve => { - browser.tabs.executeScript({ - file: "http://example.com/script.js", - }, result => { - browser.test.assertEq(undefined, result, "Result value"); - - browser.test.assertTrue(browser.extension.lastError instanceof Error, - "runtime.lastError is Error"); - - browser.test.assertTrue(browser.runtime.lastError instanceof Error, - "runtime.lastError is Error"); - - browser.test.assertEq( - "Files to be injected must be within the extension", - browser.extension.lastError && browser.extension.lastError.message, - "extension.lastError value"); - - browser.test.assertEq( - "Files to be injected must be within the extension", - browser.runtime.lastError && browser.runtime.lastError.message, - "runtime.lastError value"); - - resolve(); - }); - }), - - browser.tabs.executeScript({ - file: "http://example.com/script.js", - }).catch(error => { - browser.test.assertTrue(error instanceof Error, "Error is Error"); - - browser.test.assertEq(null, browser.extension.lastError, - "extension.lastError value"); - - browser.test.assertEq(null, browser.runtime.lastError, - "runtime.lastError value"); - - browser.test.assertEq( - "Files to be injected must be within the extension", - error && error.message, - "error value"); - }), - ]; - - await Promise.all(promises); - - browser.test.notifyPass("executeScript-lastError"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["<all_urls>"], - }, - - background, - }); - - yield extension.startup(); - - yield extension.awaitFinish("executeScript-lastError"); - - yield extension.unload(); -}); - -// TODO: Test that |executeScript| fails if the tab has navigated to a -// new page, and no longer matches our expected state. This involves -// intentionally trying to trigger a race condition, and is probably not -// even worth attempting until we have proper |executeScript| callbacks. - -add_task(forceGC); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js deleted file mode 100644 index cf4721310..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_good.js +++ /dev/null @@ -1,189 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -requestLongerTimeout(2); - -function* testHasPermission(params) { - let contentSetup = params.contentSetup || (() => Promise.resolve()); - - async function background(contentSetup) { - browser.runtime.onMessage.addListener((msg, sender) => { - browser.test.assertEq(msg, "script ran", "script ran"); - browser.test.notifyPass("executeScript"); - }); - - browser.test.onMessage.addListener(msg => { - browser.test.assertEq(msg, "execute-script"); - - browser.tabs.executeScript({ - file: "script.js", - }); - }); - - await contentSetup(); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: params.manifest, - - background: `(${background})(${contentSetup})`, - - files: { - "script.js": function() { - browser.runtime.sendMessage("script ran"); - }, - }, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - if (params.setup) { - yield params.setup(extension); - } - - extension.sendMessage("execute-script"); - - yield extension.awaitFinish("executeScript"); - - if (params.tearDown) { - yield params.tearDown(extension); - } - - yield extension.unload(); -} - -add_task(function* testGoodPermissions() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true); - - info("Test explicit host permission"); - yield testHasPermission({ - manifest: {"permissions": ["http://mochi.test/"]}, - }); - - info("Test explicit host subdomain permission"); - yield testHasPermission({ - manifest: {"permissions": ["http://*.mochi.test/"]}, - }); - - info("Test explicit <all_urls> permission"); - yield testHasPermission({ - manifest: {"permissions": ["<all_urls>"]}, - }); - - info("Test activeTab permission with a command key press"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab"], - "commands": { - "test-tabs-executeScript": { - "suggested_key": { - "default": "Alt+Shift+K", - }, - }, - }, - }, - contentSetup() { - browser.commands.onCommand.addListener(function(command) { - if (command == "test-tabs-executeScript") { - browser.test.sendMessage("tabs-command-key-pressed"); - } - }); - return Promise.resolve(); - }, - setup: function* (extension) { - yield EventUtils.synthesizeKey("k", {altKey: true, shiftKey: true}); - yield extension.awaitMessage("tabs-command-key-pressed"); - }, - }); - - info("Test activeTab permission with a browser action click"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab"], - "browser_action": {}, - }, - contentSetup() { - browser.browserAction.onClicked.addListener(() => { - browser.test.log("Clicked."); - }); - return Promise.resolve(); - }, - setup: clickBrowserAction, - tearDown: closeBrowserAction, - }); - - info("Test activeTab permission with a page action click"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab"], - "page_action": {}, - }, - contentSetup: async () => { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - await browser.pageAction.show(tab.id); - }, - setup: clickPageAction, - tearDown: closePageAction, - }); - - info("Test activeTab permission with a browser action w/popup click"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab"], - "browser_action": {"default_popup": "_blank.html"}, - }, - setup: async extension => { - await clickBrowserAction(extension); - return awaitExtensionPanel(extension, window, "_blank.html"); - }, - tearDown: closeBrowserAction, - }); - - info("Test activeTab permission with a page action w/popup click"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab"], - "page_action": {"default_popup": "_blank.html"}, - }, - contentSetup: async () => { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - await browser.pageAction.show(tab.id); - }, - setup: clickPageAction, - tearDown: closePageAction, - }); - - info("Test activeTab permission with a context menu click"); - yield testHasPermission({ - manifest: { - "permissions": ["activeTab", "contextMenus"], - }, - contentSetup() { - browser.contextMenus.create({title: "activeTab", contexts: ["all"]}); - return Promise.resolve(); - }, - setup: function* (extension) { - let contextMenu = document.getElementById("contentAreaContextMenu"); - let awaitPopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - let awaitPopupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden"); - - yield BrowserTestUtils.synthesizeMouseAtCenter("a[href]", {type: "contextmenu", button: 2}, - gBrowser.selectedBrowser); - yield awaitPopupShown; - - let item = contextMenu.querySelector("[label=activeTab]"); - - yield EventUtils.synthesizeMouseAtCenter(item, {}, window); - - yield awaitPopupHidden; - }, - }); - - yield BrowserTestUtils.removeTab(tab); -}); - -add_task(forceGC); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js deleted file mode 100644 index 7b2ffe175..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_no_create.js +++ /dev/null @@ -1,67 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testExecuteScriptAtOnUpdated() { - const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/"; - const URL = BASE + "file_iframe_document.html"; - // This is a regression test for bug 1325830. - // The bug (executeScript not completing any more) occurred when executeScript - // was called early at the onUpdated event, unless the tabs.create method is - // called. So this test does not use tabs.create to open new tabs. - // Note that if this test is run together with other tests that do call - // tabs.create, then this test case does not properly test the conditions of - // the regression any more. To verify that the regression has been resolved, - // this test must be run in isolation. - - function background() { - // Using variables to prevent listeners from running more than once, instead - // of removing the listener. This is to minimize any IPC, since the bug that - // is being tested is sensitive to timing. - let ignore = false; - let url; - browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { - if (changeInfo.status === "loading" && tab.url === url && !ignore) { - ignore = true; - browser.tabs.executeScript(tabId, { - code: "document.URL", - }).then(results => { - browser.test.assertEq(url, results[0], "Content script should run"); - browser.test.notifyPass("executeScript-at-onUpdated"); - }, error => { - browser.test.fail(`Unexpected error: ${error} :: ${error.stack}`); - browser.test.notifyFail("executeScript-at-onUpdated"); - }); - // (running this log call after executeScript to minimize IPC between - // onUpdated and executeScript.) - browser.test.log(`Found expected navigation to ${url}`); - } else { - // The bug occurs when executeScript is called before a tab is - // initialized. - browser.tabs.executeScript(tabId, {code: ""}); - } - }); - browser.test.onMessage.addListener(testUrl => { - url = testUrl; - browser.test.sendMessage("open-test-tab"); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/", "tabs"], - }, - background, - }); - - yield extension.startup(); - extension.sendMessage(URL); - yield extension.awaitMessage("open-test-tab"); - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URL, true); - - yield extension.awaitFinish("executeScript-at-onUpdated"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js b/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js deleted file mode 100644 index a4c0ed6f1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_executeScript_runAt.js +++ /dev/null @@ -1,107 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/** - * These tests ensure that the runAt argument to tabs.executeScript delays - * script execution until the document has reached the correct state. - * - * Since tests of this nature are especially race-prone, it relies on a - * server-JS script to delay the completion of our test page's load cycle long - * enough for us to attempt to load our scripts in the earlies phase we support. - * - * And since we can't actually rely on that timing, it retries any attempts that - * fail to load as early as expected, but don't load at any illegal time. - */ - -add_task(function* testExecuteScript() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank", true); - - async function background() { - let tab; - - const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/"; - const URL = BASE + "file_iframe_document.sjs"; - - const MAX_TRIES = 10; - - try { - [tab] = await browser.tabs.query({active: true, currentWindow: true}); - - let success = false; - for (let tries = 0; !success && tries < MAX_TRIES; tries++) { - let url = `${URL}?r=${Math.random()}`; - - let loadingPromise = new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changed, tab_) { - if (tabId == tab.id && changed.status == "loading" && tab_.url == url) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - - // TODO: Test allFrames and frameId. - - await browser.tabs.update({url}); - await loadingPromise; - - let states = await Promise.all([ - // Send the executeScript requests in the reverse order that we expect - // them to execute in, to avoid them passing only because of timing - // races. - browser.tabs.executeScript({ - code: "document.readyState", - runAt: "document_idle", - }), - browser.tabs.executeScript({ - code: "document.readyState", - runAt: "document_end", - }), - browser.tabs.executeScript({ - code: "document.readyState", - runAt: "document_start", - }), - ].reverse()); - - browser.test.log(`Got states: ${states}`); - - // Make sure that none of our scripts executed earlier than expected, - // regardless of retries. - browser.test.assertTrue(states[1] == "interactive" || states[1] == "complete", - `document_end state is valid: ${states[1]}`); - browser.test.assertTrue(states[2] == "complete", - `document_idle state is valid: ${states[2]}`); - - // If we have the earliest valid states for each script, we're done. - // Otherwise, try again. - success = (states[0] == "loading" && - states[1] == "interactive" && - states[2] == "complete"); - } - - browser.test.assertTrue(success, "Got the earliest expected states at least once"); - - browser.test.notifyPass("executeScript-runAt"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("executeScript-runAt"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/", "tabs"], - }, - - background, - }); - - yield extension.startup(); - - yield extension.awaitFinish("executeScript-runAt"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js b/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js deleted file mode 100644 index b67d935cb..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_getCurrent.js +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "browser_action": {"default_popup": "popup.html"}, - }, - - files: { - "tab.js": function() { - let url = document.location.href; - - browser.tabs.getCurrent(currentTab => { - browser.test.assertEq(currentTab.url, url, "getCurrent in non-active background tab"); - - // Activate the tab. - browser.tabs.onActivated.addListener(function listener({tabId}) { - if (tabId == currentTab.id) { - browser.tabs.onActivated.removeListener(listener); - - browser.tabs.getCurrent(currentTab => { - browser.test.assertEq(currentTab.id, tabId, "in active background tab"); - browser.test.assertEq(currentTab.url, url, "getCurrent in non-active background tab"); - - browser.test.sendMessage("tab-finished"); - }); - } - }); - browser.tabs.update(currentTab.id, {active: true}); - }); - }, - - "popup.js": function() { - browser.tabs.getCurrent(tab => { - browser.test.assertEq(tab, undefined, "getCurrent in popup script"); - browser.test.sendMessage("popup-finished"); - }); - }, - - "tab.html": `<head><meta charset="utf-8"><script src="tab.js"></script></head>`, - "popup.html": `<head><meta charset="utf-8"><script src="popup.js"></script></head>`, - }, - - background: function() { - browser.tabs.getCurrent(tab => { - browser.test.assertEq(tab, undefined, "getCurrent in background script"); - browser.test.sendMessage("background-finished"); - }); - - browser.tabs.create({url: "tab.html", active: false}); - }, - }); - - yield extension.startup(); - - yield extension.awaitMessage("background-finished"); - yield extension.awaitMessage("tab-finished"); - - clickBrowserAction(extension); - yield awaitExtensionPanel(extension); - yield extension.awaitMessage("popup-finished"); - yield closeBrowserAction(extension); - - // The extension tab is automatically closed when the extension unloads. - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js b/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js deleted file mode 100644 index a8e172d94..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_insertCSS.js +++ /dev/null @@ -1,86 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testExecuteScript() { - let {MessageChannel} = Cu.import("resource://gre/modules/MessageChannel.jsm", {}); - - let messageManagersSize = MessageChannel.messageManagers.size; - let responseManagersSize = MessageChannel.responseManagers.size; - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true); - - async function background() { - let tasks = [ - { - background: "transparent", - foreground: "rgb(0, 113, 4)", - promise: () => { - return browser.tabs.insertCSS({ - file: "file2.css", - }); - }, - }, - { - background: "rgb(42, 42, 42)", - foreground: "rgb(0, 113, 4)", - promise: () => { - return browser.tabs.insertCSS({ - code: "* { background: rgb(42, 42, 42) }", - }); - }, - }, - ]; - - function checkCSS() { - let computedStyle = window.getComputedStyle(document.body); - return [computedStyle.backgroundColor, computedStyle.color]; - } - - try { - for (let {promise, background, foreground} of tasks) { - let result = await promise(); - - browser.test.assertEq(undefined, result, "Expected callback result"); - - [result] = await browser.tabs.executeScript({ - code: `(${checkCSS})()`, - }); - - browser.test.assertEq(background, result[0], "Expected background color"); - browser.test.assertEq(foreground, result[1], "Expected foreground color"); - } - - browser.test.notifyPass("insertCSS"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFailure("insertCSS"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/"], - }, - - background, - - files: { - "file2.css": "* { color: rgb(0, 113, 4) }", - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("insertCSS"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); - - // Make sure that we're not holding on to references to closed message - // managers. - is(MessageChannel.messageManagers.size, messageManagersSize, "Message manager count"); - is(MessageChannel.responseManagers.size, responseManagersSize, "Response manager count"); - is(MessageChannel.pendingResponses.size, 0, "Pending response count"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move.js b/browser/components/extensions/test/browser/browser_ext_tabs_move.js deleted file mode 100644 index 917cdc146..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_move.js +++ /dev/null @@ -1,103 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: async function() { - let [tab] = await browser.tabs.query({lastFocusedWindow: true}); - - browser.tabs.move(tab.id, {index: 0}); - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - - browser.test.assertEq(tabs[0].url, tab.url, "should be first tab"); - browser.test.notifyPass("tabs.move.single"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.single"); - yield extension.unload(); - - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: async function() { - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - - tabs.sort(function(a, b) { return a.url > b.url; }); - - browser.tabs.move(tabs.map(tab => tab.id), {index: 0}); - - tabs = await browser.tabs.query({lastFocusedWindow: true}); - - browser.test.assertEq(tabs[0].url, "about:blank", "should be first tab"); - browser.test.assertEq(tabs[1].url, "about:config", "should be second tab"); - browser.test.assertEq(tabs[2].url, "about:robots", "should be third tab"); - - browser.test.notifyPass("tabs.move.multiple"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.multiple"); - yield extension.unload(); - - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - async background() { - let [, tab] = await browser.tabs.query({lastFocusedWindow: true}); - - // Assuming that tab.id of 12345 does not exist. - await browser.test.assertRejects( - browser.tabs.move([tab.id, 12345], {index: 0}), - /Invalid tab/, - "Should receive invalid tab error"); - - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - browser.test.assertEq(tabs[1].url, tab.url, "should be second tab"); - browser.test.notifyPass("tabs.move.invalid"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.invalid"); - yield extension.unload(); - - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: async function() { - let [tab] = await browser.tabs.query({lastFocusedWindow: true}); - browser.tabs.move(tab.id, {index: -1}); - - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - - browser.test.assertEq(tabs[2].url, tab.url, "should be last tab"); - browser.test.notifyPass("tabs.move.last"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.last"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js deleted file mode 100644 index f3bce364a..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window.js +++ /dev/null @@ -1,98 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - let window1 = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - async background() { - let tabs = await browser.tabs.query({url: "<all_urls>"}); - let destination = tabs[0]; - let source = tabs[1]; // skip over about:blank in window1 - - // Assuming that this windowId does not exist. - await browser.test.assertRejects( - browser.tabs.move(source.id, {windowId: 123144576, index: 0}), - /Invalid window/, - "Should receive invalid window error"); - - browser.tabs.move(source.id, {windowId: destination.windowId, index: 0}); - - tabs = await browser.tabs.query({url: "<all_urls>"}); - browser.test.assertEq(tabs[0].url, "http://example.com/"); - browser.test.assertEq(tabs[0].windowId, destination.windowId); - browser.test.notifyPass("tabs.move.window"); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.window"); - yield extension.unload(); - - for (let tab of window.gBrowser.tabs) { - yield BrowserTestUtils.removeTab(tab); - } - yield BrowserTestUtils.closeWindow(window1); -}); - -add_task(function* test_currentWindowAfterTabMoved() { - const files = { - "current.html": "<meta charset=utf-8><script src=current.js></script>", - "current.js": function() { - browser.test.onMessage.addListener(msg => { - if (msg === "current") { - browser.windows.getCurrent(win => { - browser.test.sendMessage("id", win.id); - }); - } - }); - browser.test.sendMessage("ready"); - }, - }; - - async function background() { - let tabId; - - const url = browser.extension.getURL("current.html"); - - browser.test.onMessage.addListener(async msg => { - if (msg === "move") { - await browser.windows.create({tabId}); - browser.test.sendMessage("moved"); - } else if (msg === "close") { - await browser.tabs.remove(tabId); - browser.test.sendMessage("done"); - } - }); - - let tab = await browser.tabs.create({url}); - tabId = tab.id; - } - - const extension = ExtensionTestUtils.loadExtension({files, background}); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - extension.sendMessage("current"); - const first = yield extension.awaitMessage("id"); - - extension.sendMessage("move"); - yield extension.awaitMessage("moved"); - - extension.sendMessage("current"); - const second = yield extension.awaitMessage("id"); - - isnot(first, second, "current window id is different after moving the tab"); - - extension.sendMessage("close"); - yield extension.awaitMessage("done"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js deleted file mode 100644 index dacd547f2..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_multiple.js +++ /dev/null @@ -1,43 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let window1 = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, "http://example.net/"); - yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, "http://example.com/"); - yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.net/"); - yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/"); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query( - {url: "<all_urls>"}, - tabs => { - let move1 = tabs[1]; - let move3 = tabs[3]; - browser.tabs.move([move1.id, move3.id], {index: 0}); - browser.tabs.query( - {url: "<all_urls>"}, - tabs => { - browser.test.assertEq(tabs[0].url, move1.url); - browser.test.assertEq(tabs[2].url, move3.url); - browser.test.notifyPass("tabs.move.multiple"); - }); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.multiple"); - yield extension.unload(); - - for (let tab of window.gBrowser.tabs) { - yield BrowserTestUtils.removeTab(tab); - } - yield BrowserTestUtils.closeWindow(window1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js b/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js deleted file mode 100644 index c592dc56d..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_move_window_pinned.js +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - let window1 = yield BrowserTestUtils.openNewBrowserWindow(); - let tab1 = yield BrowserTestUtils.openNewForegroundTab(window1.gBrowser, "http://example.com/"); - window1.gBrowser.pinTab(tab1); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query( - {url: "<all_urls>"}, - tabs => { - let destination = tabs[0]; - let source = tabs[1]; // remember, pinning moves it to the left. - browser.tabs.move(source.id, {windowId: destination.windowId, index: 0}); - - browser.tabs.query( - {url: "<all_urls>"}, - tabs => { - browser.test.assertEq(true, tabs[0].pinned); - browser.test.notifyPass("tabs.move.pin"); - }); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.move.pin"); - yield extension.unload(); - - for (let tab of window.gBrowser.tabs) { - yield BrowserTestUtils.removeTab(tab); - } - yield BrowserTestUtils.closeWindow(window1); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js b/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js deleted file mode 100644 index 9cc2554d6..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_onHighlighted.js +++ /dev/null @@ -1,126 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testTabEvents() { - async function background() { - /** The list of active tab ID's */ - let tabIds = []; - - /** - * Stores the events that fire for each tab. - * - * events { - * tabId1: [event1, event2, ...], - * tabId2: [event1, event2, ...], - * } - */ - let events = {}; - - browser.tabs.onActivated.addListener((info) => { - if (info.tabId in events) { - events[info.tabId].push("onActivated"); - } else { - events[info.tabId] = ["onActivated"]; - } - }); - - browser.tabs.onHighlighted.addListener((info) => { - if (info.tabIds[0] in events) { - events[info.tabIds[0]].push("onHighlighted"); - } else { - events[info.tabIds[0]] = ["onHighlighted"]; - } - }); - - /** - * Asserts that the expected events are fired for the tab with id = tabId. - * The events associated to the specified tab are removed after this check is made. - * - * @param {number} tabId - * @param {Array<string>} expectedEvents - */ - async function expectEvents(tabId, expectedEvents) { - browser.test.log(`Expecting events: ${expectedEvents.join(", ")}`); - - await new Promise(resolve => setTimeout(resolve, 0)); - - browser.test.assertEq(expectedEvents.length, events[tabId].length, - `Got expected number of events for ${tabId}`); - - for (let [i, name] of expectedEvents.entries()) { - browser.test.assertEq(name, i in events[tabId] && events[tabId][i], - `Got expected ${name} event`); - } - delete events[tabId]; - } - - /** - * Opens a new tab and asserts that the correct events are fired. - * - * @param {number} windowId - */ - async function openTab(windowId) { - let tab = await browser.tabs.create({windowId}); - - tabIds.push(tab.id); - browser.test.log(`Opened tab ${tab.id}`); - - await expectEvents(tab.id, [ - "onActivated", - "onHighlighted", - ]); - } - - /** - * Highlights an existing tab and asserts that the correct events are fired. - * - * @param {number} tabId - */ - async function highlightTab(tabId) { - browser.test.log(`Highlighting tab ${tabId}`); - let tab = await browser.tabs.update(tabId, {active: true}); - - browser.test.assertEq(tab.id, tabId, `Tab ${tab.id} highlighted`); - - await expectEvents(tab.id, [ - "onActivated", - "onHighlighted", - ]); - } - - /** - * The main entry point to the tests. - */ - let tabs = await browser.tabs.query({active: true, currentWindow: true}); - - let activeWindow = tabs[0].windowId; - await Promise.all([ - openTab(activeWindow), - openTab(activeWindow), - openTab(activeWindow), - ]); - - await Promise.all([ - highlightTab(tabIds[0]), - highlightTab(tabIds[1]), - highlightTab(tabIds[2]), - ]); - - await Promise.all(tabIds.map(id => browser.tabs.remove(id))); - - browser.test.notifyPass("tabs.highlight"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.highlight"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js b/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js deleted file mode 100644 index 2c26bbd16..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_onUpdated.js +++ /dev/null @@ -1,198 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -requestLongerTimeout(2); - -add_task(function* () { - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - - yield focusWindow(win1); - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - "content_scripts": [{ - "matches": ["http://mochi.test/*/context_tabs_onUpdated_page.html"], - "js": ["content-script.js"], - "run_at": "document_start", - }], - }, - - background: function() { - let pageURL = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html"; - - let expectedSequence = [ - {status: "loading"}, - {status: "loading", url: pageURL}, - {status: "complete"}, - ]; - let collectedSequence = []; - - browser.tabs.onUpdated.addListener(function(tabId, updatedInfo) { - // onUpdated also fires with updatedInfo.faviconUrl, so explicitly - // check for updatedInfo.status before recording the event. - if ("status" in updatedInfo) { - collectedSequence.push(updatedInfo); - } - }); - - browser.runtime.onMessage.addListener(function() { - if (collectedSequence.length !== expectedSequence.length) { - browser.test.assertEq( - JSON.stringify(expectedSequence), - JSON.stringify(collectedSequence), - "got unexpected number of updateInfo data" - ); - } else { - for (let i = 0; i < expectedSequence.length; i++) { - browser.test.assertEq( - expectedSequence[i].status, - collectedSequence[i].status, - "check updatedInfo status" - ); - if (expectedSequence[i].url || collectedSequence[i].url) { - browser.test.assertEq( - expectedSequence[i].url, - collectedSequence[i].url, - "check updatedInfo url" - ); - } - } - } - - browser.test.notifyPass("tabs.onUpdated"); - }); - - browser.tabs.create({url: pageURL}); - }, - files: { - "content-script.js": ` - window.addEventListener("message", function(evt) { - if (evt.data == "frame-updated") { - browser.runtime.sendMessage("load-completed"); - } - }, true); - `, - }, - }); - - yield Promise.all([ - extension.startup(), - extension.awaitFinish("tabs.onUpdated"), - ]); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(win1); -}); - -function* do_test_update(background, withPermissions = true) { - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - - yield focusWindow(win1); - - let manifest = {}; - if (withPermissions) { - manifest.permissions = ["tabs"]; - } - let extension = ExtensionTestUtils.loadExtension({manifest, background}); - - yield Promise.all([ - yield extension.startup(), - yield extension.awaitFinish("finish"), - ]); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(win1); -} - -add_task(function* test_pinned() { - yield do_test_update(function background() { - // Create a new tab for testing update. - browser.tabs.create({}, function(tab) { - browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) { - // Check callback - browser.test.assertEq(tabId, tab.id, "Check tab id"); - browser.test.log("onUpdate: " + JSON.stringify(changeInfo)); - if ("pinned" in changeInfo) { - browser.test.assertTrue(changeInfo.pinned, "Check changeInfo.pinned"); - browser.tabs.onUpdated.removeListener(onUpdated); - // Remove created tab. - browser.tabs.remove(tabId); - browser.test.notifyPass("finish"); - return; - } - }); - browser.tabs.update(tab.id, {pinned: true}); - }); - }); -}); - -add_task(function* test_unpinned() { - yield do_test_update(function background() { - // Create a new tab for testing update. - browser.tabs.create({pinned: true}, function(tab) { - browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) { - // Check callback - browser.test.assertEq(tabId, tab.id, "Check tab id"); - browser.test.log("onUpdate: " + JSON.stringify(changeInfo)); - if ("pinned" in changeInfo) { - browser.test.assertFalse(changeInfo.pinned, "Check changeInfo.pinned"); - browser.tabs.onUpdated.removeListener(onUpdated); - // Remove created tab. - browser.tabs.remove(tabId); - browser.test.notifyPass("finish"); - return; - } - }); - browser.tabs.update(tab.id, {pinned: false}); - }); - }); -}); - -add_task(function* test_url() { - yield do_test_update(function background() { - // Create a new tab for testing update. - browser.tabs.create({}, function(tab) { - browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) { - // Check callback - browser.test.assertEq(tabId, tab.id, "Check tab id"); - browser.test.log("onUpdate: " + JSON.stringify(changeInfo)); - if ("url" in changeInfo) { - browser.test.assertEq("about:blank", changeInfo.url, - "Check changeInfo.url"); - browser.tabs.onUpdated.removeListener(onUpdated); - // Remove created tab. - browser.tabs.remove(tabId); - browser.test.notifyPass("finish"); - return; - } - }); - browser.tabs.update(tab.id, {url: "about:blank"}); - }); - }); -}); - -add_task(function* test_without_tabs_permission() { - yield do_test_update(function background() { - browser.tabs.create({url: "about:blank"}, function(tab) { - browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) { - if (tabId == tab.id) { - browser.test.assertFalse("url" in changeInfo, "url should not be included without tabs permission"); - browser.test.assertFalse("favIconUrl" in changeInfo, "favIconUrl should not be included without tabs permission"); - - if (changeInfo.status == "complete") { - browser.tabs.onUpdated.removeListener(onUpdated); - browser.tabs.remove(tabId); - browser.test.notifyPass("finish"); - } - } - }); - browser.tabs.reload(tab.id); - }); - }, false /* withPermissions */); -}); - -add_task(forceGC); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_query.js b/browser/components/extensions/test/browser/browser_ext_tabs_query.js deleted file mode 100644 index 7804d1454..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_query.js +++ /dev/null @@ -1,224 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -requestLongerTimeout(2); - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - lastFocusedWindow: true, - }, function(tabs) { - browser.test.assertEq(tabs.length, 3, "should have three tabs"); - - tabs.sort((tab1, tab2) => tab1.index - tab2.index); - - browser.test.assertEq(tabs[0].url, "about:blank", "first tab blank"); - tabs.shift(); - - browser.test.assertTrue(tabs[0].active, "tab 0 active"); - browser.test.assertFalse(tabs[1].active, "tab 1 inactive"); - - browser.test.assertFalse(tabs[0].pinned, "tab 0 unpinned"); - browser.test.assertFalse(tabs[1].pinned, "tab 1 unpinned"); - - browser.test.assertEq(tabs[0].url, "about:robots", "tab 0 url correct"); - browser.test.assertEq(tabs[1].url, "about:config", "tab 1 url correct"); - - browser.test.assertEq(tabs[0].status, "complete", "tab 0 status correct"); - browser.test.assertEq(tabs[1].status, "complete", "tab 1 status correct"); - - browser.test.assertEq(tabs[0].title, "Gort! Klaatu barada nikto!", "tab 0 title correct"); - - browser.test.notifyPass("tabs.query"); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.query"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); - - tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - let tab3 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://test1.example.org/MochiKit/"); - - // test simple queries - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - url: "<all_urls>", - }, function(tabs) { - browser.test.assertEq(tabs.length, 3, "should have three tabs"); - - tabs.sort((tab1, tab2) => tab1.index - tab2.index); - - browser.test.assertEq(tabs[0].url, "http://example.com/", "tab 0 url correct"); - browser.test.assertEq(tabs[1].url, "http://example.net/", "tab 1 url correct"); - browser.test.assertEq(tabs[2].url, "http://test1.example.org/MochiKit/", "tab 2 url correct"); - - browser.test.notifyPass("tabs.query"); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.query"); - yield extension.unload(); - - // match pattern - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - url: "http://*/MochiKit*", - }, function(tabs) { - browser.test.assertEq(tabs.length, 1, "should have one tab"); - - browser.test.assertEq(tabs[0].url, "http://test1.example.org/MochiKit/", "tab 0 url correct"); - - browser.test.notifyPass("tabs.query"); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.query"); - yield extension.unload(); - - // match array of patterns - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - url: ["http://*/MochiKit*", "http://*.com/*"], - }, function(tabs) { - browser.test.assertEq(tabs.length, 2, "should have two tabs"); - - tabs.sort((tab1, tab2) => tab1.index - tab2.index); - - browser.test.assertEq(tabs[0].url, "http://example.com/", "tab 0 url correct"); - browser.test.assertEq(tabs[1].url, "http://test1.example.org/MochiKit/", "tab 1 url correct"); - - browser.test.notifyPass("tabs.query"); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.query"); - yield extension.unload(); - - // test width and height - extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.test.onMessage.addListener(async msg => { - let tabs = await browser.tabs.query({active: true}); - - browser.test.assertEq(tabs.length, 1, "should have one tab"); - browser.test.sendMessage("dims", {width: tabs[0].width, height: tabs[0].height}); - }); - browser.test.sendMessage("ready"); - }, - }); - - const RESOLUTION_PREF = "layout.css.devPixelsPerPx"; - registerCleanupFunction(() => { - SpecialPowers.clearUserPref(RESOLUTION_PREF); - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("ready")]); - - for (let resolution of [2, 1]) { - SpecialPowers.setCharPref(RESOLUTION_PREF, String(resolution)); - is(window.devicePixelRatio, resolution, "window has the required resolution"); - - let {clientHeight, clientWidth} = gBrowser.selectedBrowser; - - extension.sendMessage("check-size"); - let dims = yield extension.awaitMessage("dims"); - is(dims.width, clientWidth, "tab reports expected width"); - is(dims.height, clientHeight, "tab reports expected height"); - } - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); - yield BrowserTestUtils.removeTab(tab3); - SpecialPowers.clearUserPref(RESOLUTION_PREF); -}); - -add_task(function* testQueryPermissions() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": [], - }, - - async background() { - try { - let tabs = await browser.tabs.query({currentWindow: true, active: true}); - browser.test.assertEq(tabs.length, 1, "Expect query to return tabs"); - browser.test.notifyPass("queryPermissions"); - } catch (e) { - browser.test.notifyFail("queryPermissions"); - } - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("queryPermissions"); - - yield extension.unload(); -}); - -add_task(function* testQueryWithURLPermissions() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": [], - }, - - async background() { - await browser.test.assertRejects( - browser.tabs.query({"url": "http://www.bbc.com/"}), - 'The "tabs" permission is required to use the query API with the "url" parameter', - "Expected tabs.query with 'url' to fail with permissions error message"); - - browser.test.notifyPass("queryWithURLPermissions"); - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("queryWithURLPermissions"); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_reload.js b/browser/components/extensions/test/browser/browser_ext_tabs_reload.js deleted file mode 100644 index 99b2d426b..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_reload.js +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - files: { - "tab.js": function() { - browser.runtime.sendMessage("tab-loaded"); - }, - "tab.html": - `<head> - <meta charset="utf-8"> - <script src="tab.js"></script> - </head>`, - }, - - async background() { - let tabLoadedCount = 0; - - let tab = await browser.tabs.create({url: "tab.html", active: true}); - - browser.runtime.onMessage.addListener(msg => { - if (msg == "tab-loaded") { - tabLoadedCount++; - - if (tabLoadedCount == 1) { - // Reload the tab once passing no arguments. - return browser.tabs.reload(); - } - - if (tabLoadedCount == 2) { - // Reload the tab again with explicit arguments. - return browser.tabs.reload(tab.id, { - bypassCache: false, - }); - } - - if (tabLoadedCount == 3) { - browser.test.notifyPass("tabs.reload"); - } - } - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.reload"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js b/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js deleted file mode 100644 index 648361724..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_reload_bypass_cache.js +++ /dev/null @@ -1,58 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs", "<all_urls>"], - }, - - async background() { - const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/"; - const URL = BASE + "file_bypass_cache.sjs"; - - function awaitLoad(tabId) { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId_, changed, tab) { - if (tabId == tabId_ && changed.status == "complete" && tab.url == URL) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - } - - try { - let tab = await browser.tabs.create({url: URL}); - await awaitLoad(tab.id); - - await browser.tabs.reload(tab.id, {bypassCache: false}); - await awaitLoad(tab.id); - - let [textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"}); - browser.test.assertEq("", textContent, "`textContent` should be empty when bypassCache=false"); - - await browser.tabs.reload(tab.id, {bypassCache: true}); - await awaitLoad(tab.id); - - [textContent] = await browser.tabs.executeScript(tab.id, {code: "document.body.textContent"}); - - let [pragma, cacheControl] = textContent.split(":"); - browser.test.assertEq("no-cache", pragma, "`pragma` should be set to `no-cache` when bypassCache is true"); - browser.test.assertEq("no-cache", cacheControl, "`cacheControl` should be set to `no-cache` when bypassCache is true"); - - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("tabs.reload_bypass_cache"); - } catch (error) { - browser.test.fail(`${error} :: ${error.stack}`); - browser.test.notifyFail("tabs.reload_bypass_cache"); - } - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("tabs.reload_bypass_cache"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js b/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js deleted file mode 100644 index e0eadab64..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_removeCSS.js +++ /dev/null @@ -1,95 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testExecuteScript() { - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/", true); - - async function background() { - let tasks = [ - // Insert CSS file. - { - background: "transparent", - foreground: "rgb(0, 113, 4)", - promise: () => { - return browser.tabs.insertCSS({ - file: "file2.css", - }); - }, - }, - // Insert CSS code. - { - background: "rgb(42, 42, 42)", - foreground: "rgb(0, 113, 4)", - promise: () => { - return browser.tabs.insertCSS({ - code: "* { background: rgb(42, 42, 42) }", - }); - }, - }, - // Remove CSS code again. - { - background: "transparent", - foreground: "rgb(0, 113, 4)", - promise: () => { - return browser.tabs.removeCSS({ - code: "* { background: rgb(42, 42, 42) }", - }); - }, - }, - // Remove CSS file again. - { - background: "transparent", - foreground: "rgb(0, 0, 0)", - promise: () => { - return browser.tabs.removeCSS({ - file: "file2.css", - }); - }, - }, - ]; - - function checkCSS() { - let computedStyle = window.getComputedStyle(document.body); - return [computedStyle.backgroundColor, computedStyle.color]; - } - - try { - for (let {promise, background, foreground} of tasks) { - let result = await promise(); - browser.test.assertEq(undefined, result, "Expected callback result"); - - [result] = await browser.tabs.executeScript({ - code: `(${checkCSS})()`, - }); - browser.test.assertEq(background, result[0], "Expected background color"); - browser.test.assertEq(foreground, result[1], "Expected foreground color"); - } - - browser.test.notifyPass("removeCSS"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFailure("removeCSS"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["http://mochi.test/"], - }, - - background, - - files: { - "file2.css": "* { color: rgb(0, 113, 4) }", - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("removeCSS"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js b/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js deleted file mode 100644 index 64e97afb1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_sendMessage.js +++ /dev/null @@ -1,227 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* tabsSendMessageReply() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "content_scripts": [{ - "matches": ["http://example.com/"], - "js": ["content-script.js"], - "run_at": "document_start", - }], - }, - - background: async function() { - let firstTab; - let promiseResponse = new Promise(resolve => { - browser.runtime.onMessage.addListener((msg, sender, respond) => { - if (msg == "content-script-ready") { - let tabId = sender.tab.id; - - Promise.all([ - promiseResponse, - - browser.tabs.sendMessage(tabId, "respond-now"), - browser.tabs.sendMessage(tabId, "respond-now-2"), - new Promise(resolve => browser.tabs.sendMessage(tabId, "respond-soon", resolve)), - browser.tabs.sendMessage(tabId, "respond-promise"), - browser.tabs.sendMessage(tabId, "respond-never"), - new Promise(resolve => { - browser.runtime.sendMessage("respond-never", response => { resolve(response); }); - }), - - browser.tabs.sendMessage(tabId, "respond-error").catch(error => Promise.resolve({error})), - browser.tabs.sendMessage(tabId, "throw-error").catch(error => Promise.resolve({error})), - - browser.tabs.sendMessage(firstTab, "no-listener").catch(error => Promise.resolve({error})), - ]).then(([response, respondNow, respondNow2, respondSoon, respondPromise, respondNever, respondNever2, respondError, throwError, noListener]) => { - browser.test.assertEq("expected-response", response, "Content script got the expected response"); - - browser.test.assertEq("respond-now", respondNow, "Got the expected immediate response"); - browser.test.assertEq("respond-now-2", respondNow2, "Got the expected immediate response from the second listener"); - browser.test.assertEq("respond-soon", respondSoon, "Got the expected delayed response"); - browser.test.assertEq("respond-promise", respondPromise, "Got the expected promise response"); - browser.test.assertEq(undefined, respondNever, "Got the expected no-response resolution"); - browser.test.assertEq(undefined, respondNever2, "Got the expected no-response resolution"); - - browser.test.assertEq("respond-error", respondError.error.message, "Got the expected error response"); - browser.test.assertEq("throw-error", throwError.error.message, "Got the expected thrown error response"); - - browser.test.assertEq("Could not establish connection. Receiving end does not exist.", - noListener.error.message, - "Got the expected no listener response"); - - return browser.tabs.remove(tabId); - }).then(() => { - browser.test.notifyPass("sendMessage"); - }); - - return Promise.resolve("expected-response"); - } else if (msg[0] == "got-response") { - resolve(msg[1]); - } - }); - }); - - let tabs = await browser.tabs.query({currentWindow: true, active: true}); - firstTab = tabs[0].id; - browser.tabs.create({url: "http://example.com/"}); - }, - - files: { - "content-script.js": async function() { - browser.runtime.onMessage.addListener((msg, sender, respond) => { - if (msg == "respond-now") { - respond(msg); - } else if (msg == "respond-soon") { - setTimeout(() => { respond(msg); }, 0); - return true; - } else if (msg == "respond-promise") { - return Promise.resolve(msg); - } else if (msg == "respond-never") { - return; - } else if (msg == "respond-error") { - return Promise.reject(new Error(msg)); - } else if (msg == "throw-error") { - throw new Error(msg); - } - }); - - browser.runtime.onMessage.addListener((msg, sender, respond) => { - if (msg == "respond-now") { - respond("hello"); - } else if (msg == "respond-now-2") { - respond(msg); - } - }); - - let response = await browser.runtime.sendMessage("content-script-ready"); - browser.runtime.sendMessage(["got-response", response]); - }, - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("sendMessage"); - - yield extension.unload(); -}); - - -add_task(function* tabsSendHidden() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - - "content_scripts": [{ - "matches": ["http://example.com/content*"], - "js": ["content-script.js"], - "run_at": "document_start", - }], - }, - - background: async function() { - let resolveContent; - browser.runtime.onMessage.addListener((msg, sender) => { - if (msg[0] == "content-ready") { - resolveContent(msg[1]); - } - }); - - let awaitContent = url => { - return new Promise(resolve => { - resolveContent = resolve; - }).then(result => { - browser.test.assertEq(url, result, "Expected content script URL"); - }); - }; - - try { - const URL1 = "http://example.com/content1.html"; - const URL2 = "http://example.com/content2.html"; - - let tab = await browser.tabs.create({url: URL1}); - await awaitContent(URL1); - - let url = await browser.tabs.sendMessage(tab.id, URL1); - browser.test.assertEq(URL1, url, "Should get response from expected content window"); - - await browser.tabs.update(tab.id, {url: URL2}); - await awaitContent(URL2); - - url = await browser.tabs.sendMessage(tab.id, URL2); - browser.test.assertEq(URL2, url, "Should get response from expected content window"); - - // Repeat once just to be sure the first message was processed by all - // listeners before we exit the test. - url = await browser.tabs.sendMessage(tab.id, URL2); - browser.test.assertEq(URL2, url, "Should get response from expected content window"); - - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("contentscript-bfcache-window"); - } catch (error) { - browser.test.fail(`Error: ${error} :: ${error.stack}`); - browser.test.notifyFail("contentscript-bfcache-window"); - } - }, - - files: { - "content-script.js": function() { - // Store this in a local variable to make sure we don't touch any - // properties of the possibly-hidden content window. - let href = window.location.href; - - browser.runtime.onMessage.addListener((msg, sender) => { - browser.test.assertEq(href, msg, "Should be in the expected content window"); - - return Promise.resolve(href); - }); - - browser.runtime.sendMessage(["content-ready", href]); - }, - }, - }); - - yield extension.startup(); - - yield extension.awaitFinish("contentscript-bfcache-window"); - - yield extension.unload(); -}); - - -add_task(function* tabsSendMessageNoExceptionOnNonExistentTab() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - async background() { - let url = "http://example.com/mochitest/browser/browser/components/extensions/test/browser/file_dummy.html"; - let tab = await browser.tabs.create({url}); - - try { - browser.tabs.sendMessage(tab.id, "message"); - browser.tabs.sendMessage(tab.id + 100, "message"); - } catch (e) { - browser.test.fail("no exception should be raised on tabs.sendMessage to nonexistent tabs"); - } - - await browser.tabs.remove(tab.id); - - browser.test.notifyPass("tabs.sendMessage"); - }, - }); - - yield Promise.all([ - extension.startup(), - extension.awaitFinish("tabs.sendMessage"), - ]); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_update.js b/browser/components/extensions/test/browser/browser_ext_tabs_update.js deleted file mode 100644 index 8e56a746c..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_update.js +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:robots"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:config"); - - gBrowser.selectedTab = tab1; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background: function() { - browser.tabs.query({ - lastFocusedWindow: true, - }, function(tabs) { - browser.test.assertEq(tabs.length, 3, "should have three tabs"); - - tabs.sort((tab1, tab2) => tab1.index - tab2.index); - - browser.test.assertEq(tabs[0].url, "about:blank", "first tab blank"); - tabs.shift(); - - browser.test.assertTrue(tabs[0].active, "tab 0 active"); - browser.test.assertFalse(tabs[1].active, "tab 1 inactive"); - - browser.tabs.update(tabs[1].id, {active: true}, function() { - browser.test.sendMessage("check"); - }); - }); - }, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("check")]); - - ok(gBrowser.selectedTab == tab2, "correct tab selected"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js b/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js deleted file mode 100644 index b43855fb1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_update_url.js +++ /dev/null @@ -1,110 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* testTabsUpdateURL(existentTabURL, tabsUpdateURL, isErrorExpected) { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - files: { - "tab.html": ` - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - <body> - <h1>tab page</h1> - </body> - </html> - `.trim(), - }, - background: function() { - browser.test.sendMessage("ready", browser.runtime.getURL("tab.html")); - - browser.test.onMessage.addListener(async (msg, tabsUpdateURL, isErrorExpected) => { - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - - try { - let tab = await browser.tabs.update(tabs[1].id, {url: tabsUpdateURL}); - - browser.test.assertFalse(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should be rejected`); - browser.test.assertTrue(tab, "on success the tab should be defined"); - } catch (error) { - browser.test.assertTrue(isErrorExpected, `tabs.update with URL ${tabsUpdateURL} should not be rejected`); - browser.test.assertTrue(/^Illegal URL/.test(error.message), - "tabs.update should be rejected with the expected error message"); - } - - browser.test.sendMessage("done"); - }); - }, - }); - - yield extension.startup(); - - let mozExtTabURL = yield extension.awaitMessage("ready"); - - if (tabsUpdateURL == "self") { - tabsUpdateURL = mozExtTabURL; - } - - info(`tab.update URL "${tabsUpdateURL}" on tab with URL "${existentTabURL}"`); - - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, existentTabURL); - - extension.sendMessage("start", tabsUpdateURL, isErrorExpected); - yield extension.awaitMessage("done"); - - yield BrowserTestUtils.removeTab(tab1); - yield extension.unload(); -} - -add_task(function* () { - info("Start testing tabs.update on javascript URLs"); - - let dataURLPage = `data:text/html, - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - <body> - <h1>data url page</h1> - </body> - </html>`; - - let checkList = [ - { - tabsUpdateURL: "http://example.net", - isErrorExpected: false, - }, - { - tabsUpdateURL: "self", - isErrorExpected: false, - }, - { - tabsUpdateURL: "about:addons", - isErrorExpected: true, - }, - { - tabsUpdateURL: "javascript:console.log('tabs.update execute javascript')", - isErrorExpected: true, - }, - { - tabsUpdateURL: dataURLPage, - isErrorExpected: true, - }, - ]; - - let testCases = checkList - .map((check) => Object.assign({}, check, {existentTabURL: "about:blank"})); - - for (let {existentTabURL, tabsUpdateURL, isErrorExpected} of testCases) { - yield* testTabsUpdateURL(existentTabURL, tabsUpdateURL, isErrorExpected); - } - - info("done"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js b/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js deleted file mode 100644 index c2e54d3ea..000000000 --- a/browser/components/extensions/test/browser/browser_ext_tabs_zoom.js +++ /dev/null @@ -1,222 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -const SITE_SPECIFIC_PREF = "browser.zoom.siteSpecific"; - -add_task(function* () { - let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - let tab2 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.net/"); - - gBrowser.selectedTab = tab1; - - async function background() { - function promiseUpdated(tabId, attr) { - return new Promise(resolve => { - let onUpdated = (tabId_, changeInfo, tab) => { - if (tabId == tabId_ && attr in changeInfo) { - browser.tabs.onUpdated.removeListener(onUpdated); - - resolve({changeInfo, tab}); - } - }; - browser.tabs.onUpdated.addListener(onUpdated); - }); - } - - let deferred = {}; - browser.test.onMessage.addListener((message, msg, result) => { - if (message == "msg-done" && deferred[msg]) { - deferred[msg].resolve(result); - } - }); - - let _id = 0; - function msg(...args) { - return new Promise((resolve, reject) => { - let id = ++_id; - deferred[id] = {resolve, reject}; - browser.test.sendMessage("msg", id, ...args); - }); - } - - - let zoomEvents = []; - let eventPromises = []; - browser.tabs.onZoomChange.addListener(info => { - zoomEvents.push(info); - if (eventPromises.length) { - eventPromises.shift().resolve(); - } - }); - - let awaitZoom = async (tabId, newValue) => { - let listener; - - await new Promise(async resolve => { - listener = info => { - if (info.tabId == tabId && info.newZoomFactor == newValue) { - resolve(); - } - }; - browser.tabs.onZoomChange.addListener(listener); - - let zoomFactor = await browser.tabs.getZoom(tabId); - if (zoomFactor == newValue) { - resolve(); - } - }); - - browser.tabs.onZoomChange.removeListener(listener); - }; - - let checkZoom = async (tabId, newValue, oldValue = null) => { - let awaitEvent; - if (oldValue != null && !zoomEvents.length) { - awaitEvent = new Promise(resolve => { - eventPromises.push({resolve}); - }); - } - - let [apiZoom, realZoom] = await Promise.all([ - browser.tabs.getZoom(tabId), - msg("get-zoom", tabId), - awaitEvent, - ]); - - browser.test.assertEq(newValue, apiZoom, `Got expected zoom value from API`); - browser.test.assertEq(newValue, realZoom, `Got expected zoom value from parent`); - - if (oldValue != null) { - let event = zoomEvents.shift(); - browser.test.assertEq(tabId, event.tabId, `Got expected zoom event tab ID`); - browser.test.assertEq(newValue, event.newZoomFactor, `Got expected zoom event zoom factor`); - browser.test.assertEq(oldValue, event.oldZoomFactor, `Got expected zoom event old zoom factor`); - - browser.test.assertEq(3, Object.keys(event.zoomSettings).length, `Zoom settings should have 3 keys`); - browser.test.assertEq("automatic", event.zoomSettings.mode, `Mode should be "automatic"`); - browser.test.assertEq("per-origin", event.zoomSettings.scope, `Scope should be "per-origin"`); - browser.test.assertEq(1, event.zoomSettings.defaultZoomFactor, `Default zoom should be 1`); - } - }; - - try { - let tabs = await browser.tabs.query({lastFocusedWindow: true}); - browser.test.assertEq(tabs.length, 3, "We have three tabs"); - - let tabIds = [tabs[1].id, tabs[2].id]; - await checkZoom(tabIds[0], 1); - - await browser.tabs.setZoom(tabIds[0], 2); - await checkZoom(tabIds[0], 2, 1); - - let zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]); - browser.test.assertEq(3, Object.keys(zoomSettings).length, `Zoom settings should have 3 keys`); - browser.test.assertEq("automatic", zoomSettings.mode, `Mode should be "automatic"`); - browser.test.assertEq("per-origin", zoomSettings.scope, `Scope should be "per-origin"`); - browser.test.assertEq(1, zoomSettings.defaultZoomFactor, `Default zoom should be 1`); - - - browser.test.log(`Switch to tab 2`); - await browser.tabs.update(tabIds[1], {active: true}); - await checkZoom(tabIds[1], 1); - - - browser.test.log(`Navigate tab 2 to origin of tab 1`); - browser.tabs.update(tabIds[1], {url: "http://example.com"}); - await promiseUpdated(tabIds[1], "url"); - await checkZoom(tabIds[1], 2, 1); - - - browser.test.log(`Update zoom in tab 2, expect changes in both tabs`); - await browser.tabs.setZoom(tabIds[1], 1.5); - await checkZoom(tabIds[1], 1.5, 2); - - - browser.test.log(`Switch to tab 1, expect asynchronous zoom change just after the switch`); - await Promise.all([ - awaitZoom(tabIds[0], 1.5), - browser.tabs.update(tabIds[0], {active: true}), - ]); - await checkZoom(tabIds[0], 1.5, 2); - - - browser.test.log("Set zoom to 0, expect it set to 1"); - await browser.tabs.setZoom(tabIds[0], 0); - await checkZoom(tabIds[0], 1, 1.5); - - - browser.test.log("Change zoom externally, expect changes reflected"); - await msg("enlarge"); - await checkZoom(tabIds[0], 1.1, 1); - - await Promise.all([ - browser.tabs.setZoom(tabIds[0], 0), - browser.tabs.setZoom(tabIds[1], 0), - ]); - await Promise.all([ - checkZoom(tabIds[0], 1, 1.1), - checkZoom(tabIds[1], 1, 1.5), - ]); - - - browser.test.log("Check that invalid zoom values throw an error"); - await browser.test.assertRejects( - browser.tabs.setZoom(tabIds[0], 42), - /Zoom value 42 out of range/, - "Expected an out of range error"); - - browser.test.log("Disable site-specific zoom, expect correct scope"); - await msg("site-specific", false); - zoomSettings = await browser.tabs.getZoomSettings(tabIds[0]); - - browser.test.assertEq("per-tab", zoomSettings.scope, `Scope should be "per-tab"`); - await msg("site-specific", null); - - browser.test.notifyPass("tab-zoom"); - } catch (e) { - browser.test.fail(`Error: ${e} :: ${e.stack}`); - browser.test.notifyFail("tab-zoom"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - extension.onMessage("msg", (id, msg, ...args) => { - let {Management: {global: {TabManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let resp; - if (msg == "get-zoom") { - let tab = TabManager.getTab(args[0]); - resp = ZoomManager.getZoomForBrowser(tab.linkedBrowser); - } else if (msg == "set-zoom") { - let tab = TabManager.getTab(args[0]); - ZoomManager.setZoomForBrowser(tab.linkedBrowser); - } else if (msg == "enlarge") { - FullZoom.enlarge(); - } else if (msg == "site-specific") { - if (args[0] == null) { - SpecialPowers.clearUserPref(SITE_SPECIFIC_PREF); - } else { - SpecialPowers.setBoolPref(SITE_SPECIFIC_PREF, args[0]); - } - } - - extension.sendMessage("msg-done", id, resp); - }); - - yield extension.startup(); - - yield extension.awaitFinish("tab-zoom"); - - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_topwindowid.js b/browser/components/extensions/test/browser/browser_ext_topwindowid.js deleted file mode 100644 index 9176ac946..000000000 --- a/browser/components/extensions/test/browser/browser_ext_topwindowid.js +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* test_topwindowid_cleanup() { - let {Frames} = Cu.import("resource://gre/modules/ExtensionManagement.jsm", {}); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/"); - - let {outerWindowID, messageManager} = tab.linkedBrowser; - - ok(Frames.topWindowIds.has(outerWindowID), "Outer window ID is registered"); - - let awaitDisconnect = TestUtils.topicObserved("message-manager-disconnect", - subject => subject === messageManager); - - yield BrowserTestUtils.removeTab(tab); - - yield awaitDisconnect; - - ok(!Frames.topWindowIds.has(outerWindowID), "Outer window ID is no longer registered"); -}); - diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js deleted file mode 100644 index 0058ca065..000000000 --- a/browser/components/extensions/test/browser/browser_ext_webNavigation_frameId0.js +++ /dev/null @@ -1,45 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* webNavigation_getFrameId_of_existing_main_frame() { - // Whether the frame ID in the extension API is 0 is determined by a map that - // is maintained by |Frames| in ExtensionManagement.jsm. This map is filled - // using data from content processes. But if ExtensionManagement.jsm is not - // imported, then the "Extension:TopWindowID" message gets lost. - // As a result, if the state is not synchronized again, the webNavigation API - // will mistakenly report a non-zero frame ID for top-level frames. - // - // If you want to be absolutely sure that the frame ID is correct, don't open - // tabs before starting an extension, or explicitly load the module in the - // main process: - // Cu.import("resource://gre/modules/ExtensionManagement.jsm", {}); - // - // Or simply run the test again. - const BASE = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/"; - const DUMMY_URL = BASE + "file_dummy.html"; - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, DUMMY_URL, true); - - async function background(DUMMY_URL) { - let tabs = await browser.tabs.query({active: true, currentWindow: true}); - let frames = await browser.webNavigation.getAllFrames({tabId: tabs[0].id}); - browser.test.assertEq(1, frames.length, "The dummy page has one frame"); - browser.test.assertEq(0, frames[0].frameId, "Main frame's ID must be 0"); - browser.test.assertEq(DUMMY_URL, frames[0].url, "Main frame URL must match"); - browser.test.notifyPass("frameId checked"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["webNavigation"], - }, - - background: `(${background})(${JSON.stringify(DUMMY_URL)});`, - }); - - yield extension.startup(); - yield extension.awaitFinish("frameId checked"); - yield extension.unload(); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js deleted file mode 100644 index 6b4a597ad..000000000 --- a/browser/components/extensions/test/browser/browser_ext_webNavigation_getFrames.js +++ /dev/null @@ -1,168 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testWebNavigationGetNonExistentTab() { - let extension = ExtensionTestUtils.loadExtension({ - background: async function() { - // There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js) - // starts from 1. - await browser.test.assertRejects( - browser.webNavigation.getAllFrames({tabId: 0}), - "Invalid tab ID: 0", - "getAllFrames rejected Promise should pass the expected error"); - - // There is no "tabId = 0" because the id assigned by TabManager (defined in ext-utils.js) - // starts from 1, processId is currently marked as optional and it is ignored. - await browser.test.assertRejects( - browser.webNavigation.getFrame({tabId: 0, frameId: 15, processId: 20}), - "Invalid tab ID: 0", - "getFrame rejected Promise should pass the expected error"); - - browser.test.sendMessage("getNonExistentTab.done"); - }, - manifest: { - permissions: ["webNavigation"], - }, - }); - info("load complete"); - - yield extension.startup(); - info("startup complete"); - - yield extension.awaitMessage("getNonExistentTab.done"); - - yield extension.unload(); - info("extension unloaded"); -}); - -add_task(function* testWebNavigationFrames() { - let extension = ExtensionTestUtils.loadExtension({ - background: async function() { - let tabId; - let collectedDetails = []; - - browser.webNavigation.onCompleted.addListener(async details => { - collectedDetails.push(details); - - if (details.frameId !== 0) { - // wait for the top level iframe to be complete - return; - } - - let getAllFramesDetails = await browser.webNavigation.getAllFrames({tabId}); - - let getFramePromises = getAllFramesDetails.map(({frameId}) => { - // processId is currently marked as optional and it is ignored. - return browser.webNavigation.getFrame({tabId, frameId, processId: 0}); - }); - - let getFrameResults = await Promise.all(getFramePromises); - browser.test.sendMessage("webNavigationFrames.done", { - collectedDetails, getAllFramesDetails, getFrameResults, - }); - - // Pick a random frameId. - let nonExistentFrameId = Math.floor(Math.random() * 10000); - - // Increment the picked random nonExistentFrameId until it doesn't exists. - while (getAllFramesDetails.filter((details) => details.frameId == nonExistentFrameId).length > 0) { - nonExistentFrameId += 1; - } - - // Check that getFrame Promise is rejected with the expected error message on nonexistent frameId. - await browser.test.assertRejects( - browser.webNavigation.getFrame({tabId, frameId: nonExistentFrameId, processId: 20}), - `No frame found with frameId: ${nonExistentFrameId}`, - "getFrame promise should be rejected with the expected error message on unexistent frameId"); - - await browser.tabs.remove(tabId); - browser.test.sendMessage("webNavigationFrames.done"); - }); - - let tab = await browser.tabs.create({url: "tab.html"}); - tabId = tab.id; - }, - manifest: { - permissions: ["webNavigation", "tabs"], - }, - files: { - "tab.html": ` - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - <body> - <iframe src="subframe.html"></iframe> - <iframe src="subframe.html"></iframe> - </body> - </html> - `, - "subframe.html": ` - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"> - </head> - </html> - `, - }, - }); - info("load complete"); - - yield extension.startup(); - info("startup complete"); - - let { - collectedDetails, - getAllFramesDetails, - getFrameResults, - } = yield extension.awaitMessage("webNavigationFrames.done"); - - is(getAllFramesDetails.length, 3, "expected number of frames found"); - is(getAllFramesDetails.length, collectedDetails.length, - "number of frames found should equal the number onCompleted events collected"); - - is(getAllFramesDetails[0].frameId, 0, "the root frame has the expected frameId"); - is(getAllFramesDetails[0].parentFrameId, -1, "the root frame has the expected parentFrameId"); - - // ordered by frameId - let sortByFrameId = (el1, el2) => { - let val1 = el1 ? el1.frameId : -1; - let val2 = el2 ? el2.frameId : -1; - return val1 - val2; - }; - - collectedDetails = collectedDetails.sort(sortByFrameId); - getAllFramesDetails = getAllFramesDetails.sort(sortByFrameId); - getFrameResults = getFrameResults.sort(sortByFrameId); - - info("check frame details content"); - - is(getFrameResults.length, getAllFramesDetails.length, - "getFrame and getAllFrames should return the same number of results"); - - Assert.deepEqual(getFrameResults, getAllFramesDetails, - "getFrame and getAllFrames should return the same results"); - - info(`check frame details collected and retrieved with getAllFrames`); - - for (let [i, collected] of collectedDetails.entries()) { - let getAllFramesDetail = getAllFramesDetails[i]; - - is(getAllFramesDetail.frameId, collected.frameId, "frameId"); - is(getAllFramesDetail.parentFrameId, collected.parentFrameId, "parentFrameId"); - is(getAllFramesDetail.tabId, collected.tabId, "tabId"); - - // This can be uncommented once Bug 1246125 has been fixed - // is(getAllFramesDetail.url, collected.url, "url"); - } - - info("frame details content checked"); - - yield extension.awaitMessage("webNavigationFrames.done"); - - yield extension.unload(); - info("extension unloaded"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js b/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js deleted file mode 100644 index f2ea0d901..000000000 --- a/browser/components/extensions/test/browser/browser_ext_webNavigation_urlbar_transitions.js +++ /dev/null @@ -1,251 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", - "resource://gre/modules/PlacesUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); - -const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches"; -const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml"; - -function* promiseAutocompleteResultPopup(inputText) { - gURLBar.focus(); - gURLBar.value = inputText; - gURLBar.controller.startSearch(inputText); - yield promisePopupShown(gURLBar.popup); - yield BrowserTestUtils.waitForCondition(() => { - return gURLBar.controller.searchStatus >= - Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH; - }); -} - -function* addBookmark(bookmark) { - if (bookmark.keyword) { - yield PlacesUtils.keywords.insert({ - keyword: bookmark.keyword, - url: bookmark.url, - }); - } - - yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - url: bookmark.url, - title: bookmark.title, - }); - - registerCleanupFunction(function* () { - yield PlacesUtils.bookmarks.eraseEverything(); - }); -} - -function addSearchEngine(basename) { - return new Promise((resolve, reject) => { - info("Waiting for engine to be added: " + basename); - let url = getRootDirectory(gTestPath) + basename; - Services.search.addEngine(url, null, "", false, { - onSuccess: (engine) => { - info(`Search engine added: ${basename}`); - registerCleanupFunction(() => Services.search.removeEngine(engine)); - resolve(engine); - }, - onError: (errCode) => { - ok(false, `addEngine failed with error code ${errCode}`); - reject(); - }, - }); - }); -} - -function* prepareSearchEngine() { - let oldCurrentEngine = Services.search.currentEngine; - Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true); - let engine = yield addSearchEngine(TEST_ENGINE_BASENAME); - Services.search.currentEngine = engine; - - registerCleanupFunction(function* () { - Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF); - Services.search.currentEngine = oldCurrentEngine; - - // Make sure the popup is closed for the next test. - gURLBar.blur(); - gURLBar.popup.selectedIndex = -1; - gURLBar.popup.hidePopup(); - ok(!gURLBar.popup.popupOpen, "popup should be closed"); - - // Clicking suggestions causes visits to search results pages, so clear that - // history now. - yield PlacesTestUtils.clearHistory(); - }); -} - -add_task(function* test_webnavigation_urlbar_typed_transitions() { - function backgroundScript() { - browser.webNavigation.onCommitted.addListener((msg) => { - browser.test.assertEq("http://example.com/?q=typed", msg.url, - "Got the expected url"); - // assert from_address_bar transition qualifier - browser.test.assertTrue(msg.transitionQualifiers && - msg.transitionQualifiers.includes("from_address_bar"), - "Got the expected from_address_bar transitionQualifier"); - browser.test.assertEq("typed", msg.transitionType, - "Got the expected transitionType"); - browser.test.notifyPass("webNavigation.from_address_bar.typed"); - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: backgroundScript, - manifest: { - permissions: ["webNavigation"], - }, - }); - - yield extension.startup(); - - yield extension.awaitMessage("ready"); - - gURLBar.focus(); - gURLBar.textValue = "http://example.com/?q=typed"; - - EventUtils.synthesizeKey("VK_RETURN", {altKey: true}); - - yield extension.awaitFinish("webNavigation.from_address_bar.typed"); - - yield extension.unload(); - info("extension unloaded"); -}); - -add_task(function* test_webnavigation_urlbar_bookmark_transitions() { - function backgroundScript() { - browser.webNavigation.onCommitted.addListener((msg) => { - browser.test.assertEq("http://example.com/?q=bookmark", msg.url, - "Got the expected url"); - - // assert from_address_bar transition qualifier - browser.test.assertTrue(msg.transitionQualifiers && - msg.transitionQualifiers.includes("from_address_bar"), - "Got the expected from_address_bar transitionQualifier"); - browser.test.assertEq("auto_bookmark", msg.transitionType, - "Got the expected transitionType"); - browser.test.notifyPass("webNavigation.from_address_bar.auto_bookmark"); - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: backgroundScript, - manifest: { - permissions: ["webNavigation"], - }, - }); - - yield addBookmark({ - title: "Bookmark To Click", - url: "http://example.com/?q=bookmark", - }); - - yield extension.startup(); - - yield extension.awaitMessage("ready"); - - yield promiseAutocompleteResultPopup("Bookmark To Click"); - - let item = gURLBar.popup.richlistbox.getItemAtIndex(1); - item.click(); - yield extension.awaitFinish("webNavigation.from_address_bar.auto_bookmark"); - - yield extension.unload(); - info("extension unloaded"); -}); - -add_task(function* test_webnavigation_urlbar_keyword_transition() { - function backgroundScript() { - browser.webNavigation.onCommitted.addListener((msg) => { - browser.test.assertEq(`http://example.com/?q=search`, msg.url, - "Got the expected url"); - - // assert from_address_bar transition qualifier - browser.test.assertTrue(msg.transitionQualifiers && - msg.transitionQualifiers.includes("from_address_bar"), - "Got the expected from_address_bar transitionQualifier"); - browser.test.assertEq("keyword", msg.transitionType, - "Got the expected transitionType"); - browser.test.notifyPass("webNavigation.from_address_bar.keyword"); - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: backgroundScript, - manifest: { - permissions: ["webNavigation"], - }, - }); - - yield addBookmark({ - title: "Test Keyword", - url: "http://example.com/?q=%s", - keyword: "testkw", - }); - - yield extension.startup(); - - yield extension.awaitMessage("ready"); - - yield promiseAutocompleteResultPopup("testkw search"); - - let item = gURLBar.popup.richlistbox.getItemAtIndex(0); - item.click(); - - yield extension.awaitFinish("webNavigation.from_address_bar.keyword"); - - yield extension.unload(); - info("extension unloaded"); -}); - -add_task(function* test_webnavigation_urlbar_search_transitions() { - function backgroundScript() { - browser.webNavigation.onCommitted.addListener((msg) => { - browser.test.assertEq("http://mochi.test:8888/", msg.url, - "Got the expected url"); - - // assert from_address_bar transition qualifier - browser.test.assertTrue(msg.transitionQualifiers && - msg.transitionQualifiers.includes("from_address_bar"), - "Got the expected from_address_bar transitionQualifier"); - browser.test.assertEq("generated", msg.transitionType, - "Got the expected 'generated' transitionType"); - browser.test.notifyPass("webNavigation.from_address_bar.generated"); - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: backgroundScript, - manifest: { - permissions: ["webNavigation"], - }, - }); - - yield extension.startup(); - - yield extension.awaitMessage("ready"); - - yield prepareSearchEngine(); - yield promiseAutocompleteResultPopup("foo"); - - let item = gURLBar.popup.richlistbox.getItemAtIndex(0); - item.click(); - - yield extension.awaitFinish("webNavigation.from_address_bar.generated"); - - yield extension.unload(); - info("extension unloaded"); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_webRequest.js b/browser/components/extensions/test/browser/browser_ext_webRequest.js deleted file mode 100644 index ab9f58480..000000000 --- a/browser/components/extensions/test/browser/browser_ext_webRequest.js +++ /dev/null @@ -1,95 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -/* globals makeExtension */ -"use strict"; - -Services.scriptloader.loadSubScript(new URL("head_webrequest.js", gTestPath).href, - this); - -Cu.import("resource:///modules/HiddenFrame.jsm", this); -const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; - -function createHiddenBrowser(url) { - let frame = new HiddenFrame(); - return new Promise(resolve => - frame.get().then(subframe => { - let doc = subframe.document; - let browser = doc.createElementNS(XUL_NS, "browser"); - browser.setAttribute("type", "content"); - browser.setAttribute("disableglobalhistory", "true"); - browser.setAttribute("src", url); - - doc.documentElement.appendChild(browser); - resolve({frame: frame, browser: browser}); - })); -} - -let extension; -let dummy = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/file_dummy.html"; - -add_task(function* setup() { - // SelfSupport has a tendency to fire when running this test alone, without - // a good way to turn it off we just set the url to "" - yield SpecialPowers.pushPrefEnv({ - set: [["browser.selfsupport.url", ""]], - }); - extension = makeExtension(); - yield extension.startup(); -}); - -add_task(function* test_newWindow() { - let expect = { - "file_dummy.html": { - type: "main_frame", - }, - }; - // NOTE: When running solo, favicon will be loaded at some point during - // the tests in this file, so all tests ignore it. When running with - // other tests in this directory, favicon gets loaded at some point before - // we run, and we never see the request, thus it cannot be handled as part - // of expect above. - extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]}); - yield extension.awaitMessage("continue"); - - let openedWindow = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.openNewForegroundTab(openedWindow.gBrowser, dummy + "?newWindow"); - - yield extension.awaitMessage("done"); - yield BrowserTestUtils.closeWindow(openedWindow); -}); - -add_task(function* test_newTab() { - // again, in this window - let expect = { - "file_dummy.html": { - type: "main_frame", - }, - }; - extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]}); - yield extension.awaitMessage("continue"); - let tab = yield BrowserTestUtils.openNewForegroundTab(window.gBrowser, dummy + "?newTab"); - - yield extension.awaitMessage("done"); - yield BrowserTestUtils.removeTab(tab); -}); - -add_task(function* test_subframe() { - let expect = { - "file_dummy.html": { - type: "main_frame", - }, - }; - // test a content subframe attached to hidden window - extension.sendMessage("set-expected", {expect, ignore: ["favicon.ico"]}); - yield extension.awaitMessage("continue"); - let frameInfo = yield createHiddenBrowser(dummy + "?subframe"); - yield extension.awaitMessage("done"); - // cleanup - frameInfo.browser.remove(); - frameInfo.frame.destroy(); -}); - -add_task(function* teardown() { - yield extension.unload(); -}); - diff --git a/browser/components/extensions/test/browser/browser_ext_windows.js b/browser/components/extensions/test/browser/browser_ext_windows.js deleted file mode 100644 index d3dd6ecdb..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows.js +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - let raisedWin = Services.ww.openWindow( - null, Services.prefs.getCharPref("browser.chromeURL"), "_blank", - "chrome,dialog=no,all,alwaysRaised", null); - - yield TestUtils.topicObserved("browser-delayed-startup-finished", - subject => subject == raisedWin); - - let extension = ExtensionTestUtils.loadExtension({ - background: function() { - browser.windows.getAll((wins) => { - browser.test.assertEq(wins.length, 2, "Expect two windows"); - - browser.test.assertEq(false, wins[0].alwaysOnTop, - "Expect first window not to be always on top"); - browser.test.assertEq(true, wins[1].alwaysOnTop, - "Expect first window to be always on top"); - - browser.test.notifyPass("alwaysOnTop"); - }); - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("alwaysOnTop"); - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(raisedWin); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js b/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js deleted file mode 100644 index 13f8b2eee..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_allowScriptsToClose.js +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -// Tests allowScriptsToClose option -add_task(function* test_allowScriptsToClose() { - const files = { - "dummy.html": "<meta charset=utf-8><script src=close.js></script>", - "close.js": function() { - window.close(); - if (!window.closed) { - browser.test.sendMessage("close-failed"); - } - }, - }; - - function background() { - browser.test.onMessage.addListener((msg, options) => { - function listener(_, {status}, {url}) { - if (status == "complete" && url == options.url) { - browser.tabs.onUpdated.removeListener(listener); - browser.tabs.executeScript({file: "close.js"}); - } - } - options.url = browser.runtime.getURL(options.url); - browser.windows.create(options); - if (msg === "create+execute") { - browser.tabs.onUpdated.addListener(listener); - } - }); - browser.test.notifyPass(); - } - - const example = "http://example.com/"; - const manifest = {permissions: ["tabs", example]}; - - const extension = ExtensionTestUtils.loadExtension({files, background, manifest}); - yield SpecialPowers.pushPrefEnv({set: [["dom.allow_scripts_to_close_windows", false]]}); - - yield extension.startup(); - yield extension.awaitFinish(); - - extension.sendMessage("create", {url: "dummy.html"}); - let win = yield BrowserTestUtils.waitForNewWindow(); - yield BrowserTestUtils.windowClosed(win); - info("script allowed to close the window"); - - extension.sendMessage("create+execute", {url: example}); - win = yield BrowserTestUtils.waitForNewWindow(); - yield extension.awaitMessage("close-failed"); - info("script prevented from closing the window"); - win.close(); - - extension.sendMessage("create+execute", {url: example, allowScriptsToClose: true}); - win = yield BrowserTestUtils.waitForNewWindow(); - yield BrowserTestUtils.windowClosed(win); - info("script allowed to close the window"); - - yield SpecialPowers.popPrefEnv(); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create.js b/browser/components/extensions/test/browser/browser_ext_windows_create.js deleted file mode 100644 index f209c9836..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_create.js +++ /dev/null @@ -1,142 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -requestLongerTimeout(2); - -add_task(function* testWindowCreate() { - let extension = ExtensionTestUtils.loadExtension({ - async background() { - let _checkWindowPromise; - browser.test.onMessage.addListener(msg => { - if (msg == "checked-window") { - _checkWindowPromise.resolve(); - _checkWindowPromise = null; - } - }); - - let os; - - function checkWindow(expected) { - return new Promise(resolve => { - _checkWindowPromise = {resolve}; - browser.test.sendMessage("check-window", expected); - }); - } - - async function createWindow(params, expected, keep = false) { - let window = await browser.windows.create(...params); - // params is null when testing create without createData - params = params[0] || {}; - - for (let key of Object.keys(params)) { - if (key == "state" && os == "mac" && params.state == "normal") { - // OS-X doesn't have a hard distinction between "normal" and - // "maximized" states. - browser.test.assertTrue(window.state == "normal" || window.state == "maximized", - `Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`); - } else { - browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`); - } - } - - browser.test.assertEq(1, window.tabs.length, "tabs property got populated"); - - await checkWindow(expected); - if (keep) { - return window; - } - - if (params.state == "fullscreen" && os == "win") { - // FIXME: Closing a fullscreen window causes a window leak in - // Windows tests. - await browser.windows.update(window.id, {state: "normal"}); - } - await browser.windows.remove(window.id); - } - - try { - ({os} = await browser.runtime.getPlatformInfo()); - - // Set the current window to state: "normal" because the test is failing on Windows - // where the current window is maximized. - let currentWindow = await browser.windows.getCurrent(); - await browser.windows.update(currentWindow.id, {state: "normal"}); - - await createWindow([], {state: "STATE_NORMAL"}); - await createWindow([{state: "maximized"}], {state: "STATE_MAXIMIZED"}); - await createWindow([{state: "minimized"}], {state: "STATE_MINIMIZED"}); - await createWindow([{state: "normal"}], {state: "STATE_NORMAL", hiddenChrome: []}); - await createWindow([{state: "fullscreen"}], {state: "STATE_FULLSCREEN"}); - - let window = await createWindow( - [{type: "popup"}], - {hiddenChrome: ["menubar", "toolbar", "location", "directories", "status", "extrachrome"], - chromeFlags: ["CHROME_OPENAS_DIALOG"]}, - true); - - let tabs = await browser.tabs.query({windowType: "popup", active: true}); - - browser.test.assertEq(1, tabs.length, "Expected only one popup"); - browser.test.assertEq(window.id, tabs[0].windowId, "Expected new window to be returned in query"); - - await browser.windows.remove(window.id); - - browser.test.notifyPass("window-create"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-create"); - } - }, - }); - - let latestWindow; - let windowListener = (window, topic) => { - if (topic == "domwindowopened") { - latestWindow = window; - } - }; - Services.ww.registerNotification(windowListener); - - extension.onMessage("check-window", expected => { - if (expected.state != null) { - let {windowState} = latestWindow; - if (latestWindow.fullScreen) { - windowState = latestWindow.STATE_FULLSCREEN; - } - - if (expected.state == "STATE_NORMAL" && AppConstants.platform == "macosx") { - ok(windowState == window.STATE_NORMAL || windowState == window.STATE_MAXIMIZED, - `Expected windowState (currently ${windowState}) to be STATE_NORMAL but will accept STATE_MAXIMIZED`); - } else { - is(windowState, window[expected.state], - `Expected window state to be ${expected.state}`); - } - } - if (expected.hiddenChrome) { - let chromeHidden = latestWindow.document.documentElement.getAttribute("chromehidden"); - is(chromeHidden.trim().split(/\s+/).sort().join(" "), - expected.hiddenChrome.sort().join(" "), - "Got expected hidden chrome"); - } - if (expected.chromeFlags) { - let {chromeFlags} = latestWindow.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDocShell) - .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIXULWindow); - for (let flag of expected.chromeFlags) { - ok(chromeFlags & Ci.nsIWebBrowserChrome[flag], - `Expected window to have the ${flag} flag`); - } - } - - extension.sendMessage("checked-window"); - }); - - yield extension.startup(); - yield extension.awaitFinish("window-create"); - yield extension.unload(); - - Services.ww.unregisterNotification(windowListener); - latestWindow = null; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_params.js b/browser/components/extensions/test/browser/browser_ext_windows_create_params.js deleted file mode 100644 index c54d94e05..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_create_params.js +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - - -// Tests that incompatible parameters can't be used together. -add_task(function* testWindowCreateParams() { - let extension = ExtensionTestUtils.loadExtension({ - async background() { - try { - for (let state of ["minimized", "maximized", "fullscreen"]) { - for (let param of ["left", "top", "width", "height"]) { - let expected = `"state": "${state}" may not be combined with "left", "top", "width", or "height"`; - - await browser.test.assertRejects( - browser.windows.create({state, [param]: 100}), - RegExp(expected), - `Got expected error from create(${param}=100)`); - } - } - - browser.test.notifyPass("window-create-params"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-create-params"); - } - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("window-create-params"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js b/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js deleted file mode 100644 index 52ffaea8b..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_create_tabId.js +++ /dev/null @@ -1,140 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testWindowCreate() { - async function background() { - let promiseTabAttached = () => { - return new Promise(resolve => { - browser.tabs.onAttached.addListener(function listener() { - browser.tabs.onAttached.removeListener(listener); - resolve(); - }); - }); - }; - - let promiseTabUpdated = (expected) => { - return new Promise(resolve => { - browser.tabs.onUpdated.addListener(function listener(tabId, changeInfo, tab) { - if (changeInfo.url === expected) { - browser.tabs.onUpdated.removeListener(listener); - resolve(); - } - }); - }); - }; - - try { - let window = await browser.windows.getCurrent(); - let windowId = window.id; - - browser.test.log("Create additional tab in window 1"); - let tab = await browser.tabs.create({windowId, url: "about:blank"}); - let tabId = tab.id; - - browser.test.log("Create a new window, adopting the new tab"); - - // Note that we want to check against actual boolean values for - // all of the `incognito` property tests. - browser.test.assertEq(false, tab.incognito, "Tab is not private"); - - { - let [, window] = await Promise.all([ - promiseTabAttached(), - browser.windows.create({tabId: tabId}), - ]); - browser.test.assertEq(false, window.incognito, "New window is not private"); - browser.test.assertEq(tabId, window.tabs[0].id, "tabs property populated correctly"); - - browser.test.log("Close the new window"); - await browser.windows.remove(window.id); - } - - { - browser.test.log("Create a new private window"); - let privateWindow = await browser.windows.create({incognito: true}); - browser.test.assertEq(true, privateWindow.incognito, "Private window is private"); - - browser.test.log("Create additional tab in private window"); - let privateTab = await browser.tabs.create({windowId: privateWindow.id}); - browser.test.assertEq(true, privateTab.incognito, "Private tab is private"); - - browser.test.log("Create a new window, adopting the new private tab"); - let [, newWindow] = await Promise.all([ - promiseTabAttached(), - browser.windows.create({tabId: privateTab.id}), - ]); - browser.test.assertEq(true, newWindow.incognito, "New private window is private"); - - browser.test.log("Close the new private window"); - await browser.windows.remove(newWindow.id); - - browser.test.log("Close the private window"); - await browser.windows.remove(privateWindow.id); - } - - - browser.test.log("Try to create a window with both a tab and a URL"); - [tab] = await browser.tabs.query({windowId, active: true}); - await browser.test.assertRejects( - browser.windows.create({tabId: tab.id, url: "http://example.com/"}), - /`tabId` may not be used in conjunction with `url`/, - "Create call failed as expected"); - - browser.test.log("Try to create a window with both a tab and an invalid incognito setting"); - await browser.test.assertRejects( - browser.windows.create({tabId: tab.id, incognito: true}), - /`incognito` property must match the incognito state of tab/, - "Create call failed as expected"); - - - browser.test.log("Try to create a window with an invalid tabId"); - await browser.test.assertRejects( - browser.windows.create({tabId: 0}), - /Invalid tab ID: 0/, - "Create call failed as expected"); - - - browser.test.log("Try to create a window with two URLs"); - let readyPromise = Promise.all([ - // tabs.onUpdated can be invoked between the call of windows.create and - // the invocation of its callback/promise, so set up the listeners - // before creating the window. - promiseTabUpdated("http://example.com/"), - promiseTabUpdated("http://example.org/"), - ]); - - window = await browser.windows.create({url: ["http://example.com/", "http://example.org/"]}); - await readyPromise; - - browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window"); - browser.test.assertEq("about:blank", window.tabs[0].url, "about:blank, page not loaded yet"); - browser.test.assertEq("about:blank", window.tabs[1].url, "about:blank, page not loaded yet"); - - window = await browser.windows.get(window.id, {populate: true}); - - browser.test.assertEq(2, window.tabs.length, "2 tabs were opened in new window"); - browser.test.assertEq("http://example.com/", window.tabs[0].url, "Correct URL was loaded in tab 1"); - browser.test.assertEq("http://example.org/", window.tabs[1].url, "Correct URL was loaded in tab 2"); - - await browser.windows.remove(window.id); - - browser.test.notifyPass("window-create"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-create"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - "permissions": ["tabs"], - }, - - background, - }); - - yield extension.startup(); - yield extension.awaitFinish("window-create"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_create_url.js b/browser/components/extensions/test/browser/browser_ext_windows_create_url.js deleted file mode 100644 index c5c7aaf20..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_create_url.js +++ /dev/null @@ -1,84 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testWindowCreate() { - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["tabs"], - }, - - background: async function() { - const EXTENSION_URL = browser.runtime.getURL("test.html"); - const REMOTE_URL = browser.runtime.getURL("test.html"); - - let windows = new class extends Map { // eslint-disable-line new-parens - get(id) { - if (!this.has(id)) { - let window = { - tabs: new Map(), - }; - window.promise = new Promise(resolve => { - window.resolvePromise = resolve; - }); - - this.set(id, window); - } - - return super.get(id); - } - }; - - browser.tabs.onUpdated.addListener((tabId, changed, tab) => { - if (changed.status == "complete" && tab.url !== "about:blank") { - let window = windows.get(tab.windowId); - window.tabs.set(tab.index, tab); - - if (window.tabs.size === window.expectedTabs) { - window.resolvePromise(window); - } - } - }); - - async function create(options) { - let window = await browser.windows.create(options); - let win = windows.get(window.id); - - win.expectedTabs = Array.isArray(options.url) ? options.url.length : 1; - - return win.promise; - } - - try { - let windows = await Promise.all([ - create({url: REMOTE_URL}), - create({url: "test.html"}), - create({url: EXTENSION_URL}), - create({url: [REMOTE_URL, "test.html", EXTENSION_URL]}), - ]); - browser.test.assertEq(REMOTE_URL, windows[0].tabs.get(0).url, "Single, absolute, remote URL"); - - browser.test.assertEq(REMOTE_URL, windows[1].tabs.get(0).url, "Single, relative URL"); - - browser.test.assertEq(REMOTE_URL, windows[2].tabs.get(0).url, "Single, absolute, extension URL"); - - browser.test.assertEq(REMOTE_URL, windows[3].tabs.get(0).url, "url[0]: Absolute, remote URL"); - browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(1).url, "url[1]: Relative URL"); - browser.test.assertEq(EXTENSION_URL, windows[3].tabs.get(2).url, "url[2]: Absolute, extension URL"); - - browser.test.notifyPass("window-create-url"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-create-url"); - } - }, - - files: { - "test.html": `<DOCTYPE html><html><head><meta charset="utf-8"></head></html>`, - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("window-create-url"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_events.js b/browser/components/extensions/test/browser/browser_ext_windows_events.js deleted file mode 100644 index dc3485b98..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_events.js +++ /dev/null @@ -1,115 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -SimpleTest.requestCompleteLog(); - -add_task(function* testWindowsEvents() { - function background() { - browser.windows.onCreated.addListener(window => { - browser.test.log(`onCreated: windowId=${window.id}`); - - browser.test.assertTrue(Number.isInteger(window.id), - "Window object's id is an integer"); - browser.test.assertEq("normal", window.type, - "Window object returned with the correct type"); - browser.test.sendMessage("window-created", window.id); - }); - - let lastWindowId, os; - browser.windows.onFocusChanged.addListener(async windowId => { - browser.test.log(`onFocusChange: windowId=${windowId} lastWindowId=${lastWindowId}`); - - if (windowId === browser.windows.WINDOW_ID_NONE && os === "linux") { - browser.test.log("Ignoring a superfluous WINDOW_ID_NONE (blur) event on Linux"); - return; - } - - browser.test.assertTrue(lastWindowId !== windowId, - "onFocusChanged fired once for the given window"); - lastWindowId = windowId; - - browser.test.assertTrue(Number.isInteger(windowId), - "windowId is an integer"); - - let window = await browser.windows.getLastFocused(); - - browser.test.assertEq(windowId, window.id, - "Last focused window has the correct id"); - browser.test.sendMessage(`window-focus-changed`, window.id); - }); - - browser.windows.onRemoved.addListener(windowId => { - browser.test.log(`onRemoved: windowId=${windowId}`); - - browser.test.assertTrue(Number.isInteger(windowId), - "windowId is an integer"); - browser.test.sendMessage(`window-removed`, windowId); - browser.test.notifyPass("windows.events"); - }); - - browser.runtime.getPlatformInfo(info => { - os = info.os; - browser.test.sendMessage("ready"); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - background: `(${background})()`, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - - let {Management: {global: {WindowManager}}} = Cu.import("resource://gre/modules/Extension.jsm", {}); - - let currentWindow = window; - let currentWindowId = WindowManager.getId(currentWindow); - info(`Current window ID: ${currentWindowId}`); - - info(`Create browser window 1`); - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - let win1Id = yield extension.awaitMessage("window-created"); - info(`Window 1 ID: ${win1Id}`); - - // This shouldn't be necessary, but tests intermittently fail, so let's give - // it a try. - win1.focus(); - - let winId = yield extension.awaitMessage(`window-focus-changed`); - is(winId, win1Id, "Got focus change event for the correct window ID."); - - info(`Create browser window 2`); - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - let win2Id = yield extension.awaitMessage("window-created"); - info(`Window 2 ID: ${win2Id}`); - - win2.focus(); - - winId = yield extension.awaitMessage(`window-focus-changed`); - is(winId, win2Id, "Got focus change event for the correct window ID."); - - info(`Focus browser window 1`); - yield focusWindow(win1); - - winId = yield extension.awaitMessage(`window-focus-changed`); - is(winId, win1Id, "Got focus change event for the correct window ID."); - - info(`Close browser window 2`); - yield BrowserTestUtils.closeWindow(win2); - - winId = yield extension.awaitMessage(`window-removed`); - is(winId, win2Id, "Got removed event for the correct window ID."); - - info(`Close browser window 1`); - yield BrowserTestUtils.closeWindow(win1); - - winId = yield extension.awaitMessage(`window-removed`); - is(winId, win1Id, "Got removed event for the correct window ID."); - - winId = yield extension.awaitMessage(`window-focus-changed`); - is(winId, currentWindowId, "Got focus change event for the correct window ID."); - - yield extension.awaitFinish("windows.events"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_size.js b/browser/components/extensions/test/browser/browser_ext_windows_size.js deleted file mode 100644 index be822fea1..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_size.js +++ /dev/null @@ -1,114 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* testWindowCreate() { - let extension = ExtensionTestUtils.loadExtension({ - async background() { - let _checkWindowPromise; - browser.test.onMessage.addListener((msg, arg) => { - if (msg == "checked-window") { - _checkWindowPromise.resolve(arg); - _checkWindowPromise = null; - } - }); - - let getWindowSize = () => { - return new Promise(resolve => { - _checkWindowPromise = {resolve}; - browser.test.sendMessage("check-window"); - }); - }; - - const KEYS = ["left", "top", "width", "height"]; - function checkGeom(expected, actual) { - for (let key of KEYS) { - browser.test.assertEq(expected[key], actual[key], `Expected '${key}' value`); - } - } - - let windowId; - async function checkWindow(expected, retries = 5) { - let geom = await getWindowSize(); - - if (retries && KEYS.some(key => expected[key] != geom[key])) { - browser.test.log(`Got mismatched size (${JSON.stringify(expected)} != ${JSON.stringify(geom)}). ` + - `Retrying after a short delay.`); - - await new Promise(resolve => setTimeout(resolve, 200)); - - return checkWindow(expected, retries - 1); - } - - browser.test.log(`Check actual window size`); - checkGeom(expected, geom); - - browser.test.log("Check API-reported window size"); - - geom = await browser.windows.get(windowId); - - checkGeom(expected, geom); - } - - try { - let geom = {left: 100, top: 100, width: 500, height: 300}; - - let window = await browser.windows.create(geom); - windowId = window.id; - - await checkWindow(geom); - - let update = {left: 150, width: 600}; - Object.assign(geom, update); - await browser.windows.update(windowId, update); - await checkWindow(geom); - - update = {top: 150, height: 400}; - Object.assign(geom, update); - await browser.windows.update(windowId, update); - await checkWindow(geom); - - geom = {left: 200, top: 200, width: 800, height: 600}; - await browser.windows.update(windowId, geom); - await checkWindow(geom); - - let platformInfo = await browser.runtime.getPlatformInfo(); - if (platformInfo.os != "linux") { - geom = {left: -50, top: -50, width: 800, height: 600}; - await browser.windows.update(windowId, geom); - await checkWindow(geom); - } - - await browser.windows.remove(windowId); - browser.test.notifyPass("window-size"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-size"); - } - }, - }); - - let latestWindow; - let windowListener = (window, topic) => { - if (topic == "domwindowopened") { - latestWindow = window; - } - }; - Services.ww.registerNotification(windowListener); - - extension.onMessage("check-window", () => { - extension.sendMessage("checked-window", { - top: latestWindow.screenY, - left: latestWindow.screenX, - width: latestWindow.outerWidth, - height: latestWindow.outerHeight, - }); - }); - - yield extension.startup(); - yield extension.awaitFinish("window-size"); - yield extension.unload(); - - Services.ww.unregisterNotification(windowListener); - latestWindow = null; -}); diff --git a/browser/components/extensions/test/browser/browser_ext_windows_update.js b/browser/components/extensions/test/browser/browser_ext_windows_update.js deleted file mode 100644 index b9475547a..000000000 --- a/browser/components/extensions/test/browser/browser_ext_windows_update.js +++ /dev/null @@ -1,189 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -add_task(function* () { - function promiseWaitForFocus(window) { - return new Promise(resolve => { - waitForFocus(function() { - ok(Services.focus.activeWindow === window, "correct window focused"); - resolve(); - }, window); - }); - } - - let window1 = window; - let window2 = yield BrowserTestUtils.openNewBrowserWindow(); - - Services.focus.activeWindow = window2; - yield promiseWaitForFocus(window2); - - let extension = ExtensionTestUtils.loadExtension({ - background: function() { - browser.windows.getAll(undefined, function(wins) { - browser.test.assertEq(wins.length, 2, "should have two windows"); - - // Sort the unfocused window to the lower index. - wins.sort(function(win1, win2) { - if (win1.focused === win2.focused) { - return 0; - } - - return win1.focused ? 1 : -1; - }); - - browser.windows.update(wins[0].id, {focused: true}, function() { - browser.test.sendMessage("check"); - }); - }); - }, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("check")]); - - yield promiseWaitForFocus(window1); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(window2); -}); - - -add_task(function* testWindowUpdate() { - let extension = ExtensionTestUtils.loadExtension({ - async background() { - let _checkWindowPromise; - browser.test.onMessage.addListener(msg => { - if (msg == "checked-window") { - _checkWindowPromise.resolve(); - _checkWindowPromise = null; - } - }); - - let os; - function checkWindow(expected) { - return new Promise(resolve => { - _checkWindowPromise = {resolve}; - browser.test.sendMessage("check-window", expected); - }); - } - - let currentWindowId; - async function updateWindow(windowId, params, expected) { - let window = await browser.windows.update(windowId, params); - - browser.test.assertEq(currentWindowId, window.id, "Expected WINDOW_ID_CURRENT to refer to the same window"); - for (let key of Object.keys(params)) { - if (key == "state" && os == "mac" && params.state == "normal") { - // OS-X doesn't have a hard distinction between "normal" and - // "maximized" states. - browser.test.assertTrue(window.state == "normal" || window.state == "maximized", - `Expected window.state (currently ${window.state}) to be "normal" but will accept "maximized"`); - } else { - browser.test.assertEq(params[key], window[key], `Got expected value for window.${key}`); - } - } - - return checkWindow(expected); - } - - try { - let windowId = browser.windows.WINDOW_ID_CURRENT; - - ({os} = await browser.runtime.getPlatformInfo()); - - let window = await browser.windows.getCurrent(); - currentWindowId = window.id; - - await updateWindow(windowId, {state: "maximized"}, {state: "STATE_MAXIMIZED"}); - await updateWindow(windowId, {state: "minimized"}, {state: "STATE_MINIMIZED"}); - await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"}); - await updateWindow(windowId, {state: "fullscreen"}, {state: "STATE_FULLSCREEN"}); - await updateWindow(windowId, {state: "normal"}, {state: "STATE_NORMAL"}); - - browser.test.notifyPass("window-update"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-update"); - } - }, - }); - - extension.onMessage("check-window", expected => { - if (expected.state != null) { - let {windowState} = window; - if (window.fullScreen) { - windowState = window.STATE_FULLSCREEN; - } - - // Temporarily accepting STATE_MAXIMIZED on Linux because of bug 1307759. - if (expected.state == "STATE_NORMAL" && (AppConstants.platform == "macosx" || AppConstants.platform == "linux")) { - ok(windowState == window.STATE_NORMAL || windowState == window.STATE_MAXIMIZED, - `Expected windowState (currently ${windowState}) to be STATE_NORMAL but will accept STATE_MAXIMIZED`); - } else { - is(windowState, window[expected.state], - `Expected window state to be ${expected.state}`); - } - } - - extension.sendMessage("checked-window"); - }); - - yield extension.startup(); - yield extension.awaitFinish("window-update"); - yield extension.unload(); -}); - -add_task(function* () { - let window2 = yield BrowserTestUtils.openNewBrowserWindow(); - - let extension = ExtensionTestUtils.loadExtension({ - background: function() { - browser.windows.getAll(undefined, function(wins) { - browser.test.assertEq(wins.length, 2, "should have two windows"); - - let unfocused = wins.find(win => !win.focused); - browser.windows.update(unfocused.id, {drawAttention: true}, function() { - browser.test.sendMessage("check"); - }); - }); - }, - }); - - yield Promise.all([extension.startup(), extension.awaitMessage("check")]); - - yield extension.unload(); - - yield BrowserTestUtils.closeWindow(window2); -}); - - -// Tests that incompatible parameters can't be used together. -add_task(function* testWindowUpdateParams() { - let extension = ExtensionTestUtils.loadExtension({ - async background() { - try { - for (let state of ["minimized", "maximized", "fullscreen"]) { - for (let param of ["left", "top", "width", "height"]) { - let expected = `"state": "${state}" may not be combined with "left", "top", "width", or "height"`; - - let windowId = browser.windows.WINDOW_ID_CURRENT; - await browser.test.assertRejects( - browser.windows.update(windowId, {state, [param]: 100}), - RegExp(expected), - `Got expected error for create(${param}=100`); - } - } - - browser.test.notifyPass("window-update-params"); - } catch (e) { - browser.test.fail(`${e} :: ${e.stack}`); - browser.test.notifyFail("window-update-params"); - } - }, - }); - - yield extension.startup(); - yield extension.awaitFinish("window-update-params"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/browser/context.html b/browser/components/extensions/test/browser/context.html deleted file mode 100644 index 954feea52..000000000 --- a/browser/components/extensions/test/browser/context.html +++ /dev/null @@ -1,23 +0,0 @@ -<html> - <head> - <meta charset="utf-8"> - </head> - <body> - just some text 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 - <img src="ctxmenu-image.png" id="img1"> - - <p> - <a href="some-link" id="link1">Some link</a> - </p> - - <p> - <a href="image-around-some-link"> - <img src="ctxmenu-image.png" id="img-wrapped-in-link"> - </a> - </p> - - <p> - <input type="text" id="edit-me"> - </p> - </body> -</html> diff --git a/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html b/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html deleted file mode 100644 index 0e9b54b52..000000000 --- a/browser/components/extensions/test/browser/context_tabs_onUpdated_iframe.html +++ /dev/null @@ -1,19 +0,0 @@ -<html> - <body> - <h3>test iframe</h3> - <script> - "use strict"; - - window.onload = function() { - window.onhashchange = function() { - window.parent.postMessage("updated-iframe-url", "*"); - }; - // NOTE: without the this setTimeout the location change is not fired - // even without the "fire only for top level windows" fix - setTimeout(function() { - window.location.hash = "updated-iframe-url"; - }, 0); - }; - </script> - </body> -</html> diff --git a/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html b/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html deleted file mode 100644 index 0f2ce1e8f..000000000 --- a/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html +++ /dev/null @@ -1,18 +0,0 @@ -<html> - <body> - <h3>test page</h3> - <iframe src="about:blank"></iframe> - <script> - "use strict"; - - window.onmessage = function(evt) { - if (evt.data === "updated-iframe-url") { - window.postMessage("frame-updated", "*"); - } - }; - window.onload = function() { - document.querySelector("iframe").setAttribute("src", "context_tabs_onUpdated_iframe.html"); - }; - </script> - </body> -</html> diff --git a/browser/components/extensions/test/browser/ctxmenu-image.png b/browser/components/extensions/test/browser/ctxmenu-image.png Binary files differdeleted file mode 100644 index 4c3be5084..000000000 --- a/browser/components/extensions/test/browser/ctxmenu-image.png +++ /dev/null diff --git a/browser/components/extensions/test/browser/file_bypass_cache.sjs b/browser/components/extensions/test/browser/file_bypass_cache.sjs deleted file mode 100644 index c91c76b88..000000000 --- a/browser/components/extensions/test/browser/file_bypass_cache.sjs +++ /dev/null @@ -1,11 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80 ft=javascript: */ -"use strict"; - -function handleRequest(request, response) { - response.setHeader("Content-Type", "text/plain; charset=UTF-8", false); - - if (request.hasHeader("pragma") && request.hasHeader("cache-control")) { - response.write(`${request.getHeader("pragma")}:${request.getHeader("cache-control")}`); - } -}
\ No newline at end of file diff --git a/browser/components/extensions/test/browser/file_dummy.html b/browser/components/extensions/test/browser/file_dummy.html deleted file mode 100644 index 1a87e2840..000000000 --- a/browser/components/extensions/test/browser/file_dummy.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> -<title>Dummy test page</title> -<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta> -</head> -<body> -<p>Dummy test page</p> -</body> -</html> diff --git a/browser/components/extensions/test/browser/file_iframe_document.html b/browser/components/extensions/test/browser/file_iframe_document.html deleted file mode 100644 index fcadccf02..000000000 --- a/browser/components/extensions/test/browser/file_iframe_document.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <meta charset="UTF-8"> - <title></title> -</head> -<body> - <iframe src="/"></iframe> -</body> -</html> diff --git a/browser/components/extensions/test/browser/file_iframe_document.sjs b/browser/components/extensions/test/browser/file_iframe_document.sjs deleted file mode 100644 index 661a768af..000000000 --- a/browser/components/extensions/test/browser/file_iframe_document.sjs +++ /dev/null @@ -1,41 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80 ft=javascript: */ -"use strict"; - -// This script slows the load of an HTML document so that we can reliably test -// all phases of the load cycle supported by the extension API. - -/* eslint-disable no-unused-vars */ - -const DELAY = 1 * 1000; // Delay one second before completing the request. - -const Ci = Components.interfaces; - -let nsTimer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback"); - -let timer; - -function handleRequest(request, response) { - response.processAsync(); - - response.setHeader("Content-Type", "text/html", false); - response.setHeader("Cache-Control", "no-cache", false); - response.write(`<!DOCTYPE html> - <html lang="en"> - <head> - <meta charset="UTF-8"> - <title></title> - </head> - <body> - `); - - // Note: We need to store a reference to the timer to prevent it from being - // canceled when it's GCed. - timer = new nsTimer(() => { - response.write(` - <iframe src="/"></iframe> - </body> - </html>`); - response.finish(); - }, DELAY, Ci.nsITimer.TYPE_ONE_SHOT); -} diff --git a/browser/components/extensions/test/browser/file_language_fr_en.html b/browser/components/extensions/test/browser/file_language_fr_en.html deleted file mode 100644 index 5e3c7b3b0..000000000 --- a/browser/components/extensions/test/browser/file_language_fr_en.html +++ /dev/null @@ -1,14 +0,0 @@ -<!DOCTYPE html> -<html lang="fr"> -<head> - <meta charset="UTF-8"> - <title></title> -</head> -<body> - France is the largest country in Western Europe and the third-largest in Europe as a whole. - A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter - Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, - Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus. - Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumps over the lazy dog. -</body> -</html> diff --git a/browser/components/extensions/test/browser/file_language_ja.html b/browser/components/extensions/test/browser/file_language_ja.html deleted file mode 100644 index ed07ba70e..000000000 --- a/browser/components/extensions/test/browser/file_language_ja.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> -<html lang="ja"> -<head> - <meta charset="UTF-8"> - <title></title> -</head> -<body> - ã“ã®ãƒš ジã§ã¯ アカウントã«æŒ‡å®šã•ã‚ŒãŸäºˆç®—ã®å±¥æ´ã‚’一覧ã«ã—ã¦ã„ã¾ã™ ãã‚Œãžã‚Œã®é …ç›®ã«ã¯ 予算é¡ã¨ç‰¹å®šæœŸé–“ã®ã‚¹ãƒ† タスãŒè¡¨ç¤ºã•ã‚Œã¾ã™ ç¾åœ¨ã¾ãŸã¯ä»Šå¾Œã®äºˆç®—ã‚’è¨å®šã™ã‚‹ã«ã¯ -</body> -</html> diff --git a/browser/components/extensions/test/browser/file_language_tlh.html b/browser/components/extensions/test/browser/file_language_tlh.html deleted file mode 100644 index dd7da7bdb..000000000 --- a/browser/components/extensions/test/browser/file_language_tlh.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE html> -<html lang="tlh"> -<head> - <meta charset="UTF-8"> - <title></title> -</head> -<body> - tlhIngan maH! - Hab SoSlI' Quch! - Heghlu'meH QaQ jajvam -</body> -</html> diff --git a/browser/components/extensions/test/browser/file_popup_api_injection_a.html b/browser/components/extensions/test/browser/file_popup_api_injection_a.html deleted file mode 100644 index 750ff1db3..000000000 --- a/browser/components/extensions/test/browser/file_popup_api_injection_a.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta charset="utf-8"> - <script type="application/javascript"> - "use strict"; - throw new Error(`WebExt Privilege Escalation: BrowserAction: typeof(browser) = ${typeof(browser)}`); - </script> -</head> -</html> diff --git a/browser/components/extensions/test/browser/file_popup_api_injection_b.html b/browser/components/extensions/test/browser/file_popup_api_injection_b.html deleted file mode 100644 index b8c287e55..000000000 --- a/browser/components/extensions/test/browser/file_popup_api_injection_b.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta charset="utf-8"> - <script type="application/javascript"> - "use strict"; - throw new Error(`WebExt Privilege Escalation: PageAction: typeof(browser) = ${typeof(browser)}`); - </script> -</head> -</html> diff --git a/browser/components/extensions/test/browser/head.js b/browser/components/extensions/test/browser/head.js deleted file mode 100644 index f8d59c944..000000000 --- a/browser/components/extensions/test/browser/head.js +++ /dev/null @@ -1,263 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* exported CustomizableUI makeWidgetId focusWindow forceGC - * getBrowserActionWidget - * clickBrowserAction clickPageAction - * getBrowserActionPopup getPageActionPopup - * closeBrowserAction closePageAction - * promisePopupShown promisePopupHidden - * openContextMenu closeContextMenu - * openExtensionContextMenu closeExtensionContextMenu - * imageBuffer getListStyleImage getPanelForNode - * awaitExtensionPanel awaitPopupResize - * promiseContentDimensions alterContent - */ - -var {AppConstants} = Cu.import("resource://gre/modules/AppConstants.jsm"); -var {CustomizableUI} = Cu.import("resource:///modules/CustomizableUI.jsm"); - -// Bug 1239884: Our tests occasionally hit a long GC pause at unpredictable -// times in debug builds, which results in intermittent timeouts. Until we have -// a better solution, we force a GC after certain strategic tests, which tend to -// accumulate a high number of unreaped windows. -function forceGC() { - if (AppConstants.DEBUG) { - Cu.forceGC(); - } -} - -function makeWidgetId(id) { - id = id.toLowerCase(); - return id.replace(/[^a-z0-9_-]/g, "_"); -} - -var focusWindow = Task.async(function* focusWindow(win) { - let fm = Cc["@mozilla.org/focus-manager;1"].getService(Ci.nsIFocusManager); - if (fm.activeWindow == win) { - return; - } - - let promise = new Promise(resolve => { - win.addEventListener("focus", function listener() { - win.removeEventListener("focus", listener, true); - resolve(); - }, true); - }); - - win.focus(); - yield promise; -}); - -let img = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=="; -var imageBuffer = Uint8Array.from(atob(img), byte => byte.charCodeAt(0)).buffer; - -function getListStyleImage(button) { - let style = button.ownerDocument.defaultView.getComputedStyle(button); - - let match = /^url\("(.*)"\)$/.exec(style.listStyleImage); - - return match && match[1]; -} - -function promisePopupShown(popup) { - return new Promise(resolve => { - if (popup.state == "open") { - resolve(); - } else { - let onPopupShown = event => { - popup.removeEventListener("popupshown", onPopupShown); - resolve(); - }; - popup.addEventListener("popupshown", onPopupShown); - } - }); -} - -function promisePopupHidden(popup) { - return new Promise(resolve => { - let onPopupHidden = event => { - popup.removeEventListener("popuphidden", onPopupHidden); - resolve(); - }; - popup.addEventListener("popuphidden", onPopupHidden); - }); -} - -function promiseContentDimensions(browser) { - return ContentTask.spawn(browser, null, function* () { - function copyProps(obj, props) { - let res = {}; - for (let prop of props) { - res[prop] = obj[prop]; - } - return res; - } - - return { - window: copyProps(content, - ["innerWidth", "innerHeight", "outerWidth", "outerHeight", - "scrollX", "scrollY", "scrollMaxX", "scrollMaxY"]), - body: copyProps(content.document.body, - ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight"]), - root: copyProps(content.document.documentElement, - ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight"]), - - isStandards: content.document.compatMode !== "BackCompat", - }; - }); -} - -function* awaitPopupResize(browser) { - return BrowserTestUtils.waitForEvent(browser, "WebExtPopupResized", - event => event.detail === "delayed"); -} - -function alterContent(browser, task, arg = null) { - return Promise.all([ - ContentTask.spawn(browser, arg, task), - awaitPopupResize(browser), - ]).then(() => { - return promiseContentDimensions(browser); - }); -} - -function getPanelForNode(node) { - while (node.localName != "panel") { - node = node.parentNode; - } - return node; -} - -var awaitBrowserLoaded = browser => ContentTask.spawn(browser, null, () => { - if (content.document.readyState !== "complete") { - return ContentTaskUtils.waitForEvent(content, "load").then(() => {}); - } -}); - -var awaitExtensionPanel = Task.async(function* (extension, win = window, awaitLoad = true) { - let {originalTarget: browser} = yield BrowserTestUtils.waitForEvent( - win.document, "WebExtPopupLoaded", true, - event => event.detail.extension.id === extension.id); - - yield Promise.all([ - promisePopupShown(getPanelForNode(browser)), - - awaitLoad && awaitBrowserLoaded(browser), - ]); - - return browser; -}); - -function getBrowserActionWidget(extension) { - return CustomizableUI.getWidget(makeWidgetId(extension.id) + "-browser-action"); -} - -function getBrowserActionPopup(extension, win = window) { - let group = getBrowserActionWidget(extension); - - if (group.areaType == CustomizableUI.TYPE_TOOLBAR) { - return win.document.getElementById("customizationui-widget-panel"); - } - return win.PanelUI.panel; -} - -var showBrowserAction = Task.async(function* (extension, win = window) { - let group = getBrowserActionWidget(extension); - let widget = group.forWindow(win); - - if (group.areaType == CustomizableUI.TYPE_TOOLBAR) { - ok(!widget.overflowed, "Expect widget not to be overflowed"); - } else if (group.areaType == CustomizableUI.TYPE_MENU_PANEL) { - yield win.PanelUI.show(); - } -}); - -var clickBrowserAction = Task.async(function* (extension, win = window) { - yield showBrowserAction(extension, win); - - let widget = getBrowserActionWidget(extension).forWindow(win); - - EventUtils.synthesizeMouseAtCenter(widget.node, {}, win); -}); - -function closeBrowserAction(extension, win = window) { - let group = getBrowserActionWidget(extension); - - let node = win.document.getElementById(group.viewId); - CustomizableUI.hidePanelForNode(node); - - return Promise.resolve(); -} - -function* openContextMenu(selector = "#img1") { - let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); - let popupShownPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popupshown"); - yield BrowserTestUtils.synthesizeMouseAtCenter(selector, {type: "contextmenu"}, gBrowser.selectedBrowser); - yield popupShownPromise; - return contentAreaContextMenu; -} - -function* closeContextMenu() { - let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); - let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden"); - contentAreaContextMenu.hidePopup(); - yield popupHiddenPromise; -} - -function* openExtensionContextMenu(selector = "#img1") { - let contextMenu = yield openContextMenu(selector); - let topLevelMenu = contextMenu.getElementsByAttribute("ext-type", "top-level-menu"); - - // Return null if the extension only has one item and therefore no extension menu. - if (topLevelMenu.length == 0) { - return null; - } - - let extensionMenu = topLevelMenu[0].childNodes[0]; - let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - EventUtils.synthesizeMouseAtCenter(extensionMenu, {}); - yield popupShownPromise; - return extensionMenu; -} - -function* closeExtensionContextMenu(itemToSelect) { - let contentAreaContextMenu = document.getElementById("contentAreaContextMenu"); - let popupHiddenPromise = BrowserTestUtils.waitForEvent(contentAreaContextMenu, "popuphidden"); - EventUtils.synthesizeMouseAtCenter(itemToSelect, {}); - yield popupHiddenPromise; -} - -function getPageActionPopup(extension, win = window) { - let panelId = makeWidgetId(extension.id) + "-panel"; - return win.document.getElementById(panelId); -} - -function clickPageAction(extension, win = window) { - // This would normally be set automatically on navigation, and cleared - // when the user types a value into the URL bar, to show and hide page - // identity info and icons such as page action buttons. - // - // Unfortunately, that doesn't happen automatically in browser chrome - // tests. - /* globals SetPageProxyState */ - SetPageProxyState("valid"); - - let pageActionId = makeWidgetId(extension.id) + "-page-action"; - let elem = win.document.getElementById(pageActionId); - - EventUtils.synthesizeMouseAtCenter(elem, {}, win); - return new Promise(SimpleTest.executeSoon); -} - -function closePageAction(extension, win = window) { - let node = getPageActionPopup(extension, win); - if (node) { - return promisePopupShown(node).then(() => { - node.hidePopup(); - }); - } - - return Promise.resolve(); -} diff --git a/browser/components/extensions/test/browser/head_pageAction.js b/browser/components/extensions/test/browser/head_pageAction.js deleted file mode 100644 index f2d81e512..000000000 --- a/browser/components/extensions/test/browser/head_pageAction.js +++ /dev/null @@ -1,157 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* exported runTests */ -/* globals getListStyleImage */ - -function* runTests(options) { - function background(getTests) { - let tabs; - let tests; - - // Gets the current details of the page action, and returns a - // promise that resolves to an object containing them. - async function getDetails() { - let [tab] = await browser.tabs.query({active: true, currentWindow: true}); - let tabId = tab.id; - - browser.test.log(`Get details: tab={id: ${tabId}, url: ${JSON.stringify(tab.url)}}`); - - return { - title: await browser.pageAction.getTitle({tabId}), - popup: await browser.pageAction.getPopup({tabId}), - }; - } - - - // Runs the next test in the `tests` array, checks the results, - // and passes control back to the outer test scope. - function nextTest() { - let test = tests.shift(); - - test(async expecting => { - function finish() { - // Check that the actual icon has the expected values, then - // run the next test. - browser.test.sendMessage("nextTest", expecting, tests.length); - } - - if (expecting) { - // Check that the API returns the expected values, and then - // run the next test. - let details = await getDetails(); - - browser.test.assertEq(expecting.title, details.title, - "expected value from getTitle"); - - browser.test.assertEq(expecting.popup, details.popup, - "expected value from getPopup"); - } - - finish(); - }); - } - - async function runTests() { - tabs = []; - tests = getTests(tabs); - - let resultTabs = await browser.tabs.query({active: true, currentWindow: true}); - - tabs[0] = resultTabs[0].id; - - nextTest(); - } - - browser.test.onMessage.addListener((msg) => { - if (msg == "runTests") { - runTests(); - } else if (msg == "runNextTest") { - nextTest(); - } else { - browser.test.fail(`Unexpected message: ${msg}`); - } - }); - - runTests(); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: options.manifest, - - files: options.files || {}, - - background: `(${background})(${options.getTests})`, - }); - - let pageActionId; - let currentWindow = window; - let windows = []; - - function checkDetails(details) { - let image = currentWindow.document.getElementById(pageActionId); - if (details == null) { - ok(image == null || image.hidden, "image is hidden"); - } else { - ok(image, "image exists"); - - is(getListStyleImage(image), details.icon, "icon URL is correct"); - - let title = details.title || options.manifest.name; - is(image.getAttribute("tooltiptext"), title, "image title is correct"); - is(image.getAttribute("aria-label"), title, "image aria-label is correct"); - // TODO: Popup URL. - } - } - - let testNewWindows = 1; - - let awaitFinish = new Promise(resolve => { - extension.onMessage("nextTest", (expecting, testsRemaining) => { - if (!pageActionId) { - pageActionId = `${makeWidgetId(extension.id)}-page-action`; - } - - checkDetails(expecting); - - if (testsRemaining) { - extension.sendMessage("runNextTest"); - } else if (testNewWindows) { - testNewWindows--; - - BrowserTestUtils.openNewBrowserWindow().then(window => { - windows.push(window); - currentWindow = window; - return focusWindow(window); - }).then(() => { - extension.sendMessage("runTests"); - }); - } else { - resolve(); - } - }); - }); - - yield SpecialPowers.pushPrefEnv({set: [["general.useragent.locale", "es-ES"]]}); - - yield extension.startup(); - - yield awaitFinish; - - yield extension.unload(); - - yield SpecialPowers.popPrefEnv(); - - let node = document.getElementById(pageActionId); - is(node, null, "pageAction image removed from document"); - - currentWindow = null; - for (let win of windows.splice(0)) { - node = win.document.getElementById(pageActionId); - is(node, null, "pageAction image removed from second document"); - - yield BrowserTestUtils.closeWindow(win); - } -} - diff --git a/browser/components/extensions/test/browser/head_sessions.js b/browser/components/extensions/test/browser/head_sessions.js deleted file mode 100644 index ca3a86c24..000000000 --- a/browser/components/extensions/test/browser/head_sessions.js +++ /dev/null @@ -1,47 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* exported recordInitialTimestamps onlyNewItemsFilter checkRecentlyClosed */ - -let initialTimestamps = []; - -function recordInitialTimestamps(timestamps) { - initialTimestamps = timestamps; -} - -function onlyNewItemsFilter(item) { - return !initialTimestamps.includes(item.lastModified); -} - -function checkWindow(window) { - for (let prop of ["focused", "incognito", "alwaysOnTop"]) { - is(window[prop], false, `closed window has the expected value for ${prop}`); - } - for (let prop of ["state", "type"]) { - is(window[prop], "normal", `closed window has the expected value for ${prop}`); - } -} - -function checkTab(tab, windowId, incognito) { - for (let prop of ["selected", "highlighted", "active", "pinned"]) { - is(tab[prop], false, `closed tab has the expected value for ${prop}`); - } - is(tab.windowId, windowId, "closed tab has the expected value for windowId"); - is(tab.incognito, incognito, "closed tab has the expected value for incognito"); -} - -function checkRecentlyClosed(recentlyClosed, expectedCount, windowId, incognito = false) { - let sessionIds = new Set(); - is(recentlyClosed.length, expectedCount, "the expected number of closed tabs/windows was found"); - for (let item of recentlyClosed) { - if (item.window) { - sessionIds.add(item.window.sessionId); - checkWindow(item.window); - } else if (item.tab) { - sessionIds.add(item.tab.sessionId); - checkTab(item.tab, windowId, incognito); - } - } - is(sessionIds.size, expectedCount, "each item has a unique sessionId"); -} diff --git a/browser/components/extensions/test/browser/searchSuggestionEngine.sjs b/browser/components/extensions/test/browser/searchSuggestionEngine.sjs deleted file mode 100644 index 1978b4f66..000000000 --- a/browser/components/extensions/test/browser/searchSuggestionEngine.sjs +++ /dev/null @@ -1,9 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -function handleRequest(req, resp) { - let suffixes = ["foo", "bar"]; - let data = [req.queryString, suffixes.map(s => req.queryString + s)]; - resp.setHeader("Content-Type", "application/json", false); - resp.write(JSON.stringify(data)); -} diff --git a/browser/components/extensions/test/browser/searchSuggestionEngine.xml b/browser/components/extensions/test/browser/searchSuggestionEngine.xml deleted file mode 100644 index 703d45925..000000000 --- a/browser/components/extensions/test/browser/searchSuggestionEngine.xml +++ /dev/null @@ -1,9 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Any copyright is dedicated to the Public Domain. - - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> -<ShortName>browser_searchSuggestionEngine searchSuggestionEngine.xml</ShortName> -<Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/components/extensions/test/browser/searchSuggestionEngine.sjs?{searchTerms}"/> -<Url type="text/html" method="GET" template="http://mochi.test:8888/" rel="searchform"/> -</SearchPlugin> diff --git a/browser/components/extensions/test/mochitest/mochitest.ini b/browser/components/extensions/test/mochitest/mochitest.ini deleted file mode 100644 index 39290db61..000000000 --- a/browser/components/extensions/test/mochitest/mochitest.ini +++ /dev/null @@ -1,6 +0,0 @@ -[DEFAULT] -support-files = - ../../../../../toolkit/components/extensions/test/mochitest/test_ext_all_apis.js -tags = webextensions - -[test_ext_all_apis.html] diff --git a/browser/components/extensions/test/mochitest/test_ext_all_apis.html b/browser/components/extensions/test/mochitest/test_ext_all_apis.html deleted file mode 100644 index 176d380c2..000000000 --- a/browser/components/extensions/test/mochitest/test_ext_all_apis.html +++ /dev/null @@ -1,75 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <title>WebExtension test</title> - <meta charset="utf-8"> - <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script> - <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"> -</head> -<body> -<script> -"use strict"; -/* exported expectedContentApisTargetSpecific, expectedBackgroundApisTargetSpecific */ -let expectedContentApisTargetSpecific = [ -]; - -let expectedBackgroundApisTargetSpecific = [ - "tabs.MutedInfoReason", - "tabs.TAB_ID_NONE", - "tabs.TabStatus", - "tabs.WindowType", - "tabs.ZoomSettingsMode", - "tabs.ZoomSettingsScope", - "tabs.connect", - "tabs.create", - "tabs.detectLanguage", - "tabs.duplicate", - "tabs.executeScript", - "tabs.get", - "tabs.getCurrent", - "tabs.getZoom", - "tabs.getZoomSettings", - "tabs.highlight", - "tabs.insertCSS", - "tabs.move", - "tabs.onActivated", - "tabs.onAttached", - "tabs.onCreated", - "tabs.onDetached", - "tabs.onHighlighted", - "tabs.onMoved", - "tabs.onRemoved", - "tabs.onReplaced", - "tabs.onUpdated", - "tabs.onZoomChange", - "tabs.query", - "tabs.reload", - "tabs.remove", - "tabs.removeCSS", - "tabs.sendMessage", - "tabs.setZoom", - "tabs.setZoomSettings", - "tabs.update", - "windows.CreateType", - "windows.WINDOW_ID_CURRENT", - "windows.WINDOW_ID_NONE", - "windows.WindowState", - "windows.WindowType", - "windows.create", - "windows.get", - "windows.getAll", - "windows.getCurrent", - "windows.getLastFocused", - "windows.onCreated", - "windows.onFocusChanged", - "windows.onRemoved", - "windows.remove", - "windows.update", -]; -</script> -<script src="test_ext_all_apis.js"></script> - -</body> -</html> diff --git a/browser/components/extensions/test/xpcshell/.eslintrc.js b/browser/components/extensions/test/xpcshell/.eslintrc.js deleted file mode 100644 index 2bfe540ea..000000000 --- a/browser/components/extensions/test/xpcshell/.eslintrc.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -module.exports = { // eslint-disable-line no-undef - "extends": "../../../../../testing/xpcshell/xpcshell.eslintrc.js", - - "globals": { - "browser": false, - }, -}; diff --git a/browser/components/extensions/test/xpcshell/head.js b/browser/components/extensions/test/xpcshell/head.js deleted file mode 100644 index de4a4a3f6..000000000 --- a/browser/components/extensions/test/xpcshell/head.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -/* exported createHttpServer */ - -Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", - "resource://gre/modules/AppConstants.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Extension", - "resource://gre/modules/Extension.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "ExtensionData", - "resource://gre/modules/Extension.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement", - "resource://gre/modules/ExtensionManagement.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestUtils", - "resource://testing-common/ExtensionXPCShellUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "HttpServer", - "resource://testing-common/httpd.js"); -XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Schemas", - "resource://gre/modules/Schemas.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Services", - "resource://gre/modules/Services.jsm"); - -ExtensionTestUtils.init(this); - - -/** - * Creates a new HttpServer for testing, and begins listening on the - * specified port. Automatically shuts down the server when the test - * unit ends. - * - * @param {integer} [port] - * The port to listen on. If omitted, listen on a random - * port. The latter is the preferred behavior. - * - * @returns {HttpServer} - */ -function createHttpServer(port = -1) { - let server = new HttpServer(); - server.start(port); - - do_register_cleanup(() => { - return new Promise(resolve => { - server.stop(resolve); - }); - }); - - return server; -} diff --git a/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js b/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js deleted file mode 100644 index 142c0a37c..000000000 --- a/browser/components/extensions/test/xpcshell/test_ext_bookmarks.js +++ /dev/null @@ -1,601 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function backgroundScript() { - let unsortedId, ourId; - let initialBookmarkCount = 0; - let createdBookmarks = new Set(); - let createdFolderId; - let collectedEvents = []; - const nonExistentId = "000000000000"; - const bookmarkGuids = { - menuGuid: "menu________", - toolbarGuid: "toolbar_____", - unfiledGuid: "unfiled_____", - }; - - function checkOurBookmark(bookmark) { - browser.test.assertEq(ourId, bookmark.id, "Bookmark has the expected Id"); - browser.test.assertTrue("parentId" in bookmark, "Bookmark has a parentId"); - browser.test.assertEq(0, bookmark.index, "Bookmark has the expected index"); // We assume there are no other bookmarks. - browser.test.assertEq("http://example.org/", bookmark.url, "Bookmark has the expected url"); - browser.test.assertEq("test bookmark", bookmark.title, "Bookmark has the expected title"); - browser.test.assertTrue("dateAdded" in bookmark, "Bookmark has a dateAdded"); - browser.test.assertFalse("dateGroupModified" in bookmark, "Bookmark does not have a dateGroupModified"); - browser.test.assertFalse("unmodifiable" in bookmark, "Bookmark is not unmodifiable"); - } - - function checkBookmark(expected, bookmark) { - browser.test.assertEq(expected.url, bookmark.url, "Bookmark has the expected url"); - browser.test.assertEq(expected.title, bookmark.title, "Bookmark has the expected title"); - browser.test.assertEq(expected.index, bookmark.index, "Bookmark has expected index"); - if ("parentId" in expected) { - browser.test.assertEq(expected.parentId, bookmark.parentId, "Bookmark has the expected parentId"); - } - } - - function expectedError() { - browser.test.fail("Did not get expected error"); - } - - function checkOnCreated(id, parentId, index, title, url, dateAdded) { - let createdData = collectedEvents.pop(); - browser.test.assertEq("onCreated", createdData.event, "onCreated was the last event received"); - browser.test.assertEq(id, createdData.id, "onCreated event received the expected id"); - let bookmark = createdData.bookmark; - browser.test.assertEq(id, bookmark.id, "onCreated event received the expected bookmark id"); - browser.test.assertEq(parentId, bookmark.parentId, "onCreated event received the expected bookmark parentId"); - browser.test.assertEq(index, bookmark.index, "onCreated event received the expected bookmark index"); - browser.test.assertEq(title, bookmark.title, "onCreated event received the expected bookmark title"); - browser.test.assertEq(url, bookmark.url, "onCreated event received the expected bookmark url"); - browser.test.assertEq(dateAdded, bookmark.dateAdded, "onCreated event received the expected bookmark dateAdded"); - } - - function checkOnChanged(id, url, title) { - // If both url and title are changed, then url is fired last. - let changedData = collectedEvents.pop(); - browser.test.assertEq("onChanged", changedData.event, "onChanged was the last event received"); - browser.test.assertEq(id, changedData.id, "onChanged event received the expected id"); - browser.test.assertEq(url, changedData.info.url, "onChanged event received the expected url"); - // title is fired first. - changedData = collectedEvents.pop(); - browser.test.assertEq("onChanged", changedData.event, "onChanged was the last event received"); - browser.test.assertEq(id, changedData.id, "onChanged event received the expected id"); - browser.test.assertEq(title, changedData.info.title, "onChanged event received the expected title"); - } - - function checkOnMoved(id, parentId, oldParentId, index, oldIndex) { - let movedData = collectedEvents.pop(); - browser.test.assertEq("onMoved", movedData.event, "onMoved was the last event received"); - browser.test.assertEq(id, movedData.id, "onMoved event received the expected id"); - let info = movedData.info; - browser.test.assertEq(parentId, info.parentId, "onMoved event received the expected parentId"); - browser.test.assertEq(oldParentId, info.oldParentId, "onMoved event received the expected oldParentId"); - browser.test.assertEq(index, info.index, "onMoved event received the expected index"); - browser.test.assertEq(oldIndex, info.oldIndex, "onMoved event received the expected oldIndex"); - } - - function checkOnRemoved(id, parentId, index, url) { - let removedData = collectedEvents.pop(); - browser.test.assertEq("onRemoved", removedData.event, "onRemoved was the last event received"); - browser.test.assertEq(id, removedData.id, "onRemoved event received the expected id"); - let info = removedData.info; - browser.test.assertEq(parentId, removedData.info.parentId, "onRemoved event received the expected parentId"); - browser.test.assertEq(index, removedData.info.index, "onRemoved event received the expected index"); - let node = info.node; - browser.test.assertEq(id, node.id, "onRemoved event received the expected node id"); - browser.test.assertEq(parentId, node.parentId, "onRemoved event received the expected node parentId"); - browser.test.assertEq(index, node.index, "onRemoved event received the expected node index"); - browser.test.assertEq(url, node.url, "onRemoved event received the expected node url"); - } - - browser.bookmarks.onChanged.addListener((id, info) => { - collectedEvents.push({event: "onChanged", id, info}); - }); - - browser.bookmarks.onCreated.addListener((id, bookmark) => { - collectedEvents.push({event: "onCreated", id, bookmark}); - }); - - browser.bookmarks.onMoved.addListener((id, info) => { - collectedEvents.push({event: "onMoved", id, info}); - }); - - browser.bookmarks.onRemoved.addListener((id, info) => { - collectedEvents.push({event: "onRemoved", id, info}); - }); - - browser.bookmarks.get(["not-a-bookmark-guid"]).then(expectedError, invalidGuidError => { - browser.test.assertTrue( - invalidGuidError.message.includes("Invalid value for property 'guid': not-a-bookmark-guid"), - "Expected error thrown when trying to get a bookmark using an invalid guid" - ); - - return browser.bookmarks.get([nonExistentId]).then(expectedError, nonExistentIdError => { - browser.test.assertTrue( - nonExistentIdError.message.includes("Bookmark not found"), - "Expected error thrown when trying to get a bookmark using a non-existent Id" - ); - }); - }).then(() => { - return browser.bookmarks.search({}); - }).then(results => { - initialBookmarkCount = results.length; - return browser.bookmarks.create({title: "test bookmark", url: "http://example.org"}); - }).then(result => { - ourId = result.id; - checkOurBookmark(result); - browser.test.assertEq(1, collectedEvents.length, "1 expected event received"); - checkOnCreated(ourId, bookmarkGuids.unfiledGuid, 0, "test bookmark", "http://example.org/", result.dateAdded); - - return browser.bookmarks.get(ourId); - }).then(results => { - browser.test.assertEq(results.length, 1); - checkOurBookmark(results[0]); - - unsortedId = results[0].parentId; - return browser.bookmarks.get(unsortedId); - }).then(results => { - let folder = results[0]; - browser.test.assertEq(1, results.length, "1 bookmark was returned"); - - browser.test.assertEq(unsortedId, folder.id, "Folder has the expected id"); - browser.test.assertTrue("parentId" in folder, "Folder has a parentId"); - browser.test.assertTrue("index" in folder, "Folder has an index"); - browser.test.assertFalse("url" in folder, "Folder does not have a url"); - browser.test.assertEq("Other Bookmarks", folder.title, "Folder has the expected title"); - browser.test.assertTrue("dateAdded" in folder, "Folder has a dateAdded"); - browser.test.assertTrue("dateGroupModified" in folder, "Folder has a dateGroupModified"); - browser.test.assertFalse("unmodifiable" in folder, "Folder is not unmodifiable"); // TODO: Do we want to enable this? - - return browser.bookmarks.getChildren(unsortedId); - }).then(results => { - browser.test.assertEq(1, results.length, "The folder has one child"); - checkOurBookmark(results[0]); - - return browser.bookmarks.update(nonExistentId, {title: "new test title"}).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("No bookmarks found for the provided GUID"), - "Expected error thrown when trying to update a non-existent bookmark" - ); - - return browser.bookmarks.update(ourId, {title: "new test title", url: "http://example.com/"}); - }); - }).then(result => { - browser.test.assertEq("new test title", result.title, "Updated bookmark has the expected title"); - browser.test.assertEq("http://example.com/", result.url, "Updated bookmark has the expected URL"); - browser.test.assertEq(ourId, result.id, "Updated bookmark has the expected id"); - - browser.test.assertEq(2, collectedEvents.length, "2 expected events received"); - checkOnChanged(ourId, "http://example.com/", "new test title"); - - return Promise.resolve().then(() => { - return browser.bookmarks.update(ourId, {url: "this is not a valid url"}); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Invalid bookmark:"), - "Expected error thrown when trying update with an invalid url" - ); - return browser.bookmarks.getTree(); - }); - }).then(results => { - browser.test.assertEq(1, results.length, "getTree returns one result"); - let bookmark = results[0].children.find(bookmarkItem => bookmarkItem.id == unsortedId); - browser.test.assertEq( - "Other Bookmarks", - bookmark.title, - "Folder returned from getTree has the expected title" - ); - - return browser.bookmarks.create({parentId: "invalid"}).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Invalid bookmark"), - "Expected error thrown when trying to create a bookmark with an invalid parentId" - ); - browser.test.assertTrue( - error.message.includes(`"parentGuid":"invalid"`), - "Expected error thrown when trying to create a bookmark with an invalid parentId" - ); - }); - }).then(() => { - return browser.bookmarks.remove(ourId); - }).then(result => { - browser.test.assertEq(undefined, result, "Removing a bookmark returns undefined"); - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnRemoved(ourId, bookmarkGuids.unfiledGuid, 0, "http://example.com/"); - - return browser.bookmarks.get(ourId).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Bookmark not found"), - "Expected error thrown when trying to get a removed bookmark" - ); - }); - }).then(() => { - return browser.bookmarks.remove(nonExistentId).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("No bookmarks found for the provided GUID"), - "Expected error thrown when trying removed a non-existent bookmark" - ); - }); - }).then(() => { - // test bookmarks.search - return Promise.all([ - browser.bookmarks.create({title: "MØzillä", url: "http://møzîllä.örg/"}), - browser.bookmarks.create({title: "Example", url: "http://example.org/"}), - browser.bookmarks.create({title: "Mozilla Folder"}), - browser.bookmarks.create({title: "EFF", url: "http://eff.org/"}), - browser.bookmarks.create({title: "Menu Item", url: "http://menu.org/", parentId: bookmarkGuids.menuGuid}), - browser.bookmarks.create({title: "Toolbar Item", url: "http://toolbar.org/", parentId: bookmarkGuids.toolbarGuid}), - ]); - }).then(results => { - browser.test.assertEq(6, collectedEvents.length, "6 expected events received"); - checkOnCreated(results[5].id, bookmarkGuids.toolbarGuid, 0, "Toolbar Item", "http://toolbar.org/", results[5].dateAdded); - checkOnCreated(results[4].id, bookmarkGuids.menuGuid, 0, "Menu Item", "http://menu.org/", results[4].dateAdded); - checkOnCreated(results[3].id, bookmarkGuids.unfiledGuid, 0, "EFF", "http://eff.org/", results[3].dateAdded); - checkOnCreated(results[2].id, bookmarkGuids.unfiledGuid, 0, "Mozilla Folder", undefined, results[2].dateAdded); - checkOnCreated(results[1].id, bookmarkGuids.unfiledGuid, 0, "Example", "http://example.org/", results[1].dateAdded); - checkOnCreated(results[0].id, bookmarkGuids.unfiledGuid, 0, "MØzillä", "http://møzîllä.örg/", results[0].dateAdded); - - for (let result of results) { - if (result.title !== "Mozilla Folder") { - createdBookmarks.add(result.id); - } - } - let folderResult = results[2]; - createdFolderId = folderResult.id; - return Promise.all([ - browser.bookmarks.create({title: "Mozilla", url: "http://allizom.org/", parentId: createdFolderId}), - browser.bookmarks.create({title: "Mozilla Corporation", url: "http://allizom.com/", parentId: createdFolderId}), - browser.bookmarks.create({title: "Firefox", url: "http://allizom.org/firefox/", parentId: createdFolderId}), - ]).then(newBookmarks => { - browser.test.assertEq(3, collectedEvents.length, "3 expected events received"); - checkOnCreated(newBookmarks[2].id, createdFolderId, 0, "Firefox", "http://allizom.org/firefox/", newBookmarks[2].dateAdded); - checkOnCreated(newBookmarks[1].id, createdFolderId, 0, "Mozilla Corporation", "http://allizom.com/", newBookmarks[1].dateAdded); - checkOnCreated(newBookmarks[0].id, createdFolderId, 0, "Mozilla", "http://allizom.org/", newBookmarks[0].dateAdded); - - return browser.bookmarks.create({ - title: "About Mozilla", - url: "http://allizom.org/about/", - parentId: createdFolderId, - index: 1, - }); - }).then(result => { - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnCreated(result.id, createdFolderId, 1, "About Mozilla", "http://allizom.org/about/", result.dateAdded); - - // returns all items on empty object - return browser.bookmarks.search({}); - }).then(bookmarksSearchResults => { - browser.test.assertTrue(bookmarksSearchResults.length >= 9, "At least as many bookmarks as added were returned by search({})"); - - return Promise.resolve().then(() => { - return browser.bookmarks.remove(createdFolderId); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Cannot remove a non-empty folder"), - "Expected error thrown when trying to remove a non-empty folder" - ); - return browser.bookmarks.getSubTree(createdFolderId); - }); - }); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of nodes returned by getSubTree"); - browser.test.assertEq("Mozilla Folder", results[0].title, "Folder has the expected title"); - let children = results[0].children; - browser.test.assertEq(4, children.length, "Expected number of bookmarks returned by getSubTree"); - browser.test.assertEq("Firefox", children[0].title, "Bookmark has the expected title"); - browser.test.assertEq("About Mozilla", children[1].title, "Bookmark has the expected title"); - browser.test.assertEq(1, children[1].index, "Bookmark has the expected index"); - browser.test.assertEq("Mozilla Corporation", children[2].title, "Bookmark has the expected title"); - browser.test.assertEq("Mozilla", children[3].title, "Bookmark has the expected title"); - - // throws an error for invalid query objects - Promise.resolve().then(() => { - return browser.bookmarks.search(); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Incorrect argument types for bookmarks.search"), - "Expected error thrown when trying to search with no arguments" - ); - }); - - Promise.resolve().then(() => { - return browser.bookmarks.search(null); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Incorrect argument types for bookmarks.search"), - "Expected error thrown when trying to search with null as an argument" - ); - }); - - Promise.resolve().then(() => { - return browser.bookmarks.search(function() {}); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Incorrect argument types for bookmarks.search"), - "Expected error thrown when trying to search with a function as an argument" - ); - }); - - Promise.resolve().then(() => { - return browser.bookmarks.search({banana: "banana"}); - }).then(expectedError, error => { - let substr = `an unexpected "banana" property`; - browser.test.assertTrue( - error.message.includes(substr), - `Expected error ${JSON.stringify(error.message)} to contain ${JSON.stringify(substr)}`); - }); - - Promise.resolve().then(() => { - return browser.bookmarks.search({url: "spider-man vs. batman"}); - }).then(expectedError, error => { - let substr = 'must match the format "url"'; - browser.test.assertTrue( - error.message.includes(substr), - `Expected error ${JSON.stringify(error.message)} to contain ${JSON.stringify(substr)}`); - }); - - // queries the full url - return browser.bookmarks.search("http://example.org/"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for url search"); - checkBookmark({title: "Example", url: "http://example.org/", index: 2}, results[0]); - - // queries a partial url - return browser.bookmarks.search("example.org"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for url search"); - checkBookmark({title: "Example", url: "http://example.org/", index: 2}, results[0]); - - // queries the title - return browser.bookmarks.search("EFF"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for title search"); - checkBookmark({title: "EFF", url: "http://eff.org/", index: 0, parentId: bookmarkGuids.unfiledGuid}, results[0]); - - // finds menu items - return browser.bookmarks.search("Menu Item"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for menu item search"); - checkBookmark({title: "Menu Item", url: "http://menu.org/", index: 0, parentId: bookmarkGuids.menuGuid}, results[0]); - - // finds toolbar items - return browser.bookmarks.search("Toolbar Item"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for toolbar item search"); - checkBookmark({title: "Toolbar Item", url: "http://toolbar.org/", index: 0, parentId: bookmarkGuids.toolbarGuid}, results[0]); - - // finds folders - return browser.bookmarks.search("Mozilla Folder"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of folders returned"); - browser.test.assertEq("Mozilla Folder", results[0].title, "Folder has the expected title"); - - // is case-insensitive - return browser.bookmarks.search("corporation"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returnedfor case-insensitive search"); - browser.test.assertEq("Mozilla Corporation", results[0].title, "Bookmark has the expected title"); - - // is case-insensitive for non-ascii - return browser.bookmarks.search("MøZILLÄ"); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for non-ascii search"); - browser.test.assertEq("MØzillä", results[0].title, "Bookmark has the expected title"); - - // returns multiple results - return browser.bookmarks.search("allizom"); - }).then(results => { - browser.test.assertEq(4, results.length, "Expected number of multiple results returned"); - browser.test.assertEq("Mozilla", results[0].title, "Bookmark has the expected title"); - browser.test.assertEq("Mozilla Corporation", results[1].title, "Bookmark has the expected title"); - browser.test.assertEq("Firefox", results[2].title, "Bookmark has the expected title"); - browser.test.assertEq("About Mozilla", results[3].title, "Bookmark has the expected title"); - - // accepts a url field - return browser.bookmarks.search({url: "http://allizom.com/"}); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for url field"); - checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]); - - // normalizes urls - return browser.bookmarks.search({url: "http://allizom.com"}); - }).then(results => { - browser.test.assertEq(results.length, 1, "Expected number of results returned for normalized url field"); - checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]); - - // normalizes urls even more - return browser.bookmarks.search({url: "http:allizom.com"}); - }).then(results => { - browser.test.assertEq(results.length, 1, "Expected number of results returned for normalized url field"); - checkBookmark({title: "Mozilla Corporation", url: "http://allizom.com/", index: 2}, results[0]); - - // accepts a title field - return browser.bookmarks.search({title: "Mozilla"}); - }).then(results => { - browser.test.assertEq(results.length, 1, "Expected number of results returned for title field"); - checkBookmark({title: "Mozilla", url: "http://allizom.org/", index: 3}, results[0]); - - // can combine title and query - return browser.bookmarks.search({title: "Mozilla", query: "allizom"}); - }).then(results => { - browser.test.assertEq(1, results.length, "Expected number of results returned for title and query fields"); - checkBookmark({title: "Mozilla", url: "http://allizom.org/", index: 3}, results[0]); - - // uses AND conditions - return browser.bookmarks.search({title: "EFF", query: "allizom"}); - }).then(results => { - browser.test.assertEq( - 0, - results.length, - "Expected number of results returned for non-matching title and query fields" - ); - - // returns an empty array on item not found - return browser.bookmarks.search("microsoft"); - }).then(results => { - browser.test.assertEq(0, results.length, "Expected number of results returned for non-matching search"); - - return Promise.resolve().then(() => { - return browser.bookmarks.getRecent(""); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Incorrect argument types for bookmarks.getRecent"), - "Expected error thrown when calling getRecent with an empty string" - ); - }); - }).then(() => { - return Promise.resolve().then(() => { - return browser.bookmarks.getRecent(1.234); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Incorrect argument types for bookmarks.getRecent"), - "Expected error thrown when calling getRecent with a decimal number" - ); - }); - }).then(() => { - return Promise.all([ - browser.bookmarks.search("corporation"), - browser.bookmarks.getChildren(bookmarkGuids.menuGuid), - ]); - }).then(results => { - let corporationBookmark = results[0][0]; - let childCount = results[1].length; - - browser.test.assertEq(2, corporationBookmark.index, "Bookmark has the expected index"); - - return browser.bookmarks.move(corporationBookmark.id, {index: 0}).then(result => { - browser.test.assertEq(0, result.index, "Bookmark has the expected index"); - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnMoved(corporationBookmark.id, createdFolderId, createdFolderId, 0, 2); - - return browser.bookmarks.move(corporationBookmark.id, {parentId: bookmarkGuids.menuGuid}); - }).then(result => { - browser.test.assertEq(bookmarkGuids.menuGuid, result.parentId, "Bookmark has the expected parent"); - browser.test.assertEq(childCount, result.index, "Bookmark has the expected index"); - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnMoved(corporationBookmark.id, bookmarkGuids.menuGuid, createdFolderId, 1, 0); - - return browser.bookmarks.move(corporationBookmark.id, {index: 0}); - }).then(result => { - browser.test.assertEq(bookmarkGuids.menuGuid, result.parentId, "Bookmark has the expected parent"); - browser.test.assertEq(0, result.index, "Bookmark has the expected index"); - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnMoved(corporationBookmark.id, bookmarkGuids.menuGuid, bookmarkGuids.menuGuid, 0, 1); - - return browser.bookmarks.move(corporationBookmark.id, {parentId: bookmarkGuids.toolbarGuid, index: 1}); - }).then(result => { - browser.test.assertEq(bookmarkGuids.toolbarGuid, result.parentId, "Bookmark has the expected parent"); - browser.test.assertEq(1, result.index, "Bookmark has the expected index"); - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnMoved(corporationBookmark.id, bookmarkGuids.toolbarGuid, bookmarkGuids.menuGuid, 1, 0); - - createdBookmarks.add(corporationBookmark.id); - }); - }).then(() => { - return browser.bookmarks.getRecent(4); - }).then(results => { - browser.test.assertEq(4, results.length, "Expected number of results returned by getRecent"); - let prevDate = results[0].dateAdded; - for (let bookmark of results) { - browser.test.assertTrue(bookmark.dateAdded <= prevDate, "The recent bookmarks are sorted by dateAdded"); - prevDate = bookmark.dateAdded; - } - let bookmarksByTitle = results.sort((a, b) => { - return a.title.localeCompare(b.title); - }); - browser.test.assertEq("About Mozilla", bookmarksByTitle[0].title, "Bookmark has the expected title"); - browser.test.assertEq("Firefox", bookmarksByTitle[1].title, "Bookmark has the expected title"); - browser.test.assertEq("Mozilla", bookmarksByTitle[2].title, "Bookmark has the expected title"); - browser.test.assertEq("Mozilla Corporation", bookmarksByTitle[3].title, "Bookmark has the expected title"); - - return browser.bookmarks.search({}); - }).then(results => { - let startBookmarkCount = results.length; - - return browser.bookmarks.search({title: "Mozilla Folder"}).then(result => { - return browser.bookmarks.removeTree(result[0].id); - }).then(() => { - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnRemoved(createdFolderId, bookmarkGuids.unfiledGuid, 1); - - return browser.bookmarks.search({}).then(searchResults => { - browser.test.assertEq( - startBookmarkCount - 4, - searchResults.length, - "Expected number of results returned after removeTree"); - }); - }); - }).then(() => { - return browser.bookmarks.create({title: "Empty Folder"}); - }).then(result => { - let emptyFolderId = result.id; - - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnCreated(emptyFolderId, bookmarkGuids.unfiledGuid, 3, "Empty Folder", undefined, result.dateAdded); - - browser.test.assertEq("Empty Folder", result.title, "Folder has the expected title"); - return browser.bookmarks.remove(emptyFolderId).then(() => { - browser.test.assertEq(1, collectedEvents.length, "1 expected events received"); - checkOnRemoved(emptyFolderId, bookmarkGuids.unfiledGuid, 3); - - return browser.bookmarks.get(emptyFolderId).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("Bookmark not found"), - "Expected error thrown when trying to get a removed folder" - ); - }); - }); - }).then(() => { - return browser.bookmarks.getChildren(nonExistentId).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("root is null"), - "Expected error thrown when trying to getChildren for a non-existent folder" - ); - }); - }).then(() => { - return Promise.resolve().then(() => { - return browser.bookmarks.move(nonExistentId, {}); - }).then(expectedError, error => { - browser.test.assertTrue( - error.message.includes("No bookmarks found for the provided GUID"), - "Expected error thrown when calling move with a non-existent bookmark" - ); - }); - }).then(() => { - // remove all created bookmarks - let promises = Array.from(createdBookmarks, guid => browser.bookmarks.remove(guid)); - return Promise.all(promises); - }).then(() => { - browser.test.assertEq(createdBookmarks.size, collectedEvents.length, "expected number of events received"); - - return browser.bookmarks.search({}); - }).then(results => { - browser.test.assertEq(initialBookmarkCount, results.length, "All created bookmarks have been removed"); - - return browser.test.notifyPass("bookmarks"); - }).catch(error => { - browser.test.fail(`Error: ${String(error)} :: ${error.stack}`); - browser.test.notifyFail("bookmarks"); - }); -} - -let extensionData = { - background: `(${backgroundScript})()`, - manifest: { - permissions: ["bookmarks"], - }, -}; - -add_task(function* test_contentscript() { - let extension = ExtensionTestUtils.loadExtension(extensionData); - yield extension.startup(); - yield extension.awaitFinish("bookmarks"); - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/xpcshell/test_ext_history.js b/browser/components/extensions/test/xpcshell/test_ext_history.js deleted file mode 100644 index 78df33151..000000000 --- a/browser/components/extensions/test/xpcshell/test_ext_history.js +++ /dev/null @@ -1,487 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", - "resource://gre/modules/PlacesUtils.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils", - "resource://gre/modules/ExtensionUtils.jsm"); - -add_task(function* test_delete() { - function background() { - let historyClearedCount = 0; - let removedUrls = []; - - browser.history.onVisitRemoved.addListener(data => { - if (data.allHistory) { - historyClearedCount++; - browser.test.assertEq(0, data.urls.length, "onVisitRemoved received an empty urls array"); - } else { - browser.test.assertEq(1, data.urls.length, "onVisitRemoved received one URL"); - removedUrls.push(data.urls[0]); - } - }); - - browser.test.onMessage.addListener((msg, arg) => { - if (msg === "delete-url") { - browser.history.deleteUrl({url: arg}).then(result => { - browser.test.assertEq(undefined, result, "browser.history.deleteUrl returns nothing"); - browser.test.sendMessage("url-deleted"); - }); - } else if (msg === "delete-range") { - browser.history.deleteRange(arg).then(result => { - browser.test.assertEq(undefined, result, "browser.history.deleteRange returns nothing"); - browser.test.sendMessage("range-deleted", removedUrls); - }); - } else if (msg === "delete-all") { - browser.history.deleteAll().then(result => { - browser.test.assertEq(undefined, result, "browser.history.deleteAll returns nothing"); - browser.test.sendMessage("history-cleared", [historyClearedCount, removedUrls]); - }); - } - }); - - browser.test.sendMessage("ready"); - } - - const BASE_URL = "http://mozilla.com/test_history/"; - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["history"], - }, - background: `(${background})()`, - }); - - yield extension.startup(); - yield extension.awaitMessage("ready"); - yield PlacesTestUtils.clearHistory(); - - let historyClearedCount; - let visits = []; - let visitDate = new Date(1999, 9, 9, 9, 9).getTime(); - - function pushVisit(subvisits) { - visitDate += 1000; - subvisits.push({date: new Date(visitDate)}); - } - - // Add 5 visits for one uri and 3 visits for 3 others - for (let i = 0; i < 4; ++i) { - let visit = { - url: `${BASE_URL}${i}`, - title: "visit " + i, - visits: [], - }; - if (i === 0) { - for (let j = 0; j < 5; ++j) { - pushVisit(visit.visits); - } - } else { - pushVisit(visit.visits); - } - visits.push(visit); - } - - yield PlacesUtils.history.insertMany(visits); - equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 5, "5 visits for uri found in history database"); - - let testUrl = visits[2].url; - ok((yield PlacesTestUtils.isPageInDB(testUrl)), "expected url found in history database"); - - extension.sendMessage("delete-url", testUrl); - yield extension.awaitMessage("url-deleted"); - equal((yield PlacesTestUtils.isPageInDB(testUrl)), false, "expected url not found in history database"); - - // delete 3 of the 5 visits for url 1 - let filter = { - startTime: visits[0].visits[0].date, - endTime: visits[0].visits[2].date, - }; - - extension.sendMessage("delete-range", filter); - let removedUrls = yield extension.awaitMessage("range-deleted"); - ok(!removedUrls.includes(visits[0].url), `${visits[0].url} not received by onVisitRemoved`); - ok((yield PlacesTestUtils.isPageInDB(visits[0].url)), "expected uri found in history database"); - equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 2, "2 visits for uri found in history database"); - ok((yield PlacesTestUtils.isPageInDB(visits[1].url)), "expected uri found in history database"); - equal((yield PlacesTestUtils.visitsInDB(visits[1].url)), 1, "1 visit for uri found in history database"); - - // delete the rest of the visits for url 1, and the visit for url 2 - filter.startTime = visits[0].visits[0].date; - filter.endTime = visits[1].visits[0].date; - - extension.sendMessage("delete-range", filter); - yield extension.awaitMessage("range-deleted"); - - equal((yield PlacesTestUtils.isPageInDB(visits[0].url)), false, "expected uri not found in history database"); - equal((yield PlacesTestUtils.visitsInDB(visits[0].url)), 0, "0 visits for uri found in history database"); - equal((yield PlacesTestUtils.isPageInDB(visits[1].url)), false, "expected uri not found in history database"); - equal((yield PlacesTestUtils.visitsInDB(visits[1].url)), 0, "0 visits for uri found in history database"); - - ok((yield PlacesTestUtils.isPageInDB(visits[3].url)), "expected uri found in history database"); - - extension.sendMessage("delete-all"); - [historyClearedCount, removedUrls] = yield extension.awaitMessage("history-cleared"); - equal(PlacesUtils.history.hasHistoryEntries, false, "history is empty"); - equal(historyClearedCount, 2, "onVisitRemoved called for each clearing of history"); - equal(removedUrls.length, 3, "onVisitRemoved called the expected number of times"); - for (let i = 1; i < 3; ++i) { - let url = visits[i].url; - ok(removedUrls.includes(url), `${url} received by onVisitRemoved`); - } - yield extension.unload(); -}); - -add_task(function* test_search() { - const SINGLE_VISIT_URL = "http://example.com/"; - const DOUBLE_VISIT_URL = "http://example.com/2/"; - const MOZILLA_VISIT_URL = "http://mozilla.com/"; - const REFERENCE_DATE = new Date(); - // pages/visits to add via History.insert - const PAGE_INFOS = [ - { - url: SINGLE_VISIT_URL, - title: `test visit for ${SINGLE_VISIT_URL}`, - visits: [ - {date: new Date(Number(REFERENCE_DATE) - 1000)}, - ], - }, - { - url: DOUBLE_VISIT_URL, - title: `test visit for ${DOUBLE_VISIT_URL}`, - visits: [ - {date: REFERENCE_DATE}, - {date: new Date(Number(REFERENCE_DATE) - 2000)}, - ], - }, - { - url: MOZILLA_VISIT_URL, - title: `test visit for ${MOZILLA_VISIT_URL}`, - visits: [ - {date: new Date(Number(REFERENCE_DATE) - 3000)}, - ], - }, - ]; - - function background(BGSCRIPT_REFERENCE_DATE) { - const futureTime = Date.now() + 24 * 60 * 60 * 1000; - - browser.test.onMessage.addListener(msg => { - browser.history.search({text: ""}).then(results => { - browser.test.sendMessage("empty-search", results); - return browser.history.search({text: "mozilla.com"}); - }).then(results => { - browser.test.sendMessage("text-search", results); - return browser.history.search({text: "example.com", maxResults: 1}); - }).then(results => { - browser.test.sendMessage("max-results-search", results); - return browser.history.search({text: "", startTime: BGSCRIPT_REFERENCE_DATE - 2000, endTime: BGSCRIPT_REFERENCE_DATE - 1000}); - }).then(results => { - browser.test.sendMessage("date-range-search", results); - return browser.history.search({text: "", startTime: futureTime}); - }).then(results => { - browser.test.assertEq(0, results.length, "no results returned for late start time"); - return browser.history.search({text: "", endTime: 0}); - }).then(results => { - browser.test.assertEq(0, results.length, "no results returned for early end time"); - return browser.history.search({text: "", startTime: Date.now(), endTime: 0}); - }).then(results => { - browser.test.fail("history.search rejects with startTime that is after the endTime"); - }, error => { - browser.test.assertEq( - "The startTime cannot be after the endTime", - error.message, - "history.search rejects with startTime that is after the endTime"); - }).then(() => { - browser.test.notifyPass("search"); - }); - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["history"], - }, - background: `(${background})(${Number(REFERENCE_DATE)})`, - }); - - function findResult(url, results) { - return results.find(r => r.url === url); - } - - function checkResult(results, url, expectedCount) { - let result = findResult(url, results); - notEqual(result, null, `history.search result was found for ${url}`); - equal(result.visitCount, expectedCount, `history.search reports ${expectedCount} visit(s)`); - equal(result.title, `test visit for ${url}`, "title for search result is correct"); - } - - yield extension.startup(); - yield extension.awaitMessage("ready"); - yield PlacesTestUtils.clearHistory(); - - yield PlacesUtils.history.insertMany(PAGE_INFOS); - - extension.sendMessage("check-history"); - - let results = yield extension.awaitMessage("empty-search"); - equal(results.length, 3, "history.search with empty text returned 3 results"); - checkResult(results, SINGLE_VISIT_URL, 1); - checkResult(results, DOUBLE_VISIT_URL, 2); - checkResult(results, MOZILLA_VISIT_URL, 1); - - results = yield extension.awaitMessage("text-search"); - equal(results.length, 1, "history.search with specific text returned 1 result"); - checkResult(results, MOZILLA_VISIT_URL, 1); - - results = yield extension.awaitMessage("max-results-search"); - equal(results.length, 1, "history.search with maxResults returned 1 result"); - checkResult(results, DOUBLE_VISIT_URL, 2); - - results = yield extension.awaitMessage("date-range-search"); - equal(results.length, 2, "history.search with a date range returned 2 result"); - checkResult(results, DOUBLE_VISIT_URL, 2); - checkResult(results, SINGLE_VISIT_URL, 1); - - yield extension.awaitFinish("search"); - yield extension.unload(); - yield PlacesTestUtils.clearHistory(); -}); - -add_task(function* test_add_url() { - function background() { - const TEST_DOMAIN = "http://example.com/"; - - browser.test.onMessage.addListener((msg, testData) => { - let [details, type] = testData; - details.url = details.url || `${TEST_DOMAIN}${type}`; - if (msg === "add-url") { - details.title = `Title for ${type}`; - browser.history.addUrl(details).then(() => { - return browser.history.search({text: details.url}); - }).then(results => { - browser.test.assertEq(1, results.length, "1 result found when searching for added URL"); - browser.test.sendMessage("url-added", {details, result: results[0]}); - }); - } else if (msg === "expect-failure") { - let expectedMsg = testData[2]; - browser.history.addUrl(details).then(() => { - browser.test.fail(`Expected error thrown for ${type}`); - }, error => { - browser.test.assertTrue( - error.message.includes(expectedMsg), - `"Expected error thrown when trying to add a URL with ${type}` - ); - browser.test.sendMessage("add-failed"); - }); - } - }); - - browser.test.sendMessage("ready"); - } - - let addTestData = [ - [{}, "default"], - [{visitTime: new Date()}, "with_date"], - [{visitTime: Date.now()}, "with_ms_number"], - [{visitTime: new Date().toISOString()}, "with_iso_string"], - [{transition: "typed"}, "valid_transition"], - ]; - - let failTestData = [ - [{transition: "generated"}, "an invalid transition", "|generated| is not a supported transition for history"], - [{visitTime: Date.now() + 1000000}, "a future date", "cannot be a future date"], - [{url: "about.config"}, "an invalid url", "about.config is not a valid URL"], - ]; - - function* checkUrl(results) { - ok((yield PlacesTestUtils.isPageInDB(results.details.url)), `${results.details.url} found in history database`); - ok(PlacesUtils.isValidGuid(results.result.id), "URL was added with a valid id"); - equal(results.result.title, results.details.title, "URL was added with the correct title"); - if (results.details.visitTime) { - equal(results.result.lastVisitTime, - Number(ExtensionUtils.normalizeTime(results.details.visitTime)), - "URL was added with the correct date"); - } - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["history"], - }, - background: `(${background})()`, - }); - - yield PlacesTestUtils.clearHistory(); - yield extension.startup(); - yield extension.awaitMessage("ready"); - - for (let data of addTestData) { - extension.sendMessage("add-url", data); - let results = yield extension.awaitMessage("url-added"); - yield checkUrl(results); - } - - for (let data of failTestData) { - extension.sendMessage("expect-failure", data); - yield extension.awaitMessage("add-failed"); - } - - yield extension.unload(); -}); - -add_task(function* test_get_visits() { - function background() { - const TEST_DOMAIN = "http://example.com/"; - const FIRST_DATE = Date.now(); - const INITIAL_DETAILS = { - url: TEST_DOMAIN, - visitTime: FIRST_DATE, - transition: "link", - }; - - let visitIds = new Set(); - - function checkVisit(visit, expected) { - visitIds.add(visit.visitId); - browser.test.assertEq(expected.visitTime, visit.visitTime, "visit has the correct visitTime"); - browser.test.assertEq(expected.transition, visit.transition, "visit has the correct transition"); - browser.history.search({text: expected.url}).then(results => { - // all results will have the same id, so we only need to use the first one - browser.test.assertEq(results[0].id, visit.id, "visit has the correct id"); - }); - } - - let details = Object.assign({}, INITIAL_DETAILS); - - browser.history.addUrl(details).then(() => { - return browser.history.getVisits({url: details.url}); - }).then(results => { - browser.test.assertEq(1, results.length, "the expected number of visits were returned"); - checkVisit(results[0], details); - details.url = `${TEST_DOMAIN}/1/`; - return browser.history.addUrl(details); - }).then(() => { - return browser.history.getVisits({url: details.url}); - }).then(results => { - browser.test.assertEq(1, results.length, "the expected number of visits were returned"); - checkVisit(results[0], details); - details.visitTime = FIRST_DATE - 1000; - details.transition = "typed"; - return browser.history.addUrl(details); - }).then(() => { - return browser.history.getVisits({url: details.url}); - }).then(results => { - browser.test.assertEq(2, results.length, "the expected number of visits were returned"); - checkVisit(results[0], INITIAL_DETAILS); - checkVisit(results[1], details); - }).then(() => { - browser.test.assertEq(3, visitIds.size, "each visit has a unique visitId"); - browser.test.notifyPass("get-visits"); - }); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["history"], - }, - background: `(${background})()`, - }); - - yield PlacesTestUtils.clearHistory(); - yield extension.startup(); - - yield extension.awaitFinish("get-visits"); - yield extension.unload(); -}); - -add_task(function* test_on_visited() { - const SINGLE_VISIT_URL = "http://example.com/1/"; - const DOUBLE_VISIT_URL = "http://example.com/2/"; - let visitDate = new Date(1999, 9, 9, 9, 9).getTime(); - - // pages/visits to add via History.insertMany - const PAGE_INFOS = [ - { - url: SINGLE_VISIT_URL, - title: `visit to ${SINGLE_VISIT_URL}`, - visits: [ - {date: new Date(visitDate)}, - ], - }, - { - url: DOUBLE_VISIT_URL, - title: `visit to ${DOUBLE_VISIT_URL}`, - visits: [ - {date: new Date(visitDate += 1000)}, - {date: new Date(visitDate += 1000)}, - ], - }, - ]; - - function background() { - let onVisitedData = []; - - browser.history.onVisited.addListener(data => { - if (data.url.includes("moz-extension")) { - return; - } - onVisitedData.push(data); - if (onVisitedData.length == 3) { - browser.test.sendMessage("on-visited-data", onVisitedData); - } - }); - - browser.test.sendMessage("ready"); - } - - let extension = ExtensionTestUtils.loadExtension({ - manifest: { - permissions: ["history"], - }, - background: `(${background})()`, - }); - - yield PlacesTestUtils.clearHistory(); - yield extension.startup(); - yield extension.awaitMessage("ready"); - - yield PlacesUtils.history.insertMany(PAGE_INFOS); - - let onVisitedData = yield extension.awaitMessage("on-visited-data"); - - function checkOnVisitedData(index, expected) { - let onVisited = onVisitedData[index]; - ok(PlacesUtils.isValidGuid(onVisited.id), "onVisited received a valid id"); - equal(onVisited.url, expected.url, "onVisited received the expected url"); - // Title will be blank until bug 1287928 lands - // https://bugzilla.mozilla.org/show_bug.cgi?id=1287928 - equal(onVisited.title, "", "onVisited received a blank title"); - equal(onVisited.lastVisitTime, expected.time, "onVisited received the expected time"); - equal(onVisited.visitCount, expected.visitCount, "onVisited received the expected visitCount"); - } - - let expected = { - url: PAGE_INFOS[0].url, - title: PAGE_INFOS[0].title, - time: PAGE_INFOS[0].visits[0].date.getTime(), - visitCount: 1, - }; - checkOnVisitedData(0, expected); - - expected.url = PAGE_INFOS[1].url; - expected.title = PAGE_INFOS[1].title; - expected.time = PAGE_INFOS[1].visits[0].date.getTime(); - checkOnVisitedData(1, expected); - - expected.time = PAGE_INFOS[1].visits[1].date.getTime(); - expected.visitCount = 2; - checkOnVisitedData(2, expected); - - yield extension.unload(); -}); diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js deleted file mode 100644 index 4de7afe01..000000000 --- a/browser/components/extensions/test/xpcshell/test_ext_manifest_commands.js +++ /dev/null @@ -1,24 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - - -add_task(function* test_manifest_commands() { - let normalized = yield ExtensionTestUtils.normalizeManifest({ - "commands": { - "toggle-feature": { - "suggested_key": {"default": "Shifty+Y"}, - "description": "Send a 'toggle-feature' event to the extension", - }, - }, - }); - - let expectedError = ( - String.raw`commands.toggle-feature.suggested_key.default: Value must either: ` + - String.raw`match the pattern /^\s*(Alt|Ctrl|Command|MacCtrl)\s*\+\s*(Shift\s*\+\s*)?([A-Z0-9]|Comma|Period|Home|End|PageUp|PageDown|Space|Insert|Delete|Up|Down|Left|Right)\s*$/, or ` + - String.raw`match the pattern /^(MediaNextTrack|MediaPlayPause|MediaPrevTrack|MediaStop)$/` - ); - - ok(normalized.error.includes(expectedError), - `The manifest error ${JSON.stringify(normalized.error)} must contain ${JSON.stringify(expectedError)}`); -}); diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js deleted file mode 100644 index 2cb141235..000000000 --- a/browser/components/extensions/test/xpcshell/test_ext_manifest_omnibox.js +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -function* testKeyword(params) { - let normalized = yield ExtensionTestUtils.normalizeManifest({ - "omnibox": { - "keyword": params.keyword, - }, - }); - - if (params.expectError) { - let expectedError = ( - String.raw`omnibox.keyword: String "${params.keyword}" ` + - String.raw`must match /^[^?\s:]([^\s:]*[^/\s:])?$/` - ); - ok(normalized.error.includes(expectedError), - `The manifest error ${JSON.stringify(normalized.error)} ` + - `must contain ${JSON.stringify(expectedError)}`); - } else { - equal(normalized.error, undefined, "Should not have an error"); - equal(normalized.errors.length, 0, "Should not have warnings"); - } -} - -add_task(function* test_manifest_commands() { - // accepted single character keywords - yield testKeyword({keyword: "a", expectError: false}); - yield testKeyword({keyword: "-", expectError: false}); - yield testKeyword({keyword: "å—¨", expectError: false}); - yield testKeyword({keyword: "*", expectError: false}); - yield testKeyword({keyword: "/", expectError: false}); - - // rejected single character keywords - yield testKeyword({keyword: "?", expectError: true}); - yield testKeyword({keyword: " ", expectError: true}); - yield testKeyword({keyword: ":", expectError: true}); - - // accepted multi-character keywords - yield testKeyword({keyword: "aa", expectError: false}); - yield testKeyword({keyword: "http", expectError: false}); - yield testKeyword({keyword: "f?a", expectError: false}); - yield testKeyword({keyword: "fa?", expectError: false}); - yield testKeyword({keyword: "f/x", expectError: false}); - yield testKeyword({keyword: "/fx", expectError: false}); - - // rejected multi-character keywords - yield testKeyword({keyword: " a", expectError: true}); - yield testKeyword({keyword: "a ", expectError: true}); - yield testKeyword({keyword: " ", expectError: true}); - yield testKeyword({keyword: " a ", expectError: true}); - yield testKeyword({keyword: "?fx", expectError: true}); - yield testKeyword({keyword: "fx/", expectError: true}); - yield testKeyword({keyword: "f:x", expectError: true}); - yield testKeyword({keyword: "fx:", expectError: true}); - yield testKeyword({keyword: "f x", expectError: true}); - - // miscellaneous tests - yield testKeyword({keyword: "ã“ã‚“ã«ã¡ã¯", expectError: false}); - yield testKeyword({keyword: "http://", expectError: true}); -}); diff --git a/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js b/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js deleted file mode 100644 index 2c436535d..000000000 --- a/browser/components/extensions/test/xpcshell/test_ext_manifest_permissions.js +++ /dev/null @@ -1,57 +0,0 @@ -/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set sts=2 sw=2 et tw=80: */ -"use strict"; - -/* globals chrome */ - -function* testPermission(options) { - function background(bgOptions) { - browser.test.sendMessage("typeof-namespace", { - browser: typeof browser[bgOptions.namespace], - chrome: typeof chrome[bgOptions.namespace], - }); - } - - let extensionDetails = { - background: `(${background})(${JSON.stringify(options)})`, - }; - - let extension = ExtensionTestUtils.loadExtension(extensionDetails); - - yield extension.startup(); - - let types = yield extension.awaitMessage("typeof-namespace"); - equal(types.browser, "undefined", `Type of browser.${options.namespace} without manifest entry`); - equal(types.chrome, "undefined", `Type of chrome.${options.namespace} without manifest entry`); - - yield extension.unload(); - - extensionDetails.manifest = options.manifest; - extension = ExtensionTestUtils.loadExtension(extensionDetails); - - yield extension.startup(); - - types = yield extension.awaitMessage("typeof-namespace"); - equal(types.browser, "object", `Type of browser.${options.namespace} with manifest entry`); - equal(types.chrome, "object", `Type of chrome.${options.namespace} with manifest entry`); - - yield extension.unload(); -} - -add_task(function* test_browserAction() { - yield testPermission({ - namespace: "browserAction", - manifest: { - browser_action: {}, - }, - }); -}); - -add_task(function* test_pageAction() { - yield testPermission({ - namespace: "pageAction", - manifest: { - page_action: {}, - }, - }); -}); diff --git a/browser/components/extensions/test/xpcshell/xpcshell.ini b/browser/components/extensions/test/xpcshell/xpcshell.ini deleted file mode 100644 index b9148a697..000000000 --- a/browser/components/extensions/test/xpcshell/xpcshell.ini +++ /dev/null @@ -1,11 +0,0 @@ -[DEFAULT] -head = head.js -tail = -firefox-appdir = browser -tags = webextensions - -[test_ext_bookmarks.js] -[test_ext_history.js] -[test_ext_manifest_commands.js] -[test_ext_manifest_omnibox.js] -[test_ext_manifest_permissions.js] diff --git a/browser/components/feeds/test/.eslintrc.js b/browser/components/feeds/test/.eslintrc.js deleted file mode 100644 index 3c788d6d6..000000000 --- a/browser/components/feeds/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/mochitest.eslintrc.js" - ] -}; diff --git a/browser/components/feeds/test/bug368464-data.xml b/browser/components/feeds/test/bug368464-data.xml deleted file mode 100644 index 2745b061d..000000000 --- a/browser/components/feeds/test/bug368464-data.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0"?> - <rdf:RDF - xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" - xmlns="http://my.netscape.com/rdf/simple/0.9/"> - <channel> - <title>Tinderbox - Firefox</title> - <description>Build bustages for Firefox</description> - <link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link> - </channel> - <image> - <title>Bad</title> - <url>http://tinderbox.mozilla.org/channelflames.gif</url> - <link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link> - </image> - <item><title>The tree is currently closed</title><link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link></item> - -<item><title>MacOSX Darwin 8.8.4 qm-xserve01 dep unit test is in flames</title><link>http://tinderbox.mozilla.org/showbuilds.cgi?tree=Firefox</link></item> -</rdf:RDF> diff --git a/browser/components/feeds/test/bug408328-data.xml b/browser/components/feeds/test/bug408328-data.xml deleted file mode 100644 index e9385e5ab..000000000 --- a/browser/components/feeds/test/bug408328-data.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2003-12-13T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> - - <entry> - - <title>Good item</title> - <link href="http://example.org/first"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> - <updated>2003-12-13T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - - <entry> - - <title>data: link</title> - <link href="data:text/plain,Hi"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6b</id> - <updated>2003-12-13T18:30:03Z</updated> - - <summary>Some text.</summary> - </entry> - - <entry> - - <title>javascript: link</title> - <link href="javascript:alert('Hi')"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6c</id> - <updated>2003-12-13T18:30:04Z</updated> - - <summary>Some text.</summary> - </entry> - - <entry> - - <title>file: link</title> - <link href="file:///var/"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6d</id> - <updated>2003-12-13T18:30:05Z</updated> - - <summary>Some text.</summary> - </entry> - - <entry> - - <title>chrome: link</title> - <link href="chrome://browser/content/browser.js"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6e</id> - <updated>2003-12-13T18:30:06Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/feeds/test/bug436801-data.xml b/browser/components/feeds/test/bug436801-data.xml deleted file mode 100644 index 0e45c7ed8..000000000 --- a/browser/components/feeds/test/bug436801-data.xml +++ /dev/null @@ -1,44 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom" xml:base="http://www.example.com/"> - - <title type="xhtml" xml:base="/foo/bar/"> - <div xmlns="http://www.w3.org/1999/xhtml">Example of a <em>special</em> feed (<img height="20px" src="baz.png" alt="base test sprite"/>)</div> - </title> - - <subtitle type="html" xml:base="/foo/bar/"> - <![CDATA[ - With a <em>special</em> subtitle (<img height="20px" src="baz.png" alt="base test sprite"/>) - ]]> - </subtitle> - - <link href="http://example.org/"/> - - <updated>2010-09-02T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - - <id>urn:uuid:22906062-ecbd-46e2-b6a7-3039506a398f</id> - - <entry> - <title type="xhtml" xml:base="/foo/bar/"> - <div xmlns="http://www.w3.org/1999/xhtml">Some <abbr title="Extensible Hyper-text Mark-up Language">XHTML</abbr> examples (<img height="20px" src="baz.png" alt="base test sprite"/>)</div> - </title> - <id>urn:uuid:b48083a7-71a7-4c9c-8515-b7c0d22955e7</id> - <updated>2010-09-02T18:30:02Z</updated> - <summary>Some text.</summary> - </entry> - - <entry> - <title type="html" xml:base="/foo/bar/"> - <![CDATA[ - Some <abbr title="Hyper-text Mark-up Language">HTML</abbr> examples (<img height="20px" src="baz.png" alt="base test sprite"/>) - ]]> - </title> - <id>urn:uuid:1424967a-280a-414d-b0ab-8b11c4ac1bb7</id> - <updated>2010-09-02T18:30:02Z</updated> - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/feeds/test/bug494328-data.xml b/browser/components/feeds/test/bug494328-data.xml deleted file mode 100644 index 58342bafc..000000000 --- a/browser/components/feeds/test/bug494328-data.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<rss version="2.0">
- <channel>
- <title>Channel title</title>
- <description>Channel description</description>
- <link>Channel link</link>
- <item>
- <title>Episode 1</title>
- <enclosure url="http://www.example.com/podcasts/Episode%201" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 2</title>
- <enclosure url="http://www.example.com/podcasts/Episode%20%232" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 3</title>
- <enclosure url="http://www.example.com/podcasts/Episode%20%233/" length="0" type="audio/x-m4a" />
- </item>
- <item>
- <title>Episode 4</title>
- <enclosure url="http://www.example.com/podcasts/Is%20This%20Episode%20%234%3F" length="0" type="audio/x-m4a" />
- </item>
- </channel>
-</rss>
diff --git a/browser/components/feeds/test/bug589543-data.xml b/browser/components/feeds/test/bug589543-data.xml deleted file mode 100644 index 0e700b6d8..000000000 --- a/browser/components/feeds/test/bug589543-data.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2010-08-22T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id> - - <entry> - - <title>Item</title> - <link href="http://example.org/first"/> - <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id> - <updated>2010-08-22T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/feeds/test/chrome/.eslintrc.js b/browser/components/feeds/test/chrome/.eslintrc.js deleted file mode 100644 index 8c0f4f574..000000000 --- a/browser/components/feeds/test/chrome/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/chrome.eslintrc.js" - ] -}; diff --git a/browser/components/feeds/test/chrome/chrome.ini b/browser/components/feeds/test/chrome/chrome.ini deleted file mode 100644 index 7bad142ab..000000000 --- a/browser/components/feeds/test/chrome/chrome.ini +++ /dev/null @@ -1,10 +0,0 @@ -[DEFAULT] -support-files = sample_feed.atom - !/browser/components/feeds/test/bug408328-data.xml - !/browser/components/feeds/test/valid-feed.xml - !/browser/components/feeds/test/valid-unsniffable-feed.xml - -[test_423060.xul] -[test_bug368464.html] -[test_bug408328.html] -[test_maxSniffing.html] diff --git a/browser/components/feeds/test/chrome/sample_feed.atom b/browser/components/feeds/test/chrome/sample_feed.atom deleted file mode 100644 index add75efb4..000000000 --- a/browser/components/feeds/test/chrome/sample_feed.atom +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2003-12-13T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id> - - <entry> - - <title>Atom-Powered Robots Run Amok</title> - <link href="http://example.org/2003/12/13/atom03"/> - <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id> - <updated>2003-12-13T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/feeds/test/chrome/test_423060.xul b/browser/components/feeds/test/chrome/test_423060.xul deleted file mode 100644 index 465cf2dd2..000000000 --- a/browser/components/feeds/test/chrome/test_423060.xul +++ /dev/null @@ -1,56 +0,0 @@ -<?xml version="1.0"?> -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet - href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?> -<window title="Make sure feed preview works when a default reader is selected" - xmlns:html="http://www.w3.org/1999/xhtml" - xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <script type="application/javascript"> - SimpleTest.waitForExplicitFinish(); - - const Cc = Components.classes; - const Ci = Components.interfaces; - - var wccrID = "@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"; - /* abort the test if web feed handlers are not available */ - if (!Cc[wccrID]) - SimpleTest.finish() - - /* Turn off the first run UI */ - var prefBranch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); - prefBranch.setBoolPref("browser.feeds.showFirstRunUI", false); - - /* register a handler for the feed type */ - const MAYBE_FEED = "application/vnd.mozilla.maybe.feed"; - var handlerPage = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/demohandler.html?feedurl=%s"; - var wccr = Cc[wccrID].getService(Ci.nsIWebContentConverterService); - wccr.registerContentHandler(MAYBE_FEED, handlerPage, "Demo handler", null); - var demoHandler = wccr.getWebContentHandlerByURI(MAYBE_FEED, handlerPage); - wccr.setAutoHandler(MAYBE_FEED, demoHandler); - - /* Don't show the preview page */ - prefBranch.setCharPref("browser.feeds.handler", "reader"); - - function finishUp() { - var theframe = document.getElementById('theframe'); - var previewURL = "http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/demohandler.html?feedurl=http%3A%2F%2Fmochi.test%3A8888%2Ftests%2Ftoolkit%2Fcomponents%2Fplaces%2Ftests%2Fchrome%2Fsample_feed.atom"; - is(theframe.contentDocument.URL, previewURL); - - /* remove our demoHandler */ - wccr.setAutoHandler(MAYBE_FEED, null); - wccr.removeContentHandler(MAYBE_FEED, handlerPage); - prefBranch.setCharPref("browser.feeds.handler", "ask"); - prefBranch.setBoolPref("browser.feeds.showFirstRunUI", true); - - SimpleTest.finish(); - } - </script> - <html:iframe src="http://mochi.test:8888/tests/toolkit/components/places/tests/chrome/sample_feed.atom" height="400px" - id="theframe" onload="finishUp();"> - </html:iframe> -</window> diff --git a/browser/components/feeds/test/chrome/test_bug368464.html b/browser/components/feeds/test/chrome/test_bug368464.html deleted file mode 100644 index dd7486f66..000000000 --- a/browser/components/feeds/test/chrome/test_bug368464.html +++ /dev/null @@ -1,32 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=368464 ---> -<head> - <title>Test that RSS 0.90 isn't sniffed</title> - <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=368464">Mozilla Bug 368464</a> -<p id="display"><iframe id="testFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/bug368464-data.xml"></iframe></p> -<div id="content" style="display: none"> - -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 368464 **/ -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function() { - ok($("testFrame").contentDocument.documentElement.id != "feedHandler", - "RSS 0.90 shouldn't be sniffed as a feed"); -}); -addLoadEvent(SimpleTest.finish); - -</script> -</pre> -</body> -</html> diff --git a/browser/components/feeds/test/chrome/test_bug408328.html b/browser/components/feeds/test/chrome/test_bug408328.html deleted file mode 100644 index e4901320a..000000000 --- a/browser/components/feeds/test/chrome/test_bug408328.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=408328 ---> -<head> - <title>Test feed preview safe-linkification</title> - <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=408328">Mozilla Bug 408328</a> -<p id="display"><iframe id="testFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/bug408328-data.xml"></iframe></p> -<div id="content" style="display: none"> - -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 408328 **/ -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function() { - var links = $("testFrame").contentDocument.getElementById("feedContent").getElementsByTagName("a"); - is(links.length, 5, "wrong number of linked items in feed preview"); - for (var i = 0; i < links.length; i++) { - if (links[i].href) - is(links[i].href, "http://example.org/first", "bad linkified item"); - } -}); -addLoadEvent(SimpleTest.finish); - -</script> -</pre> -</body> -</html> - diff --git a/browser/components/feeds/test/chrome/test_maxSniffing.html b/browser/components/feeds/test/chrome/test_maxSniffing.html deleted file mode 100644 index 7a2044687..000000000 --- a/browser/components/feeds/test/chrome/test_maxSniffing.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=739040 ---> -<head> - <title>Test that we only sniff 512 bytes</title> - <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=739040">Mozilla Bug 739040</a> -<p id="display"> - <iframe id="validTestFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/valid-feed.xml"></iframe> - <iframe id="unsniffableTestFrame" src="http://mochi.test:8888/tests/browser/components/feeds/test/valid-unsniffable-feed.xml"></iframe> -</p> -<div id="content" style="display: none"> - -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 739040 **/ -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function() { - is($("validTestFrame").contentDocument.documentElement.id, "feedHandler", - "valid feed should be sniffed"); - isnot($("unsniffableTestFrame").contentDocument.documentElement.id, "feedHandler", - "unsniffable feed should not be sniffed"); -}); -addLoadEvent(SimpleTest.finish); - -</script> -</pre> -</body> -</html> diff --git a/browser/components/feeds/test/mochitest.ini b/browser/components/feeds/test/mochitest.ini deleted file mode 100644 index fc1e6a1a9..000000000 --- a/browser/components/feeds/test/mochitest.ini +++ /dev/null @@ -1,14 +0,0 @@ -[DEFAULT] -support-files = - bug368464-data.xml - bug408328-data.xml - bug436801-data.xml - bug494328-data.xml - bug589543-data.xml - valid-feed.xml - valid-unsniffable-feed.xml - -[test_bug436801.html] -[test_bug494328.html] -[test_bug589543.html] -[test_registerHandler.html] diff --git a/browser/components/feeds/test/test_bug436801.html b/browser/components/feeds/test/test_bug436801.html deleted file mode 100644 index 29fb5acf0..000000000 --- a/browser/components/feeds/test/test_bug436801.html +++ /dev/null @@ -1,118 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=436801 ---> -<head> - <title>Test feed preview subscribe UI</title> - <script type="text/javascript" src="/MochiKit/packed.js"></script> - <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=436801">Mozilla Bug 436801</a> -<p id="display"><iframe id="testFrame" src="bug436801-data.xml"></iframe></p> -<div id="content" style="display: none"> -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function () { - var doc = SpecialPowers.wrap($("testFrame")).contentDocument; - - checkNode(doc.getElementById("feedTitleText"), [ - "ELEMENT", "h1", { "xml:base": "http://www.example.com/foo/bar/" }, [ - ["TEXT", "Example of a "], - ["ELEMENT", "em", [ - ["TEXT", "special"], - ]], - ["TEXT", " feed ("], - ["ELEMENT", "img", { "src": "baz.png" }], - ["TEXT", ")"], - ] - ]); - - checkNode(doc.getElementById("feedSubtitleText"), [ - "ELEMENT", "h2", { "xml:base": "http://www.example.com/foo/bar/" }, [ - ["TEXT", "With a "], - ["ELEMENT", "em", [ - ["TEXT", "special"], - ]], - ["TEXT", " subtitle ("], - ["ELEMENT", "img", { "src": "baz.png" }], - ["TEXT", ")"], - ] - ]); - - checkNode(doc.querySelector(".entry").firstChild.firstChild.firstChild, [ - "ELEMENT", "span", { "xml:base": "http://www.example.com/foo/bar/" }, [ - ["TEXT", "Some "], - ["ELEMENT", "abbr", { title: "Extensible Hyper-text Mark-up Language" }, [ - ["TEXT", "XHTML"], - ]], - ["TEXT", " examples ("], - ["ELEMENT", "img", { "src": "baz.png" }], - ["TEXT", ")"], - ] - ]); - - checkNode(doc.querySelectorAll(".entry")[1].firstChild.firstChild.firstChild, [ - "ELEMENT", "span", { "xml:base": "http://www.example.com/foo/bar/" }, [ - ["TEXT", "Some "], - ["ELEMENT", "abbr", { title: "Hyper-text Mark-up Language" }, [ - ["TEXT", "HTML"], - ]], - ["TEXT", " examples ("], - ["ELEMENT", "img", { "src": "baz.png" }], - ["TEXT", ")"], - ] - ]); -}); - -addLoadEvent(SimpleTest.finish); - -function checkNode(node, schema) { - var typeName = schema.shift() + "_NODE"; - var type = Node[typeName]; - is(node.nodeType, type, "Node should be expected type " + typeName); - if (type == Node.TEXT_NODE) { - var text = schema.shift(); - is(node.data, text, "Text should match"); - return; - } - // type == Node.ELEMENT_NODE - var tag = schema.shift(); - is(node.localName, tag, "Element should have expected tag"); - while (schema.length) { - let val = schema.shift(); - if (Array.isArray(val)) - var childSchema = val; - else - var attrSchema = val; - } - if (attrSchema) { - var nsTable = { - xml: "http://www.w3.org/XML/1998/namespace", - }; - for (var name in attrSchema) { - var [ns, nsName] = name.split(":"); - let val = nsName ? node.getAttributeNS(nsTable[ns], nsName) : - node.getAttribute(name); - is(val, attrSchema[name], "Attribute " + name + " should match"); - } - } - if (childSchema) { - var numChildren = node.childNodes.length; - is(childSchema.length, numChildren, - "Element should have expected number of children"); - for (var i = 0; i < numChildren; i++) - checkNode(node.childNodes[i], childSchema[i]); - } -} - -</script> -</pre> -</body> -</html> diff --git a/browser/components/feeds/test/test_bug494328.html b/browser/components/feeds/test/test_bug494328.html deleted file mode 100644 index 054f62c1d..000000000 --- a/browser/components/feeds/test/test_bug494328.html +++ /dev/null @@ -1,36 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=494328 ---> -<head> - <title>Test for bug 494328</title> - <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=494328">Mozilla Bug 494328</a> -<p id="display"><iframe id="testFrame" src="bug494328-data.xml"></iframe></p> -<div id="content" style="display: none"> - -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 494328 **/ -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function() { - var links = SpecialPowers.wrap($("testFrame")).contentDocument.getElementById("feedContent").querySelectorAll("div.enclosure > a"); - is(links[0].textContent, "Episode 1", "filename decoded incorrectly"); - is(links[1].textContent, "Episode #2", "filename decoded incorrectly"); - is(links[2].textContent, "http://www.example.com/podcasts/Episode #3/", "filename decoded incorrectly"); - is(links[3].textContent, "Is This Episode #4?", "filename decoded incorrectly"); -}); -addLoadEvent(SimpleTest.finish); - -</script> -</pre> -</body> -</html> - diff --git a/browser/components/feeds/test/test_bug589543.html b/browser/components/feeds/test/test_bug589543.html deleted file mode 100644 index cee2a9661..000000000 --- a/browser/components/feeds/test/test_bug589543.html +++ /dev/null @@ -1,32 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=589543 ---> -<head> - <title>Test feed preview subscribe UI</title> - <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=589543">Mozilla Bug 589543</a> -<p id="display"><iframe id="testFrame" src="bug589543-data.xml"></iframe></p> -<div id="content" style="display: none"> -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 589543 **/ -SimpleTest.waitForExplicitFinish(); - -addLoadEvent(function() { - var doc = SpecialPowers.wrap($("testFrame")).contentDocument; - var popup = doc.getElementById("handlersMenuList"); - isnot(popup, null, "Feed preview should have a handlers popup"); -}); -addLoadEvent(SimpleTest.finish); - -</script> -</pre> -</body> -</html> diff --git a/browser/components/feeds/test/test_registerHandler.html b/browser/components/feeds/test/test_registerHandler.html deleted file mode 100644 index 34e61d034..000000000 --- a/browser/components/feeds/test/test_registerHandler.html +++ /dev/null @@ -1,85 +0,0 @@ -<!DOCTYPE HTML> -<html> -<!-- -https://bugzilla.mozilla.org/show_bug.cgi?id=402788 ---> -<head> - <title>Test for Bug 402788</title> - <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" /> -</head> -<body> -<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=402788">Mozilla Bug 402788</a> -<p id="display"></p> -<div id="content" style="display: none"> - -</div> -<pre id="test"> -<script class="testbody" type="text/javascript"> - -/** Test for Bug 402788 **/ - - // return false if an exception has been catched, true otherwise - function testRegisterHandler(aIsProtocol, aTxt, aUri, aTitle) - { - try { - if (aIsProtocol) - navigator.registerProtocolHandler(aTxt, aUri, aTitle); - else - navigator.registerContentHandler(aTxt, aUri, aTitle); - } - catch (e) { - return false; - } - - return true; - } - - ok(navigator.registerProtocolHandler, "navigator.registerProtocolHandler should be defined"); - ok(navigator.registerContentHandler, "navigator.registerContentHandler should be defined"); - - // testing a generic case - is(testRegisterHandler(true, "foo", "http://mochi.test:8888/%s", "Foo handler"), true, "registering a foo protocol handler should work"); - is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering a foo content handler should work"); - - // testing with wrong uris - is(testRegisterHandler(true, "foo", "http://mochi.test:8888/", "Foo handler"), false, "a protocol handler uri should contain %s"); - is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/", "Foo handler"), false, "a content handler uri should contain %s"); - - // the spec explicitly allows relative urls to be passed - is(testRegisterHandler(true, "foo", "foo/%s", "Foo handler"), true, "a protocol handler uri should be valid"); - is(testRegisterHandler(false, "application/rss+xml", "foo/%s", "Foo handler"), true, "a content handler uri should be valid"); - - // we should only accept to register when the handler has the same host as the current page (bug 402287) - is(testRegisterHandler(true, "foo", "http://remotehost:8888/%s", "Foo handler"), false, "registering a foo protocol handler with a different host should not work"); - is(testRegisterHandler(false, "application/rss+xml", "http://remotehost:8888/%s", "Foo handler"), false, "registering a foo content handler with a different host should not work"); - - // restriction to http(s) for the uri of the handler (bug 401343) - // https should work (http already tested in the generic case) - is(testRegisterHandler(true, "foo", "https://mochi.test:8888/%s", "Foo handler"), true, "registering a foo protocol handler with https scheme should work"); - is(testRegisterHandler(false, "application/rss+xml", "https://mochi.test:8888/%s", "Foo handler"), true, "registering a foo content handler with https scheme should work"); - // ftp should not work - is(testRegisterHandler(true, "foo", "ftp://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with ftp scheme should not work"); - is(testRegisterHandler(false, "application/rss+xml", "ftp://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with ftp scheme should not work"); - // chrome should not work - is(testRegisterHandler(true, "foo", "chrome://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with chrome scheme should not work"); - is(testRegisterHandler(false, "application/rss+xml", "chrome://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with chrome scheme should not work"); - // foo should not work - is(testRegisterHandler(true, "foo", "foo://mochi.test:8888/%s", "Foo handler"), false, "registering a foo protocol handler with foo scheme should not work"); - is(testRegisterHandler(false, "application/rss+xml", "foo://mochi.test:8888/%s", "Foo handler"), false, "registering a foo content handler with foo scheme should not work"); - - // for security reasons, protocol handlers should never be registered for some schemes (chrome, vbscript, ...) (bug 402788) - is(testRegisterHandler(true, "chrome", "http://mochi.test:8888/%s", "chrome handler"), false, "registering a chrome protocol handler should not work"); - is(testRegisterHandler(true, "vbscript", "http://mochi.test:8888/%s", "vbscript handler"), false, "registering a vbscript protocol handler should not work"); - is(testRegisterHandler(true, "javascript", "http://mochi.test:8888/%s", "javascript handler"), false, "registering a javascript protocol handler should not work"); - is(testRegisterHandler(true, "moz-icon", "http://mochi.test:8888/%s", "moz-icon handler"), false, "registering a moz-icon protocol handler should not work"); - - // for security reasons, content handlers should never be registered for some types (html, ...) - is(testRegisterHandler(false, "application/rss+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering rss content handlers should work"); - is(testRegisterHandler(false, "application/atom+xml", "http://mochi.test:8888/%s", "Foo handler"), true, "registering atom content handlers should work"); - todo_is(testRegisterHandler(false, "text/html", "http://mochi.test:8888/%s", "Foo handler"), false, "registering html content handlers should not work"); // bug 403798 - -</script> -</pre> -</body> -</html> diff --git a/browser/components/feeds/test/unit/.eslintrc.js b/browser/components/feeds/test/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/feeds/test/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/feeds/test/unit/head_feeds.js b/browser/components/feeds/test/unit/head_feeds.js deleted file mode 100644 index 3b1135ef7..000000000 --- a/browser/components/feeds/test/unit/head_feeds.js +++ /dev/null @@ -1,5 +0,0 @@ -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cr = Components.results; - -var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); diff --git a/browser/components/feeds/test/unit/test_355473.js b/browser/components/feeds/test/unit/test_355473.js deleted file mode 100644 index 8a20d1389..000000000 --- a/browser/components/feeds/test/unit/test_355473.js +++ /dev/null @@ -1,43 +0,0 @@ -var Cu = Components.utils; -Cu.import("resource://gre/modules/NetUtil.jsm"); - -function run_test() { - var feedFeedURI = ios.newURI("feed://example.com/feed.xml", null, null); - var httpFeedURI = ios.newURI("feed:http://example.com/feed.xml", null, null); - var httpURI = ios.newURI("http://example.com/feed.xml", null, null); - - var httpsFeedURI = - ios.newURI("feed:https://example.com/feed.xml", null, null); - var httpsURI = ios.newURI("https://example.com/feed.xml", null, null); - - var feedChannel = NetUtil.newChannel({ - uri: feedFeedURI, - loadUsingSystemPrincipal: true - }); - - var httpChannel = NetUtil.newChannel({ - uri: httpFeedURI, - loadUsingSystemPrincipal: true - }); - - var httpsChannel = NetUtil.newChannel({ - uri: httpsFeedURI, - loadUsingSystemPrincipal: true - }); - - // not setting .originalURI to the original URI is naughty - do_check_true(feedFeedURI.equals(feedChannel.originalURI)); - do_check_true(httpFeedURI.equals(httpChannel.originalURI)); - do_check_true(httpsFeedURI.equals(httpsChannel.originalURI)); - - // actually using the horrible mess that's a feed: URI is suicidal - do_check_true(httpURI.equals(feedChannel.URI)); - do_check_true(httpURI.equals(httpChannel.URI)); - do_check_true(httpsURI.equals(httpsChannel.URI)); - - // check that we throw creating feed: URIs from file and ftp - Assert.throws(function() { ios.newURI("feed:ftp://example.com/feed.xml", null, null); }, - "Should throw an exception when trying to create a feed: URI with an ftp: inner"); - Assert.throws(function() { ios.newURI("feed:file:///var/feed.xml", null, null); }, - "Should throw an exception when trying to create a feed: URI with a file: inner"); -} diff --git a/browser/components/feeds/test/unit/test_758990.js b/browser/components/feeds/test/unit/test_758990.js deleted file mode 100644 index e6f88baf2..000000000 --- a/browser/components/feeds/test/unit/test_758990.js +++ /dev/null @@ -1,42 +0,0 @@ -function run_test() { - var success = false; - try { - ios.newURI("feed:javascript:alert('hi');", null, null); - } - catch (e) { - success = e.result == Cr.NS_ERROR_MALFORMED_URI; - } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:javascript: URI"); - - success = false; - try { - ios.newURI("feed:data:text/html,hi", null, null); - } - catch (e) { - success = e.result == Cr.NS_ERROR_MALFORMED_URI; - } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a feed:data: URI"); - - success = false; - try { - ios.newURI("pcast:javascript:alert('hi');", null, null); - } - catch (e) { - success = e.result == Cr.NS_ERROR_MALFORMED_URI; - } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:javascript: URI"); - - success = false; - try { - ios.newURI("pcast:data:text/html,hi", null, null); - } - catch (e) { - success = e.result == Cr.NS_ERROR_MALFORMED_URI; - } - if (!success) - do_throw("We didn't throw NS_ERROR_MALFORMED_URI creating a pcast:data: URI"); - -} diff --git a/browser/components/feeds/test/unit/xpcshell.ini b/browser/components/feeds/test/unit/xpcshell.ini deleted file mode 100644 index 9faf57396..000000000 --- a/browser/components/feeds/test/unit/xpcshell.ini +++ /dev/null @@ -1,8 +0,0 @@ -[DEFAULT] -head = head_feeds.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_355473.js] -[test_758990.js] diff --git a/browser/components/feeds/test/valid-feed.xml b/browser/components/feeds/test/valid-feed.xml deleted file mode 100644 index 0e700b6d8..000000000 --- a/browser/components/feeds/test/valid-feed.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2010-08-22T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id> - - <entry> - - <title>Item</title> - <link href="http://example.org/first"/> - <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id> - <updated>2010-08-22T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/feeds/test/valid-unsniffable-feed.xml b/browser/components/feeds/test/valid-unsniffable-feed.xml deleted file mode 100644 index e75315739..000000000 --- a/browser/components/feeds/test/valid-unsniffable-feed.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- 512 bytes! -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - --> -<feed xmlns="http://www.w3.org/2005/Atom"> - - <title>Example Feed</title> - <link href="http://example.org/"/> - <updated>2010-08-22T18:30:02Z</updated> - - <author> - <name>John Doe</name> - </author> - <id>urn:uuid:e2df8375-99be-4848-b05e-b9d407555267</id> - - <entry> - - <title>Item</title> - <link href="http://example.org/first"/> - <id>urn:uuid:9e0f4bed-33d3-4a9d-97ab-ecaa31b3f14a</id> - <updated>2010-08-22T18:30:02Z</updated> - - <summary>Some text.</summary> - </entry> - -</feed> diff --git a/browser/components/migration/tests/browser/.eslintrc.js b/browser/components/migration/tests/browser/.eslintrc.js deleted file mode 100644 index 3ea6eeb8c..000000000 --- a/browser/components/migration/tests/browser/.eslintrc.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js", - "../../../../../testing/mochitest/mochitest.eslintrc.js", - ] -}; - diff --git a/browser/components/migration/tests/browser/browser.ini b/browser/components/migration/tests/browser/browser.ini deleted file mode 100644 index 94edfe7aa..000000000 --- a/browser/components/migration/tests/browser/browser.ini +++ /dev/null @@ -1,3 +0,0 @@ -[browser_undo_notification.js] -[browser_undo_notification_wording.js] -[browser_undo_notification_multiple_dismissal.js] diff --git a/browser/components/migration/tests/browser/browser_undo_notification.js b/browser/components/migration/tests/browser/browser_undo_notification.js deleted file mode 100644 index 6c97922e0..000000000 --- a/browser/components/migration/tests/browser/browser_undo_notification.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; - -let scope = {}; -Cu.import("resource:///modules/AutoMigrate.jsm", scope); -let oldCanUndo = scope.AutoMigrate.canUndo; -let oldUndo = scope.AutoMigrate.undo; -registerCleanupFunction(function() { - scope.AutoMigrate.canUndo = oldCanUndo; - scope.AutoMigrate.undo = oldUndo; -}); - -const kExpectedNotificationId = "automigration-undo"; - -add_task(function* autoMigrationUndoNotificationShows() { - let getNotification = browser => - gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId); - - scope.AutoMigrate.canUndo = () => true; - let undoCalled; - scope.AutoMigrate.undo = () => { undoCalled = true }; - for (let url of ["about:newtab", "about:home"]) { - undoCalled = false; - // Can't use pushPrefEnv because of bug 1323779 - Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser"); - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false); - let browser = tab.linkedBrowser; - if (!getNotification(browser)) { - info(`Notification for ${url} not immediately present, waiting for it.`); - yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId); - } - - ok(true, `Got notification for ${url}`); - let notification = getNotification(browser); - let notificationBox = notification.parentNode; - notification.querySelector("button.notification-button-default").click(); - ok(!undoCalled, "Undo should not be called when clicking the default button"); - is(notification, notificationBox._closedNotification, "Notification should be closing"); - yield BrowserTestUtils.removeTab(tab); - - undoCalled = false; - Services.prefs.setCharPref("browser.migrate.automigrate.browser", "chrome"); - tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false); - browser = tab.linkedBrowser; - if (!getNotification(browser)) { - info(`Notification for ${url} not immediately present, waiting for it.`); - yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId); - } - - ok(true, `Got notification for ${url}`); - notification = getNotification(browser); - notificationBox = notification.parentNode; - // Set up the survey: - yield SpecialPowers.pushPrefEnv({set: [ - ["browser.migrate.automigrate.undo-survey", "https://example.com/?browser=%IMPORTEDBROWSER%"], - ["browser.migrate.automigrate.undo-survey-locales", "en-US"], - ]}); - let tabOpenedPromise = BrowserTestUtils.waitForNewTab(gBrowser, "https://example.com/?browser=Google%20Chrome"); - notification.querySelector("button:not(.notification-button-default)").click(); - ok(undoCalled, "Undo should be called when clicking the non-default (Don't Keep) button"); - is(notification, notificationBox._closedNotification, "Notification should be closing"); - let surveyTab = yield tabOpenedPromise; - ok(surveyTab, "Should have opened a tab with a survey"); - yield BrowserTestUtils.removeTab(surveyTab); - yield BrowserTestUtils.removeTab(tab); - } -}); - diff --git a/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js b/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js deleted file mode 100644 index 90b5d0d08..000000000 --- a/browser/components/migration/tests/browser/browser_undo_notification_multiple_dismissal.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; - - -const kExpectedNotificationId = "automigration-undo"; - -/** - * Pretend we can undo something, trigger a notification, pick the undo option, - * and verify that the notifications are all dismissed immediately. - */ -add_task(function* checkNotificationsDismissed() { - yield SpecialPowers.pushPrefEnv({set: [ - ["browser.migrate.automigrate.enabled", true], - ["browser.migrate.automigrate.ui.enabled", true], - ]}); - let getNotification = browser => - gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId); - - Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser"); - - let {guid, lastModified} = yield PlacesUtils.bookmarks.insert( - {title: "Some imported bookmark", parentGuid: PlacesUtils.bookmarks.toolbarGuid, url: "http://www.example.com"} - ); - - let testUndoData = { - visits: [], - bookmarks: [{guid, lastModified: lastModified.getTime()}], - logins: [], - }; - let path = OS.Path.join(OS.Constants.Path.profileDir, "initialMigrationMetadata.jsonlz4"); - registerCleanupFunction(() => { - return OS.File.remove(path, {ignoreAbsent: true}); - }); - yield OS.File.writeAtomic(path, JSON.stringify(testUndoData), { - encoding: "utf-8", - compression: "lz4", - tmpPath: path + ".tmp", - }); - - let firstTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home", false); - if (!getNotification(firstTab.linkedBrowser)) { - info(`Notification not immediately present on first tab, waiting for it.`); - yield BrowserTestUtils.waitForNotificationBar(gBrowser, firstTab.linkedBrowser, kExpectedNotificationId); - } - let secondTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home", false); - if (!getNotification(secondTab.linkedBrowser)) { - info(`Notification not immediately present on second tab, waiting for it.`); - yield BrowserTestUtils.waitForNotificationBar(gBrowser, secondTab.linkedBrowser, kExpectedNotificationId); - } - - // Create a listener for the removal in the first tab, and a listener for bookmarks removal, - // then click 'Don't keep' in the second tab, and verify that the notification is removed - // before we start removing bookmarks. - let haveRemovedBookmark = false; - let bmObserver; - let bookmarkRemovedPromise = new Promise(resolve => { - bmObserver = { - onItemRemoved(itemId, parentId, index, itemType, uri, removedGuid) { - if (guid == removedGuid) { - haveRemovedBookmark = true; - resolve(); - } - }, - }; - PlacesUtils.bookmarks.addObserver(bmObserver, false); - registerCleanupFunction(() => PlacesUtils.bookmarks.removeObserver(bmObserver)); - }); - - let firstTabNotificationRemovedPromise = new Promise(resolve => { - let notification = getNotification(firstTab.linkedBrowser); - // Save this reference because notification.parentNode will be null once it's removed. - let notificationBox = notification.parentNode; - let mut = new MutationObserver(mutations => { - // Yucky, but we have to detect either the removal via animation (with marginTop) - // or when the element is removed. We can't just detect the element being removed - // because this happens asynchronously (after the animation) and so it'd race - // with the rest of the undo happening. - for (let mutation of mutations) { - if (mutation.target == notification && mutation.attributeName == "style" && - parseInt(notification.style.marginTop, 10) < 0) { - ok(!haveRemovedBookmark, "Should not have removed bookmark yet"); - mut.disconnect(); - resolve(); - return; - } - if (mutation.target == notificationBox && mutation.removedNodes.length && - mutation.removedNodes[0] == notification) { - ok(!haveRemovedBookmark, "Should not have removed bookmark yet"); - mut.disconnect(); - resolve(); - return; - } - } - }); - mut.observe(notification.parentNode, {childList: true}); - mut.observe(notification, {attributes: true}); - }); - - let prefResetPromise = new Promise(resolve => { - const kObservedPref = "browser.migrate.automigrate.browser"; - let obs = () => { - Services.prefs.removeObserver(kObservedPref, obs); - ok(!Services.prefs.prefHasUserValue(kObservedPref), - "Pref should have been reset"); - resolve(); - }; - Services.prefs.addObserver(kObservedPref, obs, false); - }); - - // Click "Don't keep" button: - let notificationToActivate = getNotification(secondTab.linkedBrowser); - notificationToActivate.querySelector("button:not(.notification-button-default)").click(); - info("Waiting for notification to be removed in first (background) tab"); - yield firstTabNotificationRemovedPromise; - info("Waiting for bookmark to be removed"); - yield bookmarkRemovedPromise; - info("Waiting for prefs to be reset"); - yield prefResetPromise; - - info("Removing spare tabs"); - yield BrowserTestUtils.removeTab(firstTab); - yield BrowserTestUtils.removeTab(secondTab); -}); diff --git a/browser/components/migration/tests/browser/browser_undo_notification_wording.js b/browser/components/migration/tests/browser/browser_undo_notification_wording.js deleted file mode 100644 index f0a9ceec9..000000000 --- a/browser/components/migration/tests/browser/browser_undo_notification_wording.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; - -let scope = {}; -Cu.import("resource:///modules/AutoMigrate.jsm", scope); -let oldCanUndo = scope.AutoMigrate.canUndo; -registerCleanupFunction(function() { - scope.AutoMigrate.canUndo = oldCanUndo; -}); - -const kExpectedNotificationId = "automigration-undo"; - -add_task(function* autoMigrationUndoNotificationShows() { - let getNotification = browser => - gBrowser.getNotificationBox(browser).getNotificationWithValue(kExpectedNotificationId); - let localizedVersionOf = str => { - if (str == "logins") { - return "passwords"; - } - if (str == "visits") { - return "history"; - } - return str; - }; - - scope.AutoMigrate.canUndo = () => true; - let url = "about:newtab"; - Services.prefs.setCharPref("browser.migrate.automigrate.browser", "someunknownbrowser"); - const kSubsets = [ - ["bookmarks", "logins", "visits"], - ["bookmarks", "logins"], - ["bookmarks", "visits"], - ["logins", "visits"], - ["bookmarks"], - ["logins"], - ["visits"], - ]; - const kAllItems = ["bookmarks", "logins", "visits"]; - for (let subset of kSubsets) { - let state = new Map(subset.map(item => [item, [{}]])); - scope.AutoMigrate._setImportedItemPrefFromState(state); - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, url, false); - let browser = tab.linkedBrowser; - - if (!getNotification(browser)) { - info(`Notification for ${url} not immediately present, waiting for it.`); - yield BrowserTestUtils.waitForNotificationBar(gBrowser, browser, kExpectedNotificationId); - } - - ok(true, `Got notification for ${url}`); - let notification = getNotification(browser); - let notificationText = document.getAnonymousElementByAttribute(notification, "class", "messageText"); - notificationText = notificationText.textContent; - for (let potentiallyImported of kAllItems) { - let localizedImportItem = localizedVersionOf(potentiallyImported); - if (subset.includes(potentiallyImported)) { - ok(notificationText.includes(localizedImportItem), - "Expected notification to contain " + localizedImportItem); - } else { - ok(!notificationText.includes(localizedImportItem), - "Expected notification not to contain " + localizedImportItem); - } - } - - yield BrowserTestUtils.removeTab(tab); - } -}); - diff --git a/browser/components/migration/tests/marionette/manifest.ini b/browser/components/migration/tests/marionette/manifest.ini deleted file mode 100644 index 3f404e724..000000000 --- a/browser/components/migration/tests/marionette/manifest.ini +++ /dev/null @@ -1,5 +0,0 @@ -[DEFAULT] -run-if = buildapp == 'browser' - -[test_refresh_firefox.py] - diff --git a/browser/components/migration/tests/marionette/test_refresh_firefox.py b/browser/components/migration/tests/marionette/test_refresh_firefox.py deleted file mode 100644 index b348a3dcd..000000000 --- a/browser/components/migration/tests/marionette/test_refresh_firefox.py +++ /dev/null @@ -1,416 +0,0 @@ -import os -import shutil - -from marionette_harness import MarionetteTestCase - - -class TestFirefoxRefresh(MarionetteTestCase): - _username = "marionette-test-login" - _password = "marionette-test-password" - _bookmarkURL = "about:mozilla" - _bookmarkText = "Some bookmark from Marionette" - - _cookieHost = "firefox-refresh.marionette-test.mozilla.org" - _cookiePath = "some/cookie/path" - _cookieName = "somecookie" - _cookieValue = "some cookie value" - - _historyURL = "http://firefox-refresh.marionette-test.mozilla.org/" - _historyTitle = "Test visit for Firefox Reset" - - _formHistoryFieldName = "some-very-unique-marionette-only-firefox-reset-field" - _formHistoryValue = "special-pumpkin-value" - - _expectedURLs = ["about:robots", "about:mozilla"] - - def savePassword(self): - self.runCode(""" - let myLogin = new global.LoginInfo( - "test.marionette.mozilla.com", - "http://test.marionette.mozilla.com/some/form/", - null, - arguments[0], - arguments[1], - "username", - "password" - ); - Services.logins.addLogin(myLogin) - """, script_args=[self._username, self._password]) - - def createBookmark(self): - self.marionette.execute_script(""" - let url = arguments[0]; - let title = arguments[1]; - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarks.bookmarksMenuFolder, - makeURI(url), 0, title); - """, script_args=[self._bookmarkURL, self._bookmarkText]) - - def createHistory(self): - error = self.runAsyncCode(""" - // Copied from PlacesTestUtils, which isn't available in Marionette tests. - let didReturn; - PlacesUtils.asyncHistory.updatePlaces( - [{title: arguments[1], uri: makeURI(arguments[0]), visits: [{ - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - visitDate: (Date.now() - 5000) * 1000, - referrerURI: makeURI("about:mozilla"), - }] - }], - { - handleError(resultCode, place) { - didReturn = true; - marionetteScriptFinished("Unexpected error in adding visit: " + resultCode); - }, - handleResult() {}, - handleCompletion() { - if (!didReturn) { - marionetteScriptFinished(false); - } - }, - } - ); - """, script_args=[self._historyURL, self._historyTitle]) - if error: - print error - - def createFormHistory(self): - error = self.runAsyncCode(""" - let updateDefinition = { - op: "add", - fieldname: arguments[0], - value: arguments[1], - firstUsed: (Date.now() - 5000) * 1000, - }; - let finished = false; - global.FormHistory.update(updateDefinition, { - handleError(error) { - finished = true; - marionetteScriptFinished(error); - }, - handleCompletion() { - if (!finished) { - marionetteScriptFinished(false); - } - } - }); - """, script_args=[self._formHistoryFieldName, self._formHistoryValue]) - if error: - print error - - def createCookie(self): - self.runCode(""" - // Expire in 15 minutes: - let expireTime = Math.floor(Date.now() / 1000) + 15 * 60; - Services.cookies.add(arguments[0], arguments[1], arguments[2], arguments[3], - true, false, false, expireTime); - """, script_args=[self._cookieHost, self._cookiePath, self._cookieName, self._cookieValue]) - - def createSession(self): - self.runAsyncCode(""" - const COMPLETE_STATE = Ci.nsIWebProgressListener.STATE_STOP + - Ci.nsIWebProgressListener.STATE_IS_NETWORK; - let {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {}); - let expectedURLs = Array.from(arguments[0]) - gBrowser.addTabsProgressListener({ - onStateChange(browser, webprogress, request, flags, status) { - try { - request && request.QueryInterface(Ci.nsIChannel); - } catch (ex) {} - let uriLoaded = request.originalURI && request.originalURI.spec; - if ((flags & COMPLETE_STATE == COMPLETE_STATE) && uriLoaded && - expectedURLs.includes(uriLoaded)) { - TabStateFlusher.flush(browser).then(function() { - expectedURLs.splice(expectedURLs.indexOf(uriLoaded), 1); - if (!expectedURLs.length) { - gBrowser.removeTabsProgressListener(this); - marionetteScriptFinished(); - } - }); - } - } - }); - for (let url of expectedURLs) { - gBrowser.addTab(url); - } - """, script_args=[self._expectedURLs]) - - def checkPassword(self): - loginInfo = self.marionette.execute_script(""" - let ary = Services.logins.findLogins({}, - "test.marionette.mozilla.com", - "http://test.marionette.mozilla.com/some/form/", - null, {}); - return ary.length ? ary : {username: "null", password: "null"}; - """) - self.assertEqual(len(loginInfo), 1) - self.assertEqual(loginInfo[0]['username'], self._username) - self.assertEqual(loginInfo[0]['password'], self._password) - - loginCount = self.marionette.execute_script(""" - return Services.logins.getAllLogins().length; - """) - self.assertEqual(loginCount, 1, "No other logins are present") - - def checkBookmark(self): - titleInBookmarks = self.marionette.execute_script(""" - let url = arguments[0]; - let bookmarkIds = PlacesUtils.bookmarks.getBookmarkIdsForURI(makeURI(url), {}, {}); - return bookmarkIds.length == 1 ? PlacesUtils.bookmarks.getItemTitle(bookmarkIds[0]) : ""; - """, script_args=[self._bookmarkURL]) - self.assertEqual(titleInBookmarks, self._bookmarkText) - - def checkHistory(self): - historyResults = self.runAsyncCode(""" - let placeInfos = []; - PlacesUtils.asyncHistory.getPlacesInfo(makeURI(arguments[0]), { - handleError(resultCode, place) { - placeInfos = null; - marionetteScriptFinished("Unexpected error in fetching visit: " + resultCode); - }, - handleResult(placeInfo) { - placeInfos.push(placeInfo); - }, - handleCompletion() { - if (placeInfos) { - if (!placeInfos.length) { - marionetteScriptFinished("No visits found"); - } else { - marionetteScriptFinished(placeInfos); - } - } - }, - }); - """, script_args=[self._historyURL]) - if type(historyResults) == str: - self.fail(historyResults) - return - - historyCount = len(historyResults) - self.assertEqual(historyCount, 1, "Should have exactly 1 entry for URI, got %d" % historyCount) - if historyCount == 1: - self.assertEqual(historyResults[0]['title'], self._historyTitle) - - def checkFormHistory(self): - formFieldResults = self.runAsyncCode(""" - let results = []; - global.FormHistory.search(["value"], {fieldname: arguments[0]}, { - handleError(error) { - results = error; - }, - handleResult(result) { - results.push(result); - }, - handleCompletion() { - marionetteScriptFinished(results); - }, - }); - """, script_args=[self._formHistoryFieldName]) - if type(formFieldResults) == str: - self.fail(formFieldResults) - return - - formFieldResultCount = len(formFieldResults) - self.assertEqual(formFieldResultCount, 1, "Should have exactly 1 entry for this field, got %d" % formFieldResultCount) - if formFieldResultCount == 1: - self.assertEqual(formFieldResults[0]['value'], self._formHistoryValue) - - formHistoryCount = self.runAsyncCode(""" - let count; - let callbacks = { - handleResult: rv => count = rv, - handleCompletion() { - marionetteScriptFinished(count); - }, - }; - global.FormHistory.count({}, callbacks); - """) - self.assertEqual(formHistoryCount, 1, "There should be only 1 entry in the form history") - - def checkCookie(self): - cookieInfo = self.runCode(""" - try { - let cookieEnum = Services.cookies.getCookiesFromHost(arguments[0]); - let cookie = null; - while (cookieEnum.hasMoreElements()) { - let hostCookie = cookieEnum.getNext(); - hostCookie.QueryInterface(Ci.nsICookie2); - // getCookiesFromHost returns any cookie from the BASE host. - if (hostCookie.rawHost != arguments[0]) - continue; - if (cookie != null) { - return "more than 1 cookie! That shouldn't happen!"; - } - cookie = hostCookie; - } - return {path: cookie.path, name: cookie.name, value: cookie.value}; - } catch (ex) { - return "got exception trying to fetch cookie: " + ex; - } - """, script_args=[self._cookieHost]) - if not isinstance(cookieInfo, dict): - self.fail(cookieInfo) - return - self.assertEqual(cookieInfo['path'], self._cookiePath) - self.assertEqual(cookieInfo['value'], self._cookieValue) - self.assertEqual(cookieInfo['name'], self._cookieName) - - def checkSession(self): - tabURIs = self.runCode(""" - return [... gBrowser.browsers].map(b => b.currentURI && b.currentURI.spec) - """) - self.assertSequenceEqual(tabURIs, ["about:welcomeback"]) - - tabURIs = self.runAsyncCode(""" - let mm = gBrowser.selectedBrowser.messageManager; - let fs = function() { - content.document.getElementById("errorTryAgain").click(); - }; - let {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {}); - window.addEventListener("SSWindowStateReady", function testSSPostReset() { - window.removeEventListener("SSWindowStateReady", testSSPostReset, false); - Promise.all(gBrowser.browsers.map(b => TabStateFlusher.flush(b))).then(function() { - marionetteScriptFinished([... gBrowser.browsers].map(b => b.currentURI && b.currentURI.spec)); - }); - }, false); - mm.loadFrameScript("data:application/javascript,(" + fs.toString() + ")()", true); - """) - self.assertSequenceEqual(tabURIs, ["about:blank"] + self._expectedURLs) - pass - - def checkProfile(self, hasMigrated=False): - self.checkPassword() - self.checkBookmark() - self.checkHistory() - self.checkFormHistory() - self.checkCookie() - if hasMigrated: - self.checkSession() - - def createProfileData(self): - self.savePassword() - self.createBookmark() - self.createHistory() - self.createFormHistory() - self.createCookie() - self.createSession() - - def setUpScriptData(self): - self.marionette.set_context(self.marionette.CONTEXT_CHROME) - self.marionette.execute_script(""" - global.LoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", "nsILoginInfo", "init"); - global.profSvc = Cc["@mozilla.org/toolkit/profile-service;1"].getService(Ci.nsIToolkitProfileService); - global.Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences; - global.FormHistory = Cu.import("resource://gre/modules/FormHistory.jsm", {}).FormHistory; - """, new_sandbox=False, sandbox='system') - - def runCode(self, script, *args, **kwargs): - return self.marionette.execute_script(script, new_sandbox=False, sandbox='system', *args, **kwargs) - - def runAsyncCode(self, script, *args, **kwargs): - return self.marionette.execute_async_script(script, new_sandbox=False, sandbox='system', *args, **kwargs) - - def setUp(self): - MarionetteTestCase.setUp(self) - self.setUpScriptData() - - self.reset_profile_path = None - self.desktop_backup_path = None - - self.createProfileData() - - def tearDown(self): - # Force yet another restart with a clean profile to disconnect from the - # profile and environment changes we've made, to leave a more or less - # blank slate for the next person. - self.marionette.restart(clean=True, in_app=False) - self.setUpScriptData() - - # Super - MarionetteTestCase.tearDown(self) - - # Some helpers to deal with removing a load of files - import errno, stat - def handleRemoveReadonly(func, path, exc): - excvalue = exc[1] - if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: - os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777 - func(path) - else: - raise - - if self.desktop_backup_path: - shutil.rmtree(self.desktop_backup_path, ignore_errors=False, onerror=handleRemoveReadonly) - - if self.reset_profile_path: - # Remove ourselves from profiles.ini - profileLeafName = os.path.basename(os.path.normpath(self.reset_profile_path)) - self.runCode(""" - let [salt, name] = arguments[0].split("."); - let profile = global.profSvc.getProfileByName(name); - profile.remove(false) - global.profSvc.flush(); - """, script_args=[profileLeafName]) - # And delete all the files. - shutil.rmtree(self.reset_profile_path, ignore_errors=False, onerror=handleRemoveReadonly) - - def doReset(self): - self.runCode(""" - // Ensure the current (temporary) profile is in profiles.ini: - let profD = Services.dirsvc.get("ProfD", Ci.nsIFile); - let profileName = "marionette-test-profile-" + Date.now(); - let myProfile = global.profSvc.createProfile(profD, profileName); - global.profSvc.flush() - - // Now add the reset parameters: - let env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); - let allMarionettePrefs = Services.prefs.getChildList("marionette."); - let prefObj = {}; - for (let pref of allMarionettePrefs) { - let prefSuffix = pref.substr("marionette.".length); - let prefVal = global.Preferences.get(pref); - prefObj[prefSuffix] = prefVal; - } - let marionetteInfo = JSON.stringify(prefObj); - env.set("MOZ_MARIONETTE_PREF_STATE_ACROSS_RESTARTS", marionetteInfo); - env.set("MOZ_RESET_PROFILE_RESTART", "1"); - env.set("XRE_PROFILE_PATH", arguments[0]); - env.set("XRE_PROFILE_NAME", profileName); - """, script_args=[self.marionette.instance.profile.profile]) - - profileLeafName = os.path.basename(os.path.normpath(self.marionette.instance.profile.profile)) - - # Now restart the browser to get it reset: - self.marionette.restart(clean=False, in_app=True) - self.setUpScriptData() - - # Determine the new profile path (we'll need to remove it when we're done) - self.reset_profile_path = self.runCode(""" - let profD = Services.dirsvc.get("ProfD", Ci.nsIFile); - return profD.path; - """) - - # Determine the backup path - self.desktop_backup_path = self.runCode(""" - let container; - try { - container = Services.dirsvc.get("Desk", Ci.nsIFile); - } catch (ex) { - container = Services.dirsvc.get("Home", Ci.nsIFile); - } - let bundle = Services.strings.createBundle("chrome://mozapps/locale/profile/profileSelection.properties"); - let dirName = bundle.formatStringFromName("resetBackupDirectory", [Services.appinfo.name], 1); - container.append(dirName); - container.append(arguments[0]); - return container.path; - """, script_args = [profileLeafName]) - - self.assertTrue(os.path.isdir(self.reset_profile_path), "Reset profile path should be present") - self.assertTrue(os.path.isdir(self.desktop_backup_path), "Backup profile path should be present") - - def testReset(self): - self.checkProfile() - - self.doReset() - - # Now check that we're doing OK... - self.checkProfile(hasMigrated=True) diff --git a/browser/components/migration/tests/unit/.eslintrc.js b/browser/components/migration/tests/unit/.eslintrc.js deleted file mode 100644 index ba65517f9..000000000 --- a/browser/components/migration/tests/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { // eslint-disable-line no-undef - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data b/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data Binary files differdeleted file mode 100644 index 914149c71..000000000 --- a/browser/components/migration/tests/unit/AppData/Local/Google/Chrome/User Data/Default/Login Data +++ /dev/null diff --git a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies b/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies Binary files differdeleted file mode 100644 index 83d855cb3..000000000 --- a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Default/Cookies +++ /dev/null diff --git a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State b/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State deleted file mode 100644 index 01b99455e..000000000 --- a/browser/components/migration/tests/unit/Library/Application Support/Google/Chrome/Local State +++ /dev/null @@ -1,22 +0,0 @@ -{ - "profile" : { - "info_cache" : { - "Default" : { - "active_time" : 1430950755.65137, - "is_using_default_name" : true, - "is_ephemeral" : false, - "is_omitted_from_profile_list" : false, - "user_name" : "", - "background_apps" : false, - "is_using_default_avatar" : true, - "avatar_icon" : "chrome://theme/IDR_PROFILE_AVATAR_0", - "name" : "Person 1" - } - }, - "profiles_created" : 1, - "last_used" : "Default", - "last_active_profiles" : [ - "Default" - ] - } -} diff --git a/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist b/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist Binary files differdeleted file mode 100644 index 40783c7b1..000000000 --- a/browser/components/migration/tests/unit/Library/Safari/Bookmarks.plist +++ /dev/null diff --git a/browser/components/migration/tests/unit/head_migration.js b/browser/components/migration/tests/unit/head_migration.js deleted file mode 100644 index d3c258d54..000000000 --- a/browser/components/migration/tests/unit/head_migration.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; - -/* exported gProfD, promiseMigration, registerFakePath */ - -var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components; - -Cu.importGlobalProperties([ "URL" ]); - -Cu.import("resource:///modules/MigrationUtils.jsm"); -Cu.import("resource://gre/modules/LoginHelper.jsm"); -Cu.import("resource://gre/modules/NetUtil.jsm"); -Cu.import("resource://gre/modules/PlacesUtils.jsm"); -Cu.import("resource://gre/modules/Preferences.jsm"); -Cu.import("resource://gre/modules/PromiseUtils.jsm"); -Cu.import("resource://gre/modules/Task.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://testing-common/TestUtils.jsm"); -Cu.import("resource://testing-common/PlacesTestUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", - "resource://gre/modules/FileUtils.jsm"); - -// Initialize profile. -var gProfD = do_get_profile(); - -Cu.import("resource://testing-common/AppInfo.jsm"); /* globals updateAppInfo */ -updateAppInfo(); - -/** - * Migrates the requested resource and waits for the migration to be complete. - */ -function promiseMigration(migrator, resourceType, aProfile = null) { - // Ensure resource migration is available. - let availableSources = migrator.getMigrateData(aProfile, false); - Assert.ok((availableSources & resourceType) > 0, "Resource supported by migrator"); - - return new Promise (resolve => { - Services.obs.addObserver(function onMigrationEnded() { - Services.obs.removeObserver(onMigrationEnded, "Migration:Ended"); - resolve(); - }, "Migration:Ended", false); - - migrator.migrate(resourceType, null, aProfile); - }); -} - -/** - * Replaces a directory service entry with a given nsIFile. - */ -function registerFakePath(key, file) { - // Register our own provider for the Library directory. - let provider = { - getFile(prop, persistent) { - persistent.value = true; - if (prop == key) { - return file; - } - throw Cr.NS_ERROR_FAILURE; - }, - QueryInterface: XPCOMUtils.generateQI([ Ci.nsIDirectoryServiceProvider ]) - }; - Services.dirsvc.QueryInterface(Ci.nsIDirectoryService) - .registerProvider(provider); - do_register_cleanup(() => { - Services.dirsvc.QueryInterface(Ci.nsIDirectoryService) - .unregisterProvider(provider); - }); -} diff --git a/browser/components/migration/tests/unit/test_Chrome_cookies.js b/browser/components/migration/tests/unit/test_Chrome_cookies.js deleted file mode 100644 index 006693951..000000000 --- a/browser/components/migration/tests/unit/test_Chrome_cookies.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; - -Cu.import("resource://gre/modules/ForgetAboutSite.jsm"); - -add_task(function* () { - registerFakePath("ULibDir", do_get_file("Library/")); - let migrator = MigrationUtils.getMigrator("chrome"); - - Assert.ok(migrator.sourceExists, "Sanity check the source exists"); - - const COOKIE = { - expiry: 2145934800, - host: "unencryptedcookie.invalid", - isHttpOnly: false, - isSession: false, - name: "testcookie", - path: "/", - value: "testvalue", - }; - - // Sanity check. - Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0, - "There are no cookies initially"); - - const PROFILE = { - id: "Default", - name: "Person 1", - }; - - // Migrate unencrypted cookies. - yield promiseMigration(migrator, MigrationUtils.resourceTypes.COOKIES, PROFILE); - - Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 1, - "Migrated the expected number of unencrypted cookies"); - Assert.equal(Services.cookies.countCookiesFromHost("encryptedcookie.invalid"), 0, - "Migrated the expected number of encrypted cookies"); - - // Now check the cookie details. - let enumerator = Services.cookies.getCookiesFromHost(COOKIE.host, {}); - Assert.ok(enumerator.hasMoreElements(), "Cookies available"); - let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2); - - for (let prop of Object.keys(COOKIE)) { - Assert.equal(foundCookie[prop], COOKIE[prop], "Check cookie " + prop); - } - - // Cleanup. - ForgetAboutSite.removeDataFromDomain(COOKIE.host); - Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0, - "There are no cookies after cleanup"); -}); diff --git a/browser/components/migration/tests/unit/test_Chrome_passwords.js b/browser/components/migration/tests/unit/test_Chrome_passwords.js deleted file mode 100644 index 49147bd61..000000000 --- a/browser/components/migration/tests/unit/test_Chrome_passwords.js +++ /dev/null @@ -1,219 +0,0 @@ -"use strict"; - -Cu.import("resource://gre/modules/OSCrypto.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); - -const PROFILE = { - id: "Default", - name: "Person 1", -}; - -const TEST_LOGINS = [ - { - id: 1, // id of the row in the chrome login db - username: "username", - password: "password", - hostname: "https://c9.io", - formSubmitURL: "https://c9.io", - httpRealm: null, - usernameField: "inputEmail", - passwordField: "inputPassword", - timeCreated: 1437418416037, - timePasswordChanged: 1437418416037, - timesUsed: 1, - }, - { - id: 2, - username: "username@gmail.com", - password: "password2", - hostname: "https://accounts.google.com", - formSubmitURL: "https://accounts.google.com", - httpRealm: null, - usernameField: "Email", - passwordField: "Passwd", - timeCreated: 1437418446598, - timePasswordChanged: 1437418446598, - timesUsed: 6, - }, - { - id: 3, - username: "username", - password: "password3", - hostname: "https://www.facebook.com", - formSubmitURL: "https://www.facebook.com", - httpRealm: null, - usernameField: "email", - passwordField: "pass", - timeCreated: 1437418478851, - timePasswordChanged: 1437418478851, - timesUsed: 1, - }, - { - id: 4, - username: "user", - password: "password", - hostname: "http://httpbin.org", - formSubmitURL: null, - httpRealm: "me@kennethreitz.com", // Digest auth. - usernameField: "", - passwordField: "", - timeCreated: 1437787462368, - timePasswordChanged: 1437787462368, - timesUsed: 1, - }, - { - id: 5, - username: "buser", - password: "bpassword", - hostname: "http://httpbin.org", - formSubmitURL: null, - httpRealm: "Fake Realm", // Basic auth. - usernameField: "", - passwordField: "", - timeCreated: 1437787539233, - timePasswordChanged: 1437787539233, - timesUsed: 1, - }, -]; - -var crypto = new OSCrypto(); -var dbConn; - -function promiseSetPassword(login) { - return new Promise((resolve, reject) => { - let stmt = dbConn.createAsyncStatement(` - UPDATE logins - SET password_value = :password_value - WHERE rowid = :rowid - `); - let passwordValue = crypto.stringToArray(crypto.encryptData(login.password)); - stmt.bindBlobByName("password_value", passwordValue, passwordValue.length); - stmt.params.rowid = login.id; - - stmt.executeAsync({ - handleError(aError) { - reject("Error with the query: " + aError.message); - }, - - handleCompletion(aReason) { - if (aReason === Ci.mozIStorageStatementCallback.REASON_FINISHED) { - resolve(); - } else { - reject("Query has failed: " + aReason); - } - }, - }); - stmt.finalize(); - }); -} - -function checkLoginsAreEqual(passwordManagerLogin, chromeLogin, id) { - passwordManagerLogin.QueryInterface(Ci.nsILoginMetaInfo); - - Assert.equal(passwordManagerLogin.username, chromeLogin.username, - "The two logins ID " + id + " have the same username"); - Assert.equal(passwordManagerLogin.password, chromeLogin.password, - "The two logins ID " + id + " have the same password"); - Assert.equal(passwordManagerLogin.hostname, chromeLogin.hostname, - "The two logins ID " + id + " have the same hostname"); - Assert.equal(passwordManagerLogin.formSubmitURL, chromeLogin.formSubmitURL, - "The two logins ID " + id + " have the same formSubmitURL"); - Assert.equal(passwordManagerLogin.httpRealm, chromeLogin.httpRealm, - "The two logins ID " + id + " have the same httpRealm"); - Assert.equal(passwordManagerLogin.usernameField, chromeLogin.usernameField, - "The two logins ID " + id + " have the same usernameElement"); - Assert.equal(passwordManagerLogin.passwordField, chromeLogin.passwordField, - "The two logins ID " + id + " have the same passwordElement"); - Assert.equal(passwordManagerLogin.timeCreated, chromeLogin.timeCreated, - "The two logins ID " + id + " have the same timeCreated"); - Assert.equal(passwordManagerLogin.timePasswordChanged, chromeLogin.timePasswordChanged, - "The two logins ID " + id + " have the same timePasswordChanged"); - Assert.equal(passwordManagerLogin.timesUsed, chromeLogin.timesUsed, - "The two logins ID " + id + " have the same timesUsed"); -} - -function generateDifferentLogin(login) { - let newLogin = Cc["@mozilla.org/login-manager/loginInfo;1"].createInstance(Ci.nsILoginInfo); - - newLogin.init(login.hostname, login.formSubmitURL, null, - login.username, login.password + 1, login.usernameField + 1, - login.passwordField + 1); - newLogin.QueryInterface(Ci.nsILoginMetaInfo); - newLogin.timeCreated = login.timeCreated + 1; - newLogin.timePasswordChanged = login.timePasswordChanged + 1; - newLogin.timesUsed = login.timesUsed + 1; - return newLogin; -} - -add_task(function* setup() { - let loginDataFile = do_get_file("AppData/Local/Google/Chrome/User Data/Default/Login Data"); - dbConn = Services.storage.openUnsharedDatabase(loginDataFile); - registerFakePath("LocalAppData", do_get_file("AppData/Local/")); - - do_register_cleanup(() => { - Services.logins.removeAllLogins(); - dbConn.asyncClose(); - crypto.finalize(); - }); -}); - -add_task(function* test_importIntoEmptyDB() { - for (let login of TEST_LOGINS) { - yield promiseSetPassword(login); - } - - let migrator = MigrationUtils.getMigrator("chrome"); - Assert.ok(migrator.sourceExists, "Sanity check the source exists"); - - let logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, "There are no logins initially"); - - // Migrate the logins. - yield promiseMigration(migrator, MigrationUtils.resourceTypes.PASSWORDS, PROFILE); - - logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, TEST_LOGINS.length, "Check login count after importing the data"); - Assert.equal(logins.length, MigrationUtils._importQuantities.logins, - "Check telemetry matches the actual import."); - - for (let i = 0; i < TEST_LOGINS.length; i++) { - checkLoginsAreEqual(logins[i], TEST_LOGINS[i], i + 1); - } -}); - -// Test that existing logins for the same primary key don't get overwritten -add_task(function* test_importExistingLogins() { - let migrator = MigrationUtils.getMigrator("chrome"); - Assert.ok(migrator.sourceExists, "Sanity check the source exists"); - - Services.logins.removeAllLogins(); - let logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, "There are no logins after removing all of them"); - - let newLogins = []; - - // Create 3 new logins that are different but where the key properties are still the same. - for (let i = 0; i < 3; i++) { - newLogins.push(generateDifferentLogin(TEST_LOGINS[i])); - Services.logins.addLogin(newLogins[i]); - } - - logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, newLogins.length, "Check login count after the insertion"); - - for (let i = 0; i < newLogins.length; i++) { - checkLoginsAreEqual(logins[i], newLogins[i], i + 1); - } - // Migrate the logins. - yield promiseMigration(migrator, MigrationUtils.resourceTypes.PASSWORDS, PROFILE); - - logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, TEST_LOGINS.length, - "Check there are still the same number of logins after re-importing the data"); - Assert.equal(logins.length, MigrationUtils._importQuantities.logins, - "Check telemetry matches the actual import."); - - for (let i = 0; i < newLogins.length; i++) { - checkLoginsAreEqual(logins[i], newLogins[i], i + 1); - } -}); diff --git a/browser/components/migration/tests/unit/test_Edge_availability.js b/browser/components/migration/tests/unit/test_Edge_availability.js deleted file mode 100644 index dba0e27bb..000000000 --- a/browser/components/migration/tests/unit/test_Edge_availability.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; - -const EDGE_AVAILABLE_MIGRATIONS = - MigrationUtils.resourceTypes.COOKIES | - MigrationUtils.resourceTypes.BOOKMARKS | - MigrationUtils.resourceTypes.HISTORY | - MigrationUtils.resourceTypes.PASSWORDS; - -add_task(function* () { - let migrator = MigrationUtils.getMigrator("edge"); - Cu.import("resource://gre/modules/AppConstants.jsm"); - Assert.equal(!!(migrator && migrator.sourceExists), AppConstants.isPlatformAndVersionAtLeast("win", "10"), - "Edge should be available for migration if and only if we're on Win 10+"); - if (migrator) { - let migratableData = migrator.getMigrateData(null, false); - Assert.equal(migratableData, EDGE_AVAILABLE_MIGRATIONS, - "All the data types we expect should be available"); - } -}); - diff --git a/browser/components/migration/tests/unit/test_Edge_db_migration.js b/browser/components/migration/tests/unit/test_Edge_db_migration.js deleted file mode 100644 index 56ff612d5..000000000 --- a/browser/components/migration/tests/unit/test_Edge_db_migration.js +++ /dev/null @@ -1,471 +0,0 @@ -"use strict"; - -Cu.import("resource://gre/modules/ctypes.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -let eseBackStage = Cu.import("resource:///modules/ESEDBReader.jsm"); -let ESE = eseBackStage.ESE; -let KERNEL = eseBackStage.KERNEL; -let gLibs = eseBackStage.gLibs; -let COLUMN_TYPES = eseBackStage.COLUMN_TYPES; -let declareESEFunction = eseBackStage.declareESEFunction; -let loadLibraries = eseBackStage.loadLibraries; - -let gESEInstanceCounter = 1; - -ESE.JET_COLUMNCREATE_W = new ctypes.StructType("JET_COLUMNCREATE_W", [ - {"cbStruct": ctypes.unsigned_long}, - {"szColumnName": ESE.JET_PCWSTR}, - {"coltyp": ESE.JET_COLTYP }, - {"cbMax": ctypes.unsigned_long }, - {"grbit": ESE.JET_GRBIT }, - {"pvDefault": ctypes.voidptr_t}, - {"cbDefault": ctypes.unsigned_long }, - {"cp": ctypes.unsigned_long }, - {"columnid": ESE.JET_COLUMNID}, - {"err": ESE.JET_ERR}, -]); - -function createColumnCreationWrapper({name, type, cbMax}) { - // We use a wrapper object because we need to be sure the JS engine won't GC - // data that we're "only" pointing to. - let wrapper = {}; - wrapper.column = new ESE.JET_COLUMNCREATE_W(); - wrapper.column.cbStruct = ESE.JET_COLUMNCREATE_W.size; - let wchar_tArray = ctypes.ArrayType(ctypes.char16_t); - wrapper.name = new wchar_tArray(name.length + 1); - wrapper.name.value = String(name); - wrapper.column.szColumnName = wrapper.name; - wrapper.column.coltyp = type; - let fallback = 0; - switch (type) { - case COLUMN_TYPES.JET_coltypText: - fallback = 255; - // Intentional fall-through - case COLUMN_TYPES.JET_coltypLongText: - wrapper.column.cbMax = cbMax || fallback || 64 * 1024; - break; - case COLUMN_TYPES.JET_coltypGUID: - wrapper.column.cbMax = 16; - break; - case COLUMN_TYPES.JET_coltypBit: - wrapper.column.cbMax = 1; - break; - case COLUMN_TYPES.JET_coltypLongLong: - wrapper.column.cbMax = 8; - break; - default: - throw new Error("Unknown column type!"); - } - - wrapper.column.columnid = new ESE.JET_COLUMNID(); - wrapper.column.grbit = 0; - wrapper.column.pvDefault = null; - wrapper.column.cbDefault = 0; - wrapper.column.cp = 0; - - return wrapper; -} - -// "forward declarations" of indexcreate and setinfo structs, which we don't use. -ESE.JET_INDEXCREATE = new ctypes.StructType("JET_INDEXCREATE"); -ESE.JET_SETINFO = new ctypes.StructType("JET_SETINFO"); - -ESE.JET_TABLECREATE_W = new ctypes.StructType("JET_TABLECREATE_W", [ - {"cbStruct": ctypes.unsigned_long}, - {"szTableName": ESE.JET_PCWSTR}, - {"szTemplateTableName": ESE.JET_PCWSTR}, - {"ulPages": ctypes.unsigned_long}, - {"ulDensity": ctypes.unsigned_long}, - {"rgcolumncreate": ESE.JET_COLUMNCREATE_W.ptr}, - {"cColumns": ctypes.unsigned_long}, - {"rgindexcreate": ESE.JET_INDEXCREATE.ptr}, - {"cIndexes": ctypes.unsigned_long}, - {"grbit": ESE.JET_GRBIT}, - {"tableid": ESE.JET_TABLEID}, - {"cCreated": ctypes.unsigned_long}, -]); - -function createTableCreationWrapper(tableName, columns) { - let wrapper = {}; - let wchar_tArray = ctypes.ArrayType(ctypes.char16_t); - wrapper.name = new wchar_tArray(tableName.length + 1); - wrapper.name.value = String(tableName); - wrapper.table = new ESE.JET_TABLECREATE_W(); - wrapper.table.cbStruct = ESE.JET_TABLECREATE_W.size; - wrapper.table.szTableName = wrapper.name; - wrapper.table.szTemplateTableName = null; - wrapper.table.ulPages = 1; - wrapper.table.ulDensity = 0; - let columnArrayType = ESE.JET_COLUMNCREATE_W.array(columns.length); - wrapper.columnAry = new columnArrayType(); - wrapper.table.rgcolumncreate = wrapper.columnAry.addressOfElement(0); - wrapper.table.cColumns = columns.length; - wrapper.columns = []; - for (let i = 0; i < columns.length; i++) { - let column = columns[i]; - let columnWrapper = createColumnCreationWrapper(column); - wrapper.columnAry.addressOfElement(i).contents = columnWrapper.column; - wrapper.columns.push(columnWrapper); - } - wrapper.table.rgindexcreate = null; - wrapper.table.cIndexes = 0; - return wrapper; -} - -function convertValueForWriting(value, valueType) { - let buffer; - let valueOfValueType = ctypes.UInt64.lo(valueType); - switch (valueOfValueType) { - case COLUMN_TYPES.JET_coltypLongLong: - if (value instanceof Date) { - buffer = new KERNEL.FILETIME(); - let sysTime = new KERNEL.SYSTEMTIME(); - sysTime.wYear = value.getUTCFullYear(); - sysTime.wMonth = value.getUTCMonth() + 1; - sysTime.wDay = value.getUTCDate(); - sysTime.wHour = value.getUTCHours(); - sysTime.wMinute = value.getUTCMinutes(); - sysTime.wSecond = value.getUTCSeconds(); - sysTime.wMilliseconds = value.getUTCMilliseconds(); - let rv = KERNEL.SystemTimeToFileTime(sysTime.address(), buffer.address()); - if (!rv) { - throw new Error("Failed to get FileTime."); - } - return [buffer, KERNEL.FILETIME.size]; - } - throw new Error("Unrecognized value for longlong column"); - case COLUMN_TYPES.JET_coltypLongText: - let wchar_tArray = ctypes.ArrayType(ctypes.char16_t); - buffer = new wchar_tArray(value.length + 1); - buffer.value = String(value); - return [buffer, buffer.length * 2]; - case COLUMN_TYPES.JET_coltypBit: - buffer = new ctypes.uint8_t(); - // Bizarre boolean values, but whatever: - buffer.value = value ? 255 : 0; - return [buffer, 1]; - case COLUMN_TYPES.JET_coltypGUID: - let byteArray = ctypes.ArrayType(ctypes.uint8_t); - buffer = new byteArray(16); - let j = 0; - for (let i = 0; i < value.length; i++) { - if (!(/[0-9a-f]/i).test(value[i])) { - continue; - } - let byteAsHex = value.substr(i, 2); - buffer[j++] = parseInt(byteAsHex, 16); - i++; - } - return [buffer, 16]; - } - - throw new Error("Unknown type " + valueType); -} - -let initializedESE = false; - -let eseDBWritingHelpers = { - setupDB(dbFile, tableName, columns, rows) { - if (!initializedESE) { - initializedESE = true; - loadLibraries(); - - KERNEL.SystemTimeToFileTime = gLibs.kernel.declare("SystemTimeToFileTime", - ctypes.default_abi, ctypes.bool, KERNEL.SYSTEMTIME.ptr, KERNEL.FILETIME.ptr); - - declareESEFunction("CreateDatabaseW", ESE.JET_SESID, ESE.JET_PCWSTR, - ESE.JET_PCWSTR, ESE.JET_DBID.ptr, ESE.JET_GRBIT); - declareESEFunction("CreateTableColumnIndexW", ESE.JET_SESID, ESE.JET_DBID, - ESE.JET_TABLECREATE_W.ptr); - declareESEFunction("BeginTransaction", ESE.JET_SESID); - declareESEFunction("CommitTransaction", ESE.JET_SESID, ESE.JET_GRBIT); - declareESEFunction("PrepareUpdate", ESE.JET_SESID, ESE.JET_TABLEID, - ctypes.unsigned_long); - declareESEFunction("Update", ESE.JET_SESID, ESE.JET_TABLEID, - ctypes.voidptr_t, ctypes.unsigned_long, - ctypes.unsigned_long.ptr); - declareESEFunction("SetColumn", ESE.JET_SESID, ESE.JET_TABLEID, - ESE.JET_COLUMNID, ctypes.voidptr_t, - ctypes.unsigned_long, ESE.JET_GRBIT, ESE.JET_SETINFO.ptr); - ESE.SetSystemParameterW(null, 0, 64 /* JET_paramDatabasePageSize*/, - 8192, null); - } - - let rootPath = dbFile.parent.path + "\\"; - let logPath = rootPath + "LogFiles\\"; - - try { - this._instanceId = new ESE.JET_INSTANCE(); - ESE.CreateInstanceW(this._instanceId.address(), - "firefox-dbwriter-" + (gESEInstanceCounter++)); - this._instanceCreated = true; - - ESE.SetSystemParameterW(this._instanceId.address(), 0, - 0 /* JET_paramSystemPath*/, 0, rootPath); - ESE.SetSystemParameterW(this._instanceId.address(), 0, - 1 /* JET_paramTempPath */, 0, rootPath); - ESE.SetSystemParameterW(this._instanceId.address(), 0, - 2 /* JET_paramLogFilePath*/, 0, logPath); - // Shouldn't try to call JetTerm if the following call fails. - this._instanceCreated = false; - ESE.Init(this._instanceId.address()); - this._instanceCreated = true; - this._sessionId = new ESE.JET_SESID(); - ESE.BeginSessionW(this._instanceId, this._sessionId.address(), null, - null); - this._sessionCreated = true; - - this._dbId = new ESE.JET_DBID(); - this._dbPath = rootPath + "spartan.edb"; - ESE.CreateDatabaseW(this._sessionId, this._dbPath, null, - this._dbId.address(), 0); - this._opened = this._attached = true; - - let tableCreationWrapper = createTableCreationWrapper(tableName, columns); - ESE.CreateTableColumnIndexW(this._sessionId, this._dbId, - tableCreationWrapper.table.address()); - this._tableId = tableCreationWrapper.table.tableid; - - let columnIdMap = new Map(); - if (rows.length) { - // Iterate over the struct we passed into ESENT because they have the - // created column ids. - let columnCount = ctypes.UInt64.lo(tableCreationWrapper.table.cColumns); - let columnsPassed = tableCreationWrapper.table.rgcolumncreate; - for (let i = 0; i < columnCount; i++) { - let column = columnsPassed.contents; - columnIdMap.set(column.szColumnName.readString(), column); - columnsPassed = columnsPassed.increment(); - } - ESE.ManualMove(this._sessionId, this._tableId, - -2147483648 /* JET_MoveFirst */, 0); - ESE.BeginTransaction(this._sessionId); - for (let row of rows) { - ESE.PrepareUpdate(this._sessionId, this._tableId, 0 /* JET_prepInsert */); - for (let columnName in row) { - let col = columnIdMap.get(columnName); - let colId = col.columnid; - let [val, valSize] = convertValueForWriting(row[columnName], col.coltyp); - /* JET_bitSetOverwriteLV */ - ESE.SetColumn(this._sessionId, this._tableId, colId, val.address(), valSize, 4, null); - } - let actualBookmarkSize = new ctypes.unsigned_long(); - ESE.Update(this._sessionId, this._tableId, null, 0, actualBookmarkSize.address()); - } - ESE.CommitTransaction(this._sessionId, 0 /* JET_bitWaitLastLevel0Commit */); - } - } finally { - try { - this._close(); - } catch (ex) { - Cu.reportError(ex); - } - } - }, - - _close() { - if (this._tableId) { - ESE.FailSafeCloseTable(this._sessionId, this._tableId); - delete this._tableId; - } - if (this._opened) { - ESE.FailSafeCloseDatabase(this._sessionId, this._dbId, 0); - this._opened = false; - } - if (this._attached) { - ESE.FailSafeDetachDatabaseW(this._sessionId, this._dbPath); - this._attached = false; - } - if (this._sessionCreated) { - ESE.FailSafeEndSession(this._sessionId, 0); - this._sessionCreated = false; - } - if (this._instanceCreated) { - ESE.FailSafeTerm(this._instanceId); - this._instanceCreated = false; - } - }, -}; - -add_task(function*() { - let tempFile = Services.dirsvc.get("TmpD", Ci.nsIFile); - tempFile.append("fx-xpcshell-edge-db"); - tempFile.createUnique(tempFile.DIRECTORY_TYPE, 0o600); - - let db = tempFile.clone(); - db.append("spartan.edb"); - - let logs = tempFile.clone(); - logs.append("LogFiles"); - logs.create(tempFile.DIRECTORY_TYPE, 0o600); - - let creationDate = new Date(Date.now() - 5000); - const kEdgeMenuParent = "62d07e2b-5f0d-4e41-8426-5f5ec9717beb"; - let itemsInDB = [ - { - URL: "http://www.mozilla.org/", - Title: "Mozilla", - DateUpdated: new Date(creationDate.valueOf() + 100), - ItemId: "1c00c10a-15f6-4618-92dd-22575102a4da", - ParentId: kEdgeMenuParent, - IsFolder: false, - IsDeleted: false, - }, - { - Title: "Folder", - DateUpdated: new Date(creationDate.valueOf() + 200), - ItemId: "564b21f2-05d6-4f7d-8499-304d00ccc3aa", - ParentId: kEdgeMenuParent, - IsFolder: true, - IsDeleted: false, - }, - { - Title: "Item in folder", - URL: "http://www.iteminfolder.org/", - DateUpdated: new Date(creationDate.valueOf() + 300), - ItemId: "c295ddaf-04a1-424a-866c-0ebde011e7c8", - ParentId: "564b21f2-05d6-4f7d-8499-304d00ccc3aa", - IsFolder: false, - IsDeleted: false, - }, - { - Title: "Deleted folder", - DateUpdated: new Date(creationDate.valueOf() + 400), - ItemId: "a547573c-4d4d-4406-a736-5b5462d93bca", - ParentId: kEdgeMenuParent, - IsFolder: true, - IsDeleted: true, - }, - { - Title: "Deleted item", - URL: "http://www.deleteditem.org/", - DateUpdated: new Date(creationDate.valueOf() + 500), - ItemId: "37a574bb-b44b-4bbc-a414-908615536435", - ParentId: kEdgeMenuParent, - IsFolder: false, - IsDeleted: true, - }, - { - Title: "Item in deleted folder (should be in root)", - URL: "http://www.itemindeletedfolder.org/", - DateUpdated: new Date(creationDate.valueOf() + 600), - ItemId: "74dd1cc3-4c5d-471f-bccc-7bc7c72fa621", - ParentId: "a547573c-4d4d-4406-a736-5b5462d93bca", - IsFolder: false, - IsDeleted: false, - }, - { - Title: "_Favorites_Bar_", - DateUpdated: new Date(creationDate.valueOf() + 700), - ItemId: "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf", - ParentId: kEdgeMenuParent, - IsFolder: true, - IsDeleted: false, - }, - { - Title: "Item in favorites bar", - URL: "http://www.iteminfavoritesbar.org/", - DateUpdated: new Date(creationDate.valueOf() + 800), - ItemId: "9f2b1ff8-b651-46cf-8f41-16da8bcb6791", - ParentId: "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf", - IsFolder: false, - IsDeleted: false, - }, - ]; - eseDBWritingHelpers.setupDB(db, "Favorites", [ - {type: COLUMN_TYPES.JET_coltypLongText, name: "URL", cbMax: 4096}, - {type: COLUMN_TYPES.JET_coltypLongText, name: "Title", cbMax: 4096}, - {type: COLUMN_TYPES.JET_coltypLongLong, name: "DateUpdated"}, - {type: COLUMN_TYPES.JET_coltypGUID, name: "ItemId"}, - {type: COLUMN_TYPES.JET_coltypBit, name: "IsDeleted"}, - {type: COLUMN_TYPES.JET_coltypBit, name: "IsFolder"}, - {type: COLUMN_TYPES.JET_coltypGUID, name: "ParentId"}, - ], itemsInDB); - - let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=edge"] - .createInstance(Ci.nsIBrowserProfileMigrator); - let bookmarksMigrator = migrator.wrappedJSObject.getESEMigratorForTesting(db); - Assert.ok(bookmarksMigrator.exists, "Should recognize table we just created"); - - let source = MigrationUtils.getLocalizedString("sourceNameEdge"); - let sourceLabel = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]); - - let seenBookmarks = []; - let bookmarkObserver = { - onItemAdded(itemId, parentId, index, itemType, url, title, dateAdded, itemGuid, parentGuid) { - if (title.startsWith("Deleted")) { - ok(false, "Should not see deleted items being bookmarked!"); - } - seenBookmarks.push({itemId, parentId, index, itemType, url, title, dateAdded, itemGuid, parentGuid}); - }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onItemRemoved() {}, - onItemChanged() {}, - onItemVisited() {}, - onItemMoved() {}, - }; - PlacesUtils.bookmarks.addObserver(bookmarkObserver, false); - - let migrateResult = yield new Promise(resolve => bookmarksMigrator.migrate(resolve)).catch(ex => { - Cu.reportError(ex); - Assert.ok(false, "Got an exception trying to migrate data! " + ex); - return false; - }); - PlacesUtils.bookmarks.removeObserver(bookmarkObserver); - Assert.ok(migrateResult, "Migration should succeed"); - Assert.equal(seenBookmarks.length, 7, "Should have seen 7 items being bookmarked."); - Assert.equal(seenBookmarks.filter(bm => bm.title != sourceLabel).length, - MigrationUtils._importQuantities.bookmarks, - "Telemetry should have items except for 'From Microsoft Edge' folders"); - - let menuParents = seenBookmarks.filter(item => item.parentGuid == PlacesUtils.bookmarks.menuGuid); - Assert.equal(menuParents.length, 1, "Should have a single folder added to the menu"); - let toolbarParents = seenBookmarks.filter(item => item.parentGuid == PlacesUtils.bookmarks.toolbarGuid); - Assert.equal(toolbarParents.length, 1, "Should have a single item added to the toolbar"); - let menuParentGuid = menuParents[0].itemGuid; - let toolbarParentGuid = toolbarParents[0].itemGuid; - - let expectedTitlesInMenu = itemsInDB.filter(item => item.ParentId == kEdgeMenuParent).map(item => item.Title); - // Hacky, but seems like much the simplest way: - expectedTitlesInMenu.push("Item in deleted folder (should be in root)"); - let expectedTitlesInToolbar = itemsInDB.filter(item => item.ParentId == "921dc8a0-6c83-40ef-8df1-9bd1c5c56aaf").map(item => item.Title); - - let edgeNameStr = MigrationUtils.getLocalizedString("sourceNameEdge"); - let importParentFolderName = MigrationUtils.getLocalizedString("importedBookmarksFolder", [edgeNameStr]); - - for (let bookmark of seenBookmarks) { - let shouldBeInMenu = expectedTitlesInMenu.includes(bookmark.title); - let shouldBeInToolbar = expectedTitlesInToolbar.includes(bookmark.title); - if (bookmark.title == "Folder" || bookmark.title == importParentFolderName) { - Assert.equal(bookmark.itemType, PlacesUtils.bookmarks.TYPE_FOLDER, - "Bookmark " + bookmark.title + " should be a folder"); - } else { - Assert.notEqual(bookmark.itemType, PlacesUtils.bookmarks.TYPE_FOLDER, - "Bookmark " + bookmark.title + " should not be a folder"); - } - - if (shouldBeInMenu) { - Assert.equal(bookmark.parentGuid, menuParentGuid, "Item '" + bookmark.title + "' should be in menu"); - } else if (shouldBeInToolbar) { - Assert.equal(bookmark.parentGuid, toolbarParentGuid, "Item '" + bookmark.title + "' should be in toolbar"); - } else if (bookmark.itemGuid == menuParentGuid || bookmark.itemGuid == toolbarParentGuid) { - Assert.ok(true, "Expect toolbar and menu folders to not be in menu or toolbar"); - } else { - // Bit hacky, but we do need to check this. - Assert.equal(bookmark.title, "Item in folder", "Subfoldered item shouldn't be in menu or toolbar"); - let parent = seenBookmarks.find(maybeParent => maybeParent.itemGuid == bookmark.parentGuid); - Assert.equal(parent && parent.title, "Folder", "Subfoldered item should be in subfolder labeled 'Folder'"); - } - - let dbItem = itemsInDB.find(someItem => bookmark.title == someItem.Title); - if (!dbItem) { - Assert.equal(bookmark.title, importParentFolderName, "Only the extra layer of folders isn't in the input we stuck in the DB."); - Assert.ok([menuParentGuid, toolbarParentGuid].includes(bookmark.itemGuid), "This item should be one of the containers"); - } else { - Assert.equal(dbItem.URL || null, bookmark.url && bookmark.url.spec, "URL is correct"); - Assert.equal(dbItem.DateUpdated.valueOf(), (new Date(bookmark.dateAdded / 1000)).valueOf(), "Date added is correct"); - } - } -}); - diff --git a/browser/components/migration/tests/unit/test_IE7_passwords.js b/browser/components/migration/tests/unit/test_IE7_passwords.js deleted file mode 100644 index 1ce016a7d..000000000 --- a/browser/components/migration/tests/unit/test_IE7_passwords.js +++ /dev/null @@ -1,397 +0,0 @@ -"use strict"; - -Cu.import("resource://gre/modules/AppConstants.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry", - "resource://gre/modules/WindowsRegistry.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "OSCrypto", - "resource://gre/modules/OSCrypto.jsm"); - -const IE7_FORM_PASSWORDS_MIGRATOR_NAME = "IE7FormPasswords"; -const LOGINS_KEY = "Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2"; -const EXTENSION = "-backup"; -const TESTED_WEBSITES = { - twitter: { - uri: makeURI("https://twitter.com"), - hash: "A89D42BC6406E27265B1AD0782B6F376375764A301", - data: [12, 0, 0, 0, 56, 0, 0, 0, 38, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 36, 67, 124, 118, 212, 208, 1, 8, 0, 0, 0, 18, 0, 0, 0, 68, 36, 67, 124, 118, 212, 208, 1, 9, 0, 0, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104, 0, 0, 0, 49, 0, 50, 0, 51, 0, 52, 0, 53, 0, 54, 0, 55, 0, 56, 0, 57, 0, 0, 0], - logins: [ - { - username: "abcdefgh", - password: "123456789", - hostname: "https://twitter.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439325854000, - timeLastUsed: 1439325854000, - timePasswordChanged: 1439325854000, - timesUsed: 1, - }, - ], - }, - facebook: { - uri: makeURI("https://www.facebook.com/"), - hash: "EF44D3E034009CB0FD1B1D81A1FF3F3335213BD796", - data: [12, 0, 0, 0, 152, 0, 0, 0, 160, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 88, 182, 125, 18, 121, 212, 208, 1, 9, 0, 0, 0, 20, 0, 0, 0, 88, 182, 125, 18, 121, 212, 208, 1, 9, 0, 0, 0, 40, 0, 0, 0, 134, 65, 33, 37, 121, 212, 208, 1, 9, 0, 0, 0, 60, 0, 0, 0, 134, 65, 33, 37, 121, 212, 208, 1, 9, 0, 0, 0, 80, 0, 0, 0, 45, 242, 246, 62, 121, 212, 208, 1, 9, 0, 0, 0, 100, 0, 0, 0, 45, 242, 246, 62, 121, 212, 208, 1, 9, 0, 0, 0, 120, 0, 0, 0, 28, 10, 193, 80, 121, 212, 208, 1, 9, 0, 0, 0, 140, 0, 0, 0, 28, 10, 193, 80, 121, 212, 208, 1, 9, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 48, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 48, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 49, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 49, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 50, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 50, 0, 0, 0, 117, 0, 115, 0, 101, 0, 114, 0, 110, 0, 97, 0, 109, 0, 101, 0, 51, 0, 0, 0, 112, 0, 97, 0, 115, 0, 115, 0, 119, 0, 111, 0, 114, 0, 100, 0, 51, 0, 0, 0], - logins: [ - { - username: "username0", - password: "password0", - hostname: "https://www.facebook.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439326966000, - timeLastUsed: 1439326966000, - timePasswordChanged: 1439326966000, - timesUsed: 1, - }, - { - username: "username1", - password: "password1", - hostname: "https://www.facebook.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439326997000, - timeLastUsed: 1439326997000, - timePasswordChanged: 1439326997000, - timesUsed: 1, - }, - { - username: "username2", - password: "password2", - hostname: "https://www.facebook.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439327040000, - timeLastUsed: 1439327040000, - timePasswordChanged: 1439327040000, - timesUsed: 1, - }, - { - username: "username3", - password: "password3", - hostname: "https://www.facebook.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439327070000, - timeLastUsed: 1439327070000, - timePasswordChanged: 1439327070000, - timesUsed: 1, - }, - ], - }, - live: { - uri: makeURI("https://login.live.com/"), - hash: "7B506F2D6B81D939A8E0456F036EE8970856FF705E", - data: [12, 0, 0, 0, 56, 0, 0, 0, 44, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 17, 219, 140, 148, 212, 208, 1, 9, 0, 0, 0, 20, 0, 0, 0, 212, 17, 219, 140, 148, 212, 208, 1, 11, 0, 0, 0, 114, 0, 105, 0, 97, 0, 100, 0, 104, 0, 49, 6, 74, 6, 39, 6, 54, 6, 0, 0, 39, 6, 66, 6, 49, 6, 35, 6, 80, 0, 192, 0, 223, 0, 119, 0, 246, 0, 114, 0, 100, 0, 0, 0], - logins: [ - { - username: "riadhرياض", - password: "اقرأPÀßwörd", - hostname: "https://login.live.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439338767000, - timeLastUsed: 1439338767000, - timePasswordChanged: 1439338767000, - timesUsed: 1, - }, - ], - }, - reddit: { - uri: makeURI("http://www.reddit.com/"), - hash: "B644028D1C109A91EC2C4B9D1F145E55A1FAE42065", - data: [12, 0, 0, 0, 152, 0, 0, 0, 212, 0, 0, 0, 87, 73, 67, 75, 24, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 8, 234, 114, 153, 212, 208, 1, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 97, 93, 131, 116, 153, 212, 208, 1, 3, 0, 0, 0, 14, 0, 0, 0, 97, 93, 131, 116, 153, 212, 208, 1, 16, 0, 0, 0, 48, 0, 0, 0, 88, 150, 78, 174, 153, 212, 208, 1, 4, 0, 0, 0, 58, 0, 0, 0, 88, 150, 78, 174, 153, 212, 208, 1, 29, 0, 0, 0, 118, 0, 0, 0, 79, 102, 137, 34, 154, 212, 208, 1, 15, 0, 0, 0, 150, 0, 0, 0, 79, 102, 137, 34, 154, 212, 208, 1, 30, 0, 0, 0, 97, 0, 0, 0, 0, 0, 252, 140, 173, 138, 146, 48, 0, 0, 66, 0, 105, 0, 116, 0, 116, 0, 101, 0, 32, 0, 98, 0, 101, 0, 115, 0, 116, 0, 228, 0, 116, 0, 105, 0, 103, 0, 101, 0, 110, 0, 0, 0, 205, 145, 110, 127, 198, 91, 1, 120, 0, 0, 31, 4, 48, 4, 64, 4, 62, 4, 59, 4, 76, 4, 32, 0, 67, 4, 65, 4, 63, 4, 53, 4, 72, 4, 61, 4, 62, 4, 32, 0, 65, 4, 49, 4, 64, 4, 62, 4, 72, 4, 53, 4, 61, 4, 46, 0, 32, 0, 18, 4, 62, 4, 57, 4, 66, 4, 56, 4, 0, 0, 40, 6, 51, 6, 69, 6, 32, 0, 39, 6, 68, 6, 68, 6, 71, 6, 32, 0, 39, 6, 68, 6, 49, 6, 45, 6, 69, 6, 70, 6, 0, 0, 118, 0, 101, 0, 117, 0, 105, 0, 108, 0, 108, 0, 101, 0, 122, 0, 32, 0, 108, 0, 101, 0, 32, 0, 118, 0, 233, 0, 114, 0, 105, 0, 102, 0, 105, 0, 101, 0, 114, 0, 32, 0, 224, 0, 32, 0, 110, 0, 111, 0, 117, 0, 118, 0, 101, 0, 97, 0, 117, 0, 0, 0], - logins: [ - { - username: "è³¼èªã‚’", - password: "Bitte bestätigen", - hostname: "http://www.reddit.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439340874000, - timeLastUsed: 1439340874000, - timePasswordChanged: 1439340874000, - timesUsed: 1, - }, - { - username: "é‡ç½®å¯†ç ", - password: "Пароль уÑпешно Ñброшен. Войти", - hostname: "http://www.reddit.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439340971000, - timeLastUsed: 1439340971000, - timePasswordChanged: 1439340971000, - timesUsed: 1, - }, - { - username: "بسم الله الرØمن", - password: "veuillez le vérifier à nouveau", - hostname: "http://www.reddit.com", - formSubmitURL: "", - httpRealm: null, - usernameField: "", - passwordField: "", - timeCreated: 1439341166000, - timeLastUsed: 1439341166000, - timePasswordChanged: 1439341166000, - timesUsed: 1, - }, - ], - }, -}; - -const TESTED_URLS = [ - "http://a.foo.com", - "http://b.foo.com", - "http://c.foo.com", - "http://www.test.net", - "http://www.test.net/home", - "http://www.test.net/index", - "https://a.bar.com", - "https://b.bar.com", - "https://c.bar.com", -]; - -var nsIWindowsRegKey = Ci.nsIWindowsRegKey; -var Storage2Key; - -/* - * If the key value exists, it's going to be backed up and replaced, so the value could be restored. - * Otherwise a new value is going to be created. - */ -function backupAndStore(key, name, value) { - if (key.hasValue(name)) { - // backup the the current value - let type = key.getValueType(name); - // create a new value using use the current value name followed by EXTENSION as its new name - switch (type) { - case nsIWindowsRegKey.TYPE_STRING: - key.writeStringValue(name + EXTENSION, key.readStringValue(name)); - break; - case nsIWindowsRegKey.TYPE_BINARY: - key.writeBinaryValue(name + EXTENSION, key.readBinaryValue(name)); - break; - case nsIWindowsRegKey.TYPE_INT: - key.writeIntValue(name + EXTENSION, key.readIntValue(name)); - break; - case nsIWindowsRegKey.TYPE_INT64: - key.writeInt64Value(name + EXTENSION, key.readInt64Value(name)); - break; - } - } - key.writeBinaryValue(name, value); -} - -// Remove all values where their names are members of the names array from the key of registry -function removeAllValues(key, names) { - for (let name of names) { - key.removeValue(name); - } -} - -// Restore all the backed up values -function restore(key) { - let count = key.valueCount; - let names = []; // the names of the key values - for (let i = 0; i < count; ++i) { - names.push(key.getValueName(i)); - } - - for (let name of names) { - // backed up values have EXTENSION at the end of their names - if (name.lastIndexOf(EXTENSION) == name.length - EXTENSION.length) { - let valueName = name.substr(0, name.length - EXTENSION.length); - let type = key.getValueType(name); - // create a new value using the name before the backup and removed the backed up one - switch (type) { - case nsIWindowsRegKey.TYPE_STRING: - key.writeStringValue(valueName, key.readStringValue(name)); - key.removeValue(name); - break; - case nsIWindowsRegKey.TYPE_BINARY: - key.writeBinaryValue(valueName, key.readBinaryValue(name)); - key.removeValue(name); - break; - case nsIWindowsRegKey.TYPE_INT: - key.writeIntValue(valueName, key.readIntValue(name)); - key.removeValue(name); - break; - case nsIWindowsRegKey.TYPE_INT64: - key.writeInt64Value(valueName, key.readInt64Value(name)); - key.removeValue(name); - break; - } - } - } -} - -function checkLoginsAreEqual(passwordManagerLogin, IELogin, id) { - passwordManagerLogin.QueryInterface(Ci.nsILoginMetaInfo); - for (let attribute in IELogin) { - Assert.equal(passwordManagerLogin[attribute], IELogin[attribute], - "The two logins ID " + id + " have the same " + attribute); - } -} - -function createRegistryPath(path) { - let loginPath = path.split("\\"); - let parentKey = Cc["@mozilla.org/windows-registry-key;1"]. - createInstance(nsIWindowsRegKey); - let currentPath = []; - for (let currentKey of loginPath) { - parentKey.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, currentPath.join("\\"), - nsIWindowsRegKey.ACCESS_ALL); - - if (!parentKey.hasChild(currentKey)) { - parentKey.createChild(currentKey, 0); - } - currentPath.push(currentKey); - parentKey.close(); - } -} - -function getFirstResourceOfType(type) { - let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=ie"] - .createInstance(Ci.nsISupports) - .wrappedJSObject; - let migrators = migrator.getResources(); - for (let m of migrators) { - if (m.name == IE7_FORM_PASSWORDS_MIGRATOR_NAME && m.type == type) { - return m; - } - } - throw new Error("failed to find the " + type + " migrator"); -} - -function makeURI(aURL) { - return Services.io.newURI(aURL, null, null); -} - -add_task(function* setup() { - if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) { - Assert.throws(() => getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS), - "The migrator doesn't exist for win8+"); - return; - } - // create the path to Storage2 in the registry if it doest exist. - createRegistryPath(LOGINS_KEY); - Storage2Key = Cc["@mozilla.org/windows-registry-key;1"]. - createInstance(nsIWindowsRegKey); - Storage2Key.open(nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, LOGINS_KEY, - nsIWindowsRegKey.ACCESS_ALL); - - // create a dummy value otherwise the migrator doesn't exist - if (!Storage2Key.hasValue("dummy")) { - Storage2Key.writeBinaryValue("dummy", "dummy"); - } -}); - -add_task(function* test_passwordsNotAvailable() { - if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) { - return; - } - - let migrator = getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS); - Assert.ok(migrator.exists, "The migrator has to exist"); - let logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, "There are no logins at the beginning of the test"); - - let uris = []; // the uris of the migrated logins - for (let url of TESTED_URLS) { - uris.push(makeURI(url)); - // in this test, there is no IE login data in the registry, so after the migration, the number - // of logins in the store should be 0 - migrator._migrateURIs(uris); - logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, - "There are no logins after doing the migration without adding values to the registry"); - } -}); - -add_task(function* test_passwordsAvailable() { - if (AppConstants.isPlatformAndVersionAtLeast("win", "6.2")) { - return; - } - - let crypto = new OSCrypto(); - let hashes = []; // the hashes of all migrator websites, this is going to be used for the clean up - - do_register_cleanup(() => { - Services.logins.removeAllLogins(); - logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, "There are no logins after the cleanup"); - // remove all the values created in this test from the registry - removeAllValues(Storage2Key, hashes); - // restore all backed up values - restore(Storage2Key); - - // clean the dummy value - if (Storage2Key.hasValue("dummy")) { - Storage2Key.removeValue("dummy"); - } - Storage2Key.close(); - crypto.finalize(); - }); - - let migrator = getFirstResourceOfType(MigrationUtils.resourceTypes.PASSWORDS); - Assert.ok(migrator.exists, "The migrator has to exist"); - let logins = Services.logins.getAllLogins({}); - Assert.equal(logins.length, 0, "There are no logins at the beginning of the test"); - - let uris = []; // the uris of the migrated logins - - let loginCount = 0; - for (let current in TESTED_WEBSITES) { - let website = TESTED_WEBSITES[current]; - // backup the current the registry value if it exists and replace the existing value/create a - // new value with the encrypted data - backupAndStore(Storage2Key, website.hash, - crypto.encryptData(crypto.arrayToString(website.data), - website.uri.spec, true)); - Assert.ok(migrator.exists, "The migrator has to exist"); - uris.push(website.uri); - hashes.push(website.hash); - - migrator._migrateURIs(uris); - logins = Services.logins.getAllLogins({}); - // check that the number of logins in the password manager has increased as expected which means - // that all the values for the current website were imported - loginCount += website.logins.length; - Assert.equal(logins.length, loginCount, - "The number of logins has increased after the migration"); - // NB: because telemetry records any login data passed to the login manager, it - // also gets told about logins that are duplicates or invalid (for one reason - // or another) and so its counts might exceed those of the login manager itself. - Assert.greaterOrEqual(MigrationUtils._importQuantities.logins, loginCount, - "Telemetry quantities equal or exceed the actual import."); - // Reset - this normally happens at the start of a new migration, but we're calling - // the migrator directly so can't rely on that: - MigrationUtils._importQuantities.logins = 0; - - let startIndex = loginCount - website.logins.length; - // compares the imported password manager logins with their expected logins - for (let i = 0; i < website.logins.length; i++) { - checkLoginsAreEqual(logins[startIndex + i], website.logins[i], - " " + current + " - " + i + " "); - } - } -}); diff --git a/browser/components/migration/tests/unit/test_IE_bookmarks.js b/browser/components/migration/tests/unit/test_IE_bookmarks.js deleted file mode 100644 index a166c0502..000000000 --- a/browser/components/migration/tests/unit/test_IE_bookmarks.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -add_task(function* () { - let migrator = MigrationUtils.getMigrator("ie"); - // Sanity check for the source. - Assert.ok(migrator.sourceExists); - - // Wait for the imported bookmarks. Check that "From Internet Explorer" - // folders are created in the menu and on the toolbar. - let source = MigrationUtils.getLocalizedString("sourceNameIE"); - let label = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]); - - let expectedParents = [ PlacesUtils.bookmarksMenuFolderId, - PlacesUtils.toolbarFolderId ]; - - let itemCount = 0; - let bmObserver = { - onItemAdded(aItemId, aParentId, aIndex, aItemType, aURI, aTitle) { - if (aTitle != label) { - itemCount++; - } - if (expectedParents.length > 0 && aTitle == label) { - let index = expectedParents.indexOf(aParentId); - Assert.notEqual(index, -1); - expectedParents.splice(index, 1); - } - }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onItemRemoved() {}, - onItemChanged() {}, - onItemVisited() {}, - onItemMoved() {}, - }; - PlacesUtils.bookmarks.addObserver(bmObserver, false); - - yield promiseMigration(migrator, MigrationUtils.resourceTypes.BOOKMARKS); - PlacesUtils.bookmarks.removeObserver(bmObserver); - Assert.equal(MigrationUtils._importQuantities.bookmarks, itemCount, - "Ensure telemetry matches actual number of imported items."); - - // Check the bookmarks have been imported to all the expected parents. - Assert.equal(expectedParents.length, 0, "Got all the expected parents"); -}); diff --git a/browser/components/migration/tests/unit/test_IE_cookies.js b/browser/components/migration/tests/unit/test_IE_cookies.js deleted file mode 100644 index 37a7462f2..000000000 --- a/browser/components/migration/tests/unit/test_IE_cookies.js +++ /dev/null @@ -1,111 +0,0 @@ -"use strict"; - -XPCOMUtils.defineLazyModuleGetter(this, "ctypes", - "resource://gre/modules/ctypes.jsm"); - -add_task(function* () { - let migrator = MigrationUtils.getMigrator("ie"); - // Sanity check for the source. - Assert.ok(migrator.sourceExists); - - const BOOL = ctypes.bool; - const LPCTSTR = ctypes.char16_t.ptr; - const DWORD = ctypes.uint32_t; - const LPDWORD = DWORD.ptr; - - let wininet = ctypes.open("Wininet"); - - /* - BOOL InternetSetCookieW( - _In_ LPCTSTR lpszUrl, - _In_ LPCTSTR lpszCookieName, - _In_ LPCTSTR lpszCookieData - ); - */ - let setIECookie = wininet.declare("InternetSetCookieW", - ctypes.default_abi, - BOOL, - LPCTSTR, - LPCTSTR, - LPCTSTR); - - /* - BOOL InternetGetCookieW( - _In_ LPCTSTR lpszUrl, - _In_ LPCTSTR lpszCookieName, - _Out_ LPCTSTR lpszCookieData, - _Inout_ LPDWORD lpdwSize - ); - */ - let getIECookie = wininet.declare("InternetGetCookieW", - ctypes.default_abi, - BOOL, - LPCTSTR, - LPCTSTR, - LPCTSTR, - LPDWORD); - - // We need to randomize the cookie to avoid clashing with other cookies - // that might have been set by previous tests and not properly cleared. - let date = (new Date()).getDate(); - const COOKIE = { - get host() { - return new URL(this.href).host; - }, - href: `http://mycookietest.${Math.random()}.com`, - name: "testcookie", - value: "testvalue", - expiry: new Date(new Date().setDate(date + 2)) - }; - let data = ctypes.char16_t.array()(256); - let sizeRef = DWORD(256).address(); - - do_register_cleanup(() => { - // Remove the cookie. - try { - let expired = new Date(new Date().setDate(date - 2)); - let rv = setIECookie(COOKIE.href, COOKIE.name, - `; expires=${expired.toUTCString()}`); - Assert.ok(rv, "Expired the IE cookie"); - Assert.ok(!getIECookie(COOKIE.href, COOKIE.name, data, sizeRef), - "The cookie has been properly removed"); - } catch (ex) {} - - // Close the library. - try { - wininet.close(); - } catch (ex) {} - }); - - // Create the persistent cookie in IE. - let value = `${COOKIE.value}; expires=${COOKIE.expiry.toUTCString()}`; - let rv = setIECookie(COOKIE.href, COOKIE.name, value); - Assert.ok(rv, "Added a persistent IE cookie: " + value); - - // Sanity check the cookie has been created. - Assert.ok(getIECookie(COOKIE.href, COOKIE.name, data, sizeRef), - "Found the added persistent IE cookie"); - do_print("Found cookie: " + data.readString()); - Assert.equal(data.readString(), `${COOKIE.name}=${COOKIE.value}`, - "Found the expected cookie"); - - // Sanity check that there are no cookies. - Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 0, - "There are no cookies initially"); - - // Migrate cookies. - yield promiseMigration(migrator, MigrationUtils.resourceTypes.COOKIES); - - Assert.equal(Services.cookies.countCookiesFromHost(COOKIE.host), 1, - "Migrated the expected number of cookies"); - - // Now check the cookie details. - let enumerator = Services.cookies.getCookiesFromHost(COOKIE.host, {}); - Assert.ok(enumerator.hasMoreElements()); - let foundCookie = enumerator.getNext().QueryInterface(Ci.nsICookie2); - - Assert.equal(foundCookie.name, COOKIE.name); - Assert.equal(foundCookie.value, COOKIE.value); - Assert.equal(foundCookie.host, "." + COOKIE.host); - Assert.equal(foundCookie.expiry, Math.floor(COOKIE.expiry / 1000)); -}); diff --git a/browser/components/migration/tests/unit/test_Safari_bookmarks.js b/browser/components/migration/tests/unit/test_Safari_bookmarks.js deleted file mode 100644 index edc32dc72..000000000 --- a/browser/components/migration/tests/unit/test_Safari_bookmarks.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; - -add_task(function* () { - registerFakePath("ULibDir", do_get_file("Library/")); - - let migrator = MigrationUtils.getMigrator("safari"); - // Sanity check for the source. - Assert.ok(migrator.sourceExists); - - // Wait for the imported bookmarks. Check that "From Safari" - // folders are created on the toolbar. - let source = MigrationUtils.getLocalizedString("sourceNameSafari"); - let label = MigrationUtils.getLocalizedString("importedBookmarksFolder", [source]); - - let expectedParents = [ PlacesUtils.toolbarFolderId ]; - let itemCount = 0; - - let bmObserver = { - onItemAdded(aItemId, aParentId, aIndex, aItemType, aURI, aTitle) { - if (aTitle != label) { - itemCount++; - } - if (expectedParents.length > 0 && aTitle == label) { - let index = expectedParents.indexOf(aParentId); - Assert.ok(index != -1, "Found expected parent"); - expectedParents.splice(index, 1); - } - }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onItemRemoved() {}, - onItemChanged() {}, - onItemVisited() {}, - onItemMoved() {}, - }; - PlacesUtils.bookmarks.addObserver(bmObserver, false); - - yield promiseMigration(migrator, MigrationUtils.resourceTypes.BOOKMARKS); - PlacesUtils.bookmarks.removeObserver(bmObserver); - - // Check the bookmarks have been imported to all the expected parents. - Assert.ok(!expectedParents.length, "No more expected parents"); - Assert.equal(itemCount, 13, "Should import all 13 items."); - // Check that the telemetry matches: - Assert.equal(MigrationUtils._importQuantities.bookmarks, itemCount, "Telemetry reporting correct."); -}); diff --git a/browser/components/migration/tests/unit/test_automigration.js b/browser/components/migration/tests/unit/test_automigration.js deleted file mode 100644 index bc9076a6c..000000000 --- a/browser/components/migration/tests/unit/test_automigration.js +++ /dev/null @@ -1,695 +0,0 @@ -"use strict"; - -let AutoMigrateBackstage = Cu.import("resource:///modules/AutoMigrate.jsm"); /* globals AutoMigrate */ - -let gShimmedMigratorKeyPicker = null; -let gShimmedMigrator = null; - -const kUsecPerMin = 60 * 1000000; - -// This is really a proxy on MigrationUtils, but if we specify that directly, -// we get in trouble because the object itself is frozen, and Proxies can't -// return a different value to an object when directly proxying a frozen -// object. -AutoMigrateBackstage.MigrationUtils = new Proxy({}, { - get(target, name) { - if (name == "getMigratorKeyForDefaultBrowser" && gShimmedMigratorKeyPicker) { - return gShimmedMigratorKeyPicker; - } - if (name == "getMigrator" && gShimmedMigrator) { - return function() { return gShimmedMigrator }; - } - return MigrationUtils[name]; - }, -}); - -do_register_cleanup(function() { - AutoMigrateBackstage.MigrationUtils = MigrationUtils; -}); - -// This should be replaced by using History.fetch with a fetchVisits option, -// once that becomes available -function* visitsForURL(url) -{ - let visitCount = 0; - let db = yield PlacesUtils.promiseDBConnection(); - visitCount = yield db.execute( - `SELECT count(*) FROM moz_historyvisits v - JOIN moz_places h ON h.id = v.place_id - WHERE url_hash = hash(:url) AND url = :url`, - {url}); - visitCount = visitCount[0].getInt64(0); - return visitCount; -} - - -/** - * Test automatically picking a browser to migrate from - */ -add_task(function* checkMigratorPicking() { - Assert.throws(() => AutoMigrate.pickMigrator("firefox"), - /Can't automatically migrate from Firefox/, - "Should throw when explicitly picking Firefox."); - - Assert.throws(() => AutoMigrate.pickMigrator("gobbledygook"), - /migrator object is not available/, - "Should throw when passing unknown migrator key"); - gShimmedMigratorKeyPicker = function() { - return "firefox"; - }; - Assert.throws(() => AutoMigrate.pickMigrator(), - /Can't automatically migrate from Firefox/, - "Should throw when implicitly picking Firefox."); - gShimmedMigratorKeyPicker = function() { - return "gobbledygook"; - }; - Assert.throws(() => AutoMigrate.pickMigrator(), - /migrator object is not available/, - "Should throw when an unknown migrator is the default"); - gShimmedMigratorKeyPicker = function() { - return ""; - }; - Assert.throws(() => AutoMigrate.pickMigrator(), - /Could not determine default browser key/, - "Should throw when an unknown migrator is the default"); -}); - - -/** - * Test automatically picking a profile to migrate from - */ -add_task(function* checkProfilePicking() { - let fakeMigrator = {sourceProfiles: [{id: "a"}, {id: "b"}]}; - let profB = fakeMigrator.sourceProfiles[1]; - Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator), - /Don't know how to pick a profile when more/, - "Should throw when there are multiple profiles."); - Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator, "c"), - /Profile specified was not found/, - "Should throw when the profile supplied doesn't exist."); - let profileToMigrate = AutoMigrate.pickProfile(fakeMigrator, "b"); - Assert.equal(profileToMigrate, profB, "Should return profile supplied"); - - fakeMigrator.sourceProfiles = null; - Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator, "c"), - /Profile specified but only a default profile found./, - "Should throw when the profile supplied doesn't exist."); - profileToMigrate = AutoMigrate.pickProfile(fakeMigrator); - Assert.equal(profileToMigrate, null, "Should return default profile when that's the only one."); - - fakeMigrator.sourceProfiles = []; - Assert.throws(() => AutoMigrate.pickProfile(fakeMigrator), - /No profile data found/, - "Should throw when no profile data is present."); - - fakeMigrator.sourceProfiles = [{id: "a"}]; - let profA = fakeMigrator.sourceProfiles[0]; - profileToMigrate = AutoMigrate.pickProfile(fakeMigrator); - Assert.equal(profileToMigrate, profA, "Should return the only profile if only one is present."); -}); - -/** - * Test the complete automatic process including browser and profile selection, - * and actual migration (which implies startup) - */ -add_task(function* checkIntegration() { - gShimmedMigrator = { - get sourceProfiles() { - do_print("Read sourceProfiles"); - return null; - }, - getMigrateData(profileToMigrate) { - this._getMigrateDataArgs = profileToMigrate; - return Ci.nsIBrowserProfileMigrator.BOOKMARKS; - }, - migrate(types, startup, profileToMigrate) { - this._migrateArgs = [types, startup, profileToMigrate]; - }, - }; - gShimmedMigratorKeyPicker = function() { - return "gobbledygook"; - }; - AutoMigrate.migrate("startup"); - Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null, - "getMigrateData called with 'null' as a profile"); - - let {BOOKMARKS, HISTORY, PASSWORDS} = Ci.nsIBrowserProfileMigrator; - let expectedTypes = BOOKMARKS | HISTORY | PASSWORDS; - Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null], - "migrate called with 'null' as a profile"); -}); - -/** - * Test the undo preconditions and a no-op undo in the automigrator. - */ -add_task(function* checkUndoPreconditions() { - let shouldAddData = false; - gShimmedMigrator = { - get sourceProfiles() { - do_print("Read sourceProfiles"); - return null; - }, - getMigrateData(profileToMigrate) { - this._getMigrateDataArgs = profileToMigrate; - return Ci.nsIBrowserProfileMigrator.BOOKMARKS; - }, - migrate(types, startup, profileToMigrate) { - this._migrateArgs = [types, startup, profileToMigrate]; - if (shouldAddData) { - // Insert a login and check that that worked. - MigrationUtils.insertLoginWrapper({ - hostname: "www.mozilla.org", - formSubmitURL: "http://www.mozilla.org", - username: "user", - password: "pass", - }); - } - TestUtils.executeSoon(function() { - Services.obs.notifyObservers(null, "Migration:Ended", undefined); - }); - }, - }; - - gShimmedMigratorKeyPicker = function() { - return "gobbledygook"; - }; - AutoMigrate.migrate("startup"); - let migrationFinishedPromise = TestUtils.topicObserved("Migration:Ended"); - Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null, - "getMigrateData called with 'null' as a profile"); - - let {BOOKMARKS, HISTORY, PASSWORDS} = Ci.nsIBrowserProfileMigrator; - let expectedTypes = BOOKMARKS | HISTORY | PASSWORDS; - Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null], - "migrate called with 'null' as a profile"); - - yield migrationFinishedPromise; - Assert.ok(Preferences.has("browser.migrate.automigrate.browser"), - "Should have set browser pref"); - Assert.ok(!(yield AutoMigrate.canUndo()), "Should not be able to undo migration, as there's no data"); - gShimmedMigrator._migrateArgs = null; - gShimmedMigrator._getMigrateDataArgs = null; - Preferences.reset("browser.migrate.automigrate.browser"); - shouldAddData = true; - - AutoMigrate.migrate("startup"); - migrationFinishedPromise = TestUtils.topicObserved("Migration:Ended"); - Assert.strictEqual(gShimmedMigrator._getMigrateDataArgs, null, - "getMigrateData called with 'null' as a profile"); - Assert.deepEqual(gShimmedMigrator._migrateArgs, [expectedTypes, "startup", null], - "migrate called with 'null' as a profile"); - - yield migrationFinishedPromise; - let storedLogins = Services.logins.findLogins({}, "www.mozilla.org", - "http://www.mozilla.org", null); - Assert.equal(storedLogins.length, 1, "Should have 1 login"); - - Assert.ok(Preferences.has("browser.migrate.automigrate.browser"), - "Should have set browser pref"); - Assert.ok((yield AutoMigrate.canUndo()), "Should be able to undo migration, as now there's data"); - - yield AutoMigrate.undo(); - Assert.ok(true, "Should be able to finish an undo cycle."); - - // Check that the undo removed the passwords: - storedLogins = Services.logins.findLogins({}, "www.mozilla.org", - "http://www.mozilla.org", null); - Assert.equal(storedLogins.length, 0, "Should have no logins"); -}); - -/** - * Fake a migration and then try to undo it to verify all data gets removed. - */ -add_task(function* checkUndoRemoval() { - MigrationUtils.initializeUndoData(); - Preferences.set("browser.migrate.automigrate.browser", "automationbrowser"); - // Insert a login and check that that worked. - MigrationUtils.insertLoginWrapper({ - hostname: "www.mozilla.org", - formSubmitURL: "http://www.mozilla.org", - username: "user", - password: "pass", - }); - let storedLogins = Services.logins.findLogins({}, "www.mozilla.org", - "http://www.mozilla.org", null); - Assert.equal(storedLogins.length, 1, "Should have 1 login"); - - // Insert a bookmark and check that we have exactly 1 bookmark for that URI. - yield MigrationUtils.insertBookmarkWrapper({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - url: "http://www.example.org/", - title: "Some example bookmark", - }); - - let bookmark = yield PlacesUtils.bookmarks.fetch({url: "http://www.example.org/"}); - Assert.ok(bookmark, "Should have a bookmark before undo"); - Assert.equal(bookmark.title, "Some example bookmark", "Should have correct bookmark before undo."); - - // Insert 2 history visits - let now_uSec = Date.now() * 1000; - let visitedURI = Services.io.newURI("http://www.example.com/", null, null); - let frecencyUpdatePromise = new Promise(resolve => { - let expectedChanges = 2; - let observer = { - onFrecencyChanged: function() { - if (!--expectedChanges) { - PlacesUtils.history.removeObserver(observer); - resolve(); - } - }, - }; - PlacesUtils.history.addObserver(observer, false); - }); - yield MigrationUtils.insertVisitsWrapper([{ - uri: visitedURI, - visits: [ - { - transitionType: PlacesUtils.history.TRANSITION_LINK, - visitDate: now_uSec, - }, - { - transitionType: PlacesUtils.history.TRANSITION_LINK, - visitDate: now_uSec - 100 * kUsecPerMin, - }, - ] - }]); - yield frecencyUpdatePromise; - - // Verify that both visits get reported. - let opts = PlacesUtils.history.getNewQueryOptions(); - opts.resultType = opts.RESULTS_AS_VISIT; - let query = PlacesUtils.history.getNewQuery(); - query.uri = visitedURI; - let visits = PlacesUtils.history.executeQuery(query, opts); - visits.root.containerOpen = true; - Assert.equal(visits.root.childCount, 2, "Should have 2 visits"); - // Clean up: - visits.root.containerOpen = false; - - yield AutoMigrate.saveUndoState(); - - // Verify that we can undo, then undo: - Assert.ok(AutoMigrate.canUndo(), "Should be possible to undo migration"); - yield AutoMigrate.undo(); - - let histograms = [ - "FX_STARTUP_MIGRATION_UNDO_BOOKMARKS_ERRORCOUNT", - "FX_STARTUP_MIGRATION_UNDO_LOGINS_ERRORCOUNT", - "FX_STARTUP_MIGRATION_UNDO_VISITS_ERRORCOUNT", - ]; - for (let histogramId of histograms) { - let keyedHistogram = Services.telemetry.getKeyedHistogramById(histogramId); - let histogramData = keyedHistogram.snapshot().automationbrowser; - Assert.equal(histogramData.sum, 0, `Should have reported 0 errors to ${histogramId}.`); - Assert.greaterOrEqual(histogramData.counts[0], 1, `Should have reported value of 0 one time to ${histogramId}.`); - } - histograms = [ - "FX_STARTUP_MIGRATION_UNDO_BOOKMARKS_MS", - "FX_STARTUP_MIGRATION_UNDO_LOGINS_MS", - "FX_STARTUP_MIGRATION_UNDO_VISITS_MS", - "FX_STARTUP_MIGRATION_UNDO_TOTAL_MS", - ]; - for (let histogramId of histograms) { - Assert.greater(Services.telemetry.getKeyedHistogramById(histogramId).snapshot().automationbrowser.sum, 0, - `Should have reported non-zero time spent using undo for ${histogramId}`); - } - - // Check that the undo removed the history visits: - visits = PlacesUtils.history.executeQuery(query, opts); - visits.root.containerOpen = true; - Assert.equal(visits.root.childCount, 0, "Should have no more visits"); - visits.root.containerOpen = false; - - // Check that the undo removed the bookmarks: - bookmark = yield PlacesUtils.bookmarks.fetch({url: "http://www.example.org/"}); - Assert.ok(!bookmark, "Should have no bookmarks after undo"); - - // Check that the undo removed the passwords: - storedLogins = Services.logins.findLogins({}, "www.mozilla.org", - "http://www.mozilla.org", null); - Assert.equal(storedLogins.length, 0, "Should have no logins"); -}); - -add_task(function* checkUndoBookmarksState() { - MigrationUtils.initializeUndoData(); - const {TYPE_FOLDER, TYPE_BOOKMARK} = PlacesUtils.bookmarks; - let title = "Some example bookmark"; - let url = "http://www.example.com"; - let parentGuid = PlacesUtils.bookmarks.toolbarGuid; - let {guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({ - title, url, parentGuid - }); - Assert.deepEqual((yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks"), - [{lastModified, parentGuid, guid, type: TYPE_BOOKMARK}]); - - MigrationUtils.initializeUndoData(); - ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({ - title, parentGuid, type: TYPE_FOLDER - })); - let folder = {guid, lastModified, parentGuid, type: TYPE_FOLDER}; - let folderGuid = folder.guid; - ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({ - title, url, parentGuid: folderGuid - })); - let kid1 = {guid, lastModified, parentGuid: folderGuid, type: TYPE_BOOKMARK}; - ({guid, lastModified} = yield MigrationUtils.insertBookmarkWrapper({ - title, url, parentGuid: folderGuid - })); - let kid2 = {guid, lastModified, parentGuid: folderGuid, type: TYPE_BOOKMARK}; - - let bookmarksUndo = (yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks"); - Assert.equal(bookmarksUndo.length, 3); - // We expect that the last modified time from first kid #1 and then kid #2 - // has been propagated to the folder: - folder.lastModified = kid2.lastModified; - // Not just using deepEqual on the entire array (which should work) because - // the failure messages get truncated by xpcshell which is unhelpful. - Assert.deepEqual(bookmarksUndo[0], folder); - Assert.deepEqual(bookmarksUndo[1], kid1); - Assert.deepEqual(bookmarksUndo[2], kid2); - yield PlacesUtils.bookmarks.eraseEverything(); -}); - -add_task(function* testBookmarkRemovalByUndo() { - const {TYPE_FOLDER} = PlacesUtils.bookmarks; - MigrationUtils.initializeUndoData(); - let title = "Some example bookmark"; - let url = "http://www.mymagicaluniqueurl.com"; - let parentGuid = PlacesUtils.bookmarks.toolbarGuid; - let {guid} = yield MigrationUtils.insertBookmarkWrapper({ - title: "Some folder", parentGuid, type: TYPE_FOLDER - }); - let folderGuid = guid; - let itemsToRemove = []; - ({guid} = yield MigrationUtils.insertBookmarkWrapper({ - title: "Inner folder", parentGuid: folderGuid, type: TYPE_FOLDER - })); - let innerFolderGuid = guid; - itemsToRemove.push(innerFolderGuid); - - ({guid} = yield MigrationUtils.insertBookmarkWrapper({ - title: "Inner inner folder", parentGuid: innerFolderGuid, type: TYPE_FOLDER - })); - itemsToRemove.push(guid); - - ({guid} = yield MigrationUtils.insertBookmarkWrapper({ - title: "Inner nested item", url: "http://inner-nested-example.com", parentGuid: guid - })); - itemsToRemove.push(guid); - - ({guid} = yield MigrationUtils.insertBookmarkWrapper({ - title, url, parentGuid: folderGuid - })); - itemsToRemove.push(guid); - - for (let toBeRemovedGuid of itemsToRemove) { - let dbResultForGuid = yield PlacesUtils.bookmarks.fetch(toBeRemovedGuid); - Assert.ok(dbResultForGuid, "Should be able to find items that will be removed."); - } - let bookmarkUndoState = (yield MigrationUtils.stopAndRetrieveUndoData()).get("bookmarks"); - // Now insert a separate item into this folder, not related to the migration. - let newItem = yield PlacesUtils.bookmarks.insert( - {title: "Not imported", parentGuid: folderGuid, url: "http://www.example.com"} - ); - - yield AutoMigrate._removeUnchangedBookmarks(bookmarkUndoState); - Assert.ok(true, "Successfully removed imported items."); - - let itemFromDB = yield PlacesUtils.bookmarks.fetch(newItem.guid); - Assert.ok(itemFromDB, "Item we inserted outside of migration is still there."); - itemFromDB = yield PlacesUtils.bookmarks.fetch(folderGuid); - Assert.ok(itemFromDB, "Folder we inserted in migration is still there because of new kids."); - for (let removedGuid of itemsToRemove) { - let dbResultForGuid = yield PlacesUtils.bookmarks.fetch(removedGuid); - let dbgStr = dbResultForGuid && dbResultForGuid.title; - Assert.equal(null, dbResultForGuid, "Should not be able to find items that should have been removed, but found " + dbgStr); - } - yield PlacesUtils.bookmarks.eraseEverything(); -}); - -add_task(function* checkUndoLoginsState() { - MigrationUtils.initializeUndoData(); - MigrationUtils.insertLoginWrapper({ - username: "foo", - password: "bar", - hostname: "https://example.com", - formSubmitURL: "https://example.com/", - timeCreated: new Date(), - }); - let storedLogins = Services.logins.findLogins({}, "https://example.com", "", ""); - let storedLogin = storedLogins[0]; - storedLogin.QueryInterface(Ci.nsILoginMetaInfo); - let {guid, timePasswordChanged} = storedLogin; - let undoLoginData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("logins"); - Assert.deepEqual([{guid, timePasswordChanged}], undoLoginData); - Services.logins.removeAllLogins(); -}); - -add_task(function* testLoginsRemovalByUndo() { - MigrationUtils.initializeUndoData(); - MigrationUtils.insertLoginWrapper({ - username: "foo", - password: "bar", - hostname: "https://example.com", - formSubmitURL: "https://example.com/", - timeCreated: new Date(), - }); - MigrationUtils.insertLoginWrapper({ - username: "foo", - password: "bar", - hostname: "https://example.org", - formSubmitURL: "https://example.org/", - timeCreated: new Date(new Date().getTime() - 10000), - }); - // This should update the existing login - LoginHelper.maybeImportLogin({ - username: "foo", - password: "bazzy", - hostname: "https://example.org", - formSubmitURL: "https://example.org/", - timePasswordChanged: new Date(), - }); - Assert.equal(1, LoginHelper.searchLoginsWithObject({hostname: "https://example.org", formSubmitURL: "https://example.org/"}).length, - "Should be only 1 login for example.org (that was updated)"); - let undoLoginData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("logins"); - - yield AutoMigrate._removeUnchangedLogins(undoLoginData); - Assert.equal(0, LoginHelper.searchLoginsWithObject({hostname: "https://example.com", formSubmitURL: "https://example.com/"}).length, - "unchanged example.com entry should have been removed."); - Assert.equal(1, LoginHelper.searchLoginsWithObject({hostname: "https://example.org", formSubmitURL: "https://example.org/"}).length, - "changed example.org entry should have persisted."); - Services.logins.removeAllLogins(); -}); - -add_task(function* checkUndoVisitsState() { - MigrationUtils.initializeUndoData(); - yield MigrationUtils.insertVisitsWrapper([{ - uri: NetUtil.newURI("http://www.example.com/"), - title: "Example", - visits: [{ - visitDate: new Date("2015-07-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-09-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-08-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }, { - uri: NetUtil.newURI("http://www.example.org/"), - title: "Example", - visits: [{ - visitDate: new Date("2016-04-03").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-08-03").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }, { - uri: NetUtil.newURI("http://www.example.com/"), - title: "Example", - visits: [{ - visitDate: new Date("2015-10-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }]); - let undoVisitData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("visits"); - Assert.deepEqual(Array.from(undoVisitData.map(v => v.url)).sort(), - ["http://www.example.com/", "http://www.example.org/"]); - Assert.deepEqual(undoVisitData.find(v => v.url == "http://www.example.com/"), { - url: "http://www.example.com/", - visitCount: 4, - first: new Date("2015-07-10").getTime() * 1000, - last: new Date("2015-10-10").getTime() * 1000, - }); - Assert.deepEqual(undoVisitData.find(v => v.url == "http://www.example.org/"), { - url: "http://www.example.org/", - visitCount: 2, - first: new Date("2015-08-03").getTime() * 1000, - last: new Date("2016-04-03").getTime() * 1000, - }); - - yield PlacesTestUtils.clearHistory(); -}); - -add_task(function* checkUndoVisitsState() { - MigrationUtils.initializeUndoData(); - yield MigrationUtils.insertVisitsWrapper([{ - uri: NetUtil.newURI("http://www.example.com/"), - title: "Example", - visits: [{ - visitDate: new Date("2015-07-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-09-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-08-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }, { - uri: NetUtil.newURI("http://www.example.org/"), - title: "Example", - visits: [{ - visitDate: new Date("2016-04-03").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }, { - visitDate: new Date("2015-08-03").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }, { - uri: NetUtil.newURI("http://www.example.com/"), - title: "Example", - visits: [{ - visitDate: new Date("2015-10-10").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }, { - uri: NetUtil.newURI("http://www.mozilla.org/"), - title: "Example", - visits: [{ - visitDate: new Date("2015-01-01").getTime() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK, - }], - }]); - - // We have to wait until frecency updates have been handled in order - // to accurately determine whether we're doing the right thing. - let frecencyUpdatesHandled = new Promise(resolve => { - PlacesUtils.history.addObserver({ - onFrecencyChanged(aURI) { - if (aURI.spec == "http://www.unrelated.org/") { - PlacesUtils.history.removeObserver(this); - resolve(); - } - } - }, false); - }); - yield PlacesUtils.history.insertMany([{ - url: "http://www.example.com/", - title: "Example", - visits: [{ - date: new Date("2015-08-16"), - }], - }, { - url: "http://www.example.org/", - title: "Example", - visits: [{ - date: new Date("2016-01-03"), - }, { - date: new Date("2015-05-03"), - }], - }, { - url: "http://www.unrelated.org/", - title: "Unrelated", - visits: [{ - date: new Date("2015-09-01"), - }], - }]); - yield frecencyUpdatesHandled; - let undoVisitData = (yield MigrationUtils.stopAndRetrieveUndoData()).get("visits"); - - let frecencyChangesExpected = new Map([ - ["http://www.example.com/", PromiseUtils.defer()], - ["http://www.example.org/", PromiseUtils.defer()] - ]); - let uriDeletedExpected = new Map([ - ["http://www.mozilla.org/", PromiseUtils.defer()], - ]); - let wrongMethodDeferred = PromiseUtils.defer(); - let observer = { - onBeginUpdateBatch: function() {}, - onEndUpdateBatch: function() {}, - onVisit: function(uri) { - wrongMethodDeferred.reject(new Error("Unexpected call to onVisit " + uri.spec)); - }, - onTitleChanged: function(uri) { - wrongMethodDeferred.reject(new Error("Unexpected call to onTitleChanged " + uri.spec)); - }, - onClearHistory: function() { - wrongMethodDeferred.reject("Unexpected call to onClearHistory"); - }, - onPageChanged: function(uri) { - wrongMethodDeferred.reject(new Error("Unexpected call to onPageChanged " + uri.spec)); - }, - onFrecencyChanged: function(aURI) { - do_print("frecency change"); - Assert.ok(frecencyChangesExpected.has(aURI.spec), - "Should be expecting frecency change for " + aURI.spec); - frecencyChangesExpected.get(aURI.spec).resolve(); - }, - onManyFrecenciesChanged: function() { - do_print("Many frecencies changed"); - wrongMethodDeferred.reject(new Error("This test can't deal with onManyFrecenciesChanged to be called")); - }, - onDeleteURI: function(aURI) { - do_print("delete uri"); - Assert.ok(uriDeletedExpected.has(aURI.spec), - "Should be expecting uri deletion for " + aURI.spec); - uriDeletedExpected.get(aURI.spec).resolve(); - }, - }; - PlacesUtils.history.addObserver(observer, false); - - yield AutoMigrate._removeSomeVisits(undoVisitData); - PlacesUtils.history.removeObserver(observer); - yield Promise.all(uriDeletedExpected.values()); - yield Promise.all(frecencyChangesExpected.values()); - - Assert.equal(yield visitsForURL("http://www.example.com/"), 1, - "1 example.com visit (out of 5) should have persisted despite being within the range, due to limiting"); - Assert.equal(yield visitsForURL("http://www.mozilla.org/"), 0, - "0 mozilla.org visits should have persisted (out of 1)."); - Assert.equal(yield visitsForURL("http://www.example.org/"), 2, - "2 example.org visits should have persisted (out of 4)."); - Assert.equal(yield visitsForURL("http://www.unrelated.org/"), 1, - "1 unrelated.org visits should have persisted as it's not involved in the import."); - yield PlacesTestUtils.clearHistory(); -}); - -add_task(function* checkHistoryRemovalCompletion() { - AutoMigrate._errorMap = {bookmarks: 0, visits: 0, logins: 0}; - yield AutoMigrate._removeSomeVisits([{url: "http://www.example.com/", limit: -1}]); - ok(true, "Removing visits should complete even if removing some visits failed."); - Assert.equal(AutoMigrate._errorMap.visits, 1, "Should have logged the error for visits."); - - // Unfortunately there's not a reliable way to make removing bookmarks be - // unhappy unless the DB is messed up (e.g. contains children but has - // parents removed already). - yield AutoMigrate._removeUnchangedBookmarks([ - {guid: PlacesUtils.bookmarks, lastModified: new Date(0), parentGuid: 0}, - {guid: "gobbledygook", lastModified: new Date(0), parentGuid: 0}, - ]); - ok(true, "Removing bookmarks should complete even if some items are gone or bogus."); - Assert.equal(AutoMigrate._errorMap.bookmarks, 0, - "Should have ignored removing non-existing (or builtin) bookmark."); - - - yield AutoMigrate._removeUnchangedLogins([ - {guid: "gobbledygook", timePasswordChanged: new Date(0)}, - ]); - ok(true, "Removing logins should complete even if logins don't exist."); - Assert.equal(AutoMigrate._errorMap.logins, 0, - "Should have ignored removing non-existing logins."); -}); diff --git a/browser/components/migration/tests/unit/test_fx_telemetry.js b/browser/components/migration/tests/unit/test_fx_telemetry.js deleted file mode 100644 index a276f52f8..000000000 --- a/browser/components/migration/tests/unit/test_fx_telemetry.js +++ /dev/null @@ -1,288 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* globals do_get_tempdir */ - -"use strict"; - -function run_test() { - run_next_test(); -} - -function readFile(file) { - let stream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); - stream.init(file, -1, -1, Ci.nsIFileInputStream.CLOSE_ON_EOF); - - let sis = Cc["@mozilla.org/scriptableinputstream;1"] - .createInstance(Ci.nsIScriptableInputStream); - sis.init(stream); - let contents = sis.read(file.fileSize); - sis.close(); - return contents; -} - -function checkDirectoryContains(dir, files) { - print("checking " + dir.path + " - should contain " + Object.keys(files)); - let seen = new Set(); - let enumerator = dir.directoryEntries; - while (enumerator.hasMoreElements()) { - let file = enumerator.getNext().QueryInterface(Ci.nsIFile); - print("found file: " + file.path); - Assert.ok(file.leafName in files, file.leafName + " exists, but shouldn't"); - - let expectedContents = files[file.leafName]; - if (typeof expectedContents != "string") { - // it's a subdir - recurse! - Assert.ok(file.isDirectory(), "should be a subdir"); - let newDir = dir.clone(); - newDir.append(file.leafName); - checkDirectoryContains(newDir, expectedContents); - } else { - Assert.ok(!file.isDirectory(), "should be a regular file"); - let contents = readFile(file); - Assert.equal(contents, expectedContents); - } - seen.add(file.leafName); - } - let missing = []; - for (let x in files) { - if (!seen.has(x)) { - missing.push(x); - } - } - Assert.deepEqual(missing, [], "no missing files in " + dir.path); -} - -function getTestDirs() { - // we make a directory structure in a temp dir which mirrors what we are - // testing. - let tempDir = do_get_tempdir(); - let srcDir = tempDir.clone(); - srcDir.append("test_source_dir"); - srcDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - - let targetDir = tempDir.clone(); - targetDir.append("test_target_dir"); - targetDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - - // no need to cleanup these dirs - the xpcshell harness will do it for us. - return [srcDir, targetDir]; -} - -function writeToFile(dir, leafName, contents) { - let file = dir.clone(); - file.append(leafName); - - let outputStream = FileUtils.openFileOutputStream(file); - outputStream.write(contents, contents.length); - outputStream.close(); -} - -function createSubDir(dir, subDirName) { - let subDir = dir.clone(); - subDir.append(subDirName); - subDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - return subDir; -} - -function promiseMigrator(name, srcDir, targetDir) { - let migrator = Cc["@mozilla.org/profile/migrator;1?app=browser&type=firefox"] - .createInstance(Ci.nsISupports) - .wrappedJSObject; - let migrators = migrator._getResourcesInternal(srcDir, targetDir); - for (let m of migrators) { - if (m.name == name) { - return new Promise(resolve => m.migrate(resolve)); - } - } - throw new Error("failed to find the " + name + " migrator"); -} - -function promiseTelemetryMigrator(srcDir, targetDir) { - return promiseMigrator("telemetry", srcDir, targetDir); -} - -add_task(function* test_empty() { - let [srcDir, targetDir] = getTestDirs(); - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true with empty directories"); - // check both are empty - checkDirectoryContains(srcDir, {}); - checkDirectoryContains(targetDir, {}); -}); - -add_task(function* test_migrate_files() { - let [srcDir, targetDir] = getTestDirs(); - - // Set up datareporting files, some to copy, some not. - let stateContent = JSON.stringify({ - clientId: "68d5474e-19dc-45c1-8e9a-81fca592707c", - }); - let sessionStateContent = "foobar 5432"; - let subDir = createSubDir(srcDir, "datareporting"); - writeToFile(subDir, "state.json", stateContent); - writeToFile(subDir, "session-state.json", sessionStateContent); - writeToFile(subDir, "other.file", "do not copy"); - - let archived = createSubDir(subDir, "archived"); - writeToFile(archived, "other.file", "do not copy"); - - // Set up FHR files, they should not be copied. - writeToFile(srcDir, "healthreport.sqlite", "do not copy"); - writeToFile(srcDir, "healthreport.sqlite-wal", "do not copy"); - subDir = createSubDir(srcDir, "healthreport"); - writeToFile(subDir, "state.json", "do not copy"); - writeToFile(subDir, "other.file", "do not copy"); - - // Perform migration. - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true with important telemetry files copied"); - - checkDirectoryContains(targetDir, { - "datareporting": { - "state.json": stateContent, - "session-state.json": sessionStateContent, - }, - }); -}); - -add_task(function* test_fallback_fhr_state() { - let [srcDir, targetDir] = getTestDirs(); - - // Test that we fall back to migrating FHR state if the datareporting - // state file does not exist. - let stateContent = JSON.stringify({ - clientId: "68d5474e-19dc-45c1-8e9a-81fca592707c", - }); - let subDir = createSubDir(srcDir, "healthreport"); - writeToFile(subDir, "state.json", stateContent); - - // Perform migration. - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - checkDirectoryContains(targetDir, { - "healthreport": { - "state.json": stateContent, - }, - }); -}); - - -add_task(function* test_datareporting_not_dir() { - let [srcDir, targetDir] = getTestDirs(); - - writeToFile(srcDir, "datareporting", "I'm a file but should be a directory"); - - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true even though the directory was a file"); - - checkDirectoryContains(targetDir, {}); -}); - -add_task(function* test_datareporting_empty() { - let [srcDir, targetDir] = getTestDirs(); - - // Migrate with an empty 'datareporting' subdir. - createSubDir(srcDir, "datareporting"); - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - // We should end up with no migrated files. - checkDirectoryContains(targetDir, { - "datareporting": {}, - }); -}); - -add_task(function* test_healthreport_empty() { - let [srcDir, targetDir] = getTestDirs(); - - // Migrate with no 'datareporting' and an empty 'healthreport' subdir. - createSubDir(srcDir, "healthreport"); - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - // We should end up with no migrated files. - checkDirectoryContains(targetDir, {}); -}); - -add_task(function* test_datareporting_many() { - let [srcDir, targetDir] = getTestDirs(); - - // Create some datareporting files. - let subDir = createSubDir(srcDir, "datareporting"); - let shouldBeCopied = "should be copied"; - writeToFile(subDir, "state.json", shouldBeCopied); - writeToFile(subDir, "session-state.json", shouldBeCopied); - writeToFile(subDir, "something.else", "should not"); - createSubDir(subDir, "emptyDir"); - - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - checkDirectoryContains(targetDir, { - "datareporting" : { - "state.json": shouldBeCopied, - "session-state.json": shouldBeCopied, - } - }); -}); - -add_task(function* test_no_session_state() { - let [srcDir, targetDir] = getTestDirs(); - - // Check that migration still works properly if we only have state.json. - let subDir = createSubDir(srcDir, "datareporting"); - let stateContent = "abcd984"; - writeToFile(subDir, "state.json", stateContent); - - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - checkDirectoryContains(targetDir, { - "datareporting" : { - "state.json": stateContent, - } - }); -}); - -add_task(function* test_no_state() { - let [srcDir, targetDir] = getTestDirs(); - - // Check that migration still works properly if we only have session-state.json. - let subDir = createSubDir(srcDir, "datareporting"); - let sessionStateContent = "abcd512"; - writeToFile(subDir, "session-state.json", sessionStateContent); - - let ok = yield promiseTelemetryMigrator(srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - - checkDirectoryContains(targetDir, { - "datareporting" : { - "session-state.json": sessionStateContent, - } - }); -}); - -add_task(function* test_times_migration() { - let [srcDir, targetDir] = getTestDirs(); - - // create a times.json in the source directory. - let contents = JSON.stringify({created: 1234}); - writeToFile(srcDir, "times.json", contents); - - let earliest = Date.now(); - let ok = yield promiseMigrator("times", srcDir, targetDir); - Assert.ok(ok, "callback should have been true"); - let latest = Date.now(); - - let timesFile = targetDir.clone(); - timesFile.append("times.json"); - - let raw = readFile(timesFile); - let times = JSON.parse(raw); - Assert.ok(times.reset >= earliest && times.reset <= latest); - // and it should have left the creation time alone. - Assert.equal(times.created, 1234); -}); diff --git a/browser/components/migration/tests/unit/xpcshell.ini b/browser/components/migration/tests/unit/xpcshell.ini deleted file mode 100644 index 1b9f0a5f1..000000000 --- a/browser/components/migration/tests/unit/xpcshell.ini +++ /dev/null @@ -1,26 +0,0 @@ -[DEFAULT] -head = head_migration.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' -support-files = - Library/** - AppData/** - -[test_automigration.js] -[test_Chrome_cookies.js] -skip-if = os != "mac" # Relies on ULibDir -[test_Chrome_passwords.js] -skip-if = os != "win" -[test_Edge_availability.js] -[test_Edge_db_migration.js] -skip-if = os != "win" || os_version == "5.1" || os_version == "5.2" # Relies on post-XP bits of ESEDB -[test_fx_telemetry.js] -[test_IE_bookmarks.js] -skip-if = os != "win" -[test_IE_cookies.js] -skip-if = os != "win" -[test_IE7_passwords.js] -skip-if = os != "win" -[test_Safari_bookmarks.js] -skip-if = os != "mac" diff --git a/browser/components/newtab/tests/browser/.eslintrc.js b/browser/components/newtab/tests/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/newtab/tests/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/newtab/tests/browser/blue_page.html b/browser/components/newtab/tests/browser/blue_page.html deleted file mode 100644 index a7f000bfd..000000000 --- a/browser/components/newtab/tests/browser/blue_page.html +++ /dev/null @@ -1,9 +0,0 @@ -<!DOCTYPE html> - -<html> -<head> - <meta charset="utf-8"> -</head> -<body style="background-color: blue"> -</body> -</html> diff --git a/browser/components/newtab/tests/browser/browser.ini b/browser/components/newtab/tests/browser/browser.ini deleted file mode 100644 index fa740be9e..000000000 --- a/browser/components/newtab/tests/browser/browser.ini +++ /dev/null @@ -1,16 +0,0 @@ -[DEFAULT] -support-files = - blue_page.html - dummy_page.html - newtabwebchannel_basic.html - newtabmessages_places.html - newtabmessages_prefs.html - newtabmessages_preview.html - newtabmessages_search.html - -[browser_PreviewProvider.js] -[browser_remotenewtab_pageloads.js] -[browser_newtab_overrides.js] -[browser_newtabmessages.js] -skip-if = true # Bug 1271177, bug 1262719 -[browser_newtabwebchannel.js] diff --git a/browser/components/newtab/tests/browser/browser_PreviewProvider.js b/browser/components/newtab/tests/browser/browser_PreviewProvider.js deleted file mode 100644 index b1e3eda9f..000000000 --- a/browser/components/newtab/tests/browser/browser_PreviewProvider.js +++ /dev/null @@ -1,90 +0,0 @@ -/* globals XPCOMUtils, Services, PreviewProvider, registerCleanupFunction */ -"use strict"; - -let Cu = Components.utils; -Cu.import("resource://gre/modules/Task.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "PreviewProvider", - "resource:///modules/PreviewProvider.jsm"); - -var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled"); -Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false); - -registerCleanupFunction(function() { - while (gBrowser.tabs.length > 1) { - gBrowser.removeTab(gBrowser.tabs[1]); - } - Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref); -}); - -const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/blue_page.html"; - -function pixelsForDataURI(dataURI, options) { - return new Promise(resolve => { - if (!options) { - options = {}; - } - let {width, height} = options; - if (!width) { - width = 100; - } - if (!height) { - height = 100; - } - - let htmlns = "http://www.w3.org/1999/xhtml"; - let img = document.createElementNS(htmlns, "img"); - img.setAttribute("src", dataURI); - - img.addEventListener("load", function onLoad() { - img.removeEventListener("load", onLoad, true); - let canvas = document.createElementNS(htmlns, "canvas"); - canvas.setAttribute("width", width); - canvas.setAttribute("height", height); - let ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0, width, height); - let result = ctx.getImageData(0, 0, width, height).data; - resolve(result); - }); - }); -} - -function* chunk_four(listData) { - let index = 0; - while (index < listData.length) { - yield listData.slice(index, index + 5); - index += 4; - } -} - -add_task(function* open_page() { - let dataURI = yield PreviewProvider.getThumbnail(TEST_URL); - let pixels = yield pixelsForDataURI(dataURI, {width: 10, height: 10}); - let rgbCount = {r: 0, g: 0, b: 0, a: 0}; - for (let [r, g, b, a] of chunk_four(pixels)) { - if (r === 255) { - rgbCount.r += 1; - } - if (g === 255) { - rgbCount.g += 1; - } - if (b === 255) { - rgbCount.b += 1; - } - if (a === 255) { - rgbCount.a += 1; - } - } - Assert.equal(`${rgbCount.r},${rgbCount.g},${rgbCount.b},${rgbCount.a}`, - "0,0,100,100", "there should be 100 blue-only pixels at full opacity"); -}); - -add_task(function* invalid_url() { - try { - yield PreviewProvider.getThumbnail("invalid:URL"); - } catch (err) { - Assert.ok(true, "URL Failed"); - } -}); diff --git a/browser/components/newtab/tests/browser/browser_newtab_overrides.js b/browser/components/newtab/tests/browser/browser_newtab_overrides.js deleted file mode 100644 index eab9092a0..000000000 --- a/browser/components/newtab/tests/browser/browser_newtab_overrides.js +++ /dev/null @@ -1,139 +0,0 @@ -/* globals - XPCOMUtils, - aboutNewTabService, - Services, - ContentTask, - TestUtils, - BrowserOpenTab, - registerCleanupFunction, - is, - content -*/ - -"use strict"; - -let Cu = Components.utils; -Cu.import("resource://gre/modules/Task.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/Preferences.jsm"); - -XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", - "@mozilla.org/browser/aboutnewtab-service;1", - "nsIAboutNewTabService"); - -registerCleanupFunction(function() { - Services.prefs.setBoolPref("browser.newtabpage.remote", false); - aboutNewTabService.resetNewTabURL(); -}); - -/* - * Tests that the default newtab page is always returned when one types "about:newtab" in the URL bar, - * even when overridden. - */ -add_task(function* redirector_ignores_override() { - let overrides = [ - "chrome://browser/content/downloads/contentAreaDownloadsView.xul", - "about:home", - ]; - - for (let overrideURL of overrides) { - let notificationPromise = nextChangeNotificationPromise(overrideURL, `newtab page now points to ${overrideURL}`); - aboutNewTabService.newTabURL = overrideURL; - - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "url has been overridden"); - - let tabOptions = { - gBrowser, - url: "about:newtab", - }; - - /* - * Simulate typing "about:newtab" in the url bar. - * - * Bug 1240169 - We expect the redirector to lead the user to "about:newtab", the default URL, - * due to invoking AboutRedirector. A user interacting with the chrome otherwise would lead - * to the overriding URLs. - */ - yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) { - yield ContentTask.spawn(browser, {}, function*() { - Assert.equal(content.location.href, "about:newtab", "Got right URL"); - Assert.equal(content.document.location.href, "about:newtab", "Got right URL"); - Assert.equal(content.document.nodePrincipal, - Services.scriptSecurityManager.getSystemPrincipal(), - "nodePrincipal should match systemPrincipal"); - }); - }); // jshint ignore:line - } -}); - -/* - * Tests loading an overridden newtab page by simulating opening a newtab page from chrome - */ -add_task(function* override_loads_in_browser() { - let overrides = [ - "chrome://browser/content/downloads/contentAreaDownloadsView.xul", - "about:home", - " about:home", - ]; - - for (let overrideURL of overrides) { - let notificationPromise = nextChangeNotificationPromise(overrideURL.trim(), `newtab page now points to ${overrideURL}`); - aboutNewTabService.newTabURL = overrideURL; - - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "url has been overridden"); - - // simulate a newtab open as a user would - BrowserOpenTab(); // jshint ignore:line - - let browser = gBrowser.selectedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - yield ContentTask.spawn(browser, {url: overrideURL}, function*(args) { - Assert.equal(content.location.href, args.url.trim(), "Got right URL"); - Assert.equal(content.document.location.href, args.url.trim(), "Got right URL"); - }); // jshint ignore:line - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - } -}); - -/* - * Tests edge cases when someone overrides the newtabpage with whitespace - */ -add_task(function* override_blank_loads_in_browser() { - let overrides = [ - "", - " ", - "\n\t", - " about:blank", - ]; - - for (let overrideURL of overrides) { - let notificationPromise = nextChangeNotificationPromise("about:blank", "newtab page now points to about:blank"); - aboutNewTabService.newTabURL = overrideURL; - - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "url has been overridden"); - - // simulate a newtab open as a user would - BrowserOpenTab(); // jshint ignore:line - - let browser = gBrowser.selectedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - yield ContentTask.spawn(browser, {}, function*() { - Assert.equal(content.location.href, "about:blank", "Got right URL"); - Assert.equal(content.document.location.href, "about:blank", "Got right URL"); - }); // jshint ignore:line - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - } -}); - -function nextChangeNotificationPromise(aNewURL, testMessage) { - return TestUtils.topicObserved("newtab-url-changed", function observer(aSubject, aData) { // jshint unused:false - Assert.equal(aData, aNewURL, testMessage); - return true; - }.bind(this)); -} diff --git a/browser/components/newtab/tests/browser/browser_newtabmessages.js b/browser/components/newtab/tests/browser/browser_newtabmessages.js deleted file mode 100644 index 319ca1c34..000000000 --- a/browser/components/newtab/tests/browser/browser_newtabmessages.js +++ /dev/null @@ -1,222 +0,0 @@ -/* globals Cu, XPCOMUtils, Preferences, is, registerCleanupFunction, NewTabWebChannel, -PlacesTestUtils, NewTabMessages, ok, Services, PlacesUtils, NetUtil, Task */ - -"use strict"; - -Cu.import("resource://gre/modules/Preferences.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/Task.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel", - "resource:///modules/NewTabWebChannel.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "NewTabMessages", - "resource:///modules/NewTabMessages.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); - -let setup = Task.async(function*() { - Preferences.set("browser.newtabpage.enhanced", true); - Preferences.set("browser.newtabpage.remote.mode", "test"); - Preferences.set("browser.newtabpage.remote", true); - NewTabMessages.init(); - yield PlacesTestUtils.clearHistory(); -}); - -let cleanup = Task.async(function*() { - NewTabMessages.uninit(); - Preferences.set("browser.newtabpage.remote", false); - Preferences.set("browser.newtabpage.remote.mode", "production"); -}); -registerCleanupFunction(cleanup); - -/* - * Sanity tests for pref messages - */ -add_task(function* prefMessages_request() { - yield setup(); - - let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_prefs.html"; - - let tabOptions = { - gBrowser, - url: testURL - }; - - let prefResponseAck = new Promise(resolve => { - NewTabWebChannel.once("responseAck", () => { - ok(true, "a request response has been received"); - resolve(); - }); - }); - - yield BrowserTestUtils.withNewTab(tabOptions, function*() { - yield prefResponseAck; - let prefChangeAck = new Promise(resolve => { - NewTabWebChannel.once("responseAck", () => { - ok(true, "a change response has been received"); - resolve(); - }); - }); - Preferences.set("browser.newtabpage.enhanced", false); - yield prefChangeAck; - }); - yield cleanup(); -}); - -/* - * Sanity tests for preview messages - */ -add_task(function* previewMessages_request() { - yield setup(); - var oldEnabledPref = Services.prefs.getBoolPref("browser.pagethumbnails.capturing_disabled"); - Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", false); - - let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_preview.html"; - - let tabOptions = { - gBrowser, - url: testURL - }; - - let previewResponseAck = new Promise(resolve => { - NewTabWebChannel.once("responseAck", () => { - ok(true, "a request response has been received"); - resolve(); - }); - }); - - yield BrowserTestUtils.withNewTab(tabOptions, function*() { - yield previewResponseAck; - }); - yield cleanup(); - Services.prefs.setBoolPref("browser.pagethumbnails.capturing_disabled", oldEnabledPref); -}); - -/* - * Sanity tests for places messages - */ -add_task(function* placesMessages_request() { - yield setup(); - let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_places.html"; - - // url prefix for test history population - const TEST_URL = "https://mozilla.com/"; - // time when the test starts execution - const TIME_NOW = (new Date()).getTime(); - - // utility function to compute past timestamp - function timeDaysAgo(numDays) { - return TIME_NOW - (numDays * 24 * 60 * 60 * 1000); - } - - // utility function to make a visit for insertion into places db - function makeVisit(index, daysAgo, isTyped, domain=TEST_URL) { - let { - TRANSITION_TYPED, - TRANSITION_LINK - } = PlacesUtils.history; - - return { - uri: NetUtil.newURI(`${domain}${index}`), - visitDate: timeDaysAgo(daysAgo), - transition: (isTyped) ? TRANSITION_TYPED : TRANSITION_LINK, - }; - } - - yield PlacesTestUtils.clearHistory(); - - // all four visits must come from different domains to avoid deduplication - let visits = [ - makeVisit(0, 0, true, "http://bar.com/"), // frecency 200, today - makeVisit(1, 0, true, "http://foo.com/"), // frecency 200, today - makeVisit(2, 2, true, "http://buz.com/"), // frecency 200, 2 days ago - makeVisit(3, 2, false, "http://aaa.com/"), // frecency 10, 2 days ago, transition - ]; - - yield PlacesTestUtils.addVisits(visits); - - /** Test Begins **/ - - let tabOptions = { - gBrowser, - url: testURL - }; - - let placesResponseAck = new Promise(resolve => { - NewTabWebChannel.once("numItemsAck", (_, msg) => { - ok(true, "a request response has been received"); - is(msg.data, visits.length + 1, "received an expected number of history items"); - resolve(); - }); - }); - - yield BrowserTestUtils.withNewTab(tabOptions, function*() { - yield placesResponseAck; - ok(true, "a change response has been received"); - let placesChangeAck = new Promise(resolve => { - NewTabWebChannel.once("clearHistoryAck", (_, msg) => { - is(msg.data, "clearHistory", "a clear history message has been received"); - resolve(); - }); - }); - yield PlacesTestUtils.clearHistory(); - yield placesChangeAck; - }); - yield cleanup(); -}); - -/* - * Sanity tests for search messages - */ -add_task(function* searchMessages_request() { - yield setup(); - let testURL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabmessages_search.html"; - - // create dummy test engines - Services.search.addEngineWithDetails("Engine1", "", "", "", "GET", - "http://example.com/?q={searchTerms}"); - Services.search.addEngineWithDetails("Engine2", "", "", "", "GET", - "http://example.com/?q={searchTerms}"); - - let tabOptions = { - gBrowser, - url: testURL - }; - - let UIStringsResponseAck = new Promise(resolve => { - NewTabWebChannel.once("UIStringsAck", (_, msg) => { - ok(true, "a search request response for UI string has been received"); - ok(msg.data, "received the UI Strings"); - resolve(); - }); - }); - let suggestionsResponseAck = new Promise(resolve => { - NewTabWebChannel.once("suggestionsAck", (_, msg) => { - ok(true, "a search request response for suggestions has been received"); - ok(msg.data, "received the suggestions"); - resolve(); - }); - }); - let stateResponseAck = new Promise(resolve => { - NewTabWebChannel.once("stateAck", (_, msg) => { - ok(true, "a search request response for state has been received"); - ok(msg.data, "received a state object"); - resolve(); - }); - }); - let currentEngineResponseAck = new Promise(resolve => { - NewTabWebChannel.once("currentEngineAck", (_, msg) => { - ok(true, "a search request response for current engine has been received"); - ok(msg.data, "received a current engine"); - resolve(); - }); - }); - - yield BrowserTestUtils.withNewTab(tabOptions, function*() { - yield UIStringsResponseAck; - yield suggestionsResponseAck; - yield stateResponseAck; - yield currentEngineResponseAck; - }); - - cleanup(); -}); diff --git a/browser/components/newtab/tests/browser/browser_newtabwebchannel.js b/browser/components/newtab/tests/browser/browser_newtabwebchannel.js deleted file mode 100644 index f003b105b..000000000 --- a/browser/components/newtab/tests/browser/browser_newtabwebchannel.js +++ /dev/null @@ -1,251 +0,0 @@ -/* globals XPCOMUtils, Cu, Preferences, NewTabWebChannel, is, registerCleanupFunction */ - -"use strict"; - -Cu.import("resource://gre/modules/Preferences.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel", - "resource:///modules/NewTabWebChannel.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "NewTabMessages", - "resource:///modules/NewTabMessages.jsm"); - -const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/newtabwebchannel_basic.html"; -const TEST_URL_2 = "http://mochi.test:8888/browser/browser/components/newtab/tests/browser/newtabwebchannel_basic.html"; - -function setup(mode = "test") { - Preferences.set("browser.newtabpage.remote.mode", mode); - Preferences.set("browser.newtabpage.remote", true); - NewTabWebChannel.init(); - NewTabMessages.init(); -} - -function cleanup() { - NewTabMessages.uninit(); - NewTabWebChannel.uninit(); - Preferences.set("browser.newtabpage.remote", false); - Preferences.set("browser.newtabpage.remote.mode", "production"); -} -registerCleanupFunction(cleanup); - -/* - * Tests flow of messages from newtab to chrome and chrome to newtab - */ -add_task(function* open_webchannel_basic() { - setup(); - - let tabOptions = { - gBrowser, - url: TEST_URL - }; - - let messagePromise = new Promise(resolve => { - NewTabWebChannel.once("foo", function(name, msg) { - is(name, "foo", "Correct message type sent: foo"); - is(msg.data, "bar", "Correct data sent: bar"); - resolve(msg.target); - }); - }); - - let replyPromise = new Promise(resolve => { - NewTabWebChannel.once("reply", function(name, msg) { - is(name, "reply", "Correct message type sent: reply"); - is(msg.data, "quuz", "Correct data sent: quuz"); - resolve(msg.target); - }); - }); - - let unloadPromise = new Promise(resolve => { - NewTabWebChannel.once("targetUnload", function(name) { - is(name, "targetUnload", "Correct message type sent: targetUnload"); - resolve(); - }); - }); - - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) { - let target = yield messagePromise; - is(NewTabWebChannel.numBrowsers, 1, "One target expected"); - is(target.browser, browser, "Same browser"); - NewTabWebChannel.send("respond", null, target); - yield replyPromise; - }); - - Cu.forceGC(); - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield unloadPromise; - cleanup(); -}); - -/* - * Tests message broadcast reaches all open newtab pages - */ -add_task(function* webchannel_broadcast() { - setup(); - - let countingMessagePromise = new Promise(resolve => { - let count = 0; - NewTabWebChannel.on("foo", function test_message(name, msg) { - count += 1; - if (count === 2) { - NewTabWebChannel.off("foo", test_message); - resolve(msg.target); - } - }.bind(this)); - }); - - let countingReplyPromise = new Promise(resolve => { - let count = 0; - NewTabWebChannel.on("reply", function test_message(name, msg) { - count += 1; - if (count === 2) { - NewTabWebChannel.off("reply", test_message); - resolve(msg.target); - } - }.bind(this)); - }); - - let countingUnloadPromise = new Promise(resolve => { - let count = 0; - NewTabWebChannel.on("targetUnload", function test_message() { - count += 1; - if (count === 2) { - NewTabWebChannel.off("targetUnload", test_message); - resolve(); - } - }); - }); - - let tabs = []; - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL)); - tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL)); - - yield countingMessagePromise; - is(NewTabWebChannel.numBrowsers, 2, "Two targets expected"); - - NewTabWebChannel.broadcast("respond", null); - yield countingReplyPromise; - - for (let tab of tabs) { - yield BrowserTestUtils.removeTab(tab); - } - Cu.forceGC(); - - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield countingUnloadPromise; - cleanup(); -}); - -/* - * Tests switching modes - */ -add_task(function* webchannel_switch() { - setup(); - - function newMessagePromise() { - return new Promise(resolve => { - NewTabWebChannel.once("foo", function(name, msg) { - resolve(msg.target); - }.bind(this)); - }); - } - - let replyCount = 0; - function newReplyPromise() { - return new Promise(resolve => { - NewTabWebChannel.on("reply", function() { - replyCount += 1; - resolve(); - }); - }); - } - - let unloadPromise = new Promise(resolve => { - NewTabWebChannel.once("targetUnload", function() { - resolve(); - }); - }); - - let unloadAllPromise = new Promise(resolve => { - NewTabWebChannel.once("targetUnloadAll", function() { - resolve(); - }); - }); - - let tabs = []; - let messagePromise; - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - - messagePromise = newMessagePromise(); - tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL)); - yield messagePromise; - is(NewTabWebChannel.numBrowsers, 1, "Correct number of targets"); - - messagePromise = newMessagePromise(); - Preferences.set("browser.newtabpage.remote.mode", "test2"); - tabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL_2)); - yield unloadAllPromise; - yield messagePromise; - is(NewTabWebChannel.numBrowsers, 1, "Correct number of targets"); - - NewTabWebChannel.broadcast("respond", null); - yield newReplyPromise(); - is(replyCount, 1, "only current channel is listened to for replies"); - - const webchannelWhitelistPref = "webchannel.allowObject.urlWhitelist"; - let origWhitelist = Services.prefs.getCharPref(webchannelWhitelistPref); - let newWhitelist = origWhitelist + " http://mochi.test:8888"; - Services.prefs.setCharPref(webchannelWhitelistPref, newWhitelist); - try { - NewTabWebChannel.broadcast("respond_object", null); - yield newReplyPromise(); - } finally { - Services.prefs.clearUserPref(webchannelWhitelistPref); - } - - for (let tab of tabs) { - yield BrowserTestUtils.removeTab(tab); - } - - Cu.forceGC(); - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield unloadPromise; - cleanup(); -}); - -add_task(function* open_webchannel_reload() { - setup(); - - let tabOptions = { - gBrowser, - url: TEST_URL - }; - - let messagePromise = new Promise(resolve => { - NewTabWebChannel.once("foo", function(name, msg) { - is(name, "foo", "Correct message type sent: foo"); - is(msg.data, "bar", "Correct data sent: bar"); - resolve(msg.target); - }); - }); - let unloadPromise = new Promise(resolve => { - NewTabWebChannel.once("targetUnload", function() { - resolve(); - }); - }); - - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield BrowserTestUtils.withNewTab(tabOptions, function*(browser) { - let target = yield messagePromise; - is(NewTabWebChannel.numBrowsers, 1, "One target expected"); - is(target.browser, browser, "Same browser"); - - browser.reload(); - }); - - Cu.forceGC(); - is(NewTabWebChannel.numBrowsers, 0, "Sanity check"); - yield unloadPromise; - cleanup(); -}); diff --git a/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js b/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js deleted file mode 100644 index e99aeffc2..000000000 --- a/browser/components/newtab/tests/browser/browser_remotenewtab_pageloads.js +++ /dev/null @@ -1,52 +0,0 @@ -/* globals Cu, XPCOMUtils, TestUtils, aboutNewTabService, ContentTask, content, is */ -"use strict"; - -Cu.import("resource://gre/modules/Task.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", - "@mozilla.org/browser/aboutnewtab-service;1", - "nsIAboutNewTabService"); - -const TEST_URL = "https://example.com/browser/browser/components/newtab/tests/browser/dummy_page.html"; - -/* - * Tests opening a newtab page with a remote URL. Simulates a newtab open from chrome - */ -add_task(function* open_newtab() { - let notificationPromise = nextChangeNotificationPromise(TEST_URL, "newtab page now points to test url"); - aboutNewTabService.newTabURL = TEST_URL; - - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "url has been overridden"); - - /* - * Simulate a newtab open as a user would. - * - * Bug 1240169 - We cannot set the URL to about:newtab because that would invoke the redirector. - * The redirector always yields the loading of a default newtab URL. We expect the user to use - * the browser UI to access overriding URLs, for istance by click on the "+" button in the tab - * bar, or by using the new tab shortcut key. - */ - BrowserOpenTab(); // jshint ignore:line - - let browser = gBrowser.selectedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - yield ContentTask.spawn(browser, {url: TEST_URL}, function*(args) { - Assert.equal(content.document.location.href, args.url, - "document.location should match the external resource"); - Assert.equal(content.document.documentURI, args.url, - "document.documentURI should match the external resource"); - Assert.equal(content.document.nodePrincipal.URI.spec, args.url, - "nodePrincipal should match the external resource"); - }); - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); -}); - -function nextChangeNotificationPromise(aNewURL, testMessage) { - return TestUtils.topicObserved("newtab-url-changed", function observer(aSubject, aData) { // jshint unused:false - Assert.equal(aData, aNewURL, testMessage); - return true; - }.bind(this)); -} diff --git a/browser/components/newtab/tests/browser/dummy_page.html b/browser/components/newtab/tests/browser/dummy_page.html deleted file mode 100644 index 4b0689bde..000000000 --- a/browser/components/newtab/tests/browser/dummy_page.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> - -<html> -<head> - <meta charset="utf-8"> -</head> -<body> -<p>Dummy Page</p> -</body> -</html> diff --git a/browser/components/newtab/tests/browser/newtabmessages_places.html b/browser/components/newtab/tests/browser/newtabmessages_places.html deleted file mode 100644 index e89bc4a22..000000000 --- a/browser/components/newtab/tests/browser/newtabmessages_places.html +++ /dev/null @@ -1,49 +0,0 @@ -<html> - <head> - <meta charset="utf8"> - <title>Newtab WebChannel test</title> - </head> - <body> - <script> - window.addEventListener("WebChannelMessageToContent", function(e) { - if (e.detail.message) { - let reply; - switch (e.detail.message.type) { - case "RECEIVE_FRECENT": - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "numItemsAck", data: e.detail.message.data.length}), - }) - }); - window.dispatchEvent(reply); - break; - case "RECEIVE_PLACES_CHANGE": - if (e.detail.message.data.type === "clearHistory") { - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "clearHistoryAck", data: e.detail.message.data.type}), - }) - }); - window.dispatchEvent(reply); - } - break; - } - } - }, true); - - document.onreadystatechange = function () { - if (document.readyState === "complete") { - let msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "REQUEST_FRECENT"}), - }) - }); - window.dispatchEvent(msg); - } - } - </script> - </body> -</html> diff --git a/browser/components/newtab/tests/browser/newtabmessages_prefs.html b/browser/components/newtab/tests/browser/newtabmessages_prefs.html deleted file mode 100644 index 9b38af4b9..000000000 --- a/browser/components/newtab/tests/browser/newtabmessages_prefs.html +++ /dev/null @@ -1,32 +0,0 @@ -<html> - <head> - <meta charset="utf8"> - <title>Newtab WebChannel test</title> - </head> - <body> - <script> - window.addEventListener("WebChannelMessageToContent", function(e) { - if (e.detail.message && e.detail.message.type === "RECEIVE_PREFS") { - let reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "responseAck"}), - }) - }); - window.dispatchEvent(reply); - } - }, true); - - document.onreadystatechange = function () { - let msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "REQUEST_PREFS"}), - }) - }); - window.dispatchEvent(msg); - }; - - </script> - </body> -</html> diff --git a/browser/components/newtab/tests/browser/newtabmessages_preview.html b/browser/components/newtab/tests/browser/newtabmessages_preview.html deleted file mode 100644 index 4fe55132d..000000000 --- a/browser/components/newtab/tests/browser/newtabmessages_preview.html +++ /dev/null @@ -1,37 +0,0 @@ -<html> - <head> - <meta charset="utf8"> - <title>Newtab WebChannel test</title> - </head> - <body> - <script> - let thumbURL = "https://example.com/browser/browser/components/newtab/tests/browser/blue_page.html"; - - window.addEventListener("WebChannelMessageToContent", function(e) { - if (e.detail.message && e.detail.message.type === "RECEIVE_THUMB") { - if (e.detail.message.data.imgData && e.detail.message.data.url === thumbURL) { - let reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "responseAck"}), - }) - }); - window.dispatchEvent(reply); - } - } - }, true); - - document.onreadystatechange = function () { - if (document.readyState === "complete") { - let msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "REQUEST_THUMB", data: thumbURL}), - }) - }); - window.dispatchEvent(msg); - } - }; - </script> - </body> -</html> diff --git a/browser/components/newtab/tests/browser/newtabmessages_search.html b/browser/components/newtab/tests/browser/newtabmessages_search.html deleted file mode 100644 index b8b21c42a..000000000 --- a/browser/components/newtab/tests/browser/newtabmessages_search.html +++ /dev/null @@ -1,113 +0,0 @@ -<html> - <head> - <meta charset="utf8"> - <title>Newtab WebChannel test</title> - </head> - <body> - <script> - let suggestionsData = { - engineName: "Engine1", - searchString: "test", - }; - let removeFormHistoryData = "test"; - let performSearchData = { - engineName: "Engine1", - healthReportKey: "1", - searchPurpose: "d", - searchString: "test", - }; - let cycleEngineData = "Engine2"; - - window.addEventListener("WebChannelMessageToContent", function(e) { - if (e.detail.message) { - let reply; - switch (e.detail.message.type) { - case "RECEIVE_UISTRINGS": - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "UIStringsAck", data: e.detail.message.data}), - } - }); - window.dispatchEvent(reply); - break; - case "RECEIVE_SEARCH_SUGGESTIONS": - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "suggestionsAck", data: e.detail.message.data}), - } - }); - window.dispatchEvent(reply); - break; - case "RECEIVE_SEARCH_STATE": - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "stateAck", data: e.detail.message.data}), - } - }); - window.dispatchEvent(reply); - break; - case "RECEIVE_CURRENT_ENGINE": - reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "currentEngineAck", data: e.detail.message.data}), - } - }); - window.dispatchEvent(reply); - break; - } - } - }, true); - - document.onreadystatechange = function () { - if (document.readyState === "complete") { - let msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_UISTRINGS"}), - } - }); - window.dispatchEvent(msg); - msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_SEARCH_SUGGESTIONS", data: suggestionsData}), - } - }); - window.dispatchEvent(msg); - msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_SEARCH_STATE"}), - } - }); - window.dispatchEvent(msg); - msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_REMOVE_FORM_HISTORY", data: removeFormHistoryData}), - } - }); - window.dispatchEvent(msg); - msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_PERFORM_SEARCH", data: performSearchData}), - } - }); - window.dispatchEvent(msg); - msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: { - id: "newtab", - message: JSON.stringify({type: "REQUEST_CYCLE_ENGINE", data: cycleEngineData}), - } - }); - window.dispatchEvent(msg); - } - } - </script> - </body> -</html> diff --git a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html b/browser/components/newtab/tests/browser/newtabwebchannel_basic.html deleted file mode 100644 index 7f3c79920..000000000 --- a/browser/components/newtab/tests/browser/newtabwebchannel_basic.html +++ /dev/null @@ -1,36 +0,0 @@ -<html> - <head> - <meta charset="utf8"> - <title>Newtab WebChannel test</title> - </head> - <body> - <script> - document.onreadystatechange = function () { - let msg = new window.CustomEvent("WebChannelMessageToChrome", { - detail: JSON.stringify({ - id: "newtab", - message: JSON.stringify({type: "foo", data: "bar"}), - }) - }); - window.dispatchEvent(msg); - }; - - window.addEventListener("WebChannelMessageToContent", function(e) { - if (e.detail.message && e.detail.message.type.startsWith("respond")) { - var detail = { - id: "newtab", - message: JSON.stringify({type: "reply", data: "quuz"}), - }; - if (e.detail.message.type !== "respond_object") { - detail = JSON.stringify(detail); - } - let reply = new window.CustomEvent("WebChannelMessageToChrome", { - detail: detail - }); - window.dispatchEvent(reply); - } - }, true); - - </script> - </body> -</html> diff --git a/browser/components/newtab/tests/xpcshell/.eslintrc.js b/browser/components/newtab/tests/xpcshell/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/newtab/tests/xpcshell/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js b/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js deleted file mode 100644 index 21f68ab70..000000000 --- a/browser/components/newtab/tests/xpcshell/test_AboutNewTabService.js +++ /dev/null @@ -1,236 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -/* globals Services, XPCOMUtils, NewTabPrefsProvider, Preferences, aboutNewTabService, do_register_cleanup */ - -"use strict"; - -const {utils: Cu} = Components; -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Preferences.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider", - "resource:///modules/NewTabPrefsProvider.jsm"); - -XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", - "@mozilla.org/browser/aboutnewtab-service;1", - "nsIAboutNewTabService"); - -XPCOMUtils.defineLazyModuleGetter(this, "Locale", - "resource://gre/modules/Locale.jsm"); - -const DEFAULT_HREF = aboutNewTabService.generateRemoteURL(); -const DEFAULT_CHROME_URL = "chrome://browser/content/newtab/newTab.xhtml"; -const DOWNLOADS_URL = "chrome://browser/content/downloads/contentAreaDownloadsView.xul"; -const DEFAULT_VERSION = aboutNewTabService.remoteVersion; - -function cleanup() { - Services.prefs.setBoolPref("browser.newtabpage.remote", false); - Services.prefs.setCharPref("browser.newtabpage.remote.version", DEFAULT_VERSION); - aboutNewTabService.resetNewTabURL(); - NewTabPrefsProvider.prefs.uninit(); -} - -do_register_cleanup(cleanup); - -/** - * Test the overriding of the default URL - */ -add_task(function* test_override_remote_disabled() { - NewTabPrefsProvider.prefs.init(); - let notificationPromise; - Services.prefs.setBoolPref("browser.newtabpage.remote", false); - - // tests default is the local newtab resource - Assert.equal(aboutNewTabService.defaultURL, DEFAULT_CHROME_URL, - `Default newtab URL should be ${DEFAULT_CHROME_URL}`); - - // override with some remote URL - let url = "http://example.com/"; - notificationPromise = nextChangeNotificationPromise(url); - aboutNewTabService.newTabURL = url; - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden"); - Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled"); - Assert.equal(aboutNewTabService.newTabURL, url, "Newtab URL should be the custom URL"); - - // test reset with remote disabled - notificationPromise = nextChangeNotificationPromise("about:newtab"); - aboutNewTabService.resetNewTabURL(); - yield notificationPromise; - Assert.ok(!aboutNewTabService.overridden, "Newtab URL should not be overridden"); - Assert.equal(aboutNewTabService.newTabURL, "about:newtab", "Newtab URL should be the default"); - - // test override to a chrome URL - notificationPromise = nextChangeNotificationPromise(DOWNLOADS_URL); - aboutNewTabService.newTabURL = DOWNLOADS_URL; - yield notificationPromise; - Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden"); - Assert.equal(aboutNewTabService.newTabURL, DOWNLOADS_URL, "Newtab URL should be the custom URL"); - - cleanup(); -}); - -add_task(function* test_override_remote_enabled() { - NewTabPrefsProvider.prefs.init(); - let notificationPromise; - // change newtab page to remote - notificationPromise = nextChangeNotificationPromise("about:newtab"); - Services.prefs.setBoolPref("browser.newtabpage.remote", true); - yield notificationPromise; - let remoteHref = aboutNewTabService.generateRemoteURL(); - Assert.equal(aboutNewTabService.defaultURL, remoteHref, "Newtab URL should be the default remote URL"); - Assert.ok(!aboutNewTabService.overridden, "Newtab URL should not be overridden"); - Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled"); - - // change to local newtab page while remote is enabled - notificationPromise = nextChangeNotificationPromise(DEFAULT_CHROME_URL); - aboutNewTabService.newTabURL = DEFAULT_CHROME_URL; - yield notificationPromise; - Assert.equal(aboutNewTabService.newTabURL, DEFAULT_CHROME_URL, - "Newtab URL set to chrome url"); - Assert.equal(aboutNewTabService.defaultURL, DEFAULT_CHROME_URL, - "Newtab URL defaultURL set to the default chrome URL"); - Assert.ok(aboutNewTabService.overridden, "Newtab URL should be overridden"); - Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled"); - - cleanup(); -}); - -/** - * Tests reponse to updates to prefs - */ -add_task(function* test_updates() { - /* - * Simulates a "cold-boot" situation, with some pref already set before testing a series - * of changes. - */ - Preferences.set("browser.newtabpage.remote", true); - aboutNewTabService.resetNewTabURL(); // need to set manually because pref notifs are off - let notificationPromise; - let productionModeBaseUrl = "https://content.cdn.mozilla.net"; - let testModeBaseUrl = "https://example.com"; - let expectedPath = `/newtab` + - `/v${aboutNewTabService.remoteVersion}` + - `/${aboutNewTabService.remoteReleaseName}` + - "/en-GB" + - "/index.html"; - let expectedHref = productionModeBaseUrl + expectedPath; - Preferences.set("intl.locale.matchOS", true); - Preferences.set("general.useragent.locale", "en-GB"); - Preferences.set("browser.newtabpage.remote.mode", "production"); - NewTabPrefsProvider.prefs.init(); - - // test update checks for prefs - notificationPromise = nextChangeNotificationPromise( - expectedHref, "Remote href should be updated"); - Preferences.set("intl.locale.matchOS", false); - yield notificationPromise; - - notificationPromise = nextChangeNotificationPromise( - DEFAULT_HREF, "Remote href changes back to default"); - Preferences.set("general.useragent.locale", "en-US"); - yield notificationPromise; - - // test update fires when mode is changed - expectedPath = expectedPath.replace("/en-GB/", "/en-US/"); - notificationPromise = nextChangeNotificationPromise( - testModeBaseUrl + expectedPath, "Remote href changes back to origin of test mode"); - Preferences.set("browser.newtabpage.remote.mode", "test"); - yield notificationPromise; - - // test invalid mode ends up pointing to production url - notificationPromise = nextChangeNotificationPromise( - DEFAULT_HREF, "Remote href changes back to production default"); - Preferences.set("browser.newtabpage.remote.mode", "invalid"); - yield notificationPromise; - - // test update fires on override and reset - let testURL = "https://example.com/"; - notificationPromise = nextChangeNotificationPromise( - testURL, "a notification occurs on override"); - aboutNewTabService.newTabURL = testURL; - yield notificationPromise; - - // from overridden to default - notificationPromise = nextChangeNotificationPromise( - "about:newtab", "a notification occurs on reset"); - aboutNewTabService.resetNewTabURL(); - Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled"); - Assert.equal(aboutNewTabService.defaultURL, DEFAULT_HREF, "Default URL should be the remote page"); - yield notificationPromise; - - // override to default URL from default URL - notificationPromise = nextChangeNotificationPromise( - testURL, "a notification only occurs for a change in overridden urls"); - aboutNewTabService.newTabURL = aboutNewTabService.generateRemoteURL(); - Assert.ok(aboutNewTabService.remoteEnabled, "Newtab remote should be enabled"); - aboutNewTabService.newTabURL = testURL; - yield notificationPromise; - Assert.ok(!aboutNewTabService.remoteEnabled, "Newtab remote should not be enabled"); - - // reset twice, only one notification for default URL - notificationPromise = nextChangeNotificationPromise( - "about:newtab", "reset occurs"); - aboutNewTabService.resetNewTabURL(); - yield notificationPromise; - - cleanup(); -}); - -/** - * Verifies that releaseFromUpdateChannel - * Returns the correct release names - */ -add_task(function* test_release_names() { - let valid_channels = ["esr", "release", "beta", "aurora", "nightly"]; - let invalid_channels = new Set(["default", "invalid"]); - - for (let channel of valid_channels) { - Assert.equal(channel, aboutNewTabService.releaseFromUpdateChannel(channel), - "release == channel name when valid"); - } - - for (let channel of invalid_channels) { - Assert.equal("nightly", aboutNewTabService.releaseFromUpdateChannel(channel), - "release == nightly when invalid"); - } -}); - -/** - * Verifies that remote version updates changes the remote newtab url - */ -add_task(function* test_version_update() { - NewTabPrefsProvider.prefs.init(); - - Services.prefs.setBoolPref("browser.newtabpage.remote", true); - Assert.ok(aboutNewTabService.remoteEnabled, "remote mode enabled"); - - let productionModeBaseUrl = "https://content.cdn.mozilla.net"; - let version_incr = String(parseInt(DEFAULT_VERSION) + 1); - let expectedPath = `/newtab` + - `/v${version_incr}` + - `/${aboutNewTabService.remoteReleaseName}` + - `/${Locale.getLocale()}` + - `/index.html`; - let expectedHref = productionModeBaseUrl + expectedPath; - - let notificationPromise; - notificationPromise = nextChangeNotificationPromise(expectedHref); - Preferences.set("browser.newtabpage.remote.version", version_incr); - yield notificationPromise; - - cleanup(); -}); - -function nextChangeNotificationPromise(aNewURL, testMessage) { - return new Promise(resolve => { - Services.obs.addObserver(function observer(aSubject, aTopic, aData) { // jshint unused:false - Services.obs.removeObserver(observer, aTopic); - Assert.equal(aData, aNewURL, testMessage); - resolve(); - }, "newtab-url-changed", false); - }); -} diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js b/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js deleted file mode 100644 index f364d0300..000000000 --- a/browser/components/newtab/tests/xpcshell/test_NewTabPrefsProvider.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -/* global XPCOMUtils, equal, Preferences, NewTabPrefsProvider, run_next_test */ -/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ - -const Cu = Components.utils; -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Preferences.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider", - "resource:///modules/NewTabPrefsProvider.jsm"); - -function run_test() { - run_next_test(); -} - -add_task(function* test_observe() { - let prefsMap = NewTabPrefsProvider.prefs.prefsMap; - for (let prefName of prefsMap.keys()) { - let prefValueType = prefsMap.get(prefName); - - let beforeVal; - let afterVal; - - switch (prefValueType) { - case "bool": - beforeVal = false; - afterVal = true; - Preferences.set(prefName, beforeVal); - break; - case "localized": - case "str": - beforeVal = ""; - afterVal = "someStr"; - Preferences.set(prefName, beforeVal); - break; - } - NewTabPrefsProvider.prefs.init(); - let promise = new Promise(resolve => { - NewTabPrefsProvider.prefs.once(prefName, (name, data) => { // jshint ignore:line - resolve([name, data]); - }); - }); - Preferences.set(prefName, afterVal); - let [actualName, actualData] = yield promise; - equal(prefName, actualName, `emitter sent the correct pref: ${prefName}`); - equal(afterVal, actualData, `emitter collected correct pref data for ${prefName}`); - NewTabPrefsProvider.prefs.uninit(); - } -}); diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js b/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js deleted file mode 100644 index 3e60b282a..000000000 --- a/browser/components/newtab/tests/xpcshell/test_NewTabSearchProvider.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; - -/* global XPCOMUtils, NewTabSearchProvider, run_next_test, ok, equal, do_check_true, do_get_profile, Services */ -/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ - -const Cu = Components.utils; -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "NewTabSearchProvider", - "resource:///modules/NewTabSearchProvider.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "ContentSearch", - "resource:///modules/ContentSearch.jsm"); - -// ensure a profile exists -do_get_profile(); - -function run_test() { - run_next_test(); -} - -function hasProp(obj) { - return function(aProp) { - ok(obj.hasOwnProperty(aProp), `expect to have property ${aProp}`); - }; -} - -add_task(function* test_search() { - ContentSearch.init(); - let observerPromise = new Promise(resolve => { - Services.obs.addObserver(function observer(aSubject, aTopic, aData) { - if (aData === "init-complete" && aTopic === "browser-search-service") { - Services.obs.removeObserver(observer, "browser-search-service"); - resolve(); - } - }, "browser-search-service", false); - }); - Services.search.init(); - yield observerPromise; - do_check_true(Services.search.isInitialized); - - // get initial state of search and check it has correct properties - let state = yield NewTabSearchProvider.search.asyncGetState(); - let stateProps = hasProp(state); - ["engines", "currentEngine"].forEach(stateProps); - - // check that the current engine is correct and has correct properties - let {currentEngine} = state; - equal(currentEngine.name, Services.search.currentEngine.name, "Current engine has been correctly set"); - var engineProps = hasProp(currentEngine); - ["name", "placeholder", "iconBuffer"].forEach(engineProps); - - // create dummy test engines to test observer - Services.search.addEngineWithDetails("TestSearch1", "", "", "", "GET", - "http://example.com/?q={searchTerms}"); - Services.search.addEngineWithDetails("TestSearch2", "", "", "", "GET", - "http://example.com/?q={searchTerms}"); - - // set one of the dummy test engines to the default engine - Services.search.defaultEngine = Services.search.getEngineByName("TestSearch1"); - - // test that the event emitter is working by setting a new current engine "TestSearch2" - let engineName = "TestSearch2"; - NewTabSearchProvider.search.init(); - - // event emitter will fire when current engine is changed - let promise = new Promise(resolve => { - NewTabSearchProvider.search.once("browser-search-engine-modified", (name, data) => { // jshint ignore:line - resolve([name, data.name]); - }); - }); - - // set a new current engine - Services.search.currentEngine = Services.search.getEngineByName(engineName); - let expectedEngineName = Services.search.currentEngine.name; - - // emitter should fire and return the new engine - let [eventName, actualEngineName] = yield promise; - equal(eventName, "browser-search-engine-modified", `emitter sent the correct event ${eventName}`); - equal(expectedEngineName, actualEngineName, `emitter set the correct engine ${expectedEngineName}`); - NewTabSearchProvider.search.uninit(); -}); diff --git a/browser/components/newtab/tests/xpcshell/test_NewTabURL.js b/browser/components/newtab/tests/xpcshell/test_NewTabURL.js deleted file mode 100644 index 1505e638c..000000000 --- a/browser/components/newtab/tests/xpcshell/test_NewTabURL.js +++ /dev/null @@ -1,52 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -/* globals Services, NewTabURL, XPCOMUtils, aboutNewTabService, NewTabPrefsProvider */ -"use strict"; - -const {utils: Cu} = Components; -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource:///modules/NewTabURL.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider", - "resource:///modules/NewTabPrefsProvider.jsm"); -XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", - "@mozilla.org/browser/aboutnewtab-service;1", - "nsIAboutNewTabService"); - -add_task(function*() { - let defaultURL = aboutNewTabService.newTabURL; - Services.prefs.setBoolPref("browser.newtabpage.remote", false); - - Assert.equal(NewTabURL.get(), defaultURL, `Default newtab URL should be ${defaultURL}`); - let url = "http://example.com/"; - let notificationPromise = promiseNewtabURLNotification(url); - NewTabURL.override(url); - yield notificationPromise; - Assert.ok(NewTabURL.overridden, "Newtab URL should be overridden"); - Assert.equal(NewTabURL.get(), url, "Newtab URL should be the custom URL"); - - notificationPromise = promiseNewtabURLNotification(defaultURL); - NewTabURL.reset(); - yield notificationPromise; - Assert.ok(!NewTabURL.overridden, "Newtab URL should not be overridden"); - Assert.equal(NewTabURL.get(), defaultURL, "Newtab URL should be the default"); - - // change newtab page to remote - NewTabPrefsProvider.prefs.init(); - Services.prefs.setBoolPref("browser.newtabpage.remote", true); - Assert.equal(NewTabURL.get(), "about:newtab", `Newtab URL should be about:newtab`); - Assert.ok(!NewTabURL.overridden, "Newtab URL should not be overridden"); - NewTabPrefsProvider.prefs.uninit(); -}); - -function promiseNewtabURLNotification(aNewURL) { - return new Promise(resolve => { - Services.obs.addObserver(function observer(aSubject, aTopic, aData) { // jshint ignore:line - Services.obs.removeObserver(observer, aTopic); - Assert.equal(aData, aNewURL, "Data for newtab-url-changed notification should be new URL."); - resolve(); - }, "newtab-url-changed", false); - }); -} diff --git a/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js b/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js deleted file mode 100644 index 22815741b..000000000 --- a/browser/components/newtab/tests/xpcshell/test_PlacesProvider.js +++ /dev/null @@ -1,358 +0,0 @@ -"use strict"; - -/* global XPCOMUtils, PlacesUtils, PlacesTestUtils, PlacesProvider, NetUtil */ -/* global do_get_profile, run_next_test, add_task */ -/* global equal, ok */ - -const { - utils: Cu, - interfaces: Ci, -} = Components; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesProvider", - "resource:///modules/PlacesProvider.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", - "resource://gre/modules/PlacesUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm"); - -// ensure a profile exists -do_get_profile(); - -function run_test() { - PlacesProvider.links.init(); - run_next_test(); -} - -// url prefix for test history population -const TEST_URL = "https://mozilla.com/"; -// time when the test starts execution -const TIME_NOW = (new Date()).getTime(); - -// utility function to compute past timestap -function timeDaysAgo(numDays) { - return TIME_NOW - (numDays * 24 * 60 * 60 * 1000); -} - -// utility function to make a visit for insetion into places db -function makeVisit(index, daysAgo, isTyped, domain=TEST_URL) { - let { - TRANSITION_TYPED, - TRANSITION_LINK - } = PlacesUtils.history; - - return { - uri: NetUtil.newURI(`${domain}${index}`), - visitDate: timeDaysAgo(daysAgo), - transition: (isTyped) ? TRANSITION_TYPED : TRANSITION_LINK, - }; -} - -/** Test LinkChecker **/ - -add_task(function test_LinkChecker_securityCheck() { - - let urls = [ - {url: "javascript:alert('hello')", expected: false}, // jshint ignore:line - {url: "data:image/png;base64,XXX", expected: false}, - {url: "about:newtab", expected: true}, - {url: "https://example.com", expected: true}, - {url: "ftp://example.com", expected: true}, - {url: "file://home/file/image.png", expected: true}, - {url: "resource:///modules/PlacesProvider.jsm", expected: true}, - ]; - for (let {url, expected} of urls) { - let observed = PlacesProvider.LinkChecker.checkLoadURI(url); - equal(observed, expected, `can load "${url}"?`); - } -}); - -/** Test Provider **/ - -add_task(function* test_Links_getLinks() { - yield PlacesTestUtils.clearHistory(); - let provider = PlacesProvider.links; - - let links = yield provider.getLinks(); - equal(links.length, 0, "empty history yields empty links"); - - // add a visit - let testURI = NetUtil.newURI("http://mozilla.com"); - yield PlacesTestUtils.addVisits(testURI); - - links = yield provider.getLinks(); - equal(links.length, 1, "adding a visit yields a link"); - equal(links[0].url, testURI.spec, "added visit corresponds to added url"); -}); - -add_task(function* test_Links_getLinks_Order() { - yield PlacesTestUtils.clearHistory(); - let provider = PlacesProvider.links; - - // all four visits must come from different domains to avoid deduplication - let visits = [ - makeVisit(0, 0, true, "http://bar.com/"), // frecency 200, today - makeVisit(1, 0, true, "http://foo.com/"), // frecency 200, today - makeVisit(2, 2, true, "http://buz.com/"), // frecency 200, 2 days ago - makeVisit(3, 2, false, "http://aaa.com/"), // frecency 10, 2 days ago, transition - ]; - - let links = yield provider.getLinks(); - equal(links.length, 0, "empty history yields empty links"); - yield PlacesTestUtils.addVisits(visits); - - links = yield provider.getLinks(); - equal(links.length, visits.length, "number of links added is the same as obtain by getLinks"); - for (let i = 0; i < links.length; i++) { - equal(links[i].url, visits[i].uri.spec, "links are obtained in the expected order"); - } -}); - -add_task(function* test_Links_getLinks_Deduplication() { - yield PlacesTestUtils.clearHistory(); - let provider = PlacesProvider.links; - - // all for visits must come from different domains to avoid deduplication - let visits = [ - makeVisit(0, 2, true, "http://bar.com/"), // frecency 200, 2 days ago - makeVisit(1, 0, true, "http://bar.com/"), // frecency 200, today - makeVisit(2, 0, false, "http://foo.com/"), // frecency 10, today - makeVisit(3, 0, true, "http://foo.com/"), // frecency 200, today - ]; - - let links = yield provider.getLinks(); - equal(links.length, 0, "empty history yields empty links"); - yield PlacesTestUtils.addVisits(visits); - - links = yield provider.getLinks(); - equal(links.length, 2, "only two links must be left after deduplication"); - equal(links[0].url, visits[1].uri.spec, "earliest link is present"); - equal(links[1].url, visits[3].uri.spec, "most fresent link is present"); -}); - -add_task(function* test_Links_onLinkChanged() { - let provider = PlacesProvider.links; - - let url = "https://example.com/onFrecencyChanged1"; - let linkChangedMsgCount = 0; - - let linkChangedPromise = new Promise(resolve => { - let handler = (_, link) => { // jshint ignore:line - /* There are 3 linkChanged events: - * 1. visit insertion (-1 frecency by default) - * 2. frecency score update (after transition type calculation etc) - * 3. title change - */ - if (link.url === url) { - equal(link.url, url, `expected url on linkChanged event`); - linkChangedMsgCount += 1; - if (linkChangedMsgCount === 3) { - ok(true, `all linkChanged events captured`); - provider.off("linkChanged", this); - resolve(); - } - } - }; - provider.on("linkChanged", handler); - }); - - // add a visit - let testURI = NetUtil.newURI(url); - yield PlacesTestUtils.addVisits(testURI); - yield linkChangedPromise; - - yield PlacesTestUtils.clearHistory(); -}); - -add_task(function* test_Links_onClearHistory() { - let provider = PlacesProvider.links; - - let clearHistoryPromise = new Promise(resolve => { - let handler = () => { - ok(true, `clearHistory event captured`); - provider.off("clearHistory", handler); - resolve(); - }; - provider.on("clearHistory", handler); - }); - - // add visits - for (let i = 0; i <= 10; i++) { - let url = `https://example.com/onClearHistory${i}`; - let testURI = NetUtil.newURI(url); - yield PlacesTestUtils.addVisits(testURI); - } - yield PlacesTestUtils.clearHistory(); - yield clearHistoryPromise; -}); - -add_task(function* test_Links_onDeleteURI() { - let provider = PlacesProvider.links; - - let testURL = "https://example.com/toDelete"; - - let deleteURIPromise = new Promise(resolve => { - let handler = (_, {url}) => { // jshint ignore:line - equal(testURL, url, "deleted url and expected url are the same"); - provider.off("deleteURI", handler); - resolve(); - }; - - provider.on("deleteURI", handler); - }); - - let testURI = NetUtil.newURI(testURL); - yield PlacesTestUtils.addVisits(testURI); - yield PlacesUtils.history.remove(testURL); - yield deleteURIPromise; -}); - -add_task(function* test_Links_onManyLinksChanged() { - let provider = PlacesProvider.links; - - let promise = new Promise(resolve => { - let handler = () => { - ok(true); - provider.off("manyLinksChanged", handler); - resolve(); - }; - - provider.on("manyLinksChanged", handler); - }); - - let testURL = "https://example.com/toDelete"; - let testURI = NetUtil.newURI(testURL); - yield PlacesTestUtils.addVisits(testURI); - - // trigger DecayFrecency - PlacesUtils.history.QueryInterface(Ci.nsIObserver). - observe(null, "idle-daily", ""); - - yield promise; -}); - -add_task(function* test_Links_execute_query() { - yield PlacesTestUtils.clearHistory(); - let provider = PlacesProvider.links; - - let visits = [ - makeVisit(0, 0, true), // frecency 200, today - makeVisit(1, 0, true), // frecency 200, today - makeVisit(2, 2, true), // frecency 200, 2 days ago - makeVisit(3, 2, false), // frecency 10, 2 days ago, transition - ]; - - yield PlacesTestUtils.addVisits(visits); - - function testItemValue(results, index, value) { - equal(results[index][0], `${TEST_URL}${value}`, "raw url"); - equal(results[index][1], `test visit for ${TEST_URL}${value}`, "raw title"); - } - - function testItemObject(results, index, columnValues) { - Object.keys(columnValues).forEach(name => { - equal(results[index][name], columnValues[name], "object name " + name); - }); - } - - // select all 4 records - let results = yield provider.executePlacesQuery("select url, title from moz_places"); - equal(results.length, 4, "expect 4 items"); - // check for insert order sequence - for (let i = 0; i < results.length; i++) { - testItemValue(results, i, i); - } - - // test parameter passing - results = yield provider.executePlacesQuery( - "select url, title from moz_places limit :limit", - {params: {limit: 2}} - ); - equal(results.length, 2, "expect 2 items"); - for (let i = 0; i < results.length; i++) { - testItemValue(results, i, i); - } - - // test extracting items by name - results = yield provider.executePlacesQuery( - "select url, title from moz_places limit :limit", - {columns: ["url", "title"], params: {limit: 4}} - ); - equal(results.length, 4, "expect 4 items"); - for (let i = 0; i < results.length; i++) { - testItemObject(results, i, { - "url": `${TEST_URL}${i}`, - "title": `test visit for ${TEST_URL}${i}`, - }); - } - - // test ordering - results = yield provider.executePlacesQuery( - "select url, title, last_visit_date, frecency from moz_places " + - "order by frecency DESC, last_visit_date DESC, url DESC limit :limit", - {columns: ["url", "title", "last_visit_date", "frecency"], params: {limit: 4}} - ); - equal(results.length, 4, "expect 4 items"); - testItemObject(results, 0, {url: `${TEST_URL}1`}); - testItemObject(results, 1, {url: `${TEST_URL}0`}); - testItemObject(results, 2, {url: `${TEST_URL}2`}); - testItemObject(results, 3, {url: `${TEST_URL}3`}); - - // test callback passing - results = []; - function handleRow(aRow) { - results.push({ - url: aRow.getResultByName("url"), - title: aRow.getResultByName("title"), - last_visit_date: aRow.getResultByName("last_visit_date"), - frecency: aRow.getResultByName("frecency") - }); - } - yield provider.executePlacesQuery( - "select url, title, last_visit_date, frecency from moz_places " + - "order by frecency DESC, last_visit_date DESC, url DESC", - {callback: handleRow} - ); - equal(results.length, 4, "expect 4 items"); - testItemObject(results, 0, {url: `${TEST_URL}1`}); - testItemObject(results, 1, {url: `${TEST_URL}0`}); - testItemObject(results, 2, {url: `${TEST_URL}2`}); - testItemObject(results, 3, {url: `${TEST_URL}3`}); - - // negative test cases - // bad sql - try { - yield provider.executePlacesQuery("select from moz"); - do_throw("bad sql should've thrown"); - } - catch (e) { - do_check_true("expected failure - bad sql"); - } - // missing bindings - try { - yield provider.executePlacesQuery("select * from moz_places limit :limit"); - do_throw("bad sql should've thrown"); - } - catch (e) { - do_check_true("expected failure - missing bidning"); - } - // non-existent column name - try { - yield provider.executePlacesQuery("select * from moz_places limit :limit", - {columns: ["no-such-column"], params: {limit: 4}}); - do_throw("bad sql should've thrown"); - } - catch (e) { - do_check_true("expected failure - wrong column name"); - } - - // cleanup - yield PlacesTestUtils.clearHistory(); -}); diff --git a/browser/components/newtab/tests/xpcshell/xpcshell.ini b/browser/components/newtab/tests/xpcshell/xpcshell.ini deleted file mode 100644 index c249ee3e2..000000000 --- a/browser/components/newtab/tests/xpcshell/xpcshell.ini +++ /dev/null @@ -1,11 +0,0 @@ -[DEFAULT] -head = -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_AboutNewTabService.js] -[test_NewTabPrefsProvider.js] -[test_NewTabSearchProvider.js] -[test_NewTabURL.js] -[test_PlacesProvider.js] diff --git a/browser/components/originattributes/moz.build b/browser/components/originattributes/moz.build deleted file mode 100644 index ea5943ea1..000000000 --- a/browser/components/originattributes/moz.build +++ /dev/null @@ -1,16 +0,0 @@ -# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# 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/. - -BROWSER_CHROME_MANIFESTS += [ - 'test/browser/browser.ini', -] - -MOCHITEST_MANIFESTS += [ - 'test/mochitest/mochitest.ini' -] - -with Files('**'): - BUG_COMPONENT = ('Firefox', 'OriginAttributes') diff --git a/browser/components/originattributes/test/browser/.eslintrc.js b/browser/components/originattributes/test/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/originattributes/test/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/originattributes/test/browser/browser.ini b/browser/components/originattributes/test/browser/browser.ini deleted file mode 100644 index 61f674377..000000000 --- a/browser/components/originattributes/test/browser/browser.ini +++ /dev/null @@ -1,64 +0,0 @@ -[DEFAULT] -tags = usercontextid firstpartyisolation originattributes -support-files = - dummy.html - file_broadcastChannel.html - file_broadcastChanneliFrame.html - file_cache.html - file_favicon.html - file_favicon.png - file_favicon.png^headers^ - file_favicon_cache.html - file_favicon_cache.png - file_favicon_thirdParty.html - file_firstPartyBasic.html - file_sharedworker.html - file_sharedworker.js - file_thirdPartyChild.audio.ogg - file_thirdPartyChild.embed.png - file_thirdPartyChild.fetch.html - file_thirdPartyChild.iframe.html - file_thirdPartyChild.img.png - file_thirdPartyChild.import.js - file_thirdPartyChild.link.css - file_thirdPartyChild.object.png - file_thirdPartyChild.request.html - file_thirdPartyChild.script.js - file_thirdPartyChild.sharedworker.js - file_thirdPartyChild.track.vtt - file_thirdPartyChild.video.ogv - file_thirdPartyChild.worker.fetch.html - file_thirdPartyChild.worker.js - file_thirdPartyChild.worker.request.html - file_thirdPartyChild.worker.xhr.html - file_thirdPartyChild.xhr.html - head.js - test.js - test.js^headers^ - test.html - test2.html - test2.js - test2.js^headers^ - test_firstParty.html - test_firstParty_cookie.html - test_firstParty_html_redirect.html - test_firstParty_http_redirect.html - test_firstParty_http_redirect.html^headers^ - test_firstParty_iframe_http_redirect.html - test_firstParty_postMessage.html - window.html - worker_blobify.js - worker_deblobify.js - -[browser_broadcastChannel.js] -[browser_cache.js] -[browser_cookieIsolation.js] -[browser_favicon_firstParty.js] -[browser_favicon_userContextId.js] -[browser_firstPartyIsolation.js] -[browser_localStorageIsolation.js] -[browser_blobURLIsolation.js] -[browser_imageCacheIsolation.js] -[browser_sharedworker.js] -[browser_httpauth.js] -[browser_clientAuth.js] diff --git a/browser/components/originattributes/test/browser/browser_blobURLIsolation.js b/browser/components/originattributes/test/browser/browser_blobURLIsolation.js deleted file mode 100644 index 1d1b7c8e1..000000000 --- a/browser/components/originattributes/test/browser/browser_blobURLIsolation.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Bug 1264573 - A test case for blob url isolation. - */ - -const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" + - "originattributes/test/browser/file_firstPartyBasic.html"; -const SCRIPT_WORKER_BLOBIFY = "worker_blobify.js"; -const SCRIPT_WORKER_DEBLOBIFY = "worker_deblobify.js"; - -function page_blobify(browser, input) { - return ContentTask.spawn(browser, input, function(input) { - return { blobURL: content.URL.createObjectURL(new content.Blob([input])) }; - }); -} - -function page_deblobify(browser, blobURL) { - return ContentTask.spawn(browser, blobURL, function* (blobURL) { - if ("error" in blobURL) { - return blobURL; - } - blobURL = blobURL.blobURL; - - function blobURLtoBlob(blobURL) { - return new content.Promise(function (resolve) { - let xhr = new content.XMLHttpRequest(); - xhr.open("GET", blobURL, true); - xhr.onload = function () { - resolve(xhr.response); - }; - xhr.onerror = function () { - resolve("xhr error"); - }; - xhr.responseType = "blob"; - xhr.send(); - }); - } - - function blobToString(blob) { - return new content.Promise(function (resolve) { - let fileReader = new content.FileReader(); - fileReader.onload = function () { - resolve(fileReader.result); - }; - fileReader.readAsText(blob); - }); - } - - let blob = yield blobURLtoBlob(blobURL); - if (blob == "xhr error") { - return "xhr error"; - } - - return yield blobToString(blob); - }); -} - -function workerIO(browser, scriptFile, message) { - return ContentTask.spawn(browser, {scriptFile, message}, function* (args) { - let worker = new content.Worker(args.scriptFile); - let promise = new content.Promise(function(resolve) { - let listenFunction = function(event) { - worker.removeEventListener("message", listenFunction, false); - worker.terminate(); - resolve(event.data); - }; - worker.addEventListener("message", listenFunction, false); - }); - worker.postMessage(args.message); - return yield promise; - }); -} - -let worker_blobify = (browser, input) => workerIO(browser, SCRIPT_WORKER_BLOBIFY, input); -let worker_deblobify = (browser, blobURL) => workerIO(browser, SCRIPT_WORKER_DEBLOBIFY, blobURL); - -function doTest(blobify, deblobify) { - let blobURL = null; - return function* (browser) { - if (blobURL === null) { - let input = Math.random().toString(); - blobURL = yield blobify(browser, input); - return input; - } - let result = yield deblobify(browser, blobURL); - blobURL = null; - return result; - } -} - -let tests = []; -for (let blobify of [page_blobify, worker_blobify]) { - for (let deblobify of [page_deblobify, worker_deblobify]) { - tests.push(doTest(blobify, deblobify)); - } -} - -IsolationTestTools.runTests(TEST_PAGE, tests); diff --git a/browser/components/originattributes/test/browser/browser_broadcastChannel.js b/browser/components/originattributes/test/browser/browser_broadcastChannel.js deleted file mode 100644 index 3a2bd7405..000000000 --- a/browser/components/originattributes/test/browser/browser_broadcastChannel.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Bug 1264571 - A test case of broadcast channels for first party isolation. - */ - -const TEST_DOMAIN = "http://example.net/"; -const TEST_PATH = TEST_DOMAIN + "browser/browser/components/originattributes/test/browser/"; -const TEST_PAGE = TEST_PATH + "file_broadcastChannel.html"; - -function* doTest(aBrowser) { - let response = yield ContentTask.spawn(aBrowser, null, function* () { - - let displayItem = content.document.getElementById("display"); - - // If there is nothing in the 'display', we will try to send a message to - // the broadcast channel and wait until this message has been delivered. - // The way that how we make sure the message is delivered is based on an - // iframe which will reply everything it receives from the broadcast channel - // to the current window through the postMessage. So, we can know that the - // boradcast message is sent successfully when the window receives a message - // from the iframe. - if (displayItem.innerHTML === "") { - let data = Math.random().toString(); - - let receivedData = yield new Promise(resolve => { - let listenFunc = event => { - content.removeEventListener("message", listenFunc); - resolve(event.data); - }; - - let bc = new content.BroadcastChannel("testBroadcastChannel"); - - content.addEventListener("message", listenFunc, false); - bc.postMessage(data); - }); - - is(receivedData, data, "The value should be the same."); - - return receivedData; - } - - return displayItem.innerHTML; - }); - - return response; -} - -IsolationTestTools.runTests(TEST_PAGE, doTest); diff --git a/browser/components/originattributes/test/browser/browser_cache.js b/browser/components/originattributes/test/browser/browser_cache.js deleted file mode 100644 index d5f3a8f58..000000000 --- a/browser/components/originattributes/test/browser/browser_cache.js +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Bug 1264577 - A test case for testing caches of various submodules. - * This test case will load two pages that each page loads various resources - * within the same third party domain for the same originAttributes or different - * originAttributes. And then, it verifies the number of cache entries and - * the originAttributes of loading channels. If these two pages belong to - * the same originAttributes, the number of cache entries for a certain - * resource would be one. Otherwise, it would be two. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -let {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", {}); -let protocolProxyService = Cc["@mozilla.org/network/protocol-proxy-service;1"] - .getService(Ci.nsIProtocolProxyService); - -const TEST_DOMAIN = "http://example.net"; -const TEST_PATH = "/browser/browser/components/originattributes/test/browser/"; -const TEST_PAGE = TEST_DOMAIN + TEST_PATH + "file_cache.html"; - -let suffixes = ["iframe.html", "link.css", "script.js", "img.png", "object.png", - "embed.png", "xhr.html", "worker.xhr.html", "audio.ogg", - "video.ogv", "track.vtt", - "fetch.html", "worker.fetch.html", - "request.html", "worker.request.html", - "import.js", "worker.js", "sharedworker.js"]; - -// A random value for isolating video/audio elements across different tests. -let randomSuffix; - -function clearAllImageCaches() { - let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"] - .getService(SpecialPowers.Ci.imgITools); - let imageCache = tools.getImgCacheForDocument(window.document); - imageCache.clearCache(true); // true=chrome - imageCache.clearCache(false); // false=content -} - -function cacheDataForContext(loadContextInfo) { - return new Promise(resolve => { - let cacheEntries = []; - let cacheVisitor = { - onCacheStorageInfo(num, consumption) {}, - onCacheEntryInfo(uri, idEnhance) { - cacheEntries.push({ uri: uri, - idEnhance: idEnhance }); - }, - onCacheEntryVisitCompleted() { - resolve(cacheEntries); - }, - QueryInterface(iid) { - if (iid.equals(Ci.nsICacheStorageVisitor)) - return this; - - throw Components.results.NS_ERROR_NO_INTERFACE; - } - }; - // Visiting the disk cache also visits memory storage so we do not - // need to use Services.cache2.memoryCacheStorage() here. - let storage = Services.cache2.diskCacheStorage(loadContextInfo, false); - storage.asyncVisitStorage(cacheVisitor, true); - }); -} - -let countMatchingCacheEntries = function (cacheEntries, domain, fileSuffix) { - return cacheEntries.map(entry => entry.uri.asciiSpec) - .filter(spec => spec.includes(domain)) - .filter(spec => spec.includes("file_thirdPartyChild." + fileSuffix)) - .length; -}; - -function observeChannels(onChannel) { - // We use a dummy proxy filter to catch all channels, even those that do not - // generate an "http-on-modify-request" notification, such as link preconnects. - let proxyFilter = { - applyFilter : function (aProxyService, aChannel, aProxy) { - // We have the channel; provide it to the callback. - onChannel(aChannel); - // Pass on aProxy unmodified. - return aProxy; - } - }; - protocolProxyService.registerChannelFilter(proxyFilter, 0); - // Return the stop() function: - return () => protocolProxyService.unregisterChannelFilter(proxyFilter); -} - -function startObservingChannels(aMode) { - let stopObservingChannels = observeChannels(function (channel) { - let originalURISpec = channel.originalURI.spec; - if (originalURISpec.includes("example.net")) { - let loadInfo = channel.loadInfo; - - switch (aMode) { - case TEST_MODE_FIRSTPARTY: - ok(loadInfo.originAttributes.firstPartyDomain === "example.com" || - loadInfo.originAttributes.firstPartyDomain === "example.org", - "first party for " + originalURISpec + " is " + loadInfo.originAttributes.firstPartyDomain); - break; - - case TEST_MODE_NO_ISOLATION: - ok(ChromeUtils.isOriginAttributesEqual(loadInfo.originAttributes, ChromeUtils.fillNonDefaultOriginAttributes()), - "OriginAttributes for " + originalURISpec + " is default."); - break; - - case TEST_MODE_CONTAINERS: - ok(loadInfo.originAttributes.userContextId === 1 || - loadInfo.originAttributes.userContextId === 2, - "userContextId for " + originalURISpec + " is " + loadInfo.originAttributes.userContextId); - break; - - default: - ok(false, "Unknown test mode."); - } - } - }); - return stopObservingChannels; -} - -let stopObservingChannels; - -// The init function, which clears image and network caches, and generates -// the random value for isolating video and audio elements across different -// test runs. -function* doInit(aMode) { - yield SpecialPowers.pushPrefEnv({"set": [["network.predictor.enabled", false], - ["network.predictor.enable-prefetch", false]]}); - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - randomSuffix = Math.random(); - stopObservingChannels = startObservingChannels(aMode); -} - -// In the test function, we dynamically generate the video and audio element, -// and assign a random suffix to their URL to isolate them across different -// test runs. -function* doTest(aBrowser) { - - let argObj = { - randomSuffix: randomSuffix, - urlPrefix: TEST_DOMAIN + TEST_PATH, - }; - - yield ContentTask.spawn(aBrowser, argObj, function* (arg) { - let videoURL = arg.urlPrefix + "file_thirdPartyChild.video.ogv"; - let audioURL = arg.urlPrefix + "file_thirdPartyChild.audio.ogg"; - let trackURL = arg.urlPrefix + "file_thirdPartyChild.track.vtt"; - let URLSuffix = "?r=" + arg.randomSuffix; - - // Create the audio and video elements. - let audio = content.document.createElement('audio'); - let video = content.document.createElement('video'); - let audioSource = content.document.createElement('source'); - let audioTrack = content.document.createElement('track'); - - // Append the audio and track element into the body, and wait until they're finished. - yield new Promise(resolve => { - let audioLoaded = false; - let trackLoaded = false; - - let audioListener = () => { - audio.removeEventListener("canplaythrough", audioListener); - - audioLoaded = true; - if (audioLoaded && trackLoaded) { - resolve(); - } - }; - - let trackListener = () => { - audioTrack.removeEventListener("load", trackListener); - - trackLoaded = true; - if (audioLoaded && trackLoaded) { - resolve(); - } - }; - - // Add the event listeners before everything in case we lose events. - audioTrack.addEventListener("load", trackListener, false); - audio.addEventListener("canplaythrough", audioListener, false); - - // Assign attributes for the audio element. - audioSource.setAttribute("src", audioURL + URLSuffix); - audioSource.setAttribute("type", "audio/ogg"); - audioTrack.setAttribute("src", trackURL); - audioTrack.setAttribute("kind", "subtitles"); - - audio.appendChild(audioSource); - audio.appendChild(audioTrack); - audio.autoplay = true; - - content.document.body.appendChild(audio); - }); - - // Append the video element into the body, and wait until it's finished. - yield new Promise(resolve => { - let listener = () => { - video.removeEventListener("canplaythrough", listener); - resolve(); - }; - - // Add the event listener before everything in case we lose the event. - video.addEventListener("canplaythrough", listener, false); - - // Assign attributes for the video element. - video.setAttribute("src", videoURL + URLSuffix); - video.setAttribute("type", "video/ogg"); - - content.document.body.appendChild(video); - }); - }); - - return 0; -} - -// The check function, which checks the number of cache entries. -function* doCheck(aShouldIsolate, aInputA, aInputB) { - let expectedEntryCount = 1; - let data = []; - data = data.concat(yield cacheDataForContext(LoadContextInfo.default)); - data = data.concat(yield cacheDataForContext(LoadContextInfo.private)); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, {}))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { userContextId: 1 }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { userContextId: 1 }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { userContextId: 2 }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { userContextId: 2 }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { firstPartyDomain: "example.com" }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { firstPartyDomain: "example.com" }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(false, { firstPartyDomain: "example.org" }))); - data = data.concat(yield cacheDataForContext(LoadContextInfo.custom(true, { firstPartyDomain: "example.org" }))); - - if (aShouldIsolate) { - expectedEntryCount = 2; - } - - for (let suffix of suffixes) { - let foundEntryCount = countMatchingCacheEntries(data, "example.net", suffix); - let result = (expectedEntryCount === foundEntryCount); - ok(result, "Cache entries expected for " + suffix + ": " + expectedEntryCount + - ", and found " + foundEntryCount); - } - - stopObservingChannels(); - stopObservingChannels = undefined; - return true; -} - -let testArgs = { - url: TEST_PAGE, - firstFrameSetting: DEFAULT_FRAME_SETTING, - secondFrameSetting: [TEST_TYPE_FRAME], -}; - -IsolationTestTools.runTests(testArgs, doTest, doCheck, doInit); diff --git a/browser/components/originattributes/test/browser/browser_clientAuth.js b/browser/components/originattributes/test/browser/browser_clientAuth.js deleted file mode 100644 index 48961dce0..000000000 --- a/browser/components/originattributes/test/browser/browser_clientAuth.js +++ /dev/null @@ -1,44 +0,0 @@ -let certCached = true; -let secondTabStarted = false; - -function onCertDialogLoaded(subject) { - certCached = false; - // Click OK. - subject.acceptDialog(); -} - -Services.obs.addObserver(onCertDialogLoaded, "cert-dialog-loaded", false); - -registerCleanupFunction(() => { - Services.obs.removeObserver(onCertDialogLoaded, "cert-dialog-loaded"); -}); - -function* setup() { - yield SpecialPowers.pushPrefEnv({ - set: [["security.default_personal_cert", "Ask Every Time"]] - }); -} - -function getResult() { - // The first tab always returns true. - if (!secondTabStarted) { - certCached = true; - secondTabStarted = true; - return true; - } - - // The second tab returns true if the cert is cached, so it will be different - // from the result of the first tab, and considered isolated. - let ret = certCached; - certCached = true; - secondTabStarted = false; - return ret; -} - -// aGetResultImmediately must be true because we need to get the result before -// the next tab is opened. -IsolationTestTools.runTests("https://requireclientcert.example.com", - getResult, - null, // aCompareResultFunc - setup, // aBeginFunc - true); // aGetResultImmediately diff --git a/browser/components/originattributes/test/browser/browser_cookieIsolation.js b/browser/components/originattributes/test/browser/browser_cookieIsolation.js deleted file mode 100644 index 6259723ba..000000000 --- a/browser/components/originattributes/test/browser/browser_cookieIsolation.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Bug 1312541 - A test case for document.cookie isolation. - */ - -const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" + - "originattributes/test/browser/file_firstPartyBasic.html"; - -// Use a random key so we don't access it in later tests. -const key = "key" + Math.random().toString(); -const re = new RegExp(key + "=([0-9\.]+)"); - -// Define the testing function -function* doTest(aBrowser) { - return yield ContentTask.spawn(aBrowser, {key, re}, - function ({key, re}) { - let result = re.exec(content.document.cookie); - if (result) { - return result[1]; - } - // No value is found, so we create one. - let value = Math.random().toString(); - content.document.cookie = key + "=" + value; - return value; - }); -} - -registerCleanupFunction(() => { - Services.cookies.removeAll(); -}); - -IsolationTestTools.runTests(TEST_PAGE, doTest); diff --git a/browser/components/originattributes/test/browser/browser_favicon_firstParty.js b/browser/components/originattributes/test/browser/browser_favicon_firstParty.js deleted file mode 100644 index b3a18947b..000000000 --- a/browser/components/originattributes/test/browser/browser_favicon_firstParty.js +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Bug 1277803 - A test case for testing favicon loading across different first party domains. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -Cu.import("resource://gre/modules/PlacesUtils.jsm"); - -const FIRST_PARTY_ONE = "example.com"; -const FIRST_PARTY_TWO = "example.org"; -const THIRD_PARTY = "mochi.test:8888"; - -const TEST_SITE_ONE = "http://" + FIRST_PARTY_ONE; -const TEST_SITE_TWO = "http://" + FIRST_PARTY_TWO; -const THIRD_PARTY_SITE = "http://" + THIRD_PARTY; -const TEST_DIRECTORY = "/browser/browser/components/originattributes/test/browser/"; - -const TEST_PAGE = TEST_DIRECTORY + "file_favicon.html"; -const TEST_THIRD_PARTY_PAGE = TEST_DIRECTORY + "file_favicon_thirdParty.html"; -const TEST_CACHE_PAGE = TEST_DIRECTORY + "file_favicon_cache.html"; - -const FAVICON_URI = TEST_DIRECTORY + "file_favicon.png"; -const TEST_FAVICON_CACHE_URI = TEST_DIRECTORY + "file_favicon_cache.png"; - -let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); -let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI; - -function clearAllImageCaches() { - let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"] - .getService(SpecialPowers.Ci.imgITools); - let imageCache = tools.getImgCacheForDocument(window.document); - imageCache.clearCache(true); // true=chrome - imageCache.clearCache(false); // false=content -} - -function clearAllPlacesFavicons() { - let faviconService = Cc["@mozilla.org/browser/favicon-service;1"] - .getService(Ci.nsIFaviconService); - - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - if (aTopic === "places-favicons-expired") { - resolve(); - Services.obs.removeObserver(observer, "places-favicons-expired", false); - } - } - }; - - Services.obs.addObserver(observer, "places-favicons-expired", false); - faviconService.expireAllFavicons(); - }); -} - -function observeFavicon(aFirstPartyDomain, aExpectedCookie, aPageURI) { - let faviconReqXUL = false; - let faviconReqPlaces = false; - let expectedPrincipal = Services.scriptSecurityManager - .createCodebasePrincipal(aPageURI, { firstPartyDomain: aFirstPartyDomain }); - - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - // Make sure that the topic is 'http-on-modify-request'. - if (aTopic === "http-on-modify-request") { - // We check the firstPartyDomain for the originAttributes of the loading - // channel. All requests for the favicon should contain the correct - // firstPartyDomain. There are two requests for a favicon loading, one - // from the Places library and one from the XUL image. The difference - // of them is the loading principal. The Places will use the content - // principal and the XUL image will use the system principal. - - let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel); - let reqLoadInfo = httpChannel.loadInfo; - let loadingPrincipal = reqLoadInfo.loadingPrincipal; - let triggeringPrincipal = reqLoadInfo.triggeringPrincipal; - - // Make sure this is a favicon request. - if (!httpChannel.URI.spec.endsWith(FAVICON_URI)) { - return; - } - - // Check the first party domain. - is(reqLoadInfo.originAttributes.firstPartyDomain, aFirstPartyDomain, - "The loadInfo has correct first party domain"); - - if (loadingPrincipal.equals(systemPrincipal)) { - faviconReqXUL = true; - ok(triggeringPrincipal.equals(expectedPrincipal), - "The triggeringPrincipal of favicon loading from XUL should be the content principal."); - } else { - faviconReqPlaces = true; - ok(loadingPrincipal.equals(expectedPrincipal), - "The loadingPrincipal of favicon loading from Places should be the content prinicpal"); - } - - let faviconCookie = httpChannel.getRequestHeader("cookie"); - - is(faviconCookie, aExpectedCookie, "The cookie of the favicon loading is correct."); - } else { - ok(false, "Received unexpected topic: ", aTopic); - } - - if (faviconReqXUL && faviconReqPlaces) { - Services.obs.removeObserver(observer, "http-on-modify-request", false); - resolve(); - } - } - }; - - Services.obs.addObserver(observer, "http-on-modify-request", false); - }); -} - -function waitOnFaviconResponse(aFaviconURL) { - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - if (aTopic === "http-on-examine-response" || - aTopic === "http-on-examine-cached-response") { - - let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel); - let loadInfo = httpChannel.loadInfo; - - if (httpChannel.URI.spec !== aFaviconURL) { - return; - } - - let result = { - topic: aTopic, - firstPartyDomain: loadInfo.originAttributes.firstPartyDomain - }; - - resolve(result); - Services.obs.removeObserver(observer, "http-on-examine-response", false); - Services.obs.removeObserver(observer, "http-on-examine-cached-response", false); - } - } - }; - - Services.obs.addObserver(observer, "http-on-examine-response", false); - Services.obs.addObserver(observer, "http-on-examine-cached-response", false); - }); -} - -function waitOnFaviconLoaded(aFaviconURL) { - return new Promise(resolve => { - let observer = { - onPageChanged(uri, attr, value, id) { - - if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON && - value === aFaviconURL) { - resolve(); - PlacesUtils.history.removeObserver(observer, false); - } - }, - }; - - PlacesUtils.history.addObserver(observer, false); - }); -} - -function* openTab(aURL) { - let tab = gBrowser.addTab(aURL); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -function* assignCookiesUnderFirstParty(aURL, aFirstParty, aCookieValue) { - // Open a tab under the given aFirstParty, and this tab will have an - // iframe which loads the aURL. - let tabInfo = yield openTabInFirstParty(aURL, aFirstParty); - - // Add cookies into the iframe. - yield ContentTask.spawn(tabInfo.browser, aCookieValue, function* (value) { - content.document.cookie = value; - }); - - yield BrowserTestUtils.removeTab(tabInfo.tab); -} - -function* generateCookies(aThirdParty) { - // we generate two different cookies for two first party domains. - let cookies = []; - cookies.push(Math.random().toString()); - cookies.push(Math.random().toString()); - - let firstSiteURL; - let secondSiteURL; - - if (aThirdParty) { - // Add cookies into the third party site with different first party domain. - firstSiteURL = THIRD_PARTY_SITE; - secondSiteURL = THIRD_PARTY_SITE; - } else { - // Add cookies into sites. - firstSiteURL = TEST_SITE_ONE; - secondSiteURL = TEST_SITE_TWO; - } - - yield assignCookiesUnderFirstParty(firstSiteURL, TEST_SITE_ONE, cookies[0]); - yield assignCookiesUnderFirstParty(secondSiteURL, TEST_SITE_TWO, cookies[1]); - - return cookies; -} - -function* doTest(aTestPage, aExpectedCookies, aFaviconURL) { - let firstPageURI = makeURI(TEST_SITE_ONE + aTestPage); - let secondPageURI = makeURI(TEST_SITE_TWO + aTestPage); - - // Start to observe the event of that favicon has been fully loaded. - let promiseFaviconLoaded = waitOnFaviconLoaded(aFaviconURL); - - // Start to observe the favicon requests earlier in case we miss it. - let promiseObserveFavicon = observeFavicon(FIRST_PARTY_ONE, aExpectedCookies[0], firstPageURI); - - // Open the tab for the first site. - let tabInfo = yield openTab(TEST_SITE_ONE + aTestPage); - - // Waiting until favicon requests are all made. - yield promiseObserveFavicon; - - // Waiting until favicon loaded. - yield promiseFaviconLoaded; - - // Close the tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - - // Start to observe the favicon requests earlier in case we miss it. - promiseObserveFavicon = observeFavicon(FIRST_PARTY_TWO, aExpectedCookies[1], secondPageURI); - - // Open the tab for the second site. - tabInfo = yield openTab(TEST_SITE_TWO + aTestPage); - - // Waiting until favicon requests are all made. - yield promiseObserveFavicon; - - yield BrowserTestUtils.removeTab(tabInfo.tab); -} - -add_task(function* setup() { - // Make sure first party isolation is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - ["privacy.firstparty.isolate", true] - ]}); -}); - -// A clean up function to prevent affecting other tests. -registerCleanupFunction(() => { - // Clear all cookies. - let cookieMgr = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); - cookieMgr.removeAll(); - - // Clear all image caches and network caches. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); -}); - -add_task(function* test_favicon_firstParty() { - for (let testThirdParty of [false, true]) { - // Clear all image caches and network caches before running the test. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Clear Places favicon caches. - yield clearAllPlacesFavicons(); - - let cookies = yield generateCookies(testThirdParty); - - if (testThirdParty) { - yield doTest(TEST_THIRD_PARTY_PAGE, cookies, THIRD_PARTY_SITE + FAVICON_URI); - } else { - yield doTest(TEST_PAGE, cookies, TEST_SITE_ONE + FAVICON_URI); - } - } -}); - -add_task(function* test_favicon_cache_firstParty() { - // Clear all image caches and network caches before running the test. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Start to observer the event of that favicon has been fully loaded and cached. - let promiseForFaviconLoaded = waitOnFaviconLoaded(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI); - - // Start to observer for the favicon response of the first tab. - let responsePromise = waitOnFaviconResponse(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI); - - // Open the tab for the first site. - let tabInfoA = yield openTab(TEST_SITE_ONE + TEST_CACHE_PAGE); - - // Waiting for the favicon response. - let response = yield responsePromise; - - // Make sure the favicon is loaded through the network and its first party domain is correct. - is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network."); - is(response.firstPartyDomain, FIRST_PARTY_ONE, "We should only observe the network response for the first first party."); - - // Waiting until the favicon has been loaded and cached. - yield promiseForFaviconLoaded; - - // Open the tab again for checking the image cache is working correctly. - let tabInfoB = yield openTab(TEST_SITE_ONE + TEST_CACHE_PAGE); - - // Start to observe the favicon response, the second tab actually will not - // make any network request since the favicon will be loaded by the cache for - // both Places and XUL image. So here, we are going to observe the favicon - // response for the third tab which opens with the second first party. - let promiseForFaviconResponse = waitOnFaviconResponse(THIRD_PARTY_SITE + TEST_FAVICON_CACHE_URI); - - // Open the tab for the second site. - let tabInfoC = yield openTab(TEST_SITE_TWO + TEST_CACHE_PAGE); - - // Wait for the favicon response. In this case, we suppose to catch the - // response for the third tab but not the second tab since it will not - // go through the network. - response = yield promiseForFaviconResponse; - - // Check that the favicon response has came from the network and it has the - // correct first party domain. - is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network again."); - is(response.firstPartyDomain, FIRST_PARTY_TWO, "We should only observe the network response for the second first party."); - - yield BrowserTestUtils.removeTab(tabInfoA.tab); - yield BrowserTestUtils.removeTab(tabInfoB.tab); - yield BrowserTestUtils.removeTab(tabInfoC.tab); -}); diff --git a/browser/components/originattributes/test/browser/browser_favicon_userContextId.js b/browser/components/originattributes/test/browser/browser_favicon_userContextId.js deleted file mode 100644 index 507e0a6d4..000000000 --- a/browser/components/originattributes/test/browser/browser_favicon_userContextId.js +++ /dev/null @@ -1,257 +0,0 @@ -/** - * Bug 1277803 - A test caes for testing favicon loading across different userContextId. - */ - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -XPCOMUtils.defineLazyModuleGetter(this, "Promise", - "resource://gre/modules/Promise.jsm"); - -const TEST_SITE = "http://example.net"; -const TEST_THIRD_PARTY_SITE = "http://mochi.test:8888"; - -const TEST_PAGE = TEST_SITE + "/browser/browser/components/originattributes/" + - "test/browser/file_favicon.html"; -const FAVICON_URI = TEST_SITE + "/browser/browser/components/originattributes/" + - "test/browser/file_favicon.png"; -const TEST_THIRD_PARTY_PAGE = "http://example.com/browser/browser/components/" + - "originattributes/test/browser/file_favicon_thirdParty.html"; -const THIRD_PARTY_FAVICON_URI = TEST_THIRD_PARTY_SITE + "/browser/browser/components/" + - "originattributes/test/browser/file_favicon.png"; - -const USER_CONTEXT_ID_PERSONAL = 1; -const USER_CONTEXT_ID_WORK = 2; - -let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); -let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI; - -function clearAllImageCaches() { - var tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"] - .getService(SpecialPowers.Ci.imgITools); - var imageCache = tools.getImgCacheForDocument(window.document); - imageCache.clearCache(true); // true=chrome - imageCache.clearCache(false); // false=content -} - -function clearAllPlacesFavicons() { - let faviconService = Cc["@mozilla.org/browser/favicon-service;1"] - .getService(Ci.nsIFaviconService); - - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - if (aTopic === "places-favicons-expired") { - resolve(); - Services.obs.removeObserver(observer, "places-favicons-expired", false); - } - } - }; - - Services.obs.addObserver(observer, "places-favicons-expired", false); - faviconService.expireAllFavicons(); - }); -} - -function FaviconObserver(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL) { - this.reset(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL); -} - -FaviconObserver.prototype = { - observe(aSubject, aTopic, aData) { - // Make sure that the topic is 'http-on-modify-request'. - if (aTopic === "http-on-modify-request") { - // We check the userContextId for the originAttributes of the loading - // channel. All requests for the favicon should contain the correct - // userContextId. There are two requests for a favicon loading, one - // from the Places library and one from the XUL image. The difference - // of them is the loading principal. The Places will use the content - // principal and the XUL image will use the system principal. - - let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel); - let reqLoadInfo = httpChannel.loadInfo; - let loadingPrincipal; - let triggeringPrincipal; - - // Make sure this is a favicon request. - if (httpChannel.URI.spec !== this._faviconURL) { - return; - } - - if (reqLoadInfo) { - loadingPrincipal = reqLoadInfo.loadingPrincipal; - triggeringPrincipal = reqLoadInfo.triggeringPrincipal; - } - - // Check the userContextId. - is(reqLoadInfo.originAttributes.userContextId, this._curUserContextId, - "The loadInfo has correct userContextId"); - - if (loadingPrincipal.equals(systemPrincipal)) { - this._faviconReqXUL = true; - ok(triggeringPrincipal.equals(this._expectedPrincipal), - "The triggeringPrincipal of favicon loading from XUL should be the content principal."); - } else { - this._faviconReqPlaces = true; - ok(loadingPrincipal.equals(this._expectedPrincipal), - "The loadingPrincipal of favicon loading from Places should be the content prinicpal"); - } - - let faviconCookie = httpChannel.getRequestHeader("cookie"); - - is(faviconCookie, this._expectedCookie, "The cookie of the favicon loading is correct."); - } else { - ok(false, "Received unexpected topic: ", aTopic); - } - - if (this._faviconReqXUL && this._faviconReqPlaces) { - this._faviconLoaded.resolve(); - } - }, - - reset(aUserContextId, aExpectedCookie, aPageURI, aFaviconURL) { - this._curUserContextId = aUserContextId; - this._expectedCookie = aExpectedCookie; - this._expectedPrincipal = Services.scriptSecurityManager - .createCodebasePrincipal(aPageURI, { userContextId: aUserContextId }); - this._faviconReqXUL = false; - this._faviconReqPlaces = false; - this._faviconURL = aFaviconURL; - this._faviconLoaded = new Promise.defer(); - }, - - get promise() { - return this._faviconLoaded.promise; - } -}; - -function waitOnFaviconLoaded(aFaviconURL) { - return new Promise(resolve => { - let observer = { - onPageChanged(uri, attr, value, id) { - - if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON && - value === aFaviconURL) { - resolve(); - PlacesUtils.history.removeObserver(observer, false); - } - }, - }; - - PlacesUtils.history.addObserver(observer, false); - }); -} - -function* generateCookies(aHost) { - // we generate two different cookies for two userContextIds. - let cookies = []; - cookies.push(Math.random().toString()); - cookies.push(Math.random().toString()); - - // Then, we add cookies into the site for 'personal' and 'work'. - let tabInfoA = yield openTabInUserContext(aHost, USER_CONTEXT_ID_PERSONAL); - let tabInfoB = yield openTabInUserContext(aHost, USER_CONTEXT_ID_WORK); - - yield ContentTask.spawn(tabInfoA.browser, cookies[0], function* (value) { - content.document.cookie = value; - }); - - yield ContentTask.spawn(tabInfoB.browser, cookies[1], function* (value) { - content.document.cookie = value; - }); - - yield BrowserTestUtils.removeTab(tabInfoA.tab); - yield BrowserTestUtils.removeTab(tabInfoB.tab); - - return cookies; -} - -function* doTest(aTestPage, aFaviconHost, aFaviconURL) { - let cookies = yield generateCookies(aFaviconHost); - let pageURI = makeURI(aTestPage); - - // Create the observer object for observing request channels of the personal - // container. - let observer = new FaviconObserver(USER_CONTEXT_ID_PERSONAL, cookies[0], pageURI, aFaviconURL); - - // Add the observer earlier in case we miss it. - let promiseWaitOnFaviconLoaded = waitOnFaviconLoaded(aFaviconURL); - - Services.obs.addObserver(observer, "http-on-modify-request", false); - - // Open the tab with the personal container. - let tabInfo = yield openTabInUserContext(aTestPage, USER_CONTEXT_ID_PERSONAL); - - // Waiting for favicon requests are all made. - yield observer.promise; - // Waiting for favicon loaded. - yield promiseWaitOnFaviconLoaded; - - // Close the tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - - // Reset the observer for observing requests for the work container. - observer.reset(USER_CONTEXT_ID_WORK, cookies[1], pageURI, aFaviconURL); - tabInfo = yield openTabInUserContext(aTestPage, USER_CONTEXT_ID_WORK); - - // Waiting for favicon requests are all made. - yield observer.promise; - - Services.obs.removeObserver(observer, "http-on-modify-request", false); - - yield BrowserTestUtils.removeTab(tabInfo.tab); -} - -add_task(function* setup() { - // Make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({"set": [ - ["privacy.userContext.enabled", true] - ]}); -}); - -// A clean up function to prevent affecting other tests. -registerCleanupFunction(() => { - // Clear all cookies. - let cookieMgr = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); - cookieMgr.removeAll(); - - // Clear all image caches and network caches. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Clear Places favicon caches. - clearAllPlacesFavicons(); -}); - -add_task(function* test_favicon_userContextId() { - // Clear all image caches before running the test. - clearAllImageCaches(); - - // Clear all network caches. - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Clear Places favicon caches. - yield clearAllPlacesFavicons(); - - yield doTest(TEST_PAGE, TEST_SITE, FAVICON_URI); -}); - -add_task(function* test_thirdPartyFavicon_userContextId() { - // Clear all image caches before running the test. - clearAllImageCaches(); - - // Clear all network caches. - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Clear Places favicon caches. - yield clearAllPlacesFavicons(); - - yield doTest(TEST_THIRD_PARTY_PAGE, TEST_THIRD_PARTY_SITE, THIRD_PARTY_FAVICON_URI); -}); diff --git a/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js b/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js deleted file mode 100644 index ddda6afae..000000000 --- a/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js +++ /dev/null @@ -1,174 +0,0 @@ -const BASE_URL = "http://mochi.test:8888/browser/browser/components/originattributes/test/browser/"; -const BASE_DOMAIN = "mochi.test"; - -add_task(function* setup() { - Services.prefs.setBoolPref("privacy.firstparty.isolate", true); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("privacy.firstparty.isolate"); - }); -}); - -/** - * Test for the top-level document and child iframes should have the - * firstPartyDomain attribute. - */ -add_task(function* principal_test() { - let tab = gBrowser.addTab(BASE_URL + "test_firstParty.html"); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) { - return url == BASE_URL + "test_firstParty.html"; - }); - - yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: BASE_DOMAIN }, function* (attrs) { - info("document principal: " + content.document.nodePrincipal.origin); - Assert.equal(docShell.getOriginAttributes().firstPartyDomain, "", - "top-level docShell shouldn't have firstPartyDomain attribute."); - Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "The document should have firstPartyDomain"); - - for (let i = 1; i < 4; i++) { - let iframe = content.document.getElementById("iframe" + i); - info("iframe principal: " + iframe.contentDocument.nodePrincipal.origin); - Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain, - attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain"); - Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "iframe should have firstPartyDomain"); - } - }); - - gBrowser.removeTab(tab); -}); - -/** - * Test for the cookie jars of the top-level document and child iframe should be - * isolated by firstPartyDomain. - */ -add_task(function* cookie_test() { - let tab = gBrowser.addTab(BASE_URL + "test_firstParty_cookie.html"); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true); - - let iter = Services.cookies.enumerator; - let count = 0; - while (iter.hasMoreElements()) { - count++; - let cookie = iter.getNext().QueryInterface(Ci.nsICookie2); - Assert.equal(cookie.value, "foo", "Cookie value should be foo"); - Assert.equal(cookie.originAttributes.firstPartyDomain, BASE_DOMAIN, "Cookie's origin attributes should be " + BASE_DOMAIN); - } - - // one cookie is from requesting test.js from top-level doc, and the other from - // requesting test2.js from iframe test2.html. - Assert.equal(count, 2, "Should have two cookies"); - - gBrowser.removeTab(tab); -}); - -/** - * Test for after redirect, the top-level document should update the firstPartyDomain - * attribute. However if the redirect is happening on the iframe, the attribute - * should remain the same. - */ -add_task(function* redirect_test() { - let tab = gBrowser.addTab(BASE_URL + "test_firstParty_http_redirect.html"); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) { - info("document principal: " + content.document.nodePrincipal.origin); - info("document uri: " + content.document.documentURI); - - Assert.equal(content.document.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html", - "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html"); - Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "The document should have firstPartyDomain"); - }); - - // Since this is a HTML redirect, we wait until the final page is loaded. - let tab2 = gBrowser.addTab(BASE_URL + "test_firstParty_html_redirect.html"); - yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser, false, function(url) { - return url == "http://example.com/"; - }); - - yield ContentTask.spawn(tab2.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) { - info("2nd tab document principal: " + content.document.nodePrincipal.origin); - info("2nd tab document uri: " + content.document.documentURI); - Assert.equal(content.document.documentURI, "http://example.com/", - "The page should have been redirected to http://example.com"); - Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "The document should have firstPartyDomain"); - }); - - let tab3 = gBrowser.addTab(BASE_URL + "test_firstParty_iframe_http_redirect.html"); - yield BrowserTestUtils.browserLoaded(tab3.linkedBrowser, true, function(url) { - return url == (BASE_URL + "test_firstParty_iframe_http_redirect.html"); - }); - - // This redirect happens on the iframe, so unlike the two redirect tests above, - // the firstPartyDomain should still stick to the current top-level document, - // which is mochi.test. - yield ContentTask.spawn(tab3.linkedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) { - let iframe = content.document.getElementById("iframe1"); - info("iframe document principal: " + iframe.contentDocument.nodePrincipal.origin); - info("iframe document uri: " + iframe.contentDocument.documentURI); - - Assert.equal(iframe.contentDocument.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html", - "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html"); - Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "The iframe should have firstPartyDomain: " + attrs.firstPartyDomain); - }); - - gBrowser.removeTab(tab); - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab3); -}); - -/** - * Test for postMessage between document and iframe. - */ -add_task(function* postMessage_test() { - let tab = gBrowser.addTab(BASE_URL + "test_firstParty_postMessage.html"); - - // The top-level page will post a message to its child iframe, and wait for - // another message from the iframe, once it receives the message, it will - // create another iframe, dummy.html. - // So we wait until dummy.html is loaded - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) { - return url == BASE_URL + "dummy.html"; - }); - - yield ContentTask.spawn(tab.linkedBrowser, {}, function* () { - info("document principal: " + content.document.nodePrincipal.origin); - let value = content.document.getElementById("message").textContent; - Assert.equal(value, "OK"); - }); - - gBrowser.removeTab(tab); -}); - -/** - * When the web page calls window.open, the new window should have the same - * firstPartyDomain attribute. - */ -add_task(function* openWindow_test() { - Services.prefs.setIntPref("browser.link.open_newwindow", 2); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.link.open_newwindow"); - }); - - let tab = gBrowser.addTab(BASE_URL + "window.html"); - let win = yield BrowserTestUtils.waitForNewWindow(); - - yield ContentTask.spawn(win.gBrowser.selectedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) { - Assert.equal(docShell.getOriginAttributes().firstPartyDomain, attrs.firstPartyDomain, - "window.open() should have firstPartyDomain attribute"); - Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "The document should have firstPartyDomain"); - - let iframe = content.document.getElementById("iframe1"); - Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain, - attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain"); - Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain, - attrs.firstPartyDomain, "iframe should have firstPartyDomain"); - }); - - gBrowser.removeTab(tab); - yield BrowserTestUtils.closeWindow(win); -}); - diff --git a/browser/components/originattributes/test/browser/browser_httpauth.js b/browser/components/originattributes/test/browser/browser_httpauth.js deleted file mode 100644 index 0b7b1540e..000000000 --- a/browser/components/originattributes/test/browser/browser_httpauth.js +++ /dev/null @@ -1,54 +0,0 @@ -let Cu = Components.utils; -let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {}); - -let server = new HttpServer(); -server.registerPathHandler('/file.html', fileHandler); -server.start(-1); - -let BASE_URI = 'http://localhost:' + server.identity.primaryPort; -let FILE_URI = BASE_URI + '/file.html'; - -let credentialQueue = []; - -// Ask the user agent for authorization. -function fileHandler(metadata, response) { - if (!metadata.hasHeader("Authorization")) { - response.setStatusLine(metadata.httpVersion, 401, "Unauthorized"); - response.setHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\""); - return; - } - - // This will be "account:password" encoded in base64. - credentialQueue.push(metadata.getHeader("Authorization")); - - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - let body = "<html><body></body></html>"; - response.bodyOutputStream.write(body, body.length); -} - -function onCommonDialogLoaded(subject) { - // Submit random account and password - let dialog = subject.Dialog; - dialog.ui.loginTextbox.setAttribute("value", Math.random()); - dialog.ui.password1Textbox.setAttribute("value", Math.random()); - dialog.ui.button0.click(); -} - -Services.obs.addObserver(onCommonDialogLoaded, "common-dialog-loaded", false); - -registerCleanupFunction(() => { - Services.obs.removeObserver(onCommonDialogLoaded, "common-dialog-loaded"); - server.stop(() => { - server = null; - }); -}); - -function getResult() { - // If two targets are isolated, they should get different credentials. - // Otherwise, the credentials will be cached and therefore the same. - return credentialQueue.shift(); -} - -IsolationTestTools.runTests(FILE_URI, getResult); - diff --git a/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js b/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js deleted file mode 100644 index a24cec9ac..000000000 --- a/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Bug 1264572 - A test case for image cache isolation. - */ - -requestLongerTimeout(2); - -let Cu = Components.utils; -let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {}); - -const NUM_ISOLATION_LOADS = 2; -const NUM_CACHED_LOADS = 1; - -let gHits = 0; - -let server = new HttpServer(); -server.registerPathHandler('/image.png', imageHandler); -server.registerPathHandler('/file.html', fileHandler); -server.start(-1); - -registerCleanupFunction(() => { - server.stop(() => { - server = null; - }); -}); - -let BASE_URI = 'http://localhost:' + server.identity.primaryPort; -let IMAGE_URI = BASE_URI + '/image.png'; -let FILE_URI = BASE_URI + '/file.html'; - -function imageHandler(metadata, response) { - info('XXX: loading image from server'); - gHits++; - response.setHeader("Cache-Control", "max-age=10000", false); - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "image/png", false); - var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII="; - response.bodyOutputStream.write(body, body.length); -} - -function fileHandler(metadata, response) { - response.setStatusLine(metadata.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - let body = `<html><body><image src=${IMAGE_URI}></body></html>`; - response.bodyOutputStream.write(body, body.length); -} - -function doBefore() { - // reset hit counter - info('XXX resetting gHits'); - gHits = 0; - info('XXX clearing image cache'); - let imageCache = Cc["@mozilla.org/image/tools;1"] - .getService(Ci.imgITools) - .getImgCacheForDocument(null); - imageCache.clearCache(true); - imageCache.clearCache(false); - info('XXX clearning network cache'); - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); -} - -// the test function does nothing on purpose. -function doTest(aBrowser) { - return 0; -} - -// the check function -function doCheck(shouldIsolate, a, b) { - // if we're doing first party isolation and the image cache isolation is - // working, then gHits should be 2 because the image would have been loaded - // one per first party domain. if first party isolation is disabled, then - // gHits should be 1 since there would be one image load from the server and - // one load from the image cache. - info(`XXX check: gHits == ${gHits}, shouldIsolate == ${shouldIsolate}`); - return shouldIsolate ? gHits == NUM_ISOLATION_LOADS - : gHits == NUM_CACHED_LOADS; -} - -IsolationTestTools.runTests(FILE_URI, doTest, doCheck, doBefore); diff --git a/browser/components/originattributes/test/browser/browser_localStorageIsolation.js b/browser/components/originattributes/test/browser/browser_localStorageIsolation.js deleted file mode 100644 index 41bde80e4..000000000 --- a/browser/components/originattributes/test/browser/browser_localStorageIsolation.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Bug 1264567 - A test case for localStorage isolation. - */ - -const TEST_PAGE = "http://mochi.test:8888/browser/browser/components/" + - "originattributes/test/browser/file_firstPartyBasic.html"; - -// Use a random key so we don't access it in later tests. -const key = Math.random().toString(); - -// Define the testing function -function* doTest(aBrowser) { - return yield ContentTask.spawn(aBrowser, key, function (key) { - let value = content.localStorage.getItem(key); - if (value === null) { - // No value is found, so we create one. - value = Math.random().toString(); - content.localStorage.setItem(key, value); - } - return value; - }); -} - -IsolationTestTools.runTests(TEST_PAGE, doTest); diff --git a/browser/components/originattributes/test/browser/browser_sharedworker.js b/browser/components/originattributes/test/browser/browser_sharedworker.js deleted file mode 100644 index 7049407f6..000000000 --- a/browser/components/originattributes/test/browser/browser_sharedworker.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Bug 1264593 - A test case for the shared worker by first party isolation. - */ - -const TEST_DOMAIN = "http://example.net/"; -const TEST_PATH = TEST_DOMAIN + "browser/browser/components/originattributes/test/browser/"; -const TEST_PAGE = TEST_PATH + "file_sharedworker.html"; - -function* getResultFromSharedworker(aBrowser) { - let response = yield ContentTask.spawn(aBrowser, null, function* () { - let worker = new content.SharedWorker("file_sharedworker.js", "isolationSharedWorkerTest"); - - let result = yield new Promise(resolve => { - worker.port.onmessage = function (e) { - content.document.getElementById("display").innerHTML = e.data; - resolve(e.data); - }; - }); - - return result; - }); - - return response; -} - -IsolationTestTools.runTests(TEST_PAGE, getResultFromSharedworker); diff --git a/browser/components/originattributes/test/browser/dummy.html b/browser/components/originattributes/test/browser/dummy.html deleted file mode 100644 index 1a87e2840..000000000 --- a/browser/components/originattributes/test/browser/dummy.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> -<title>Dummy test page</title> -<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta> -</head> -<body> -<p>Dummy test page</p> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_broadcastChannel.html b/browser/components/originattributes/test/browser/file_broadcastChannel.html deleted file mode 100644 index 14bd7a022..000000000 --- a/browser/components/originattributes/test/browser/file_broadcastChannel.html +++ /dev/null @@ -1,16 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> - <title>Page broadcast channel creator for first party isolation</title> -</head> -<body> - <div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div> - <iframe id="iframe" src="file_broadcastChanneliFrame.html"></iframe>> -<script type="text/javascript;version=1.7"> -let bc = new BroadcastChannel("testBroadcastChannel"); -bc.onmessage = function (e) { - document.getElementById("display").innerHTML = e.data; -}; -</script> -</body> diff --git a/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html b/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html deleted file mode 100644 index a2140e617..000000000 --- a/browser/components/originattributes/test/browser/file_broadcastChanneliFrame.html +++ /dev/null @@ -1,15 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> - <title>Page broadcast channel responder for first party isolation</title> -</head> -<body> - <div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div> -<script type="text/javascript;version=1.7"> -let bc = new BroadcastChannel("testBroadcastChannel"); -bc.onmessage = function (e) { - window.parent.postMessage(e.data, "*"); -}; -</script> -</body> diff --git a/browser/components/originattributes/test/browser/file_cache.html b/browser/components/originattributes/test/browser/file_cache.html deleted file mode 100644 index 788ec899d..000000000 --- a/browser/components/originattributes/test/browser/file_cache.html +++ /dev/null @@ -1,25 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<head> - <link rel="stylesheet" type="text/css" - href="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css"> - <link rel="preconnect" href="http://example.net"> -</head> -<body> -<div>file_cache.html</div> - -<iframe src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html"> -</iframe> - -<script src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js"> -</script> - -<img src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png"> - -<embed src="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png"> - -<object data="http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png" - type="image/png"></object> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_favicon.html b/browser/components/originattributes/test/browser/file_favicon.html deleted file mode 100644 index b571134e1..000000000 --- a/browser/components/originattributes/test/browser/file_favicon.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML> -<html> - <head> - <meta charset='utf-8'> - <title>Favicon Test for originAttributes</title> - <link rel="icon" type="image/png" href="file_favicon.png" /> - </head> - <body> - Favicon!! - </body> -</html>
\ No newline at end of file diff --git a/browser/components/originattributes/test/browser/file_favicon.png b/browser/components/originattributes/test/browser/file_favicon.png Binary files differdeleted file mode 100644 index 5535363c9..000000000 --- a/browser/components/originattributes/test/browser/file_favicon.png +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_favicon.png^headers^ b/browser/components/originattributes/test/browser/file_favicon.png^headers^ deleted file mode 100644 index 9e23c73b7..000000000 --- a/browser/components/originattributes/test/browser/file_favicon.png^headers^ +++ /dev/null @@ -1 +0,0 @@ -Cache-Control: no-cache diff --git a/browser/components/originattributes/test/browser/file_favicon_cache.html b/browser/components/originattributes/test/browser/file_favicon_cache.html deleted file mode 100644 index 2a7343b8e..000000000 --- a/browser/components/originattributes/test/browser/file_favicon_cache.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML> -<html> - <head> - <meta charset='utf-8'> - <title>Favicon Test for originAttributes</title> - <link rel="icon" type="image/png" href="http://mochi.test:8888/browser/browser/components/originattributes/test/browser/file_favicon_cache.png" /> - </head> - <body> - Third Party Favicon!! - </body> -</html>
\ No newline at end of file diff --git a/browser/components/originattributes/test/browser/file_favicon_cache.png b/browser/components/originattributes/test/browser/file_favicon_cache.png Binary files differdeleted file mode 100644 index 5535363c9..000000000 --- a/browser/components/originattributes/test/browser/file_favicon_cache.png +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_favicon_thirdParty.html b/browser/components/originattributes/test/browser/file_favicon_thirdParty.html deleted file mode 100644 index 4a2dd680a..000000000 --- a/browser/components/originattributes/test/browser/file_favicon_thirdParty.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML> -<html> - <head> - <meta charset='utf-8'> - <title>Favicon Test for originAttributes</title> - <link rel="icon" type="image/png" href="http://mochi.test:8888/browser/browser/components/originattributes/test/browser/file_favicon.png" /> - </head> - <body> - Third Party Favicon!! - </body> -</html>
\ No newline at end of file diff --git a/browser/components/originattributes/test/browser/file_firstPartyBasic.html b/browser/components/originattributes/test/browser/file_firstPartyBasic.html deleted file mode 100644 index 713187fb2..000000000 --- a/browser/components/originattributes/test/browser/file_firstPartyBasic.html +++ /dev/null @@ -1,8 +0,0 @@ -<html> - <head> - <meta charset="UTF-8"> - <title>First Party Isolation Tests</title> - </head> - <body> - </body> -</html> diff --git a/browser/components/originattributes/test/browser/file_sharedworker.html b/browser/components/originattributes/test/browser/file_sharedworker.html deleted file mode 100644 index b9ff793bd..000000000 --- a/browser/components/originattributes/test/browser/file_sharedworker.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> - <title>Page SharedWorker creator for first party isolation</title> -</head> -<body> -<div id="display" style="white-space:pre; font-family:monospace; display:inline;"></div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_sharedworker.js b/browser/components/originattributes/test/browser/file_sharedworker.js deleted file mode 100644 index 82f075a37..000000000 --- a/browser/components/originattributes/test/browser/file_sharedworker.js +++ /dev/null @@ -1,9 +0,0 @@ -self.randomValue = Math.random(); - -/* global onconnect:true */ - -onconnect = function (e) { - let port = e.ports[0]; - port.postMessage(self.randomValue); - port.start(); -}; diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg b/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg Binary files differdeleted file mode 100644 index edda4e912..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.audio.ogg +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png Binary files differdeleted file mode 100644 index c5916f289..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.embed.png +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html deleted file mode 100644 index 037901ad0..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.fetch.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.fetch.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html deleted file mode 100644 index b047d5b41..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.iframe.html +++ /dev/null @@ -1,18 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.html</div> -<script> - var xhr = new XMLHttpRequest(); - xhr.open("GET", "http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html", true); - xhr.send(); - var worker = new Worker("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js"); - var sharedWorker = new SharedWorker("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js"); - - fetch("file_thirdPartyChild.fetch.html", {cache: "force-cache"} ); - fetch(new Request("file_thirdPartyChild.request.html"), {cache: "force-cache"} ); -</script> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png Binary files differdeleted file mode 100644 index c5916f289..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.img.png +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js deleted file mode 100644 index dbf8f8376..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js +++ /dev/null @@ -1 +0,0 @@ -// dummy script, to be called by self.importScripts(...) diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css b/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css deleted file mode 100644 index 06d6e2672..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.link.css +++ /dev/null @@ -1 +0,0 @@ -/* Dummy CSS file, used by browser_cache.js. */
\ No newline at end of file diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png b/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png Binary files differdeleted file mode 100644 index c5916f289..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.object.png +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html deleted file mode 100644 index 108ed2ffa..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.request.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.request.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js deleted file mode 100644 index 6ddf436c0..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.script.js +++ /dev/null @@ -1 +0,0 @@ -// Dummy child script, used by browser_cache.js diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js deleted file mode 100644 index b262fa10a..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.sharedworker.js +++ /dev/null @@ -1 +0,0 @@ -// dummy file diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt b/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt deleted file mode 100644 index b37cb40e4..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.track.vtt +++ /dev/null @@ -1,13 +0,0 @@ -WEBVTT FILE - -1 -00:00:00.500 --> 00:00:02.000 D:vertical A:start -blah blah blah - -2 -00:00:02.500 --> 00:00:04.300 -this is a test - -3 -00:00:05.000 --> 00:00:07.000 -one more line diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv b/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv Binary files differdeleted file mode 100644 index 68dee3cf2..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.video.ogv +++ /dev/null diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html deleted file mode 100644 index 47e42d1e5..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.worker.fetch.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js deleted file mode 100644 index b04e2c7de..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.js +++ /dev/null @@ -1,9 +0,0 @@ -var xhr = new XMLHttpRequest(); -xhr.open("GET", "http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html", true); -xhr.send(); - -fetch("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.fetch.html", {cache: "force-cache"} ); -var myRequest = new Request("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html"); -fetch(myRequest, {cache: "force-cache"} ); - -self.importScripts("http://example.net/browser/browser/components/originattributes/test/browser/file_thirdPartyChild.import.js"); diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html deleted file mode 100644 index 5b5c55bfe..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.request.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.worker.request.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html deleted file mode 100644 index 9fc107f37..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.worker.xhr.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.worker.xhr.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html b/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html deleted file mode 100644 index f56e7b3c1..000000000 --- a/browser/components/originattributes/test/browser/file_thirdPartyChild.xhr.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<meta content="text/html;charset=utf-8" http-equiv="Content-Type"> -<!-- The child page, used by browser_cache.js --> -<body> -<div>thirdPartyChild.html</div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/head.js b/browser/components/originattributes/test/browser/head.js deleted file mode 100644 index 96559a10d..000000000 --- a/browser/components/originattributes/test/browser/head.js +++ /dev/null @@ -1,365 +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_URL_PATH = "/browser/browser/components/originattributes/test/browser/"; - -// The flags of test modes. -const TEST_MODE_FIRSTPARTY = 0; -const TEST_MODE_NO_ISOLATION = 1; -const TEST_MODE_CONTAINERS = 2; - -// The name of each mode. -const TEST_MODE_NAMES = [ "first party isolation", - "no isolation", - "containers" ]; - -// The frame types. -const TEST_TYPE_FRAME = 0; -const TEST_TYPE_IFRAME = 1; - -// The default frame setting. -const DEFAULT_FRAME_SETTING = [ TEST_TYPE_IFRAME ]; - -let gFirstPartyBasicPage = TEST_URL_PATH + "file_firstPartyBasic.html"; - -/** - * Add a tab for the given url with the specific user context id. - * - * @param aURL - * The url of the page. - * @param aUserContextId - * The user context id for this tab. - * - * @return tab - The tab object of this tab. - * browser - The browser object of this tab. - */ -function* openTabInUserContext(aURL, aUserContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab(aURL, {userContextId: aUserContextId}); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -/** - * Add a tab for a page with the given first party domain. This page will have - * an iframe which is loaded with the given url by default or you could specify - * a frame setting to create nested frames. And this function will also modify - * the 'content' in the ContentTask to the target frame's window object. - * - * @param aURL - * The url of the iframe. - * @param aFirstPartyDomain - * The first party domain. - * @param aFrameSetting - * This setting controls how frames are organized within the page. The - * setting is an array of frame types, the first item indicates the - * frame type (iframe or frame) of the first layer of the frame structure, - * and the second item indicates the second layer, and so on. The aURL will - * be loaded at the deepest layer. This is optional. - * - * @return tab - The tab object of this tab. - * browser - The browser object of this tab. - */ -function* openTabInFirstParty(aURL, aFirstPartyDomain, - aFrameSetting = DEFAULT_FRAME_SETTING) { - - // If the first party domain ends with '/', we remove it. - if (aFirstPartyDomain.endsWith('/')) { - aFirstPartyDomain = aFirstPartyDomain.slice(0, -1); - } - - let basicPageURL = aFirstPartyDomain + gFirstPartyBasicPage; - - // Open the tab for the basic first party page. - let tab = gBrowser.addTab(basicPageURL); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - - let pageArgs = { url: aURL, - frames: aFrameSetting, - typeFrame: TEST_TYPE_FRAME, - typeIFrame: TEST_TYPE_IFRAME, - basicFrameSrc: basicPageURL}; - - // Create the frame structure. - yield ContentTask.spawn(browser, pageArgs, function* (arg) { - let typeFrame = arg.typeFrame; - let typeIFrame = arg.typeIFrame; - - // Redefine the 'content' for allowing us to change its target, and making - // ContentTask.spawn can directly work on the frame element. - this.frameWindow = content; - - Object.defineProperty(this, "content", { - get: () => this.frameWindow - }); - - let frameElement; - let numOfLayers = 0; - - for (let type of arg.frames) { - let document = content.document; - numOfLayers++; - - if (type === typeFrame) { - // Add a frameset which carries the frame element. - let frameSet = document.createElement('frameset'); - frameSet.cols = "50%,50%"; - - let frame = document.createElement('frame'); - let dummyFrame = document.createElement('frame'); - - frameSet.appendChild(frame); - frameSet.appendChild(dummyFrame); - - document.body.appendChild(frameSet); - - frameElement = frame; - } else if (type === typeIFrame) { - // Add an iframe. - let iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - - frameElement = iframe; - } else { - ok(false, "Invalid frame type."); - break; - } - - // Wait for the frame to be loaded. - yield new Promise(done => { - frameElement.addEventListener("load", function loadEnd() { - frameElement.removeEventListener("load", loadEnd, true); - done(); - }, true); - - // If it is the deepest layer, we load the target URL. Otherwise, we - // load a basic page. - if (numOfLayers === arg.frames.length) { - frameElement.setAttribute("src", arg.url); - } else { - frameElement.setAttribute("src", arg.basicFrameSrc); - } - }); - - // Redirect the 'content' to the frame's window. - this.frameWindow = frameElement.contentWindow; - } - }); - - return {tab, browser}; -} - -this.IsolationTestTools = { - /** - * Adds isolation tests for first party isolation, no isolation - * and containers respectively. - * - * @param aTask - * The testing task which will be run in different settings. - */ - _add_task(aTask) { - add_task(function* addTaskForIsolationTests() { - let testSettings = [ - { mode: TEST_MODE_FIRSTPARTY, - skip: false, - prefs: [["privacy.firstparty.isolate", true]] - }, - { mode: TEST_MODE_NO_ISOLATION, - skip: false, - prefs: [["privacy.firstparty.isolate", false]] - }, - { mode: TEST_MODE_CONTAINERS, - skip: false, - prefs: [["privacy.userContext.enabled", true]] - }, - ]; - - // Add test tasks. - for (let testSetting of testSettings) { - IsolationTestTools._addTaskForMode(testSetting.mode, - testSetting.prefs, - testSetting.skip, - aTask); - } - }); - }, - - _addTaskForMode(aMode, aPref, aSkip, aTask) { - if (aSkip) { - return; - } - - add_task(function* () { - info("Starting the test for " + TEST_MODE_NAMES[aMode]); - - // Before run this task, reset the preferences first. - yield SpecialPowers.flushPrefEnv(); - - // Make sure preferences are set properly. - yield SpecialPowers.pushPrefEnv({"set": aPref}); - - yield SpecialPowers.pushPrefEnv({"set": [["dom.ipc.processCount", 1]]}); - - yield aTask(aMode); - }); - }, - - /** - * Add a tab with the given tab setting, this will open different types of - * tabs according to the given test mode. A tab setting means a isolation - * target in different test mode; a tab setting indicates a first party - * domain when testing the first party isolation, it is a user context - * id when testing containers. - * - * @param aMode - * The test mode which decides what type of tabs will be opened. - * @param aURL - * The url which is going to open. - * @param aTabSettingObj - * The tab setting object includes 'firstPartyDomain' for the first party - * domain and 'userContextId' for Containers. - * @param aFrameSetting - * This setting controls how frames are organized within the page. The - * setting is an array of frame types, the first item indicates the - * frame type (iframe or frame) of the first layer of the frame structure, - * and the second item indicates the second layer, and so on. The aURL - * will be loaded at the deepest layer. This is optional. - * - * @return tab - The tab object of this tab. - * browser - The browser object of this tab. - */ - _addTab(aMode, aURL, aTabSettingObj, aFrameSetting) { - if (aMode === TEST_MODE_CONTAINERS) { - return openTabInUserContext(aURL, aTabSettingObj.userContextId); - } - - return openTabInFirstParty(aURL, aTabSettingObj.firstPartyDomain, - aFrameSetting); - - }, - - /** - * Run isolation tests. The framework will run tests with standard combinations - * of prefs and tab settings, and checks whether the isolation is working. - * - * @param aURL - * The URL of the page that will be tested or an object contains 'url', - * the tested page, 'firstFrameSetting' for the frame setting of the first - * tab, and 'secondFrameSetting' for the second tab. - * @param aGetResultFuncs - * An array of functions or a single function which are responsible for - * returning the isolation result back to the framework for further checking. - * Each of these functions will be provided the browser object of the tab, - * that allows modifying or fetchings results from the page content. - * @param aCompareResultFunc - * An optional function which allows modifying the way how does framework - * check results. This function will be provided a boolean to indicate - * the isolation is no or off and two results. This function should return - * a boolean to tell that whether isolation is working. If this function - * is not given, the framework will take case checking by itself. - * @param aBeforeFunc - * An optional function which is called before any tabs are created so - * that the test case can set up/reset local state. - * @param aGetResultImmediately - * An optional boolean to ensure we get results before the next tab is opened. - */ - runTests(aURL, aGetResultFuncs, aCompareResultFunc, aBeforeFunc, - aGetResultImmediately) { - let pageURL; - let firstFrameSetting; - let secondFrameSetting; - - // Request a longer timeout since the test will run a test for three times - // with different settings. Thus, one test here represents three tests. - // For this reason, we triple the timeout. - requestLongerTimeout(3); - - if (typeof aURL === "string") { - pageURL = aURL; - } else if (typeof aURL === "object") { - pageURL = aURL.url; - firstFrameSetting = aURL.firstFrameSetting; - secondFrameSetting = aURL.secondFrameSetting; - } - - if (!Array.isArray(aGetResultFuncs)) { - aGetResultFuncs = [aGetResultFuncs]; - } - - let tabSettings = [ - { firstPartyDomain: "http://example.com", userContextId: 1}, - { firstPartyDomain: "http://example.org", userContextId: 2} - ]; - - this._add_task(function* (aMode) { - let tabSettingA = 0; - - for (let tabSettingB of [0, 1]) { - // Give the test a chance to set up before each case is run. - if (aBeforeFunc) { - yield aBeforeFunc(aMode); - } - - // Create Tabs. - let tabInfoA = yield IsolationTestTools._addTab(aMode, - pageURL, - tabSettings[tabSettingA], - firstFrameSetting); - let resultsA = []; - if (aGetResultImmediately) { - for (let getResultFunc of aGetResultFuncs) { - resultsA.push(yield getResultFunc(tabInfoA.browser)); - } - } - let tabInfoB = yield IsolationTestTools._addTab(aMode, - pageURL, - tabSettings[tabSettingB], - secondFrameSetting); - let i = 0; - for (let getResultFunc of aGetResultFuncs) { - // Fetch results from tabs. - let resultA = aGetResultImmediately ? resultsA[i++] : - yield getResultFunc(tabInfoA.browser); - let resultB = yield getResultFunc(tabInfoB.browser); - - // Compare results. - let result = false; - let shouldIsolate = (aMode !== TEST_MODE_NO_ISOLATION) && - tabSettingA !== tabSettingB; - if (aCompareResultFunc) { - result = yield aCompareResultFunc(shouldIsolate, resultA, resultB); - } else { - result = shouldIsolate ? resultA !== resultB : - resultA === resultB; - } - - let msg = `Testing ${TEST_MODE_NAMES[aMode]} for ` + - `isolation ${shouldIsolate ? "on" : "off"} with TabSettingA ` + - `${tabSettingA} and tabSettingB ${tabSettingB}` + - `, resultA = ${resultA}, resultB = ${resultB}`; - - ok(result, msg); - } - - // Close Tabs. - yield BrowserTestUtils.removeTab(tabInfoA.tab); - yield BrowserTestUtils.removeTab(tabInfoB.tab); - } - }); - } -}; diff --git a/browser/components/originattributes/test/browser/test.html b/browser/components/originattributes/test/browser/test.html deleted file mode 100644 index 214daa4b7..000000000 --- a/browser/components/originattributes/test/browser/test.html +++ /dev/null @@ -1,20 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> - <script> - window.onmessage = function (evt) { - if (evt.data != "HI") { - return; - } - - window.parent.postMessage("OK", "http://mochi.test:8888"); - }; - </script> -</head> -<body> - Hello World. -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test.js b/browser/components/originattributes/test/browser/test.js deleted file mode 100644 index d290af9b0..000000000 --- a/browser/components/originattributes/test/browser/test.js +++ /dev/null @@ -1 +0,0 @@ -var i = 1; diff --git a/browser/components/originattributes/test/browser/test.js^headers^ b/browser/components/originattributes/test/browser/test.js^headers^ deleted file mode 100644 index 881f5bff0..000000000 --- a/browser/components/originattributes/test/browser/test.js^headers^ +++ /dev/null @@ -1 +0,0 @@ -Set-Cookie: test=foo diff --git a/browser/components/originattributes/test/browser/test2.html b/browser/components/originattributes/test/browser/test2.html deleted file mode 100644 index 370be1560..000000000 --- a/browser/components/originattributes/test/browser/test2.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> - <script src="test2.js"></script> -</head> -<body> - Hello World. -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test2.js b/browser/components/originattributes/test/browser/test2.js deleted file mode 100644 index d290af9b0..000000000 --- a/browser/components/originattributes/test/browser/test2.js +++ /dev/null @@ -1 +0,0 @@ -var i = 1; diff --git a/browser/components/originattributes/test/browser/test2.js^headers^ b/browser/components/originattributes/test/browser/test2.js^headers^ deleted file mode 100644 index 43604be7f..000000000 --- a/browser/components/originattributes/test/browser/test2.js^headers^ +++ /dev/null @@ -1 +0,0 @@ -Set-Cookie: test2=foo diff --git a/browser/components/originattributes/test/browser/test_firstParty.html b/browser/components/originattributes/test/browser/test_firstParty.html deleted file mode 100644 index a90e01c4c..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty.html +++ /dev/null @@ -1,15 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"/> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> -</head> -<body> - <div> - <iframe id="iframe1" src="http://example.com"></iframe> - <iframe id="iframe2" sandbox="" src="http://example.com"></iframe> - <iframe id="iframe3" sandbox="allow-same-origin" src="http://example.com"></iframe> - </div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test_firstParty_cookie.html b/browser/components/originattributes/test/browser/test_firstParty_cookie.html deleted file mode 100644 index 44547c0d7..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_cookie.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> - <script src="test.js"></script> -</head> -<body> - Hello World. - <iframe id="iframe1" src="test2.html"></iframe> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html deleted file mode 100644 index 3c52d4f8c..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html +++ /dev/null @@ -1,9 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf8" http-equiv="refresh" content="0; url=http://example.com/"/> - <title>Test for Bug 1260931</title> -</head> -<body> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html deleted file mode 100644 index 7b794a011..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html +++ /dev/null @@ -1,9 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"/> - <title>Test for Bug 1260931</title> -</head> -<body> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^ b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^ deleted file mode 100644 index c6d2757aa..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^ +++ /dev/null @@ -1,2 +0,0 @@ -HTTP 302 Found -Location: http://example.com/browser/browser/components/originattributes/test/browser/dummy.html diff --git a/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html b/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html deleted file mode 100644 index fd7df46c1..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"/> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> -</head> -<body> - <div> - <iframe id="iframe1" src="test_firstParty_http_redirect.html"></iframe> - </div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/test_firstParty_postMessage.html b/browser/components/originattributes/test/browser/test_firstParty_postMessage.html deleted file mode 100644 index 5df8a5950..000000000 --- a/browser/components/originattributes/test/browser/test_firstParty_postMessage.html +++ /dev/null @@ -1,28 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"/> - <title>Test for Bug 1260931</title> - <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> -</head> -<script> -function onload() { - let iframe1 = document.getElementById("iframe1"); - iframe1.contentWindow.postMessage("HI", "http://mochi.test:8888"); -} - -window.onmessage = function (evt) { - document.getElementById("message").textContent = evt.data; - - let iframe2 = document.createElement("iframe"); - iframe2.src = "dummy.html"; - document.body.appendChild(iframe2); -}; -</script> -<body onload="onload()"> - <div> - <iframe id="iframe1" src="test.html"></iframe> - <span id="message"></span> - </div> -</body> -</html> diff --git a/browser/components/originattributes/test/browser/window.html b/browser/components/originattributes/test/browser/window.html deleted file mode 100644 index 34216030c..000000000 --- a/browser/components/originattributes/test/browser/window.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <meta charset="utf8"> - <title>Page creating a popup</title> - </head> - <body> - <script type="text/javascript"> - var w = window.open(); - w.document.body.innerHTML = "<iframe id='iframe1' src='data:text/plain,test2'></iframe>"; - </script> - </body> -</html> diff --git a/browser/components/originattributes/test/browser/worker_blobify.js b/browser/components/originattributes/test/browser/worker_blobify.js deleted file mode 100644 index 56c0996a3..000000000 --- a/browser/components/originattributes/test/browser/worker_blobify.js +++ /dev/null @@ -1,11 +0,0 @@ -// Wait for a string to be posted to this worker. -// Create a blob containing this string, and then -// post back a blob URL pointing to the blob. -self.addEventListener("message", function (e) { - try { - var blobURL = URL.createObjectURL(new Blob([e.data])); - postMessage({ blobURL }); - } catch (e) { - postMessage({ error: e.message }); - } -}, false); diff --git a/browser/components/originattributes/test/browser/worker_deblobify.js b/browser/components/originattributes/test/browser/worker_deblobify.js deleted file mode 100644 index 1d6511a20..000000000 --- a/browser/components/originattributes/test/browser/worker_deblobify.js +++ /dev/null @@ -1,31 +0,0 @@ -// Wait for a blob URL to be posted to this worker. -// Obtain the blob, and read the string contained in it. -// Post back the string. - -var postStringInBlob = function (blobObject) { - var fileReader = new FileReaderSync(); - var result = fileReader.readAsText(blobObject); - postMessage(result); -}; - -self.addEventListener("message", function (e) { - if ("error" in e.data) { - postMessage(e.data); - return; - } - var blobURL = e.data.blobURL, - xhr = new XMLHttpRequest(); - try { - xhr.open("GET", blobURL, true); - xhr.onload = function () { - postStringInBlob(xhr.response); - }; - xhr.onerror = function () { - postMessage({ error: "xhr error" }); - }; - xhr.responseType = "blob"; - xhr.send(); - } catch (e) { - postMessage({ error: e.message }); - } -}, false); diff --git a/browser/components/originattributes/test/mochitest/file_empty.html b/browser/components/originattributes/test/mochitest/file_empty.html deleted file mode 100644 index bc98b4d2e..000000000 --- a/browser/components/originattributes/test/mochitest/file_empty.html +++ /dev/null @@ -1,2 +0,0 @@ -<h1>I'm just a support file</h1> -<p>I get loaded to do permission testing.</p>
\ No newline at end of file diff --git a/browser/components/originattributes/test/mochitest/mochitest.ini b/browser/components/originattributes/test/mochitest/mochitest.ini deleted file mode 100644 index 5df9998ca..000000000 --- a/browser/components/originattributes/test/mochitest/mochitest.ini +++ /dev/null @@ -1,5 +0,0 @@ -[DEFAULT] -support-files = - file_empty.html - -[test_permissions_api.html] diff --git a/browser/components/originattributes/test/mochitest/test_permissions_api.html b/browser/components/originattributes/test/mochitest/test_permissions_api.html deleted file mode 100644 index 63c74d1fe..000000000 --- a/browser/components/originattributes/test/mochitest/test_permissions_api.html +++ /dev/null @@ -1,207 +0,0 @@ -<!-- - Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ ---> -<!DOCTYPE HTML> -<html> - -<head> - <meta charset="utf-8"> - <title>Test for Permissions API</title> - <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> - <link rel="stylesheet" href="/tests/SimpleTest/test.css"> -</head> - -<body> - <pre id="test"></pre> - <script type="application/javascript;version=1.8"> - /*globals SpecialPowers, SimpleTest, is, ok, */ - 'use strict'; - - const { - UNKNOWN_ACTION, - PROMPT_ACTION, - ALLOW_ACTION, - DENY_ACTION - } = SpecialPowers.Ci.nsIPermissionManager; - - SimpleTest.waitForExplicitFinish(); - - const PERMISSIONS = [{ - name: 'geolocation', - type: 'geo' - }, { - name: 'notifications', - type: 'desktop-notification' - }, { - name: 'push', - type: 'desktop-notification' - }, ]; - - const UNSUPPORTED_PERMISSIONS = [ - 'foobarbaz', // Not in spec, for testing only. - 'midi', - ]; - - // Create a closure, so that tests are run on the correct window object. - function createPermissionTester(aWindow) { - return { - setPermissions(allow) { - const permissions = PERMISSIONS.map(({ type }) => { - return { - type, - allow, - 'context': aWindow.document - }; - }); - return new Promise((resolve) => { - SpecialPowers.popPermissions(() => { - SpecialPowers.pushPermissions(permissions, resolve); - }); - }); - }, - revokePermissions() { - const promisesToRevoke = PERMISSIONS.map(({ name }) => { - return aWindow.navigator.permissions - .revoke({ name }) - .then( - ({ state }) => is(state, 'prompt', `correct state for '${name}'`), - () => ok(false, `revoke should not have rejected for '${name}'`) - ); - }); - return Promise.all(promisesToRevoke); - }, - revokeUnsupportedPermissions() { - const promisesToRevoke = UNSUPPORTED_PERMISSIONS.map(({ name }) => { - return aWindow.navigator.permissions - .revoke({ name }) - .then( - () => ok(false, `revoke should not have resolved for '${name}'`), - error => is(error.name, 'TypeError', `revoke should have thrown TypeError for '${name}'`) - ); - }); - return Promise.all(promisesToRevoke); - }, - checkPermissions(state) { - const promisesToQuery = PERMISSIONS.map(({ name }) => { - return aWindow.navigator.permissions - .query({ name }) - .then( - () => is(state, state, `correct state for '${name}'`), - () => ok(false, `query should not have rejected for '${name}'`) - ); - }); - return Promise.all(promisesToQuery); - }, - checkUnsupportedPermissions() { - const promisesToQuery = UNSUPPORTED_PERMISSIONS.map(({ name }) => { - return aWindow.navigator.permissions - .query({ name }) - .then( - () => ok(false, `query should not have resolved for '${name}'`), - error => { - is(error.name, 'TypeError', - `query should have thrown TypeError for '${name}'`); - } - ); - }); - return Promise.all(promisesToQuery); - }, - promiseStateChanged(name, state) { - return aWindow.navigator.permissions - .query({ name }) - .then(status => { - return new Promise( resolve => { - status.onchange = () => { - status.onchange = null; - is(status.state, state, `state changed for '${name}'`); - resolve(); - }; - }); - }, - () => ok(false, `query should not have rejected for '${name}'`)); - }, - testStatusOnChange() { - return new Promise((resolve) => { - SpecialPowers.popPermissions(() => { - const permission = 'geolocation'; - const promiseGranted = this.promiseStateChanged(permission, 'granted'); - this.setPermissions(ALLOW_ACTION); - promiseGranted.then(() => { - const promisePrompt = this.promiseStateChanged(permission, 'prompt'); - SpecialPowers.popPermissions(); - return promisePrompt; - }).then(resolve); - }); - }); - }, - testInvalidQuery() { - return aWindow.navigator.permissions - .query({ name: 'invalid' }) - .then( - () => ok(false, 'invalid query should not have resolved'), - () => ok(true, 'invalid query should have rejected') - ); - }, - testInvalidRevoke() { - return aWindow.navigator.permissions - .revoke({ name: 'invalid' }) - .then( - () => ok(false, 'invalid revoke should not have resolved'), - () => ok(true, 'invalid revoke should have rejected') - ); - }, - }; - } - - function enablePrefs() { - const ops = { - 'set': [ - ['dom.permissions.revoke.enable', true], - ['privacy.firstparty.isolate', true], - ], - }; - return SpecialPowers.pushPrefEnv(ops); - } - - function createIframe() { - return new Promise((resolve) => { - const iframe = document.createElement('iframe'); - iframe.src = 'file_empty.html'; - iframe.onload = () => resolve(iframe.contentWindow); - document.body.appendChild(iframe); - }); - } - debugger; - window.onload = () => { - enablePrefs() - .then(createIframe) - .then(createPermissionTester) - .then((tester) => { - return tester - .checkUnsupportedPermissions() - .then(() => tester.setPermissions(UNKNOWN_ACTION)) - .then(() => tester.checkPermissions('prompt')) - .then(() => tester.setPermissions(PROMPT_ACTION)) - .then(() => tester.checkPermissions('prompt')) - .then(() => tester.setPermissions(ALLOW_ACTION)) - .then(() => tester.checkPermissions('granted')) - .then(() => tester.setPermissions(DENY_ACTION)) - .then(() => tester.checkPermissions('denied')) - .then(() => tester.testStatusOnChange()) - .then(() => tester.testInvalidQuery()) - .then(() => tester.revokeUnsupportedPermissions()) - .then(() => tester.revokePermissions()) - .then(() => tester.checkPermissions('prompt')) - .then(() => tester.testInvalidRevoke()); - }) - .then(SimpleTest.finish) - .catch((e) => { - ok(false, `Unexpected error ${e}`); - SimpleTest.finish(); - }); - }; - </script> -</body> - -</html> diff --git a/browser/components/places/tests/browser/.eslintrc.js b/browser/components/places/tests/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/places/tests/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/places/tests/browser/bookmark_dummy_1.html b/browser/components/places/tests/browser/bookmark_dummy_1.html deleted file mode 100644 index c03e0c18c..000000000 --- a/browser/components/places/tests/browser/bookmark_dummy_1.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> -<title>Bookmark Dummy 1</title> -<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta> -</head> -<body> -<p>Bookmark Dummy 1</p> -</body> -</html> diff --git a/browser/components/places/tests/browser/bookmark_dummy_2.html b/browser/components/places/tests/browser/bookmark_dummy_2.html deleted file mode 100644 index 229a730b3..000000000 --- a/browser/components/places/tests/browser/bookmark_dummy_2.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> -<title>Bookmark Dummy 2</title> -<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta> -</head> -<body> -<p>Bookmark Dummy 2</p> -</body> -</html> diff --git a/browser/components/places/tests/browser/browser.ini b/browser/components/places/tests/browser/browser.ini deleted file mode 100644 index 5dce31653..000000000 --- a/browser/components/places/tests/browser/browser.ini +++ /dev/null @@ -1,58 +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/. - -[DEFAULT] -support-files = - head.js - framedPage.html - frameLeft.html - frameRight.html - sidebarpanels_click_test_page.html - keyword_form.html - -[browser_0_library_left_pane_migration.js] -[browser_410196_paste_into_tags.js] -subsuite = clipboard -[browser_416459_cut.js] -subsuite = clipboard -[browser_423515.js] -[browser_425884.js] -[browser_435851_copy_query.js] -subsuite = clipboard -[browser_475045.js] -[browser_555547.js] -[browser_bookmarklet_windowOpen.js] -support-files = - pageopeningwindow.html -[browser_bookmarkProperties_addFolderDefaultButton.js] -[browser_bookmarkProperties_addKeywordForThisSearch.js] -[browser_bookmarkProperties_addLivemark.js] -[browser_bookmarkProperties_editTagContainer.js] -[browser_bookmarkProperties_readOnlyRoot.js] -[browser_bookmarksProperties.js] -[browser_drag_bookmarks_on_toolbar.js] -[browser_forgetthissite_single.js] -[browser_history_sidebar_search.js] -[browser_library_batch_delete.js] -[browser_library_commands.js] -[browser_library_downloads.js] -[browser_library_infoBox.js] -[browser_library_left_pane_fixnames.js] -[browser_library_left_pane_select_hierarchy.js] -[browser_library_middleclick.js] -[browser_library_open_leak.js] -[browser_library_openFlatContainer.js] -[browser_library_panel_leak.js] -[browser_library_search.js] -[browser_library_views_liveupdate.js] -[browser_markPageAsFollowedLink.js] -[browser_sidebarpanels_click.js] -skip-if = true # temporarily disabled for breaking the treeview - bug 658744 -[browser_sort_in_library.js] -[browser_toolbarbutton_menu_context.js] -[browser_views_liveupdate.js] -[browser_bookmark_all_tabs.js] -support-files = - bookmark_dummy_1.html - bookmark_dummy_2.html diff --git a/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js b/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js deleted file mode 100644 index a7089b497..000000000 --- a/browser/components/places/tests/browser/browser_0_library_left_pane_migration.js +++ /dev/null @@ -1,90 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 we correctly migrate Library left pane to the latest version. - * Note: this test MUST be the first between browser chrome tests, or results - * of next tests could be unexpected due to PlacesUIUtils getters. - */ - -const TEST_URI = "http://www.mozilla.org/"; - -add_task(function* () { - // Sanity checks. - ok(PlacesUtils, "PlacesUtils is running in chrome context"); - ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context"); - ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0, - "Left pane version in chrome context, current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION ); - - // Check if we have any left pane folder already set, remove it eventually. - let leftPaneItems = PlacesUtils.annotations - .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - if (leftPaneItems.length > 0) { - // The left pane has already been created, touching it now would cause - // next tests to rely on wrong values (and possibly crash) - is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder"); - // Check version. - let version = PlacesUtils.annotations.getItemAnnotation(leftPaneItems[0], - PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, "Left pane version is actual"); - ok(true, "left pane has already been created, skipping test"); - return; - } - - // Create a fake left pane folder with an old version (current version - 1). - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.rootGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER, - title: "" - }); - - let folderId = yield PlacesUtils.promiseItemId(folder.guid); - PlacesUtils.annotations.setItemAnnotation(folderId, - PlacesUIUtils.ORGANIZER_FOLDER_ANNO, - PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION - 1, - 0, - PlacesUtils.annotations.EXPIRE_NEVER); - - // Check fake left pane root has been correctly created. - leftPaneItems = - PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder"); - is(leftPaneItems[0], folderId, "left pane root itemId is correct"); - - // Check version. - let version = PlacesUtils.annotations.getItemAnnotation(folderId, - PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION - 1, "Left pane version correctly set"); - - // Open Library, this will upgrade our left pane version. - let organizer = yield promiseLibrary(); - - // Check left pane. - ok(PlacesUIUtils.leftPaneFolderId > 0, "Left pane folder correctly created"); - leftPaneItems = - PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder"); - let leftPaneRoot = leftPaneItems[0]; - is(leftPaneRoot, PlacesUIUtils.leftPaneFolderId, - "leftPaneFolderId getter has correct value"); - - // Check version has been upgraded. - version = PlacesUtils.annotations.getItemAnnotation(leftPaneRoot, - PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, - "Left pane version has been correctly upgraded"); - - // Check left pane is populated. - organizer.PlacesOrganizer.selectLeftPaneQuery("History"); - is(organizer.PlacesOrganizer._places.selectedNode.itemId, - PlacesUIUtils.leftPaneQueries["History"], - "Library left pane is populated and working"); - - yield promiseLibraryClosed(organizer); -}); diff --git a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js deleted file mode 100644 index 2acb1d9b7..000000000 --- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js +++ /dev/null @@ -1,114 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -"use strict"; - -const TEST_URL = Services.io.newURI("http://example.com/", null, null); -const MOZURISPEC = Services.io.newURI("http://mozilla.com/", null, null); - -add_task(function* () { - let organizer = yield promiseLibrary(); - - ok(PlacesUtils, "PlacesUtils in scope"); - ok(PlacesUIUtils, "PlacesUIUtils in scope"); - - let PlacesOrganizer = organizer.PlacesOrganizer; - ok(PlacesOrganizer, "Places organizer in scope"); - - let ContentTree = organizer.ContentTree; - ok(ContentTree, "ContentTree is in scope"); - - let visits = {uri: MOZURISPEC, transition: PlacesUtils.history.TRANSITION_TYPED}; - yield PlacesTestUtils.addVisits(visits); - - // create an initial tag to work with - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - title: "bookmark/" + TEST_URL.spec, - url: TEST_URL - }); - - ok(bm, "A bookmark was added"); - PlacesUtils.tagging.tagURI(TEST_URL, ["foo"]); - let tags = PlacesUtils.tagging.getTagsForURI(TEST_URL); - is(tags[0], "foo", "tag is foo"); - - // focus the new tag - focusTag(PlacesOrganizer); - - let populate = () => copyHistNode(PlacesOrganizer, ContentTree); - yield promiseClipboard(populate, PlacesUtils.TYPE_X_MOZ_PLACE); - - focusTag(PlacesOrganizer); - PlacesOrganizer._places.controller.paste(); - - // re-focus the history again - PlacesOrganizer.selectLeftPaneQuery("History"); - let histContainer = PlacesOrganizer._places.selectedNode; - PlacesUtils.asContainer(histContainer); - histContainer.containerOpen = true; - PlacesOrganizer._places.selectNode(histContainer.getChild(0)); - let histNode = ContentTree.view.view.nodeForTreeIndex(0); - ok(histNode, "histNode exists: " + histNode.title); - - // check to see if the history node is tagged! - tags = PlacesUtils.tagging.getTagsForURI(MOZURISPEC); - ok(tags.length == 1, "history node is tagged: " + tags.length); - - // check if a bookmark was created - let bookmarks = []; - yield PlacesUtils.bookmarks.fetch({url: MOZURISPEC}, bm => { - bookmarks.push(bm); - }); - ok(bookmarks.length > 0, "bookmark exists for the tagged history item"); - - // is the bookmark visible in the UI? - // get the Unsorted Bookmarks node - PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - - // now we can see what is in the ContentTree tree - let unsortedNode = ContentTree.view.view.nodeForTreeIndex(1); - ok(unsortedNode, "unsortedNode is not null: " + unsortedNode.uri); - is(unsortedNode.uri, MOZURISPEC.spec, "node uri's are the same"); - - yield promiseLibraryClosed(organizer); - - // Remove new Places data we created. - PlacesUtils.tagging.untagURI(MOZURISPEC, ["foo"]); - PlacesUtils.tagging.untagURI(TEST_URL, ["foo"]); - tags = PlacesUtils.tagging.getTagsForURI(TEST_URL); - is(tags.length, 0, "tags are gone"); - - yield PlacesUtils.bookmarks.eraseEverything(); - yield PlacesTestUtils.clearHistory(); -}); - -function focusTag(PlacesOrganizer) { - PlacesOrganizer.selectLeftPaneQuery("Tags"); - let tags = PlacesOrganizer._places.selectedNode; - tags.containerOpen = true; - let fooTag = tags.getChild(0); - let tagNode = fooTag; - PlacesOrganizer._places.selectNode(fooTag); - is(tagNode.title, 'foo', "tagNode title is foo"); - let ip = PlacesOrganizer._places.insertionPoint; - ok(ip.isTag, "IP is a tag"); -} - -function copyHistNode(PlacesOrganizer, ContentTree) { - // focus the history object - PlacesOrganizer.selectLeftPaneQuery("History"); - let histContainer = PlacesOrganizer._places.selectedNode; - PlacesUtils.asContainer(histContainer); - histContainer.containerOpen = true; - PlacesOrganizer._places.selectNode(histContainer.getChild(0)); - let histNode = ContentTree.view.view.nodeForTreeIndex(0); - ContentTree.view.selectNode(histNode); - is(histNode.uri, MOZURISPEC.spec, - "historyNode exists: " + histNode.uri); - // copy the history node - ContentTree.view.controller.copy(); -} diff --git a/browser/components/places/tests/browser/browser_416459_cut.js b/browser/components/places/tests/browser/browser_416459_cut.js deleted file mode 100644 index 6f3f8cdd5..000000000 --- a/browser/components/places/tests/browser/browser_416459_cut.js +++ /dev/null @@ -1,83 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const TEST_URL = "http://example.com/"; - -add_task(function* () { - yield PlacesUtils.bookmarks.eraseEverything(); - let organizer = yield promiseLibrary(); - - registerCleanupFunction(function* () { - yield promiseLibraryClosed(organizer); - yield PlacesUtils.bookmarks.eraseEverything(); - }); - - let PlacesOrganizer = organizer.PlacesOrganizer; - let ContentTree = organizer.ContentTree; - - // Sanity checks. - ok(PlacesUtils, "PlacesUtils in scope"); - ok(PlacesUIUtils, "PlacesUIUtils in scope"); - ok(PlacesOrganizer, "PlacesOrganizer in scope"); - ok(ContentTree, "ContentTree is in scope"); - - // Test with multiple entries to ensure they retain their order. - let bookmarks = []; - bookmarks.push(yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: TEST_URL, - title: "0" - })); - bookmarks.push(yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: TEST_URL, - title: "1" - })); - bookmarks.push(yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: TEST_URL, - title: "2" - })); - - yield selectBookmarksIn(organizer, bookmarks, "BookmarksToolbar"); - - yield promiseClipboard(() => { - info("Cutting selection"); - ContentTree.view.controller.cut(); - }, PlacesUtils.TYPE_X_MOZ_PLACE); - - info("Selecting UnfiledBookmarks in the left pane"); - PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - info("Pasting clipboard"); - ContentTree.view.controller.paste(); - - yield selectBookmarksIn(organizer, bookmarks, "UnfiledBookmarks"); -}); - -var selectBookmarksIn = Task.async(function* (organizer, bookmarks, aLeftPaneQuery) { - let PlacesOrganizer = organizer.PlacesOrganizer; - let ContentTree = organizer.ContentTree; - info("Selecting " + aLeftPaneQuery + " in the left pane"); - PlacesOrganizer.selectLeftPaneQuery(aLeftPaneQuery); - - let ids = []; - for (let {guid} of bookmarks) { - let bookmark = yield PlacesUtils.bookmarks.fetch(guid); - is (bookmark.parentGuid, PlacesOrganizer._places.selectedNode.targetFolderGuid, - "Bookmark has the right parent"); - ids.push(yield PlacesUtils.promiseItemId(bookmark.guid)); - } - - info("Selecting the bookmarks in the right pane"); - ContentTree.view.selectItems(ids); - - for (let node of ContentTree.view.selectedNodes) { - is(node.bookmarkIndex, node.title, - "Found the expected bookmark in the expected position"); - } -}); diff --git a/browser/components/places/tests/browser/browser_423515.js b/browser/components/places/tests/browser/browser_423515.js deleted file mode 100644 index 4d3da8fc1..000000000 --- a/browser/components/places/tests/browser/browser_423515.js +++ /dev/null @@ -1,173 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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/. */ - -function test() { - // sanity check - ok(PlacesUtils, "checking PlacesUtils, running in chrome context?"); - ok(PlacesUIUtils, "checking PlacesUIUtils, running in chrome context?"); - ok(PlacesControllerDragHelper, "checking PlacesControllerDragHelper, running in chrome context?"); - - const IDX = PlacesUtils.bookmarks.DEFAULT_INDEX; - - // setup - var rootId = PlacesUtils.bookmarks.createFolder(PlacesUtils.toolbarFolderId, "", IDX); - var rootNode = PlacesUtils.getFolderContents(rootId, false, true).root; - is(rootNode.childCount, 0, "confirm test root is empty"); - - var tests = []; - - // add a regular folder, should be moveable - tests.push({ - populate: function() { - this.id = - PlacesUtils.bookmarks.createFolder(rootId, "", IDX); - }, - validate: function() { - is(rootNode.childCount, 1, - "populate added data to the test root"); - is(PlacesControllerDragHelper.canMoveNode(rootNode.getChild(0)), - true, "can move regular folder node"); - } - }); - - // add a regular folder shortcut, should be moveable - tests.push({ - populate: function() { - this.folderId = - PlacesUtils.bookmarks.createFolder(rootId, "foo", IDX); - this.shortcutId = - PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder="+this.folderId), IDX, "bar"); - }, - validate: function() { - is(rootNode.childCount, 2, - "populated data to the test root"); - - var folderNode = rootNode.getChild(0); - is(folderNode.type, 6, "node is folder"); - is(this.folderId, folderNode.itemId, "folder id and folder node item id match"); - - var shortcutNode = rootNode.getChild(1); - is(shortcutNode.type, 9, "node is folder shortcut"); - is(this.shortcutId, shortcutNode.itemId, "shortcut id and shortcut node item id match"); - - var concreteId = PlacesUtils.getConcreteItemId(shortcutNode); - is(concreteId, folderNode.itemId, "shortcut node id and concrete id match"); - - is(PlacesControllerDragHelper.canMoveNode(shortcutNode), - true, "can move folder shortcut node"); - } - }); - - // add a regular query, should be moveable - tests.push({ - populate: function() { - this.bookmarkId = - PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("http://foo.com"), IDX, "foo"); - this.queryId = - PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:terms=foo"), IDX, "bar"); - }, - validate: function() { - is(rootNode.childCount, 2, - "populated data to the test root"); - - var bmNode = rootNode.getChild(0); - is(bmNode.itemId, this.bookmarkId, "bookmark id and bookmark node item id match"); - - var queryNode = rootNode.getChild(1); - is(queryNode.itemId, this.queryId, "query id and query node item id match"); - - is(PlacesControllerDragHelper.canMoveNode(queryNode), - true, "can move query node"); - } - }); - - // test that special folders cannot be moved - // test that special folders shortcuts can be moved - tests.push({ - folders: [PlacesUtils.bookmarksMenuFolderId, - PlacesUtils.tagsFolderId, PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.toolbarFolderId], - shortcuts: {}, - populate: function() { - for (var i = 0; i < this.folders.length; i++) { - var id = this.folders[i]; - this.shortcuts[id] = - PlacesUtils.bookmarks.insertBookmark(rootId, makeURI("place:folder=" + id), IDX, ""); - } - }, - validate: function() { - // test toolbar shortcut node - is(rootNode.childCount, this.folders.length, - "populated data to the test root"); - - function getRootChildNode(aId) { - var node = PlacesUtils.getFolderContents(PlacesUtils.placesRootId, false, true).root; - for (var i = 0; i < node.childCount; i++) { - var child = node.getChild(i); - if (child.itemId == aId) { - node.containerOpen = false; - return child; - } - } - node.containerOpen = false; - ok(false, "Unable to find child node"); - return null; - } - - for (var i = 0; i < this.folders.length; i++) { - var id = this.folders[i]; - - var node = getRootChildNode(id); - isnot(node, null, "Node found"); - is(PlacesControllerDragHelper.canMoveNode(node), - false, "shouldn't be able to move special folder node"); - - var shortcutId = this.shortcuts[id]; - var shortcutNode = rootNode.getChild(i); - - is(shortcutNode.itemId, shortcutId, "shortcut id and shortcut node item id match"); - - dump("can move shortcut node?\n"); - is(PlacesControllerDragHelper.canMoveNode(shortcutNode), - true, "should be able to move special folder shortcut node"); - } - } - }); - - // test that a tag container cannot be moved - tests.push({ - populate: function() { - // tag a uri - this.uri = makeURI("http://foo.com"); - PlacesUtils.tagging.tagURI(this.uri, ["bar"]); - registerCleanupFunction(() => PlacesUtils.tagging.untagURI(this.uri, ["bar"])); - }, - validate: function() { - // get tag root - var query = PlacesUtils.history.getNewQuery(); - var options = PlacesUtils.history.getNewQueryOptions(); - options.resultType = Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY; - var tagsNode = PlacesUtils.history.executeQuery(query, options).root; - - tagsNode.containerOpen = true; - is(tagsNode.childCount, 1, "has new tag"); - - var tagNode = tagsNode.getChild(0); - - is(PlacesControllerDragHelper.canMoveNode(tagNode), - false, "should not be able to move tag container node"); - tagsNode.containerOpen = false; - } - }); - - tests.forEach(function(aTest) { - PlacesUtils.bookmarks.removeFolderChildren(rootId); - aTest.populate(); - aTest.validate(); - }); - - rootNode.containerOpen = false; - PlacesUtils.bookmarks.removeItem(rootId); -} diff --git a/browser/components/places/tests/browser/browser_425884.js b/browser/components/places/tests/browser/browser_425884.js deleted file mode 100644 index 655eb1ffd..000000000 --- a/browser/components/places/tests/browser/browser_425884.js +++ /dev/null @@ -1,127 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/* - Deep copy of bookmark data, using the front-end codepath: - - - create test folder A - - add a subfolder to folder A, and add items to it - - validate folder A (sanity check) - - copy folder A, creating new folder B, using the front-end path - - validate folder B - - undo copy transaction - - validate folder B (empty) - - redo copy transaction - - validate folder B's contents -*/ - -add_task(function* () { - // sanity check - ok(PlacesUtils, "checking PlacesUtils, running in chrome context?"); - ok(PlacesUIUtils, "checking PlacesUIUtils, running in chrome context?"); - - let toolbarId = PlacesUtils.toolbarFolderId; - let toolbarNode = PlacesUtils.getFolderContents(toolbarId).root; - - let oldCount = toolbarNode.childCount; - let testRoot = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - type: PlacesUtils.bookmarks.TYPE_FOLDER, - title: "test root" - }); - is(toolbarNode.childCount, oldCount+1, "confirm test root node is a container, and is empty"); - - let testRootNode = toolbarNode.getChild(toolbarNode.childCount-1); - testRootNode.QueryInterface(Ci.nsINavHistoryContainerResultNode); - testRootNode.containerOpen = true; - is(testRootNode.childCount, 0, "confirm test root node is a container, and is empty"); - - // create folder A, fill it, validate its contents - let folderA = yield PlacesUtils.bookmarks.insert({ - type: PlacesUtils.bookmarks.TYPE_FOLDER, - parentGuid: testRoot.guid, - title: "A" - }); - - yield populate(folderA); - - let folderAId = yield PlacesUtils.promiseItemId(folderA.guid); - let folderANode = PlacesUtils.getFolderContents(folderAId).root; - validate(folderANode); - is(testRootNode.childCount, 1, "create test folder"); - - // copy it, using the front-end helper functions - let serializedNode = PlacesUtils.wrapNode(folderANode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER); - let rawNode = PlacesUtils.unwrapNodes(serializedNode, PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER).shift(); - // confirm serialization - ok(rawNode.type, "confirm json node"); - folderANode.containerOpen = false; - - let testRootId = yield PlacesUtils.promiseItemId(testRoot.guid); - let transaction = PlacesUIUtils.makeTransaction(rawNode, - PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER, - testRootId, - -1, - true); - ok(transaction, "create transaction"); - PlacesUtils.transactionManager.doTransaction(transaction); - // confirm copy - is(testRootNode.childCount, 2, "create test folder via copy"); - - // validate the copy - let folderBNode = testRootNode.getChild(1); - validate(folderBNode); - - // undo the transaction, confirm the removal - PlacesUtils.transactionManager.undoTransaction(); - is(testRootNode.childCount, 1, "confirm undo removed the copied folder"); - - // redo the transaction - PlacesUtils.transactionManager.redoTransaction(); - is(testRootNode.childCount, 2, "confirm redo re-copied the folder"); - folderBNode = testRootNode.getChild(1); - validate(folderBNode); - - // Close containers, cleaning up their observers. - testRootNode.containerOpen = false; - toolbarNode.containerOpen = false; - - // clean up - PlacesUtils.transactionManager.undoTransaction(); - yield PlacesUtils.bookmarks.remove(folderA.guid); -}); - -var populate = Task.async(function* (parentFolder) { - let folder = yield PlacesUtils.bookmarks.insert({ - type: PlacesUtils.bookmarks.TYPE_FOLDER, - parentGuid: parentFolder.guid, - title: "test folder" - }); - - yield PlacesUtils.bookmarks.insert({ - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - parentGuid: folder.guid, - title: "test bookmark", - url: "http://foo" - }); - - yield PlacesUtils.bookmarks.insert({ - type: PlacesUtils.bookmarks.TYPE_SEPARATOR, - parentGuid: folder.guid - }); -}); - -function validate(aNode) { - PlacesUtils.asContainer(aNode); - aNode.containerOpen = true; - is(aNode.childCount, 1, "confirm child count match"); - var folderNode = aNode.getChild(0); - is(folderNode.title, "test folder", "confirm folder title"); - PlacesUtils.asContainer(folderNode); - folderNode.containerOpen = true; - is(folderNode.childCount, 2, "confirm child count match"); - folderNode.containerOpen = false; - aNode.containerOpen = false; -} diff --git a/browser/components/places/tests/browser/browser_435851_copy_query.js b/browser/components/places/tests/browser/browser_435851_copy_query.js deleted file mode 100644 index 92f818b41..000000000 --- a/browser/components/places/tests/browser/browser_435851_copy_query.js +++ /dev/null @@ -1,59 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -/* test that copying a non movable query or folder shortcut makes a new query with the same url, not a deep copy */ - -const SHORTCUT_URL = "place:folder=2"; -const QUERY_URL = "place:sort=8&maxResults=10"; - -add_task(function* copy_toolbar_shortcut() { - let library = yield promiseLibrary(); - - registerCleanupFunction(function () { - library.close(); - PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); - }); - - library.PlacesOrganizer.selectLeftPaneQuery("BookmarksToolbar"); - - yield promiseClipboard(function () { library.PlacesOrganizer._places.controller.copy(); }, - PlacesUtils.TYPE_X_MOZ_PLACE); - - library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - library.ContentTree.view.controller.paste(); - - let toolbarCopyNode = library.ContentTree.view.view.nodeForTreeIndex(0); - is(toolbarCopyNode.type, - Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT, - "copy is still a folder shortcut"); - - PlacesUtils.bookmarks.removeItem(toolbarCopyNode.itemId); - library.PlacesOrganizer.selectLeftPaneQuery("BookmarksToolbar"); - is(library.PlacesOrganizer._places.selectedNode.type, - Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT, - "original is still a folder shortcut"); -}); - -add_task(function* copy_history_query() { - let library = yield promiseLibrary(); - - library.PlacesOrganizer.selectLeftPaneQuery("History"); - - yield promiseClipboard(function () { library.PlacesOrganizer._places.controller.copy(); }, - PlacesUtils.TYPE_X_MOZ_PLACE); - - library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - library.ContentTree.view.controller.paste(); - - let historyCopyNode = library.ContentTree.view.view.nodeForTreeIndex(0); - is(historyCopyNode.type, - Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY, - "copy is still a query"); - - PlacesUtils.bookmarks.removeItem(historyCopyNode.itemId); - library.PlacesOrganizer.selectLeftPaneQuery("History"); - is(library.PlacesOrganizer._places.selectedNode.type, - Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY, - "original is still a query"); -}); diff --git a/browser/components/places/tests/browser/browser_475045.js b/browser/components/places/tests/browser/browser_475045.js deleted file mode 100644 index 7d562349b..000000000 --- a/browser/components/places/tests/browser/browser_475045.js +++ /dev/null @@ -1,65 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ -// Instead of loading EventUtils.js into the test scope in browser-test.js for all tests, -// we only need EventUtils.js for a few files which is why we are using loadSubScript. -var EventUtils = {}; -this._scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - -add_task(function* test() { - // Make sure the bookmarks bar is visible and restore its state on cleanup. - let toolbar = document.getElementById("PersonalToolbar"); - ok(toolbar, "PersonalToolbar should not be null"); - - if (toolbar.collapsed) { - yield promiseSetToolbarVisibility(toolbar, true); - registerCleanupFunction(function() { - return promiseSetToolbarVisibility(toolbar, false); - }); - } - - // Setup the node we will use to be dropped. The actual node used does not - // matter because we will set its data, effect, and mimeType manually. - let placesItems = document.getElementById("PlacesToolbarItems"); - ok(placesItems, "PlacesToolbarItems should not be null"); - ok(placesItems.localName == "scrollbox", "PlacesToolbarItems should not be null"); - ok(placesItems.childNodes[0], "PlacesToolbarItems must have at least one child"); - - /** - * Simulates a drop of a URI onto the bookmarks bar. - * - * @param aEffect - * The effect to use for the drop operation: move, copy, or link. - * @param aMimeType - * The mime type to use for the drop operation. - */ - let simulateDragDrop = function(aEffect, aMimeType) { - const uriSpec = "http://www.mozilla.org/D1995729-A152-4e30-8329-469B01F30AA7"; - let uri = makeURI(uriSpec); - EventUtils.synthesizeDrop(placesItems.childNodes[0], - placesItems, - [[{type: aMimeType, - data: uriSpec}]], - aEffect, window); - - // Verify that the drop produces exactly one bookmark. - let bookmarkIds = PlacesUtils.bookmarks - .getBookmarkIdsForURI(uri); - ok(bookmarkIds.length == 1, "There should be exactly one bookmark"); - - PlacesUtils.bookmarks.removeItem(bookmarkIds[0]); - - // Verify that we removed the bookmark successfully. - ok(!PlacesUtils.bookmarks.isBookmarked(uri), "URI should be removed"); - } - - // Simulate a bookmark drop for all of the mime types and effects. - let mimeTypes = ["text/plain", "text/unicode", "text/x-moz-url"]; - let effects = ["move", "copy", "link"]; - effects.forEach(function (effect) { - mimeTypes.forEach(function (mimeType) { - simulateDragDrop(effect, mimeType); - }); - }); -}); diff --git a/browser/components/places/tests/browser/browser_555547.js b/browser/components/places/tests/browser/browser_555547.js deleted file mode 100644 index 0654139cb..000000000 --- a/browser/components/places/tests/browser/browser_555547.js +++ /dev/null @@ -1,66 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -"use strict"; - -add_task(function* test() { - let sidebarBox = document.getElementById("sidebar-box"); - is(sidebarBox.hidden, true, "The sidebar should be hidden"); - - // Uncollapse the personal toolbar if needed. - let toolbar = document.getElementById("PersonalToolbar"); - let wasCollapsed = toolbar.collapsed; - if (wasCollapsed) { - yield promiseSetToolbarVisibility(toolbar, true); - } - - let sidebar = yield promiseLoadedSidebar("viewBookmarksSidebar"); - registerCleanupFunction(() => { - SidebarUI.hide(); - }); - - // Focus the tree and check if its controller is returned. - let tree = sidebar.contentDocument.getElementById("bookmarks-view"); - tree.focus(); - - let controller = doGetPlacesControllerForCommand("placesCmd_copy"); - let treeController = tree.controllers - .getControllerForCommand("placesCmd_copy"); - ok(controller == treeController, "tree controller was returned"); - - // Open the context menu for a toolbar item, and check if the toolbar's - // controller is returned. - let toolbarItems = document.getElementById("PlacesToolbarItems"); - EventUtils.synthesizeMouse(toolbarItems.childNodes[0], - 4, 4, { type: "contextmenu", button: 2 }, - window); - controller = doGetPlacesControllerForCommand("placesCmd_copy"); - let toolbarController = document.getElementById("PlacesToolbar") - .controllers - .getControllerForCommand("placesCmd_copy"); - ok(controller == toolbarController, "the toolbar controller was returned"); - - document.getElementById("placesContext").hidePopup(); - - // Now that the context menu is closed, try to get the tree controller again. - tree.focus(); - controller = doGetPlacesControllerForCommand("placesCmd_copy"); - ok(controller == treeController, "tree controller was returned"); - - if (wasCollapsed) { - yield promiseSetToolbarVisibility(toolbar, false); - } -}); - -function promiseLoadedSidebar(cmd) { - return new Promise(resolve => { - let sidebar = document.getElementById("sidebar"); - sidebar.addEventListener("load", function onLoad() { - sidebar.removeEventListener("load", onLoad, true); - resolve(sidebar); - }, true); - - SidebarUI.show(cmd); - }); -} diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js deleted file mode 100644 index a1f091ebe..000000000 --- a/browser/components/places/tests/browser/browser_bookmarkProperties_addFolderDefaultButton.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict" - -add_task(function* () { - info("Bug 475529 - Add is the default button for the new folder dialog + " + - "Bug 1206376 - Changing properties of a new bookmark while adding it " + - "acts on the last bookmark in the current container"); - - // Add a new bookmark at index 0 in the unfiled folder. - let insertionIndex = 0; - let newBookmark = yield PlacesUtils.bookmarks.insert({ - index: insertionIndex, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - url: "http://example.com/", - }); - let newBookmarkId = yield PlacesUtils.promiseItemId(newBookmark.guid); - - yield withSidebarTree("bookmarks", function* (tree) { - // Select the new bookmark in the sidebar. - tree.selectItems([newBookmarkId]); - ok(tree.controller.isCommandEnabled("placesCmd_new:folder"), - "'placesCmd_new:folder' on current selected node is enabled"); - - // Create a new folder. Since the new bookmark is selected, and new items - // are inserted at the index of the currently selected item, the new folder - // will be inserted at index 0. - yield withBookmarksDialog( - false, - function openDialog() { - tree.controller.doCommand("placesCmd_new:folder"); - }, - function* test(dialogWin) { - let promiseTitleChangeNotification = promiseBookmarksNotification( - "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val =="n"); - - fillBookmarkTextField("editBMPanel_namePicker", "n", dialogWin, false); - - // Confirm and close the dialog. - EventUtils.synthesizeKey("VK_RETURN", {}, dialogWin); - yield promiseTitleChangeNotification; - - let newFolder = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: insertionIndex, - }); - - is(newFolder.title, "n", "folder name has been edited"); - yield PlacesUtils.bookmarks.remove(newFolder); - yield PlacesUtils.bookmarks.remove(newBookmark); - } - ); - }); -}); diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js deleted file mode 100644 index 5283a1610..000000000 --- a/browser/components/places/tests/browser/browser_bookmarkProperties_addKeywordForThisSearch.js +++ /dev/null @@ -1,110 +0,0 @@ -"use strict" - -const TEST_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser/keyword_form.html"; - -add_task(function* () { - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: TEST_URL, - }, function* (browser) { - // We must wait for the context menu code to build metadata. - yield openContextMenuForContentSelector(browser, '#form1 > input[name="search"]'); - - yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) { - let acceptBtn = dialogWin.document.documentElement.getButton("accept"); - ok(acceptBtn.disabled, "Accept button is disabled"); - - let promiseKeywordNotification = promiseBookmarksNotification( - "onItemChanged", (itemId, prop, isAnno, val) => prop == "keyword" && val =="kw"); - - fillBookmarkTextField("editBMPanel_keywordField", "kw", dialogWin); - - ok(!acceptBtn.disabled, "Accept button is enabled"); - - // The dialog is instant apply. - yield promiseKeywordNotification; - - // After the notification, the keywords cache will update asynchronously. - info("Check the keyword entry has been created"); - let entry; - yield waitForCondition(function* () { - entry = yield PlacesUtils.keywords.fetch("kw"); - return !!entry; - }, "Unable to find the expected keyword"); - is(entry.keyword, "kw", "keyword is correct"); - is(entry.url.href, TEST_URL, "URL is correct"); - is(entry.postData, "accenti%3D%E0%E8%EC%F2%F9&search%3D%25s", "POST data is correct"); - - info("Check the charset has been saved"); - let charset = yield PlacesUtils.getCharsetForURI(NetUtil.newURI(TEST_URL)); - is(charset, "windows-1252", "charset is correct"); - - // Now check getShortcutOrURI. - let data = yield getShortcutOrURIAndPostData("kw test"); - is(getPostDataString(data.postData), "accenti=\u00E0\u00E8\u00EC\u00F2\u00F9&search=test", "getShortcutOrURI POST data is correct"); - is(data.url, TEST_URL, "getShortcutOrURI URL is correct"); - }); - }); -}); - -add_task(function* reopen_same_field() { - yield PlacesUtils.keywords.insert({ - url: TEST_URL, - keyword: "kw", - postData: "accenti%3D%E0%E8%EC%F2%F9&search%3D%25s" - }); - registerCleanupFunction(function* () { - yield PlacesUtils.keywords.remove("kw"); - }); - // Reopening on the same input field should show the existing keyword. - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: TEST_URL, - }, function* (browser) { - // We must wait for the context menu code to build metadata. - yield openContextMenuForContentSelector(browser, '#form1 > input[name="search"]'); - - yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) { - let acceptBtn = dialogWin.document.documentElement.getButton("accept"); - ok(acceptBtn.disabled, "Accept button is disabled"); - - let elt = dialogWin.document.getElementById("editBMPanel_keywordField"); - is(elt.value, "kw"); - }); - }); -}); - -add_task(function* open_other_field() { - yield PlacesUtils.keywords.insert({ - url: TEST_URL, - keyword: "kw2", - postData: "search%3D%25s" - }); - registerCleanupFunction(function* () { - yield PlacesUtils.keywords.remove("kw2"); - }); - // Reopening on another field of the same page that has different postData - // should not show the existing keyword. - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: TEST_URL, - }, function* (browser) { - // We must wait for the context menu code to build metadata. - yield openContextMenuForContentSelector(browser, '#form2 > input[name="search"]'); - - yield withBookmarksDialog(true, AddKeywordForSearchField, function* (dialogWin) { - let acceptBtn = dialogWin.document.documentElement.getButton("accept"); - ok(acceptBtn.disabled, "Accept button is disabled"); - - let elt = dialogWin.document.getElementById("editBMPanel_keywordField"); - is(elt.value, ""); - }); - }); -}); - -function getPostDataString(stream) { - let sis = Cc["@mozilla.org/scriptableinputstream;1"] - .createInstance(Ci.nsIScriptableInputStream); - sis.init(stream); - return sis.read(stream.available()).split("\n").pop(); -} diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js b/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js deleted file mode 100644 index d9f4c07d7..000000000 --- a/browser/components/places/tests/browser/browser_bookmarkProperties_addLivemark.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict" - -add_task(function* () { - info("Add a live bookmark editing its data"); - - yield withSidebarTree("bookmarks", function* (tree) { - let itemId = PlacesUIUtils.leftPaneQueries["UnfiledBookmarks"]; - tree.selectItems([itemId]); - - yield withBookmarksDialog( - true, - function openDialog() { - PlacesCommandHook.addLiveBookmark("http://livemark.com/", - "livemark", "description"); - }, - function* test(dialogWin) { - let promiseTitleChangeNotification = promiseBookmarksNotification( - "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val == "modified"); - - fillBookmarkTextField("editBMPanel_namePicker", "modified", dialogWin); - - yield promiseTitleChangeNotification; - - let bookmark = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX - }); - - is(bookmark.title, "modified", "folder name has been edited"); - - let livemark = yield PlacesUtils.livemarks.getLivemark({ - guid: bookmark.guid - }); - is(livemark.feedURI.spec, "http://livemark.com/", "livemark has the correct url"); - is(livemark.title, "modified", "livemark has the correct title"); - } - ); - }); -}); diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js b/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js deleted file mode 100644 index fde9ea272..000000000 --- a/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict" - -add_task(function* () { - info("Bug 479348 - Properties on a root should be read-only."); - let uri = NetUtil.newURI("http://example.com/"); - let bm = yield PlacesUtils.bookmarks.insert({ - url: uri.spec, - parentGuid: PlacesUtils.bookmarks.unfiledGuid - }); - registerCleanupFunction(function* () { - yield PlacesUtils.bookmarks.remove(bm); - }); - - PlacesUtils.tagging.tagURI(uri, ["tag1"]); - - let library = yield promiseLibrary(); - let PlacesOrganizer = library.PlacesOrganizer; - registerCleanupFunction(function* () { - yield promiseLibraryClosed(library); - }); - - PlacesOrganizer.selectLeftPaneQuery("Tags"); - let tree = PlacesOrganizer._places; - let tagsContainer = tree.selectedNode; - tagsContainer.containerOpen = true; - let fooTag = tagsContainer.getChild(0); - let tagNode = fooTag; - tree.selectNode(fooTag); - is(tagNode.title, 'tag1', "tagNode title is correct"); - - ok(tree.controller.isCommandEnabled("placesCmd_show:info"), - "'placesCmd_show:info' on current selected node is enabled"); - - yield withBookmarksDialog( - true, - function openDialog() { - tree.controller.doCommand("placesCmd_show:info"); - }, - function* test(dialogWin) { - // Check that the dialog is not read-only. - ok(!dialogWin.gEditItemOverlay.readOnly, "Dialog should not be read-only"); - - // Check that name picker is not read only - let namepicker = dialogWin.document.getElementById("editBMPanel_namePicker"); - ok(!namepicker.readOnly, "Name field should not be read-only"); - is(namepicker.value, "tag1", "Node title is correct"); - - let promiseTitleChangeNotification = promiseBookmarksNotification( - "onItemChanged", (itemId, prop, isAnno, val) => prop == "title" && val == "tag2"); - - fillBookmarkTextField("editBMPanel_namePicker", "tag2", dialogWin); - - yield promiseTitleChangeNotification; - - is(namepicker.value, "tag2", "Node title has been properly edited"); - - // Check the shortcut's title. - is(tree.selectedNode.title, "tag2", "The node has the correct title"); - - // Check the tags have been edited. - let tags = PlacesUtils.tagging.getTagsForURI(uri); - is(tags.length, 1, "Found the right number of tags"); - ok(tags.includes("tag2"), "Found the expected tag"); - } - ); - - // Check the tag change has been reverted. - let tags = PlacesUtils.tagging.getTagsForURI(uri); - is(tags.length, 1, "Found the right number of tags"); - ok(tags.includes("tag1"), "Found the expected tag"); -}); diff --git a/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js b/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js deleted file mode 100644 index 6f499888c..000000000 --- a/browser/components/places/tests/browser/browser_bookmarkProperties_readOnlyRoot.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict" - -add_task(function* () { - info("Bug 479348 - Properties on a root should be read-only."); - - yield withSidebarTree("bookmarks", function* (tree) { - let itemId = PlacesUIUtils.leftPaneQueries["UnfiledBookmarks"]; - tree.selectItems([itemId]); - ok(tree.controller.isCommandEnabled("placesCmd_show:info"), - "'placesCmd_show:info' on current selected node is enabled"); - - yield withBookmarksDialog( - true, - function openDialog() { - tree.controller.doCommand("placesCmd_show:info"); - }, - function* test(dialogWin) { - // Check that the dialog is read-only. - ok(dialogWin.gEditItemOverlay.readOnly, "Dialog is read-only"); - // Check that accept button is disabled - let acceptButton = dialogWin.document.documentElement.getButton("accept"); - ok(acceptButton.disabled, "Accept button is disabled"); - - // Check that name picker is read only - let namepicker = dialogWin.document.getElementById("editBMPanel_namePicker"); - ok(namepicker.readOnly, "Name field is read-only"); - is(namepicker.value, - PlacesUtils.bookmarks.getItemTitle(PlacesUtils.unfiledBookmarksFolderId), - "Node title is correct"); - // Blur the field and ensure root's name has not been changed. - namepicker.blur(); - is(namepicker.value, - PlacesUtils.bookmarks.getItemTitle(PlacesUtils.unfiledBookmarksFolderId), - "Root title is correct"); - // Check the shortcut's title. - let bookmark = yield PlacesUtils.bookmarks.fetch(tree.selectedNode.bookmarkGuid); - is(bookmark.title, null, - "Shortcut title is null"); - } - ); - }); -}); diff --git a/browser/components/places/tests/browser/browser_bookmark_all_tabs.js b/browser/components/places/tests/browser/browser_bookmark_all_tabs.js deleted file mode 100644 index afd32b78a..000000000 --- a/browser/components/places/tests/browser/browser_bookmark_all_tabs.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Test for Bug 446171 - Name field of bookmarks saved via 'Bookmark All Tabs' - * has '(null)' value if history is disabled or just in private browsing mode - */ -"use strict" - -add_task(function* () { - const BASE_URL = "http://example.org/browser/browser/components/places/tests/browser/"; - const TEST_PAGES = [ - BASE_URL + "bookmark_dummy_1.html", - BASE_URL + "bookmark_dummy_2.html", - BASE_URL + "bookmark_dummy_1.html" - ]; - - function promiseAddTab(url) { - return BrowserTestUtils.openNewForegroundTab(gBrowser, url); - } - - let tabs = yield Promise.all(TEST_PAGES.map(promiseAddTab)); - - let URIs = PlacesCommandHook.uniqueCurrentPages; - is(URIs.length, 3, "Only unique pages are returned"); - - Assert.deepEqual(URIs.map(URI => URI.uri.spec), [ - "about:blank", - BASE_URL + "bookmark_dummy_1.html", - BASE_URL + "bookmark_dummy_2.html" - ], "Correct URIs are returned"); - - Assert.deepEqual(URIs.map(URI => URI.title), [ - "New Tab", "Bookmark Dummy 1", "Bookmark Dummy 2" - ], "Correct titles are returned"); - - registerCleanupFunction(function* () { - yield Promise.all(tabs.map(BrowserTestUtils.removeTab)); - }); -}); diff --git a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js deleted file mode 100644 index 85ce25311..000000000 --- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; - -const TEST_URL = 'http://example.com/browser/browser/components/places/tests/browser/pageopeningwindow.html'; - -function makeBookmarkFor(url, keyword) { - return Promise.all([ - PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, - title: "bookmarklet", - url: url }), - PlacesUtils.keywords.insert({url: url, - keyword: keyword}) - ]); - -} - -add_task(function* openKeywordBookmarkWithWindowOpen() { - // This is the current default, but let's not assume that... - yield new Promise((resolve, reject) => { - SpecialPowers.pushPrefEnv({ 'set': [[ 'browser.link.open_newwindow', 3 ], - [ 'dom.disable_open_during_load', true ]] }, - resolve); - }); - - let moztab; - let tabOpened = BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla") - .then((tab) => { moztab = tab; }); - let keywordForBM = "openmeatab"; - - let bookmarkInfo; - let bookmarkCreated = - makeBookmarkFor("javascript:void open('" + TEST_URL + "')", keywordForBM) - .then((values) => { - bookmarkInfo = values[0]; - }); - yield Promise.all([tabOpened, bookmarkCreated]); - - registerCleanupFunction(function() { - return Promise.all([ - PlacesUtils.bookmarks.remove(bookmarkInfo), - PlacesUtils.keywords.remove(keywordForBM) - ]); - }); - gURLBar.value = keywordForBM; - gURLBar.focus(); - - let tabCreatedPromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabOpen"); - EventUtils.synthesizeKey("VK_RETURN", {}); - - info("Waiting for tab being created"); - let {target: tab} = yield tabCreatedPromise; - info("Got tab"); - let browser = tab.linkedBrowser; - if (!browser.currentURI || browser.currentURI.spec != TEST_URL) { - info("Waiting for browser load"); - yield BrowserTestUtils.browserLoaded(browser); - } - is(browser.currentURI && browser.currentURI.spec, TEST_URL, "Tab with expected URL loaded."); - info("Waiting to remove tab"); - yield Promise.all([ BrowserTestUtils.removeTab(tab), - BrowserTestUtils.removeTab(moztab) ]); -}); diff --git a/browser/components/places/tests/browser/browser_bookmarksProperties.js b/browser/components/places/tests/browser/browser_bookmarksProperties.js deleted file mode 100644 index f7f9f4762..000000000 --- a/browser/components/places/tests/browser/browser_bookmarksProperties.js +++ /dev/null @@ -1,450 +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/. */ - -/** - * Tests the bookmarks Properties dialog. - */ - -// DOM ids of Places sidebar trees. -const SIDEBAR_HISTORY_TREE_ID = "historyTree"; -const SIDEBAR_BOOKMARKS_TREE_ID = "bookmarks-view"; - -const SIDEBAR_HISTORY_ID = "viewHistorySidebar"; -const SIDEBAR_BOOKMARKS_ID = "viewBookmarksSidebar"; - -// For history sidebar. -const SIDEBAR_HISTORY_BYLASTVISITED_VIEW = "bylastvisited"; -const SIDEBAR_HISTORY_BYMOSTVISITED_VIEW = "byvisited"; -const SIDEBAR_HISTORY_BYDATE_VIEW = "byday"; -const SIDEBAR_HISTORY_BYSITE_VIEW = "bysite"; -const SIDEBAR_HISTORY_BYDATEANDSITE_VIEW = "bydateandsite"; - -// Action to execute on the current node. -const ACTION_EDIT = 0; -const ACTION_ADD = 1; - -// If action is ACTION_ADD, set type to one of those, to define what do you -// want to create. -const TYPE_FOLDER = 0; -const TYPE_BOOKMARK = 1; - -const TEST_URL = "http://www.example.com/"; - -const DIALOG_URL = "chrome://browser/content/places/bookmarkProperties.xul"; -const DIALOG_URL_MINIMAL_UI = "chrome://browser/content/places/bookmarkProperties2.xul"; - -Cu.import("resource:///modules/RecentWindow.jsm"); -var win = RecentWindow.getMostRecentBrowserWindow(); -var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"]. - getService(Ci.nsIWindowWatcher); - -function add_bookmark(aURI) { - var bId = PlacesUtils.bookmarks - .insertBookmark(PlacesUtils.unfiledBookmarksFolderId, - aURI, - PlacesUtils.bookmarks.DEFAULT_INDEX, - "bookmark/" + aURI.spec); - return bId; -} - -// Each test is an obj w/ a desc property and run method. -var gTests = []; -var gCurrentTest = null; - -// ------------------------------------------------------------------------------ -// Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog -gTests.push({ - desc: "Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog", - sidebar: SIDEBAR_BOOKMARKS_ID, - action: ACTION_EDIT, - itemType: null, - window: null, - _itemId: null, - _cleanShutdown: false, - - setup: function(aCallback) { - // Add a bookmark in unsorted bookmarks folder. - this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); - ok(this._itemId > 0, "Correctly added a bookmark"); - // Add a tag to this bookmark. - PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL), - ["testTag"]); - var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); - is(tags[0], "testTag", "Correctly added a tag"); - aCallback(); - }, - - selectNode: function(tree) { - tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); - PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; - tree.selectItems([this._itemId]); - is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); - }, - - run: function() { - // open tags autocomplete and press enter - var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); - var self = this; - - this.window.addEventListener("unload", function(event) { - self.window.removeEventListener("unload", arguments.callee, true); - tagsField.popup.removeEventListener("popuphidden", popupListener, true); - ok(self._cleanShutdown, "Dialog window should not be closed by pressing Enter on the autocomplete popup"); - executeSoon(function () { - self.finish(); - }); - }, true); - - var popupListener = { - handleEvent: function(aEvent) { - switch (aEvent.type) { - case "popuphidden": - // Everything worked fine, we can stop observing the window. - self._cleanShutdown = true; - self.window.document.documentElement.cancelDialog(); - break; - case "popupshown": - tagsField.popup.removeEventListener("popupshown", this, true); - // In case this test fails the window will close, the test will fail - // since we didn't set _cleanShutdown. - var tree = tagsField.popup.tree; - // Focus and select first result. - isnot(tree, null, "Autocomplete results tree exists"); - is(tree.view.rowCount, 1, "We have 1 autocomplete result"); - tagsField.popup.selectedIndex = 0; - is(tree.view.selection.count, 1, - "We have selected a tag from the autocomplete popup"); - info("About to focus the autocomplete results tree"); - tree.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}, self.window); - break; - default: - ok(false, "unknown event: " + aEvent.type); - return; - } - } - }; - tagsField.popup.addEventListener("popupshown", popupListener, true); - tagsField.popup.addEventListener("popuphidden", popupListener, true); - - // Open tags autocomplete popup. - info("About to focus the tagsField"); - executeSoon(() => { - tagsField.focus(); - tagsField.value = ""; - EventUtils.synthesizeKey("t", {}, this.window); - }); - }, - - finish: function() { - SidebarUI.hide(); - runNextTest(); - }, - - cleanup: function() { - // Check tags have not changed. - var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); - is(tags[0], "testTag", "Tag on node has not changed"); - - // Cleanup. - PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL), ["testTag"]); - PlacesUtils.bookmarks.removeItem(this._itemId); - } -}); - -// ------------------------------------------------------------------------------ -// Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel - -gTests.push({ - desc: "Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel", - sidebar: SIDEBAR_BOOKMARKS_ID, - action: ACTION_EDIT, - itemType: null, - window: null, - _itemId: null, - _cleanShutdown: false, - - setup: function(aCallback) { - // Add a bookmark in unsorted bookmarks folder. - this._itemId = add_bookmark(PlacesUtils._uri(TEST_URL)); - ok(this._itemId > 0, "Correctly added a bookmark"); - // Add a tag to this bookmark. - PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL), - ["testTag"]); - var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); - is(tags[0], "testTag", "Correctly added a tag"); - aCallback(); - }, - - selectNode: function(tree) { - tree.selectItems([PlacesUtils.unfiledBookmarksFolderId]); - PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; - tree.selectItems([this._itemId]); - is(tree.selectedNode.itemId, this._itemId, "Bookmark has been selected"); - }, - - run: function() { - // open tags autocomplete and press enter - var tagsField = this.window.document.getElementById("editBMPanel_tagsField"); - var self = this; - - this.window.addEventListener("unload", function(event) { - self.window.removeEventListener("unload", arguments.callee, true); - tagsField.popup.removeEventListener("popuphidden", popupListener, true); - ok(self._cleanShutdown, "Dialog window should not be closed by pressing Escape on the autocomplete popup"); - executeSoon(function () { - self.finish(); - }); - }, true); - - var popupListener = { - handleEvent: function(aEvent) { - switch (aEvent.type) { - case "popuphidden": - // Everything worked fine. - self._cleanShutdown = true; - self.window.document.documentElement.cancelDialog(); - break; - case "popupshown": - tagsField.popup.removeEventListener("popupshown", this, true); - // In case this test fails the window will close, the test will fail - // since we didn't set _cleanShutdown. - var tree = tagsField.popup.tree; - // Focus and select first result. - isnot(tree, null, "Autocomplete results tree exists"); - is(tree.view.rowCount, 1, "We have 1 autocomplete result"); - tagsField.popup.selectedIndex = 0; - is(tree.view.selection.count, 1, - "We have selected a tag from the autocomplete popup"); - info("About to focus the autocomplete results tree"); - tree.focus(); - EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window); - break; - default: - ok(false, "unknown event: " + aEvent.type); - return; - } - } - }; - tagsField.popup.addEventListener("popupshown", popupListener, true); - tagsField.popup.addEventListener("popuphidden", popupListener, true); - - // Open tags autocomplete popup. - info("About to focus the tagsField"); - tagsField.focus(); - tagsField.value = ""; - EventUtils.synthesizeKey("t", {}, this.window); - }, - - finish: function() { - SidebarUI.hide(); - runNextTest(); - }, - - cleanup: function() { - // Check tags have not changed. - var tags = PlacesUtils.tagging.getTagsForURI(PlacesUtils._uri(TEST_URL)); - is(tags[0], "testTag", "Tag on node has not changed"); - - // Cleanup. - PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL), - ["testTag"]); - PlacesUtils.bookmarks.removeItem(this._itemId); - } -}); - -// ------------------------------------------------------------------------------ -// Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog - -gTests.push({ - desc: " Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog", - sidebar: SIDEBAR_HISTORY_ID, - action: ACTION_ADD, - historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW, - window: null, - - setup: function(aCallback) { - // Add a visit. - PlacesTestUtils.addVisits( - {uri: PlacesUtils._uri(TEST_URL), - transition: PlacesUtils.history.TRANSITION_TYPED} - ).then(aCallback); - }, - - selectNode: function(tree) { - var visitNode = tree.view.nodeForTreeIndex(0); - tree.selectNode(visitNode); - is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); - is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); - }, - - run: function() { - // Open folder selector. - var foldersExpander = this.window.document.getElementById("editBMPanel_foldersExpander"); - var folderTree = this.window.document.getElementById("editBMPanel_folderTree"); - var self = this; - - this.window.addEventListener("unload", function(event) { - self.window.removeEventListener("unload", arguments.callee, true); - ok(self._cleanShutdown, "Dialog window should not be closed by pressing ESC in folder name textbox"); - executeSoon(function () { - self.finish(); - }); - }, true); - - folderTree.addEventListener("DOMAttrModified", function onDOMAttrModified(event) { - if (event.attrName != "place") - return; - folderTree.removeEventListener("DOMAttrModified", arguments.callee, false); - executeSoon(function () { - // Create a new folder. - var newFolderButton = self.window.document.getElementById("editBMPanel_newFolderButton"); - newFolderButton.doCommand(); - ok(folderTree.hasAttribute("editing"), - "We are editing new folder name in folder tree"); - - // Press Escape to discard editing new folder name. - EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window); - ok(!folderTree.hasAttribute("editing"), - "We have finished editing folder name in folder tree"); - self._cleanShutdown = true; - self.window.document.documentElement.cancelDialog(); - }); - }, false); - foldersExpander.doCommand(); - }, - - finish: function() { - SidebarUI.hide(); - runNextTest(); - }, - - cleanup: function() { - return PlacesTestUtils.clearHistory(); - } -}); - -// ------------------------------------------------------------------------------ - -function test() { - waitForExplicitFinish(); - // This test can take some time, if we timeout too early it could run - // in the middle of other tests, or hang them. - requestLongerTimeout(2); - - // Sanity checks. - ok(PlacesUtils, "PlacesUtils in context"); - ok(PlacesUIUtils, "PlacesUIUtils in context"); - - // kick off tests - runNextTest(); -} - -function runNextTest() { - // Cleanup from previous test. - if (gCurrentTest) { - Promise.resolve(gCurrentTest.cleanup()).then(() => { - info("End of test: " + gCurrentTest.desc); - gCurrentTest = null; - waitForAsyncUpdates(runNextTest); - }); - return; - } - - if (gTests.length > 0) { - // Goto next tests. - gCurrentTest = gTests.shift(); - info("Start of test: " + gCurrentTest.desc); - gCurrentTest.setup(function() { - execute_test_in_sidebar(); - }); - } - else { - // Finished all tests. - finish(); - } -} - -/** - * Global functions to run a test in Properties dialog context. - */ - -function execute_test_in_sidebar() { - var sidebar = document.getElementById("sidebar"); - sidebar.addEventListener("load", function() { - sidebar.removeEventListener("load", arguments.callee, true); - // Need to executeSoon since the tree is initialized on sidebar load. - executeSoon(open_properties_dialog); - }, true); - SidebarUI.show(gCurrentTest.sidebar); -} - -function open_properties_dialog() { - var sidebar = document.getElementById("sidebar"); - - // If this is history sidebar, set the required view. - if (gCurrentTest.sidebar == SIDEBAR_HISTORY_ID) - sidebar.contentDocument.getElementById(gCurrentTest.historyView).doCommand(); - - // Get sidebar's Places tree. - var sidebarTreeID = gCurrentTest.sidebar == SIDEBAR_BOOKMARKS_ID ? - SIDEBAR_BOOKMARKS_TREE_ID : - SIDEBAR_HISTORY_TREE_ID; - var tree = sidebar.contentDocument.getElementById(sidebarTreeID); - ok(tree, "Sidebar tree has been loaded"); - - // Ask current test to select the node to edit. - gCurrentTest.selectNode(tree); - ok(tree.selectedNode, - "We have a places node selected: " + tree.selectedNode.title); - - // Wait for the Properties dialog. - function windowObserver(aSubject, aTopic, aData) { - if (aTopic != "domwindowopened") - return; - ww.unregisterNotification(windowObserver); - let win = aSubject.QueryInterface(Ci.nsIDOMWindow); - waitForFocus(() => { - // Windows has been loaded, execute our test now. - executeSoon(function () { - // Ensure overlay is loaded - ok(win.gEditItemOverlay.initialized, "EditItemOverlay is initialized"); - gCurrentTest.window = win; - try { - gCurrentTest.run(); - } catch (ex) { - ok(false, "An error occured during test run: " + ex.message); - } - }); - }, win); - } - ww.registerNotification(windowObserver); - - var command = null; - switch (gCurrentTest.action) { - case ACTION_EDIT: - command = "placesCmd_show:info"; - break; - case ACTION_ADD: - if (gCurrentTest.sidebar == SIDEBAR_BOOKMARKS_ID) { - if (gCurrentTest.itemType == TYPE_FOLDER) - command = "placesCmd_new:folder"; - else if (gCurrentTest.itemType == TYPE_BOOKMARK) - command = "placesCmd_new:bookmark"; - else - ok(false, "You didn't set a valid itemType for adding an item"); - } - else - command = "placesCmd_createBookmark"; - break; - default: - ok(false, "You didn't set a valid action for this test"); - } - // Ensure command is enabled for this node. - ok(tree.controller.isCommandEnabled(command), - " command '" + command + "' on current selected node is enabled"); - - // This will open the dialog. - tree.controller.doCommand(command); -} diff --git a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js b/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js deleted file mode 100644 index 1ab9411f3..000000000 --- a/browser/components/places/tests/browser/browser_drag_bookmarks_on_toolbar.js +++ /dev/null @@ -1,256 +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_URL = "http://www.mozilla.org"; -const TEST_TITLE = "example_title"; - -var gBookmarksToolbar = window.document.getElementById("PlacesToolbar"); -var dragDirections = { LEFT: 0, UP: 1, RIGHT: 2, DOWN: 3 }; - -/** - * Tests dragging on toolbar. - * - * We must test these 2 cases: - * - Dragging toward left, top, right should start a drag. - * - Dragging toward down should should open the container if the item is a - * container, drag the item otherwise. - * - * @param aElement - * DOM node element we will drag - * @param aExpectedDragData - * Array of flavors and values in the form: - * [ ["text/plain: sometext", "text/html: <b>sometext</b>"], [...] ] - * Pass an empty array to check that drag even has been canceled. - * @param aDirection - * Direction for the dragging gesture, see dragDirections helper object. - */ -function synthesizeDragWithDirection(aElement, aExpectedDragData, aDirection, aCallback) { - // Dragstart listener function. - gBookmarksToolbar.addEventListener("dragstart", function(event) - { - info("A dragstart event has been trapped."); - var dataTransfer = event.dataTransfer; - is(dataTransfer.mozItemCount, aExpectedDragData.length, - "Number of dragged items should be the same."); - - for (var t = 0; t < dataTransfer.mozItemCount; t++) { - var types = dataTransfer.mozTypesAt(t); - var expecteditem = aExpectedDragData[t]; - is(types.length, expecteditem.length, - "Number of flavors for item " + t + " should be the same."); - - for (var f = 0; f < types.length; f++) { - is(types[f], expecteditem[f].substring(0, types[f].length), - "Flavor " + types[f] + " for item " + t + " should be the same."); - is(dataTransfer.mozGetDataAt(types[f], t), - expecteditem[f].substring(types[f].length + 2), - "Contents for item " + t + " with flavor " + types[f] + " should be the same."); - } - } - - if (!aExpectedDragData.length) - ok(event.defaultPrevented, "Drag has been canceled."); - - event.preventDefault(); - event.stopPropagation(); - - gBookmarksToolbar.removeEventListener("dragstart", arguments.callee, false); - - // This is likely to cause a click event, and, in case we are dragging a - // bookmark, an unwanted page visit. Prevent the click event. - aElement.addEventListener("click", prevent, false); - EventUtils.synthesizeMouse(aElement, - startingPoint.x + xIncrement * 9, - startingPoint.y + yIncrement * 9, - { type: "mouseup" }); - aElement.removeEventListener("click", prevent, false); - - // Cleanup eventually opened menus. - if (aElement.localName == "menu" && aElement.open) - aElement.open = false; - aCallback() - }, false); - - var prevent = function(aEvent) { aEvent.preventDefault(); } - - var xIncrement = 0; - var yIncrement = 0; - - switch (aDirection) { - case dragDirections.LEFT: - xIncrement = -1; - break; - case dragDirections.RIGHT: - xIncrement = +1; - break; - case dragDirections.UP: - yIncrement = -1; - break; - case dragDirections.DOWN: - yIncrement = +1; - break; - } - - var rect = aElement.getBoundingClientRect(); - var startingPoint = { x: (rect.right - rect.left)/2, - y: (rect.bottom - rect.top)/2 }; - - EventUtils.synthesizeMouse(aElement, - startingPoint.x, - startingPoint.y, - { type: "mousedown" }); - EventUtils.synthesizeMouse(aElement, - startingPoint.x + xIncrement * 1, - startingPoint.y + yIncrement * 1, - { type: "mousemove" }); - EventUtils.synthesizeMouse(aElement, - startingPoint.x + xIncrement * 9, - startingPoint.y + yIncrement * 9, - { type: "mousemove" }); -} - -function getToolbarNodeForItemId(aItemId) { - var children = document.getElementById("PlacesToolbarItems").childNodes; - var node = null; - for (var i = 0; i < children.length; i++) { - if (aItemId == children[i]._placesNode.itemId) { - node = children[i]; - break; - } - } - return node; -} - -function getExpectedDataForPlacesNode(aNode) { - var wrappedNode = []; - var flavors = ["text/x-moz-place", - "text/x-moz-url", - "text/plain", - "text/html"]; - - flavors.forEach(function(aFlavor) { - var wrappedFlavor = aFlavor + ": " + - PlacesUtils.wrapNode(aNode, aFlavor); - wrappedNode.push(wrappedFlavor); - }); - - return [wrappedNode]; -} - -var gTests = [ - -// ------------------------------------------------------------------------------ - - { - desc: "Drag a folder on toolbar", - run: function() { - // Create a test folder to be dragged. - var folderId = PlacesUtils.bookmarks - .createFolder(PlacesUtils.toolbarFolderId, - TEST_TITLE, - PlacesUtils.bookmarks.DEFAULT_INDEX); - var element = getToolbarNodeForItemId(folderId); - isnot(element, null, "Found node on toolbar"); - - isnot(element._placesNode, null, "Toolbar node has an associated Places node."); - var expectedData = getExpectedDataForPlacesNode(element._placesNode); - - info("Dragging left"); - synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT, - function () - { - info("Dragging right"); - synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT, - function () - { - info("Dragging up"); - synthesizeDragWithDirection(element, expectedData, dragDirections.UP, - function () - { - info("Dragging down"); - synthesizeDragWithDirection(element, new Array(), dragDirections.DOWN, - function () { - // Cleanup. - PlacesUtils.bookmarks.removeItem(folderId); - nextTest(); - }); - }); - }); - }); - } - }, - -// ------------------------------------------------------------------------------ - - { - desc: "Drag a bookmark on toolbar", - run: function() { - // Create a test bookmark to be dragged. - var itemId = PlacesUtils.bookmarks - .insertBookmark(PlacesUtils.toolbarFolderId, - PlacesUtils._uri(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, - TEST_TITLE); - var element = getToolbarNodeForItemId(itemId); - isnot(element, null, "Found node on toolbar"); - - isnot(element._placesNode, null, "Toolbar node has an associated Places node."); - var expectedData = getExpectedDataForPlacesNode(element._placesNode); - - info("Dragging left"); - synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT, - function () - { - info("Dragging right"); - synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT, - function () - { - info("Dragging up"); - synthesizeDragWithDirection(element, expectedData, dragDirections.UP, - function () - { - info("Dragging down"); - synthesizeDragWithDirection(element, expectedData, dragDirections.DOWN, - function () { - // Cleanup. - PlacesUtils.bookmarks.removeItem(itemId); - nextTest(); - }); - }); - }); - }); - } - }, -]; - -function nextTest() { - if (gTests.length) { - var test = gTests.shift(); - waitForFocus(function() { - info("Start of test: " + test.desc); - test.run(); - }); - } - else if (wasCollapsed) { - // Collapse the personal toolbar if needed. - promiseSetToolbarVisibility(toolbar, false).then(finish); - } else { - finish(); - } -} - -var toolbar = document.getElementById("PersonalToolbar"); -var wasCollapsed = toolbar.collapsed; - -function test() { - waitForExplicitFinish(); - - // Uncollapse the personal toolbar if needed. - if (wasCollapsed) { - promiseSetToolbarVisibility(toolbar, true).then(nextTest); - } else { - nextTest(); - } -} - diff --git a/browser/components/places/tests/browser/browser_forgetthissite_single.js b/browser/components/places/tests/browser/browser_forgetthissite_single.js deleted file mode 100644 index b1d7936e9..000000000 --- a/browser/components/places/tests/browser/browser_forgetthissite_single.js +++ /dev/null @@ -1,78 +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_URIs = [ - "http://www.mozilla.org/test1", - "http://www.mozilla.org/test2" -]; - -// This test makes sure that the Forget This Site command is hidden for multiple -// selections. -add_task(function* () { - // Add a history entry. - ok(PlacesUtils, "checking PlacesUtils, running in chrome context?"); - - let places = []; - let transition = PlacesUtils.history.TRANSITION_TYPED; - TEST_URIs.forEach(uri => places.push({uri: PlacesUtils._uri(uri), transition})); - - yield PlacesTestUtils.addVisits(places); - yield testForgetThisSiteVisibility(1); - yield testForgetThisSiteVisibility(2); - - // Cleanup. - yield PlacesTestUtils.clearHistory(); -}); - -var testForgetThisSiteVisibility = Task.async(function* (selectionCount) { - let organizer = yield promiseLibrary(); - - // Select History in the left pane. - organizer.PlacesOrganizer.selectLeftPaneQuery("History"); - let PO = organizer.PlacesOrganizer; - let histContainer = PO._places.selectedNode.QueryInterface(Ci.nsINavHistoryContainerResultNode); - histContainer.containerOpen = true; - PO._places.selectNode(histContainer.getChild(0)); - - // Select the first history entry. - let doc = organizer.document; - let tree = doc.getElementById("placeContent"); - let selection = tree.view.selection; - selection.clearSelection(); - selection.rangedSelect(0, selectionCount - 1, true); - is(selection.count, selectionCount, "The selected range is as big as expected"); - - // Open the context menu. - let contextmenu = doc.getElementById("placesContext"); - let popupShown = promisePopupShown(contextmenu); - - // Get cell coordinates. - let rect = tree.treeBoxObject.getCoordsForCellItem(0, tree.columns[0], "text"); - // Initiate a context menu for the selected cell. - EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {type: "contextmenu", button: 2}, organizer); - yield popupShown; - - let forgetThisSite = doc.getElementById("placesContext_deleteHost"); - let hideForgetThisSite = (selectionCount != 1); - is(forgetThisSite.hidden, hideForgetThisSite, - `The Forget this site menu item should ${hideForgetThisSite ? "" : "not "}` + - ` be hidden with ${selectionCount} items selected`); - - // Close the context menu. - contextmenu.hidePopup(); - - // Close the library window. - yield promiseLibraryClosed(organizer); -}); - -function promisePopupShown(popup) { - return new Promise(resolve => { - popup.addEventListener("popupshown", function onShown() { - popup.removeEventListener("popupshown", onShown, true); - resolve(); - }, true); - }); -} diff --git a/browser/components/places/tests/browser/browser_history_sidebar_search.js b/browser/components/places/tests/browser/browser_history_sidebar_search.js deleted file mode 100644 index 89472c4ab..000000000 --- a/browser/components/places/tests/browser/browser_history_sidebar_search.js +++ /dev/null @@ -1,64 +0,0 @@ -add_task(function* test () { - let sidebar = document.getElementById("sidebar"); - - // Visited pages listed by descending visit date. - let pages = [ - "http://sidebar.mozilla.org/a", - "http://sidebar.mozilla.org/b", - "http://sidebar.mozilla.org/c", - "http://www.mozilla.org/d", - ]; - - // Number of pages that will be filtered out by the search. - const FILTERED_COUNT = 1; - - yield PlacesTestUtils.clearHistory(); - - // Add some visited page. - let time = Date.now(); - let places = []; - for (let i = 0; i < pages.length; i++) { - places.push({ uri: NetUtil.newURI(pages[i]), - visitDate: (time - i) * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED }); - } - yield PlacesTestUtils.addVisits(places); - - yield withSidebarTree("history", function* () { - info("Set 'by last visited' view"); - sidebar.contentDocument.getElementById("bylastvisited").doCommand(); - let tree = sidebar.contentDocument.getElementById("historyTree"); - check_tree_order(tree, pages); - - // Set a search value. - let searchBox = sidebar.contentDocument.getElementById("search-box"); - ok(searchBox, "search box is in context"); - searchBox.value = "sidebar.mozilla"; - searchBox.doCommand(); - check_tree_order(tree, pages, -FILTERED_COUNT); - - info("Reset the search"); - searchBox.value = ""; - searchBox.doCommand(); - check_tree_order(tree, pages); - }); - - yield PlacesTestUtils.clearHistory(); -}); - -function check_tree_order(tree, pages, aNumberOfRowsDelta = 0) { - let treeView = tree.view; - let columns = tree.columns; - is(columns.count, 1, "There should be only 1 column in the sidebar"); - - let found = 0; - for (let i = 0; i < treeView.rowCount; i++) { - let node = treeView.nodeForTreeIndex(i); - // We could inherit delayed visits from previous tests, skip them. - if (!pages.includes(node.uri)) - continue; - is(node.uri, pages[i], "Node is in correct position based on its visit date"); - found++; - } - ok(found, pages.length + aNumberOfRowsDelta, "Found all expected results"); -} diff --git a/browser/components/places/tests/browser/browser_library_batch_delete.js b/browser/components/places/tests/browser/browser_library_batch_delete.js deleted file mode 100644 index 6a907c70f..000000000 --- a/browser/components/places/tests/browser/browser_library_batch_delete.js +++ /dev/null @@ -1,114 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that Library handles correctly batch deletes. - */ - -const TEST_URL = "http://www.batch.delete.me/"; - -var gTests = []; -var gLibrary; - -// ------------------------------------------------------------------------------ - -gTests.push({ - desc: "Create and batch remove bookmarks", - run: function() { - let testURI = makeURI(TEST_URL); - PlacesUtils.history.runInBatchMode({ - runBatched: function (aUserData) { - // Create a folder in unserted and populate it with bookmarks. - let folder = PlacesUtils.bookmarks.createFolder( - PlacesUtils.unfiledBookmarksFolderId, "deleteme", - PlacesUtils.bookmarks.DEFAULT_INDEX - ); - PlacesUtils.bookmarks.createFolder( - PlacesUtils.unfiledBookmarksFolderId, "keepme", - PlacesUtils.bookmarks.DEFAULT_INDEX - ); - for (let i = 0; i < 10; i++) { - PlacesUtils.bookmarks.insertBookmark(folder, - testURI, - PlacesUtils.bookmarks.DEFAULT_INDEX, - "bm" + i); - } - } - }, null); - - // Select and open the left pane "History" query. - let PO = gLibrary.PlacesOrganizer; - PO.selectLeftPaneQuery("UnfiledBookmarks"); - isnot(PO._places.selectedNode, null, "Selected unsorted bookmarks"); - - let unsortedNode = PlacesUtils.asContainer(PO._places.selectedNode); - unsortedNode.containerOpen = true; - is(unsortedNode.childCount, 2, "Unsorted node has 2 children"); - let folderNode = unsortedNode.getChild(0); - is(folderNode.title, "deleteme", "Folder found in unsorted bookmarks"); - // Check delete command is available. - PO._places.selectNode(folderNode); - is(PO._places.selectedNode.title, "deleteme", "Folder node selected"); - ok(PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - // Execute the delete command and check bookmark has been removed. - PO._places.controller.doCommand("cmd_delete"); - ok(!PlacesUtils.bookmarks.isBookmarked(testURI), - "Bookmark has been correctly removed"); - // Test live update. - is(unsortedNode.childCount, 1, "Unsorted node has 1 child"); - is(PO._places.selectedNode.title, "keepme", "Folder node selected"); - unsortedNode.containerOpen = false; - nextTest(); - } -}); - -// ------------------------------------------------------------------------------ - -gTests.push({ - desc: "Ensure correct selection and functionality in Library", - run: function() { - let PO = gLibrary.PlacesOrganizer; - let ContentTree = gLibrary.ContentTree; - // Move selection forth and back. - PO.selectLeftPaneQuery("History"); - PO.selectLeftPaneQuery("UnfiledBookmarks"); - // Now select the "keepme" folder in the right pane and delete it. - ContentTree.view.selectNode(ContentTree.view.result.root.getChild(0)); - is(ContentTree.view.selectedNode.title, "keepme", - "Found folder in content pane"); - // Test live update. - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId, - makeURI(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, - "bm"); - is(ContentTree.view.result.root.childCount, 2, - "Right pane was correctly updated"); - nextTest(); - } -}); - -// ------------------------------------------------------------------------------ - -function test() { - waitForExplicitFinish(); - registerCleanupFunction(function () { - PlacesUtils.bookmarks - .removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); - }); - - gLibrary = openLibrary(nextTest); -} - -function nextTest() { - if (gTests.length) { - var test = gTests.shift(); - info("Start of test: " + test.desc); - test.run(); - } - else { - // Close Library window. - gLibrary.close(); - finish(); - } -} diff --git a/browser/components/places/tests/browser/browser_library_commands.js b/browser/components/places/tests/browser/browser_library_commands.js deleted file mode 100644 index e3bb75a34..000000000 --- a/browser/components/places/tests/browser/browser_library_commands.js +++ /dev/null @@ -1,235 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 enabled commands in the left pane folder of the Library. - */ - -const TEST_URI = NetUtil.newURI("http://www.mozilla.org/"); - -registerCleanupFunction(function* () { - yield PlacesUtils.bookmarks.eraseEverything(); - yield PlacesTestUtils.clearHistory(); -}); - -add_task(function* test_date_container() { - let library = yield promiseLibrary(); - info("Ensure date containers under History cannot be cut but can be deleted"); - - yield PlacesTestUtils.addVisits(TEST_URI); - - // Select and open the left pane "History" query. - let PO = library.PlacesOrganizer; - - PO.selectLeftPaneQuery('History'); - isnot(PO._places.selectedNode, null, "We correctly selected History"); - - // Check that both delete and cut commands are disabled, cause this is - // a child of the left pane folder. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is disabled"); - let historyNode = PlacesUtils.asContainer(PO._places.selectedNode); - historyNode.containerOpen = true; - - // Check that we have a child container. It is "Today" container. - is(historyNode.childCount, 1, "History node has one child"); - let todayNode = historyNode.getChild(0); - let todayNodeExpectedTitle = PlacesUtils.getString("finduri-AgeInDays-is-0"); - is(todayNode.title, todayNodeExpectedTitle, - "History child is the expected container"); - - // Select "Today" container. - PO._places.selectNode(todayNode); - is(PO._places.selectedNode, todayNode, - "We correctly selected Today container"); - // Check that delete command is enabled but cut command is disabled, cause - // this is an history item. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - - // Execute the delete command and check visit has been removed. - let promiseURIRemoved = promiseHistoryNotification("onDeleteURI", - v => TEST_URI.equals(v)); - PO._places.controller.doCommand("cmd_delete"); - yield promiseURIRemoved; - - // Test live update of "History" query. - is(historyNode.childCount, 0, "History node has no more children"); - - historyNode.containerOpen = false; - - ok(!(yield promiseIsURIVisited(TEST_URI)), "Visit has been removed"); - - library.close(); -}); - -add_task(function* test_query_on_toolbar() { - let library = yield promiseLibrary(); - info("Ensure queries can be cut or deleted"); - - // Select and open the left pane "Bookmarks Toolbar" folder. - let PO = library.PlacesOrganizer; - - PO.selectLeftPaneQuery('BookmarksToolbar'); - isnot(PO._places.selectedNode, null, "We have a valid selection"); - is(PlacesUtils.getConcreteItemId(PO._places.selectedNode), - PlacesUtils.toolbarFolderId, - "We have correctly selected bookmarks toolbar node."); - - // Check that both cut and delete commands are disabled, cause this is a child - // of AllBookmarksFolderId. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is disabled"); - - let toolbarNode = PlacesUtils.asContainer(PO._places.selectedNode); - toolbarNode.containerOpen = true; - - // Add an History query to the toolbar. - let query = yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "place:sort=4", - title: "special_query", - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 }); - - // Get first child and check it is the just inserted query. - ok(toolbarNode.childCount > 0, "Toolbar node has children"); - let queryNode = toolbarNode.getChild(0); - is(queryNode.title, "special_query", "Query node is correctly selected"); - - // Select query node. - PO._places.selectNode(queryNode); - is(PO._places.selectedNode, queryNode, "We correctly selected query node"); - - // Check that both cut and delete commands are enabled. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is enabled"); - ok(PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - - // Execute the delete command and check bookmark has been removed. - let promiseItemRemoved = promiseBookmarksNotification("onItemRemoved", - (...args) => query.guid == args[5]); - PO._places.controller.doCommand("cmd_delete"); - yield promiseItemRemoved; - - is((yield PlacesUtils.bookmarks.fetch(query.guid)), null, - "Query node bookmark has been correctly removed"); - - toolbarNode.containerOpen = false; - - library.close(); -}); - -add_task(function* test_search_contents() { - yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "http://example.com/", - title: "example page", - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: 0 }); - - let library = yield promiseLibrary(); - info("Ensure query contents can be cut or deleted"); - - // Select and open the left pane "Bookmarks Toolbar" folder. - let PO = library.PlacesOrganizer; - - PO.selectLeftPaneQuery('BookmarksToolbar'); - isnot(PO._places.selectedNode, null, "We have a valid selection"); - is(PlacesUtils.getConcreteItemId(PO._places.selectedNode), - PlacesUtils.toolbarFolderId, - "We have correctly selected bookmarks toolbar node."); - - let searchBox = library.document.getElementById("searchFilter"); - searchBox.value = "example"; - library.PlacesSearchBox.search(searchBox.value); - - let bookmarkNode = library.ContentTree.view.selectedNode; - is(bookmarkNode.uri, "http://example.com/", "Found the expected bookmark"); - - // Check that both cut and delete commands are enabled. - ok(library.ContentTree.view.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(library.ContentTree.view.controller.isCommandEnabled("cmd_cut"), - "Cut command is enabled"); - ok(library.ContentTree.view.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - - library.close(); -}); - -add_task(function* test_tags() { - yield PlacesUtils.bookmarks.insert({ type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "http://example.com/", - title: "example page", - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: 0 }); - PlacesUtils.tagging.tagURI(NetUtil.newURI("http://example.com/"), ["test"]); - - let library = yield promiseLibrary(); - info("Ensure query contents can be cut or deleted"); - - // Select and open the left pane "Bookmarks Toolbar" folder. - let PO = library.PlacesOrganizer; - - PO.selectLeftPaneQuery('Tags'); - let tagsNode = PO._places.selectedNode; - isnot(tagsNode, null, "We have a valid selection"); - let tagsTitle = PlacesUtils.getString("TagsFolderTitle"); - is(tagsNode.title, tagsTitle, - "Tags has been properly selected"); - - // Check that both cut and delete commands are disabled. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is disabled"); - - // Now select the tag. - PlacesUtils.asContainer(tagsNode).containerOpen = true; - let tag = tagsNode.getChild(0); - PO._places.selectNode(tag); - is(PO._places.selectedNode.title, "test", - "The created tag has been properly selected"); - - // Check that cut is disabled but delete is enabled. - ok(PO._places.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!PO._places.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(PO._places.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - - let bookmarkNode = library.ContentTree.view.selectedNode; - is(bookmarkNode.uri, "http://example.com/", "Found the expected bookmark"); - - // Check that both cut and delete commands are enabled. - ok(library.ContentTree.view.controller.isCommandEnabled("cmd_copy"), - "Copy command is enabled"); - ok(!library.ContentTree.view.controller.isCommandEnabled("cmd_cut"), - "Cut command is disabled"); - ok(library.ContentTree.view.controller.isCommandEnabled("cmd_delete"), - "Delete command is enabled"); - - tagsNode.containerOpen = false; - - library.close(); -}); diff --git a/browser/components/places/tests/browser/browser_library_downloads.js b/browser/components/places/tests/browser/browser_library_downloads.js deleted file mode 100644 index 81daadd71..000000000 --- a/browser/components/places/tests/browser/browser_library_downloads.js +++ /dev/null @@ -1,70 +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/. */ - -/* - * Tests bug 564900: Add folder specifically for downloads to Library left pane. - * https://bugzilla.mozilla.org/show_bug.cgi?id=564900 - * This test visits various pages then opens the Library and ensures - * that both the Downloads folder shows up and that the correct visits - * are shown in it. - */ - -var now = Date.now(); - -function test() { - waitForExplicitFinish(); - - let onLibraryReady = function(win) { - // Add visits to compare contents with. - let places = [ - { uri: NetUtil.newURI("http://mozilla.com"), - visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_TYPED) ] - }, - { uri: NetUtil.newURI("http://google.com"), - visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_DOWNLOAD) ] - }, - { uri: NetUtil.newURI("http://en.wikipedia.org"), - visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_TYPED) ] - }, - { uri: NetUtil.newURI("http://ubuntu.org"), - visits: [ new VisitInfo(PlacesUtils.history.TRANSITION_DOWNLOAD) ] - }, - ] - PlacesUtils.asyncHistory.updatePlaces(places, { - handleResult: function () {}, - handleError: function () { - ok(false, "gHistory.updatePlaces() failed"); - }, - handleCompletion: function () { - // Make sure Downloads is present. - isnot(win.PlacesOrganizer._places.selectedNode, null, - "Downloads is present and selected"); - - - // Check results. - let contentRoot = win.ContentArea.currentView.result.root; - let len = contentRoot.childCount; - const TEST_URIS = ["http://ubuntu.org/", "http://google.com/"]; - for (let i = 0; i < len; i++) { - is(contentRoot.getChild(i).uri, TEST_URIS[i], - "Comparing downloads shown at index " + i); - } - - win.close(); - PlacesTestUtils.clearHistory().then(finish); - } - }) - } - - openLibrary(onLibraryReady, "Downloads"); -} - -function VisitInfo(aTransitionType) -{ - this.transitionType = - aTransitionType === undefined ? - PlacesUtils.history.TRANSITION_LINK : aTransitionType; - this.visitDate = now++ * 1000; -} -VisitInfo.prototype = {} diff --git a/browser/components/places/tests/browser/browser_library_infoBox.js b/browser/components/places/tests/browser/browser_library_infoBox.js deleted file mode 100644 index 17cd78f8c..000000000 --- a/browser/components/places/tests/browser/browser_library_infoBox.js +++ /dev/null @@ -1,197 +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 appropriate visibility of infoBoxExpanderWrapper and - * additionalInfoFields in infoBox section of library - */ - -const TEST_URI = "http://www.mozilla.org/"; - -var gTests = []; -var gLibrary; - -// ------------------------------------------------------------------------------ - -gTests.push({ - desc: "Bug 430148 - Remove or hide the more/less button in details pane...", - run: function() { - var PO = gLibrary.PlacesOrganizer; - let ContentTree = gLibrary.ContentTree; - var infoBoxExpanderWrapper = getAndCheckElmtById("infoBoxExpanderWrapper"); - - function addVisitsCallback() { - // open all bookmarks node - PO.selectLeftPaneQuery("AllBookmarks"); - isnot(PO._places.selectedNode, null, - "Correctly selected all bookmarks node."); - checkInfoBoxSelected(PO); - ok(infoBoxExpanderWrapper.hidden, - "Expander button is hidden for all bookmarks node."); - checkAddInfoFieldsCollapsed(PO); - - // open history node - PO.selectLeftPaneQuery("History"); - isnot(PO._places.selectedNode, null, "Correctly selected history node."); - checkInfoBoxSelected(PO); - ok(infoBoxExpanderWrapper.hidden, - "Expander button is hidden for history node."); - checkAddInfoFieldsCollapsed(PO); - - // open history child node - var historyNode = PO._places.selectedNode. - QueryInterface(Ci.nsINavHistoryContainerResultNode); - historyNode.containerOpen = true; - var childNode = historyNode.getChild(0); - isnot(childNode, null, "History node first child is not null."); - PO._places.selectNode(childNode); - checkInfoBoxSelected(PO); - ok(infoBoxExpanderWrapper.hidden, - "Expander button is hidden for history child node."); - checkAddInfoFieldsCollapsed(PO); - - // open history item - var view = ContentTree.view.view; - ok(view.rowCount > 0, "History item exists."); - view.selection.select(0); - ok(infoBoxExpanderWrapper.hidden, - "Expander button is hidden for history item."); - checkAddInfoFieldsCollapsed(PO); - - historyNode.containerOpen = false; - - // open bookmarks menu node - PO.selectLeftPaneQuery("BookmarksMenu"); - isnot(PO._places.selectedNode, null, - "Correctly selected bookmarks menu node."); - checkInfoBoxSelected(PO); - ok(infoBoxExpanderWrapper.hidden, - "Expander button is hidden for bookmarks menu node."); - checkAddInfoFieldsCollapsed(PO); - - // open recently bookmarked node - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId, - NetUtil.newURI("place:folder=BOOKMARKS_MENU" + - "&folder=UNFILED_BOOKMARKS" + - "&folder=TOOLBAR" + - "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS + - "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING + - "&maxResults=10" + - "&excludeQueries=1"), - 0, "Recent Bookmarks"); - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.bookmarksMenuFolderId, - NetUtil.newURI("http://mozilla.org/"), - 1, "Mozilla"); - var menuNode = PO._places.selectedNode. - QueryInterface(Ci.nsINavHistoryContainerResultNode); - menuNode.containerOpen = true; - childNode = menuNode.getChild(0); - isnot(childNode, null, "Bookmarks menu child node exists."); - is(childNode.title, "Recent Bookmarks", - "Correctly selected recently bookmarked node."); - PO._places.selectNode(childNode); - checkInfoBoxSelected(PO); - ok(!infoBoxExpanderWrapper.hidden, - "Expander button is not hidden for recently bookmarked node."); - checkAddInfoFieldsNotCollapsed(PO); - - // open first bookmark - view = ContentTree.view.view; - ok(view.rowCount > 0, "Bookmark item exists."); - view.selection.select(0); - checkInfoBoxSelected(PO); - ok(!infoBoxExpanderWrapper.hidden, - "Expander button is not hidden for bookmark item."); - checkAddInfoFieldsNotCollapsed(PO); - checkAddInfoFields(PO, "bookmark item"); - - menuNode.containerOpen = false; - - PlacesTestUtils.clearHistory().then(nextTest); - } - // add a visit to browser history - PlacesTestUtils.addVisits( - { uri: PlacesUtils._uri(TEST_URI), visitDate: Date.now() * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED } - ).then(addVisitsCallback); - } -}); - -function checkInfoBoxSelected(PO) { - is(getAndCheckElmtById("detailsDeck").selectedIndex, 1, - "Selected element in detailsDeck is infoBox."); -} - -function checkAddInfoFieldsCollapsed(PO) { - PO._additionalInfoFields.forEach(function (id) { - ok(getAndCheckElmtById(id).collapsed, - "Additional info field correctly collapsed: #" + id); - }); -} - -function checkAddInfoFieldsNotCollapsed(PO) { - ok(PO._additionalInfoFields.some(function (id) { - return !getAndCheckElmtById(id).collapsed; - }), "Some additional info field correctly not collapsed"); -} - -function checkAddInfoFields(PO, nodeName) { - ok(true, "Checking additional info fields visibiity for node: " + nodeName); - var expanderButton = getAndCheckElmtById("infoBoxExpander"); - - // make sure additional fields are hidden by default - PO._additionalInfoFields.forEach(function (id) { - ok(getAndCheckElmtById(id).hidden, - "Additional info field correctly hidden by default: #" + id); - }); - - // toggle fields and make sure they are hidden/unhidden as expected - expanderButton.click(); - PO._additionalInfoFields.forEach(function (id) { - ok(!getAndCheckElmtById(id).hidden, - "Additional info field correctly unhidden after toggle: #" + id); - }); - expanderButton.click(); - PO._additionalInfoFields.forEach(function (id) { - ok(getAndCheckElmtById(id).hidden, - "Additional info field correctly hidden after toggle: #" + id); - }); -} - -function getAndCheckElmtById(id) { - var elmt = gLibrary.document.getElementById(id); - isnot(elmt, null, "Correctly got element: #" + id); - return elmt; -} - -// ------------------------------------------------------------------------------ - -function nextTest() { - if (gTests.length) { - var test = gTests.shift(); - ok(true, "TEST: " + test.desc); - dump("TEST: " + test.desc + "\n"); - test.run(); - } - else { - // Close Library window. - gLibrary.close(); - // No need to cleanup anything, we have a correct left pane now. - finish(); - } -} - -function test() { - waitForExplicitFinish(); - // Sanity checks. - ok(PlacesUtils, "PlacesUtils is running in chrome context"); - ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context"); - - // Open Library. - openLibrary(function (library) { - gLibrary = library; - gLibrary.PlacesOrganizer._places.focus(); - nextTest(gLibrary); - }); -} diff --git a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js b/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js deleted file mode 100644 index 7cea38f20..000000000 --- a/browser/components/places/tests/browser/browser_library_left_pane_fixnames.js +++ /dev/null @@ -1,94 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 we correctly fix broken Library left pane queries names. - */ - -// Array of left pane queries objects, each one has the following properties: -// name: query's identifier got from annotations, -// itemId: query's itemId, -// correctTitle: original and correct query's title. -var leftPaneQueries = []; - -function onLibraryReady(organizer) { - // Check titles have been fixed. - for (var i = 0; i < leftPaneQueries.length; i++) { - var query = leftPaneQueries[i]; - is(PlacesUtils.bookmarks.getItemTitle(query.itemId), - query.correctTitle, "Title is correct for query " + query.name); - if ("concreteId" in query) { - is(PlacesUtils.bookmarks.getItemTitle(query.concreteId), - query.concreteTitle, "Concrete title is correct for query " + query.name); - } - } - - // Close Library window. - organizer.close(); - // No need to cleanup anything, we have a correct left pane now. - finish(); -} - -function test() { - waitForExplicitFinish(); - // Sanity checks. - ok(PlacesUtils, "PlacesUtils is running in chrome context"); - ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context"); - ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0, - "Left pane version in chrome context, current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION ); - - // Ensure left pane is initialized. - ok(PlacesUIUtils.leftPaneFolderId > 0, "left pane folder is initialized"); - - // Get the left pane folder. - var leftPaneItems = PlacesUtils.annotations - .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - - is(leftPaneItems.length, 1, "We correctly have only 1 left pane folder"); - // Check version. - var version = PlacesUtils.annotations - .getItemAnnotation(leftPaneItems[0], - PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(version, PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, "Left pane version is actual"); - - // Get all left pane queries. - var items = PlacesUtils.annotations - .getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_QUERY_ANNO); - // Get current queries names. - for (var i = 0; i < items.length; i++) { - var itemId = items[i]; - var queryName = PlacesUtils.annotations - .getItemAnnotation(items[i], - PlacesUIUtils.ORGANIZER_QUERY_ANNO); - var query = { name: queryName, - itemId: itemId, - correctTitle: PlacesUtils.bookmarks.getItemTitle(itemId) } - switch (queryName) { - case "BookmarksToolbar": - query.concreteId = PlacesUtils.toolbarFolderId; - query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId); - break; - case "BookmarksMenu": - query.concreteId = PlacesUtils.bookmarksMenuFolderId; - query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId); - break; - case "UnfiledBookmarks": - query.concreteId = PlacesUtils.unfiledBookmarksFolderId; - query.concreteTitle = PlacesUtils.bookmarks.getItemTitle(query.concreteId); - break; - } - leftPaneQueries.push(query); - // Rename to a bad title. - PlacesUtils.bookmarks.setItemTitle(query.itemId, "badName"); - if ("concreteId" in query) - PlacesUtils.bookmarks.setItemTitle(query.concreteId, "badName"); - } - - PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter); - - // Open Library, this will kick-off left pane code. - openLibrary(onLibraryReady); -} diff --git a/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js b/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js deleted file mode 100644 index b90df120c..000000000 --- a/browser/components/places/tests/browser/browser_library_left_pane_select_hierarchy.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -function test() { - waitForExplicitFinish(); - openLibrary(onLibraryReady); -} - -function onLibraryReady(aLibrary) { - let hierarchy = [ "AllBookmarks", "BookmarksMenu" ]; - - let folder1 = PlacesUtils.bookmarks - .createFolder(PlacesUtils.bookmarksMenuFolderId, - "Folder 1", - PlacesUtils.bookmarks.DEFAULT_INDEX); - hierarchy.push(folder1); - let folder2 = PlacesUtils.bookmarks - .createFolder(folder1, "Folder 2", - PlacesUtils.bookmarks.DEFAULT_INDEX); - hierarchy.push(folder2); - let bookmark = PlacesUtils.bookmarks - .insertBookmark(folder2, NetUtil.newURI("http://example.com/"), - PlacesUtils.bookmarks.DEFAULT_INDEX, - "Bookmark"); - - registerCleanupFunction(function() { - PlacesUtils.bookmarks.removeItem(folder1); - aLibrary.close(); - }); - - aLibrary.PlacesOrganizer.selectLeftPaneContainerByHierarchy(hierarchy); - - is(aLibrary.PlacesOrganizer._places.selectedNode.itemId, folder2, - "Found the expected left pane selected node"); - - is(aLibrary.ContentTree.view.view.nodeForTreeIndex(0).itemId, bookmark, - "Found the expected right pane contents"); - - finish(); -} diff --git a/browser/components/places/tests/browser/browser_library_middleclick.js b/browser/components/places/tests/browser/browser_library_middleclick.js deleted file mode 100644 index 894f89446..000000000 --- a/browser/components/places/tests/browser/browser_library_middleclick.js +++ /dev/null @@ -1,279 +0,0 @@ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 middle-clicking items in the Library. - */ - -const ENABLE_HISTORY_PREF = "places.history.enabled"; - -var gLibrary = null; -var gTests = []; -var gCurrentTest = null; - -// Listener for TabOpen and tabs progress. -var gTabsListener = { - _loadedURIs: [], - _openTabsCount: 0, - - handleEvent: function(aEvent) { - if (aEvent.type != "TabOpen") - return; - - if (++this._openTabsCount == gCurrentTest.URIs.length) { - is(gBrowser.tabs.length, gCurrentTest.URIs.length + 1, - "We have opened " + gCurrentTest.URIs.length + " new tab(s)"); - } - - var tab = aEvent.target; - is(tab.ownerGlobal, window, - "Tab has been opened in current browser window"); - }, - - onLocationChange: function(aBrowser, aWebProgress, aRequest, aLocationURI, - aFlags) { - var spec = aLocationURI.spec; - ok(true, spec); - // When a new tab is opened, location is first set to "about:blank", so - // we can ignore those calls. - // Ignore multiple notifications for the same URI too. - if (spec == "about:blank" || this._loadedURIs.includes(spec)) - return; - - ok(gCurrentTest.URIs.includes(spec), - "Opened URI found in list: " + spec); - - if (gCurrentTest.URIs.includes(spec)) - this._loadedURIs.push(spec); - - if (this._loadedURIs.length == gCurrentTest.URIs.length) { - // We have correctly opened all URIs. - - // Reset arrays. - this._loadedURIs.length = 0; - - this._openTabsCount = 0; - - executeSoon(function () { - // Close all tabs. - while (gBrowser.tabs.length > 1) - gBrowser.removeCurrentTab(); - - // Test finished. This will move to the next one. - waitForFocus(gCurrentTest.finish, gBrowser.ownerGlobal); - }); - } - } -} - -// ------------------------------------------------------------------------------ -// Open bookmark in a new tab. - -gTests.push({ - desc: "Open bookmark in a new tab.", - URIs: ["about:buildconfig"], - _itemId: -1, - - setup: function() { - var bs = PlacesUtils.bookmarks; - // Add a new unsorted bookmark. - this._itemId = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri(this.URIs[0]), - bs.DEFAULT_INDEX, - "Title"); - // Select unsorted bookmarks root in the left pane. - gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - isnot(gLibrary.PlacesOrganizer._places.selectedNode, null, - "We correctly have selection in the Library left pane"); - // Get our bookmark in the right pane. - var bookmarkNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0); - is(bookmarkNode.uri, this.URIs[0], "Found bookmark in the right pane"); - }, - - finish: function() { - setTimeout(runNextTest, 0); - }, - - cleanup: function() { - PlacesUtils.bookmarks.removeItem(this._itemId); - } -}); - -// ------------------------------------------------------------------------------ -// Open a folder in tabs. - -gTests.push({ - desc: "Open a folder in tabs.", - URIs: ["about:buildconfig", "about:"], - _folderId: -1, - - setup: function() { - var bs = PlacesUtils.bookmarks; - // Create a new folder. - var folderId = bs.createFolder(bs.unfiledBookmarksFolder, - "Folder", - bs.DEFAULT_INDEX); - this._folderId = folderId; - - // Add bookmarks in folder. - this.URIs.forEach(function(aURI) { - bs.insertBookmark(folderId, - PlacesUtils._uri(aURI), - bs.DEFAULT_INDEX, - "Title"); - }); - - // Select unsorted bookmarks root in the left pane. - gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - isnot(gLibrary.PlacesOrganizer._places.selectedNode, null, - "We correctly have selection in the Library left pane"); - // Get our bookmark in the right pane. - var folderNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0); - is(folderNode.title, "Folder", "Found folder in the right pane"); - }, - - finish: function() { - setTimeout(runNextTest, 0); - }, - - cleanup: function() { - PlacesUtils.bookmarks.removeItem(this._folderId); - } -}); - -// ------------------------------------------------------------------------------ -// Open a query in tabs. - -gTests.push({ - desc: "Open a query in tabs.", - URIs: ["about:buildconfig", "about:"], - _folderId: -1, - _queryId: -1, - - setup: function() { - var bs = PlacesUtils.bookmarks; - // Create a new folder. - var folderId = bs.createFolder(bs.unfiledBookmarksFolder, - "Folder", - bs.DEFAULT_INDEX); - this._folderId = folderId; - - // Add bookmarks in folder. - this.URIs.forEach(function(aURI) { - bs.insertBookmark(folderId, - PlacesUtils._uri(aURI), - bs.DEFAULT_INDEX, - "Title"); - }); - - // Create a bookmarks query containing our bookmarks. - var hs = PlacesUtils.history; - var options = hs.getNewQueryOptions(); - options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS; - var query = hs.getNewQuery(); - // The colon included in the terms selects only about: URIs. If not included - // we also may get pages like about.html included in the query result. - query.searchTerms = "about:"; - var queryString = hs.queriesToQueryString([query], 1, options); - this._queryId = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri(queryString), - 0, // It must be the first. - "Query"); - - // Select unsorted bookmarks root in the left pane. - gLibrary.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - isnot(gLibrary.PlacesOrganizer._places.selectedNode, null, - "We correctly have selection in the Library left pane"); - // Get our bookmark in the right pane. - var folderNode = gLibrary.ContentTree.view.view.nodeForTreeIndex(0); - is(folderNode.title, "Query", "Found query in the right pane"); - }, - - finish: function() { - setTimeout(runNextTest, 0); - }, - - cleanup: function() { - PlacesUtils.bookmarks.removeItem(this._folderId); - PlacesUtils.bookmarks.removeItem(this._queryId); - } -}); - -// ------------------------------------------------------------------------------ - -function test() { - waitForExplicitFinish(); - // Increase timeout, this test can be quite slow due to waitForFocus calls. - requestLongerTimeout(2); - - // Sanity checks. - ok(PlacesUtils, "PlacesUtils in context"); - ok(PlacesUIUtils, "PlacesUIUtils in context"); - - // Add tabs listeners. - gBrowser.tabContainer.addEventListener("TabOpen", gTabsListener, false); - gBrowser.addTabsProgressListener(gTabsListener); - - // Temporary disable history, so we won't record pages navigation. - gPrefService.setBoolPref(ENABLE_HISTORY_PREF, false); - - // Open Library window. - openLibrary(function (library) { - gLibrary = library; - // Kick off tests. - runNextTest(); - }); -} - -function runNextTest() { - // Cleanup from previous test. - if (gCurrentTest) - gCurrentTest.cleanup(); - - if (gTests.length > 0) { - // Goto next test. - gCurrentTest = gTests.shift(); - info("Start of test: " + gCurrentTest.desc); - // Test setup will set Library so that the bookmark to be opened is the - // first node in the content (right pane) tree. - gCurrentTest.setup(); - - // Middle click on first node in the content tree of the Library. - gLibrary.focus(); - waitForFocus(function() { - mouseEventOnCell(gLibrary.ContentTree.view, 0, 0, { button: 1 }); - }, gLibrary); - } - else { - // No more tests. - - // Close Library window. - gLibrary.close(); - - // Remove tabs listeners. - gBrowser.tabContainer.removeEventListener("TabOpen", gTabsListener, false); - gBrowser.removeTabsProgressListener(gTabsListener); - - // Restore history. - try { - gPrefService.clearUserPref(ENABLE_HISTORY_PREF); - } catch (ex) {} - - finish(); - } -} - -function mouseEventOnCell(aTree, aRowIndex, aColumnIndex, aEventDetails) { - var selection = aTree.view.selection; - selection.select(aRowIndex); - aTree.treeBoxObject.ensureRowIsVisible(aRowIndex); - var column = aTree.columns[aColumnIndex]; - - // get cell coordinates - var rect = aTree.treeBoxObject.getCoordsForCellItem(aRowIndex, column, "text"); - - EventUtils.synthesizeMouse(aTree.body, rect.x, rect.y, - aEventDetails, gLibrary); -} diff --git a/browser/components/places/tests/browser/browser_library_openFlatContainer.js b/browser/components/places/tests/browser/browser_library_openFlatContainer.js deleted file mode 100644 index 167b33031..000000000 --- a/browser/components/places/tests/browser/browser_library_openFlatContainer.js +++ /dev/null @@ -1,42 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -/** - * Test opening a flat container in the right pane even if its parent in the - * left pane is closed. - */ - -add_task(function* () { - let folder = PlacesUtils.bookmarks - .createFolder(PlacesUtils.unfiledBookmarksFolderId, - "Folder", - PlacesUtils.bookmarks.DEFAULT_INDEX); - let bookmark = PlacesUtils.bookmarks - .insertBookmark(folder, NetUtil.newURI("http://example.com/"), - PlacesUtils.bookmarks.DEFAULT_INDEX, - "Bookmark"); - - let library = yield promiseLibrary("AllBookmarks"); - registerCleanupFunction(function () { - library.close(); - PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); - }); - - // Select unfiled later, to ensure it's closed. - library.PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks"); - ok(!library.PlacesOrganizer._places.selectedNode.containerOpen, - "Unfiled container is closed"); - - let folderNode = library.ContentTree.view.view.nodeForTreeIndex(0); - is(folderNode.itemId, folder, - "Found the expected folder in the right pane"); - // Select the folder node in the right pane. - library.ContentTree.view.selectNode(folderNode); - - synthesizeClickOnSelectedTreeCell(library.ContentTree.view, - { clickCount: 2 }); - - is(library.ContentTree.view.view.nodeForTreeIndex(0).itemId, bookmark, - "Found the expected bookmark in the right pane"); -}); diff --git a/browser/components/places/tests/browser/browser_library_open_leak.js b/browser/components/places/tests/browser/browser_library_open_leak.js deleted file mode 100644 index f002236a9..000000000 --- a/browser/components/places/tests/browser/browser_library_open_leak.js +++ /dev/null @@ -1,23 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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/. */ - -/** - * Bug 474831 - * https://bugzilla.mozilla.org/show_bug.cgi?id=474831 - * - * Tests for leaks caused by simply opening and closing the Places Library - * window. Opens the Places Library window, waits for it to load, closes it, - * and finishes. - */ - -function test() { - waitForExplicitFinish(); - openLibrary(function (win) { - ok(true, "Library has been correctly opened"); - win.close(); - finish(); - }); -} diff --git a/browser/components/places/tests/browser/browser_library_panel_leak.js b/browser/components/places/tests/browser/browser_library_panel_leak.js deleted file mode 100644 index 643a261fb..000000000 --- a/browser/components/places/tests/browser/browser_library_panel_leak.js +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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/. */ - -/** - * Bug 433231 - Places Library leaks the nsGlobalWindow when closed with a - * history entry selected. - * https://bugzilla.mozilla.org/show_bug.cgi?id=433231 - * - * STRs: Open Library, select an history entry in History, close Library. - * ISSUE: We were adding a bookmarks observer when editing a bookmark, when - * selecting an history entry the panel was not un-initialized, and - * since an histroy entry does not have an itemId, the observer was - * never removed. - */ - -const TEST_URI = "http://www.mozilla.org/"; - -function test() { - function onLibraryReady(organizer) { - let contentTree = organizer.document.getElementById("placeContent"); - isnot(contentTree, null, "Sanity check: placeContent tree should exist"); - isnot(organizer.PlacesOrganizer, null, "Sanity check: PlacesOrganizer should exist"); - isnot(organizer.gEditItemOverlay, null, "Sanity check: gEditItemOverlay should exist"); - - ok(organizer.gEditItemOverlay.initialized, "gEditItemOverlay is initialized"); - isnot(organizer.gEditItemOverlay.itemId, -1, "Editing a bookmark"); - - // Select History in the left pane. - organizer.PlacesOrganizer.selectLeftPaneQuery('History'); - // Select the first history entry. - let selection = contentTree.view.selection; - selection.clearSelection(); - selection.rangedSelect(0, 0, true); - // Check the panel is editing the history entry. - is(organizer.gEditItemOverlay.itemId, -1, "Editing an history entry"); - // Close Library window. - organizer.close(); - // Clean up history. - PlacesTestUtils.clearHistory().then(finish); - } - - waitForExplicitFinish(); - // Add an history entry. - ok(PlacesUtils, "checking PlacesUtils, running in chrome context?"); - PlacesTestUtils.addVisits( - {uri: PlacesUtils._uri(TEST_URI), visitDate: Date.now() * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED} - ).then(() => { - openLibrary(onLibraryReady); - }); -} diff --git a/browser/components/places/tests/browser/browser_library_search.js b/browser/components/places/tests/browser/browser_library_search.js deleted file mode 100644 index 93af22363..000000000 --- a/browser/components/places/tests/browser/browser_library_search.js +++ /dev/null @@ -1,182 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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/. */ - -/** - * Bug 451151 - * https://bugzilla.mozilla.org/show_bug.cgi?id=451151 - * - * Summary: - * Tests frontend Places Library searching -- search, search reset, search scope - * consistency. - * - * Details: - * Each test below - * 1. selects a folder in the left pane and ensures that the content tree is - * appropriately updated, - * 2. performs a search and ensures that the content tree is correct for the - * folder and search and that the search UI is visible and appropriate to - * folder, - * 5. resets the search and ensures that the content tree is correct and that - * the search UI is hidden, and - * 6. if folder scope was clicked, searches again and ensures folder scope - * remains selected. - */ - -const TEST_URL = "http://dummy.mozilla.org/"; -const TEST_DOWNLOAD_URL = "http://dummy.mozilla.org/dummy.pdf"; - -var gLibrary; - -var testCases = [ - function allBookmarksScope() { - let defScope = getDefaultScope(PlacesUIUtils.allBookmarksFolderId); - search(PlacesUIUtils.allBookmarksFolderId, "dummy", defScope); - }, - - function historyScope() { - let defScope = getDefaultScope(PlacesUIUtils.leftPaneQueries["History"]); - search(PlacesUIUtils.leftPaneQueries["History"], "dummy", defScope); - }, - - function downloadsScope() { - let defScope = getDefaultScope(PlacesUIUtils.leftPaneQueries["Downloads"]); - search(PlacesUIUtils.leftPaneQueries["Downloads"], "dummy", defScope); - }, -]; - -/** - * Returns the default search scope for a given folder. - * - * @param aFolderId - * the item ID of a node in the left pane's tree - * @return the default scope when the folder is newly selected - */ -function getDefaultScope(aFolderId) { - switch (aFolderId) { - case PlacesUIUtils.leftPaneQueries["History"]: - return "scopeBarHistory" - case PlacesUIUtils.leftPaneQueries["Downloads"]: - return "scopeBarDownloads"; - default: - return "scopeBarAll"; - } -} - -/** - * Returns the single nsINavHistoryQuery represented by a given place URI. - * - * @param aPlaceURI - * a URI that represents a single query - * @return an nsINavHistoryQuery object - */ -function queryStringToQuery(aPlaceURI) { - let queries = {}; - PlacesUtils.history.queryStringToQueries(aPlaceURI, queries, {}, {}); - return queries.value[0]; -} - -/** - * Resets the search by clearing the search box's text and ensures that the - * search scope remains as expected. - * - * @param aExpectedScopeButtonId - * this button should be selected after the reset - */ -function resetSearch(aExpectedScopeButtonId) { - search(null, "", aExpectedScopeButtonId); -} - -/** - * Performs a search for a given folder and search string and ensures that the - * URI of the right pane's content tree is as expected for the folder and search - * string. Also ensures that the search scope button is as expected after the - * search. - * - * @param aFolderId - * the item ID of a node in the left pane's tree - * @param aSearchStr - * the search text; may be empty to reset the search - * @param aExpectedScopeButtonId - * after searching the selected scope button should be this - */ -function search(aFolderId, aSearchStr, aExpectedScopeButtonId) { - let doc = gLibrary.document; - let folderTree = doc.getElementById("placesList"); - let contentTree = doc.getElementById("placeContent"); - - // First, ensure that selecting the folder in the left pane updates the - // content tree properly. - if (aFolderId) { - folderTree.selectItems([aFolderId]); - isnot(folderTree.selectedNode, null, - "Sanity check: left pane tree should have selection after selecting!"); - - // getFolders() on a History query returns an empty array, so no use - // comparing against aFolderId in that case. - if (aFolderId !== PlacesUIUtils.leftPaneQueries["History"] && - aFolderId !== PlacesUIUtils.leftPaneQueries["Downloads"]) { - // contentTree.place should be equal to contentTree.result.root.uri, - // but it's not until bug 476952 is fixed. - let query = queryStringToQuery(contentTree.result.root.uri); - is(query.getFolders()[0], aFolderId, - "Content tree's folder should be what was selected in the left pane"); - } - } - - // Second, ensure that searching updates the content tree and search UI - // properly. - let searchBox = doc.getElementById("searchFilter"); - searchBox.value = aSearchStr; - gLibrary.PlacesSearchBox.search(searchBox.value); - let query = queryStringToQuery(contentTree.result.root.uri); - if (aSearchStr) { - is(query.searchTerms, aSearchStr, - "Content tree's searchTerms should be text in search box"); - } - else { - is(query.hasSearchTerms, false, - "Content tree's searchTerms should not exist after search reset"); - } -} - -/** - * test() contains window-launching boilerplate that calls this to really kick - * things off. Add functions to the testCases array, and this will call them. - */ -function onLibraryAvailable() { - testCases.forEach(aTest => aTest()); - - gLibrary.close(); - gLibrary = null; - - // Cleanup. - PlacesUtils.tagging.untagURI(PlacesUtils._uri(TEST_URL), ["dummyTag"]); - PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); - PlacesTestUtils.clearHistory().then(finish); -} - -function test() { - waitForExplicitFinish(); - - // Sanity: - ok(PlacesUtils, "PlacesUtils in context"); - - // Add visits, a bookmark and a tag. - PlacesTestUtils.addVisits( - [{ uri: PlacesUtils._uri(TEST_URL), visitDate: Date.now() * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED }, - { uri: PlacesUtils._uri(TEST_DOWNLOAD_URL), visitDate: Date.now() * 1000, - transition: PlacesUtils.history.TRANSITION_DOWNLOAD }] - ).then(() => { - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils._uri(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, - "dummy"); - PlacesUtils.tagging.tagURI(PlacesUtils._uri(TEST_URL), ["dummyTag"]); - - gLibrary = openLibrary(onLibraryAvailable); - }); -} diff --git a/browser/components/places/tests/browser/browser_library_views_liveupdate.js b/browser/components/places/tests/browser/browser_library_views_liveupdate.js deleted file mode 100644 index c78ed641a..000000000 --- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js +++ /dev/null @@ -1,300 +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/. */ - -/** - * Tests Library Left pane view for liveupdate. - */ - -var gLibrary = null; - -function test() { - waitForExplicitFinish(); - // This test takes quite some time, and timeouts frequently, so we require - // more time to run. - // See Bug 525610. - requestLongerTimeout(2); - - // Sanity checks. - ok(PlacesUtils, "PlacesUtils in context"); - ok(PlacesUIUtils, "PlacesUIUtils in context"); - - // Open Library, we will check the left pane. - openLibrary(function (library) { - gLibrary = library; - startTest(); - }); -} - -/** - * Adds bookmarks observer, and executes a bunch of bookmarks operations. - */ -function startTest() { - var bs = PlacesUtils.bookmarks; - // Add observers. - bs.addObserver(bookmarksObserver, false); - PlacesUtils.annotations.addObserver(bookmarksObserver, false); - var addedBookmarks = []; - - // MENU - ok(true, "*** Acting on menu bookmarks"); - var id = bs.insertBookmark(bs.bookmarksMenuFolder, - PlacesUtils._uri("http://bm1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bm1"); - addedBookmarks.push(id); - id = bs.insertBookmark(bs.bookmarksMenuFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "bm2"); - bs.setItemTitle(id, "bm2_edited"); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.bookmarksMenuFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.bookmarksMenuFolder, - "bmf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "bmf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://bmf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bmf1"); - addedBookmarks.push(id); - bs.moveItem(id, bs.bookmarksMenuFolder, 0); - - // TOOLBAR - ok(true, "*** Acting on toolbar bookmarks"); - bs.insertBookmark(bs.toolbarFolder, - PlacesUtils._uri("http://tb1.mozilla.org/"), - bs.DEFAULT_INDEX, - "tb1"); - bs.setItemTitle(id, "tb1_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(bs.toolbarFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "tb2"); - bs.setItemTitle(id, "tb2_edited"); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.toolbarFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.toolbarFolder, - "tbf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "tbf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://tbf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bmf1"); - addedBookmarks.push(id); - bs.moveItem(id, bs.toolbarFolder, 0); - - // UNSORTED - ok(true, "*** Acting on unsorted bookmarks"); - id = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri("http://ub1.mozilla.org/"), - bs.DEFAULT_INDEX, - "ub1"); - bs.setItemTitle(id, "ub1_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "ub2"); - bs.setItemTitle(id, "ub2_edited"); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.unfiledBookmarksFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.unfiledBookmarksFolder, - "ubf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "ubf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://ubf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "ubf1"); - addedBookmarks.push(id); - bs.moveItem(id, bs.unfiledBookmarksFolder, 0); - - // Remove all added bookmarks. - addedBookmarks.forEach(function (aItem) { - // If we remove an item after its containing folder has been removed, - // this will throw, but we can ignore that. - try { - bs.removeItem(aItem); - } catch (ex) {} - }); - - // Remove observers. - bs.removeObserver(bookmarksObserver); - PlacesUtils.annotations.removeObserver(bookmarksObserver); - finishTest(); -} - -/** - * Restores browser state and calls finish. - */ -function finishTest() { - // Close Library window. - gLibrary.close(); - finish(); -} - -/** - * The observer is where magic happens, for every change we do it will look for - * nodes positions in the affected views. - */ -var bookmarksObserver = { - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsINavBookmarkObserver - , Ci.nsIAnnotationObserver - ]), - - // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, - - // nsINavBookmarkObserver - onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, aItemType, - aURI) { - var node = null; - var index = null; - [node, index] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places); - // Left pane should not be updated for normal bookmarks or separators. - switch (aItemType) { - case PlacesUtils.bookmarks.TYPE_BOOKMARK: - var uriString = aURI.spec; - var isQuery = uriString.substr(0, 6) == "place:"; - if (isQuery) { - isnot(node, null, "Found new Places node in left pane"); - ok(index >= 0, "Node is at index " + index); - break; - } - // Fallback to separator case if this is not a query. - case PlacesUtils.bookmarks.TYPE_SEPARATOR: - is(node, null, "New Places node not added in left pane"); - break; - default: - isnot(node, null, "Found new Places node in left pane"); - ok(index >= 0, "Node is at index " + index); - } - }, - - onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) { - var node = null; - [node, ] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places); - is(node, null, "Places node not found in left pane"); - }, - - onItemMoved: function(aItemId, - aOldFolderId, aOldIndex, - aNewFolderId, aNewIndex, aItemType) { - var node = null; - var index = null; - [node, index] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places); - // Left pane should not be updated for normal bookmarks or separators. - switch (aItemType) { - case PlacesUtils.bookmarks.TYPE_BOOKMARK: - var uriString = PlacesUtils.bookmarks.getBookmarkURI(aItemId).spec; - var isQuery = uriString.substr(0, 6) == "place:"; - if (isQuery) { - isnot(node, null, "Found new Places node in left pane"); - ok(index >= 0, "Node is at index " + index); - break; - } - // Fallback to separator case if this is not a query. - case PlacesUtils.bookmarks.TYPE_SEPARATOR: - is(node, null, "New Places node not added in left pane"); - break; - default: - isnot(node, null, "Found new Places node in left pane"); - ok(index >= 0, "Node is at index " + index); - } - }, - - onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, - onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, - onItemChanged: function PSB_onItemChanged(aItemId, aProperty, - aIsAnnotationProperty, aNewValue) { - if (aProperty == "title") { - let validator = function(aTreeRowIndex) { - let tree = gLibrary.PlacesOrganizer._places; - let cellText = tree.view.getCellText(aTreeRowIndex, - tree.columns.getColumnAt(0)); - return cellText == aNewValue; - } - let [node, , valid] = getNodeForTreeItem(aItemId, gLibrary.PlacesOrganizer._places, validator); - if (node) // Only visible nodes. - ok(valid, "Title cell value has been correctly updated"); - } - } -}; - - -/** - * Get places node and index for an itemId in a tree view. - * - * @param aItemId - * item id of the item to search. - * @param aTree - * Tree to search in. - * @param aValidator [optional] - * function to check row validity if found. Defaults to {return true;}. - * @returns [node, index, valid] or [null, null, false] if not found. - */ -function getNodeForTreeItem(aItemId, aTree, aValidator) { - - function findNode(aContainerIndex) { - if (aTree.view.isContainerEmpty(aContainerIndex)) - return [null, null, false]; - - // The rowCount limit is just for sanity, but we will end looping when - // we have checked the last child of this container or we have found node. - for (var i = aContainerIndex + 1; i < aTree.view.rowCount; i++) { - var node = aTree.view.nodeForTreeIndex(i); - - if (node.itemId == aItemId) { - // Minus one because we want relative index inside the container. - let valid = aValidator ? aValidator(i) : true; - return [node, i - aTree.view.getParentIndex(i) - 1, valid]; - } - - if (PlacesUtils.nodeIsFolder(node)) { - // Open container. - aTree.view.toggleOpenState(i); - // Search inside it. - var foundNode = findNode(i); - // Close container. - aTree.view.toggleOpenState(i); - // Return node if found. - if (foundNode[0] != null) - return foundNode; - } - - // We have finished walking this container. - if (!aTree.view.hasNextSibling(aContainerIndex + 1, i)) - break; - } - return [null, null, false] - } - - // Root node is hidden, so we need to manually walk the first level. - for (var i = 0; i < aTree.view.rowCount; i++) { - // Open container. - aTree.view.toggleOpenState(i); - // Search inside it. - var foundNode = findNode(i); - // Close container. - aTree.view.toggleOpenState(i); - // Return node if found. - if (foundNode[0] != null) - return foundNode; - } - return [null, null, false]; -} diff --git a/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js b/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js deleted file mode 100644 index 02d564e28..000000000 --- a/browser/components/places/tests/browser/browser_markPageAsFollowedLink.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Tests that visits across frames are correctly represented in the database. - */ - -const BASE_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser"; -const PAGE_URL = BASE_URL + "/framedPage.html"; -const LEFT_URL = BASE_URL + "/frameLeft.html"; -const RIGHT_URL = BASE_URL + "/frameRight.html"; - -add_task(function* test() { - // We must wait for both frames to be loaded and the visits to be registered. - let deferredLeftFrameVisit = PromiseUtils.defer(); - let deferredRightFrameVisit = PromiseUtils.defer(); - - Services.obs.addObserver(function observe(subject) { - Task.spawn(function* () { - let url = subject.QueryInterface(Ci.nsIURI).spec; - if (url == LEFT_URL ) { - is((yield getTransitionForUrl(url)), null, - "Embed visits should not get a database entry."); - deferredLeftFrameVisit.resolve(); - } - else if (url == RIGHT_URL ) { - is((yield getTransitionForUrl(url)), - PlacesUtils.history.TRANSITION_FRAMED_LINK, - "User activated visits should get a FRAMED_LINK transition."); - Services.obs.removeObserver(observe, "uri-visit-saved"); - deferredRightFrameVisit.resolve(); - } - }); - }, "uri-visit-saved", false); - - // Open a tab and wait for all the subframes to load. - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, PAGE_URL); - - // Wait for the left frame visit to be registered. - info("Waiting left frame visit"); - yield deferredLeftFrameVisit.promise; - - // Click on the link in the left frame to cause a page load in the - // right frame. - info("Clicking link"); - yield ContentTask.spawn(tab.linkedBrowser, {}, function* () { - content.frames[0].document.getElementById("clickme").click(); - }); - - // Wait for the right frame visit to be registered. - info("Waiting right frame visit"); - yield deferredRightFrameVisit.promise; - - yield BrowserTestUtils.removeTab(tab); -}); - -function* getTransitionForUrl(url) { - // Ensure all the transactions completed. - yield PlacesTestUtils.promiseAsyncUpdates(); - let db = yield PlacesUtils.promiseDBConnection(); - let rows = yield db.execute(` - SELECT visit_type - FROM moz_historyvisits - JOIN moz_places h ON place_id = h.id - WHERE url_hash = hash(:url) AND url = :url`, - { url }); - if (rows.length) { - return rows[0].getResultByName("visit_type"); - } - return null; -} diff --git a/browser/components/places/tests/browser/browser_sidebarpanels_click.js b/browser/components/places/tests/browser/browser_sidebarpanels_click.js deleted file mode 100644 index 80ed2eb2b..000000000 --- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js +++ /dev/null @@ -1,157 +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 test makes sure that the items in the bookmarks and history sidebar -// panels are clickable in both LTR and RTL modes. - -function test() { - waitForExplicitFinish(); - ignoreAllUncaughtExceptions(); - - const BOOKMARKS_SIDEBAR_ID = "viewBookmarksSidebar"; - const BOOKMARKS_SIDEBAR_TREE_ID = "bookmarks-view"; - const HISTORY_SIDEBAR_ID = "viewHistorySidebar"; - const HISTORY_SIDEBAR_TREE_ID = "historyTree"; - const TEST_URL = "http://mochi.test:8888/browser/browser/components/places/tests/browser/sidebarpanels_click_test_page.html"; - - // If a sidebar is already open, close it. - if (!document.getElementById("sidebar-box").hidden) { - info("Unexpected sidebar found - a previous test failed to cleanup correctly"); - SidebarUI.hide(); - } - - let sidebar = document.getElementById("sidebar"); - let tests = []; - let currentTest; - - tests.push({ - _itemID: null, - init: function(aCallback) { - // Add a bookmark to the Unfiled Bookmarks folder. - this._itemID = PlacesUtils.bookmarks.insertBookmark( - PlacesUtils.unfiledBookmarksFolderId, PlacesUtils._uri(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, "test" - ); - aCallback(); - }, - prepare: function() { - }, - selectNode: function(tree) { - tree.selectItems([this._itemID]); - }, - cleanup: function(aCallback) { - PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId); - executeSoon(aCallback); - }, - sidebarName: BOOKMARKS_SIDEBAR_ID, - treeName: BOOKMARKS_SIDEBAR_TREE_ID, - desc: "Bookmarks sidebar test" - }); - - tests.push({ - init: function(aCallback) { - // Add a history entry. - let uri = PlacesUtils._uri(TEST_URL); - PlacesTestUtils.addVisits({ - uri: uri, visitDate: Date.now() * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED - }).then(aCallback); - }, - prepare: function() { - sidebar.contentDocument.getElementById("byvisited").doCommand(); - }, - selectNode: function(tree) { - tree.selectNode(tree.view.nodeForTreeIndex(0)); - is(tree.selectedNode.uri, TEST_URL, "The correct visit has been selected"); - is(tree.selectedNode.itemId, -1, "The selected node is not bookmarked"); - }, - cleanup: function(aCallback) { - PlacesTestUtils.clearHistory().then(aCallback); - }, - sidebarName: HISTORY_SIDEBAR_ID, - treeName: HISTORY_SIDEBAR_TREE_ID, - desc: "History sidebar test" - }); - - function testPlacesPanel(preFunc, postFunc) { - currentTest.init(function() { - SidebarUI.show(currentTest.sidebarName); - }); - - sidebar.addEventListener("load", function() { - sidebar.removeEventListener("load", arguments.callee, true); - executeSoon(function() { - currentTest.prepare(); - - if (preFunc) - preFunc(); - - function observer(aSubject, aTopic, aData) { - info("alert dialog observed as expected"); - Services.obs.removeObserver(observer, "common-dialog-loaded"); - Services.obs.removeObserver(observer, "tabmodal-dialog-loaded"); - - aSubject.Dialog.ui.button0.click(); - - executeSoon(function () { - SidebarUI.hide(); - currentTest.cleanup(postFunc); - }); - } - Services.obs.addObserver(observer, "common-dialog-loaded", false); - Services.obs.addObserver(observer, "tabmodal-dialog-loaded", false); - - let tree = sidebar.contentDocument.getElementById(currentTest.treeName); - - // Select the inserted places item. - currentTest.selectNode(tree); - - synthesizeClickOnSelectedTreeCell(tree); - // Now, wait for the observer to catch the alert dialog. - // If something goes wrong, the test will time out at this stage. - // Note that for the history sidebar, the URL itself is not opened, - // and Places will show the load-js-data-url-error prompt as an alert - // box, which means that the click actually worked, so it's good enough - // for the purpose of this test. - }); - }, true); - } - - function changeSidebarDirection(aDirection) { - sidebar.contentDocument.documentElement.style.direction = aDirection; - } - - function runNextTest() { - // Remove eventual tabs created by previous sub-tests. - while (gBrowser.tabs.length > 1) { - gBrowser.removeTab(gBrowser.tabContainer.lastChild); - } - - if (tests.length == 0) { - finish(); - } - else { - // Create a new tab and run the test. - gBrowser.selectedTab = gBrowser.addTab(); - currentTest = tests.shift(); - testPlacesPanel(function() { - changeSidebarDirection("ltr"); - info("Running " + currentTest.desc + " in LTR mode"); - }, - function() { - testPlacesPanel(function() { - // Run the test in RTL mode. - changeSidebarDirection("rtl"); - info("Running " + currentTest.desc + " in RTL mode"); - }, - function() { - runNextTest(); - }); - }); - } - } - - // Ensure history is clean before starting the test. - PlacesTestUtils.clearHistory().then(runNextTest); -} diff --git a/browser/components/places/tests/browser/browser_sort_in_library.js b/browser/components/places/tests/browser/browser_sort_in_library.js deleted file mode 100644 index af9c35e59..000000000 --- a/browser/components/places/tests/browser/browser_sort_in_library.js +++ /dev/null @@ -1,249 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 the following bugs: - * - * Bug 443745 - View>Sort>of "alpha" sort items is default to Z>A instead of A>Z - * https://bugzilla.mozilla.org/show_bug.cgi?id=443745 - * - * Bug 444179 - Library>Views>Sort>Sort by Tags does nothing - * https://bugzilla.mozilla.org/show_bug.cgi?id=444179 - * - * Basically, fully tests sorting the placeContent tree in the Places Library - * window. Sorting is verified by comparing the nsINavHistoryResult returned by - * placeContent.result to the expected sort values. - */ - -// Two properties of nsINavHistoryResult control the sort of the tree: -// sortingMode and sortingAnnotation. sortingMode's value is one of the -// nsINavHistoryQueryOptions.SORT_BY_* constants. sortingAnnotation is the -// annotation used to sort for SORT_BY_ANNOTATION_* mode. -// -// This lookup table maps the possible values of anonid's of the treecols to -// objects that represent the treecols' correct state after the user sorts the -// previously unsorted tree by selecting a column from the Views > Sort menu. -// sortingMode is constructed from the key and dir properties (i.e., -// SORT_BY_<key>_<dir>) and sortingAnnotation is checked against anno. anno -// may be undefined if key is not "ANNOTATION". -const SORT_LOOKUP_TABLE = { - title: { key: "TITLE", dir: "ASCENDING" }, - tags: { key: "TAGS", dir: "ASCENDING" }, - url: { key: "URI", dir: "ASCENDING" }, - date: { key: "DATE", dir: "DESCENDING" }, - visitCount: { key: "VISITCOUNT", dir: "DESCENDING" }, - dateAdded: { key: "DATEADDED", dir: "DESCENDING" }, - lastModified: { key: "LASTMODIFIED", dir: "DESCENDING" }, - description: { key: "ANNOTATION", - dir: "ASCENDING", - anno: "bookmarkProperties/description" } -}; - -// This is the column that's sorted if one is not specified and the tree is -// currently unsorted. Set it to a key substring in the name of one of the -// nsINavHistoryQueryOptions.SORT_BY_* constants, e.g., "TITLE", "URI". -// Method ViewMenu.setSortColumn in browser/components/places/content/places.js -// determines this value. -const DEFAULT_SORT_KEY = "TITLE"; - -// Part of the test is checking that sorts stick, so each time we sort we need -// to remember it. -var prevSortDir = null; -var prevSortKey = null; - -/** - * Ensures that the sort of aTree is aSortingMode and aSortingAnno. - * - * @param aTree - * the tree to check - * @param aSortingMode - * one of the Ci.nsINavHistoryQueryOptions.SORT_BY_* constants - * @param aSortingAnno - * checked only if sorting mode is one of the - * Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_* constants - */ -function checkSort(aTree, aSortingMode, aSortingAnno) { - // The placeContent tree's sort is determined by the nsINavHistoryResult it - // stores. Get it and check that the sort is what the caller expects. - let res = aTree.result; - isnot(res, null, - "sanity check: placeContent.result should not return null"); - - // Check sortingMode. - is(res.sortingMode, aSortingMode, - "column should now have sortingMode " + aSortingMode); - - // Check sortingAnnotation, but only if sortingMode is ANNOTATION. - if ([Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_ASCENDING, - Ci.nsINavHistoryQueryOptions.SORT_BY_ANNOTATION_DESCENDING]. - indexOf(aSortingMode) >= 0) { - is(res.sortingAnnotation, aSortingAnno, - "column should now have sorting annotation " + aSortingAnno); - } -} - -/** - * Sets the sort of aTree. - * - * @param aOrganizerWin - * the Places window - * @param aTree - * the tree to sort - * @param aUnsortFirst - * true if the sort should be set to SORT_BY_NONE before sorting by aCol - * and aDir - * @param aShouldFail - * true if setSortColumn should fail on aCol or aDir - * @param aCol - * the column of aTree by which to sort - * @param aDir - * either "ascending" or "descending" - */ -function setSort(aOrganizerWin, aTree, aUnsortFirst, aShouldFail, aCol, aDir) { - if (aUnsortFirst) { - aOrganizerWin.ViewMenu.setSortColumn(); - checkSort(aTree, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE, ""); - - // Remember the sort key and direction. - prevSortKey = null; - prevSortDir = null; - } - - let failed = false; - try { - aOrganizerWin.ViewMenu.setSortColumn(aCol, aDir); - - // Remember the sort key and direction. - if (!aCol && !aDir) { - prevSortKey = null; - prevSortDir = null; - } - else { - if (aCol) - prevSortKey = SORT_LOOKUP_TABLE[aCol.getAttribute("anonid")].key; - else if (prevSortKey === null) - prevSortKey = DEFAULT_SORT_KEY; - - if (aDir) - prevSortDir = aDir.toUpperCase(); - else if (prevSortDir === null) - prevSortDir = SORT_LOOKUP_TABLE[aCol.getAttribute("anonid")].dir; - } - } catch (exc) { - failed = true; - } - - is(failed, !!aShouldFail, - "setSortColumn on column " + - (aCol ? aCol.getAttribute("anonid") : "(no column)") + - " with direction " + (aDir || "(no direction)") + - " and table previously " + (aUnsortFirst ? "unsorted" : "sorted") + - " should " + (aShouldFail ? "" : "not ") + "fail"); -} - -/** - * Tries sorting by an invalid column and sort direction. - * - * @param aOrganizerWin - * the Places window - * @param aPlaceContentTree - * the placeContent tree in aOrganizerWin - */ -function testInvalid(aOrganizerWin, aPlaceContentTree) { - // Invalid column should fail by throwing an exception. - let bogusCol = document.createElement("treecol"); - bogusCol.setAttribute("anonid", "bogusColumn"); - setSort(aOrganizerWin, aPlaceContentTree, true, true, bogusCol, "ascending"); - - // Invalid direction reverts to SORT_BY_NONE. - setSort(aOrganizerWin, aPlaceContentTree, false, false, null, "bogus dir"); - checkSort(aPlaceContentTree, Ci.nsINavHistoryQueryOptions.SORT_BY_NONE, ""); -} - -/** - * Tests sorting aPlaceContentTree by column only and then by both column - * and direction. - * - * @param aOrganizerWin - * the Places window - * @param aPlaceContentTree - * the placeContent tree in aOrganizerWin - * @param aUnsortFirst - * true if, before each sort we try, we should sort to SORT_BY_NONE - */ -function testSortByColAndDir(aOrganizerWin, aPlaceContentTree, aUnsortFirst) { - let cols = aPlaceContentTree.getElementsByTagName("treecol"); - ok(cols.length > 0, "sanity check: placeContent should contain columns"); - - for (let i = 0; i < cols.length; i++) { - let col = cols.item(i); - ok(col.hasAttribute("anonid"), - "sanity check: column " + col.id + " should have anonid"); - - let colId = col.getAttribute("anonid"); - ok(colId in SORT_LOOKUP_TABLE, - "sanity check: unexpected placeContent column anonid"); - - let sortConst = - "SORT_BY_" + SORT_LOOKUP_TABLE[colId].key + "_" + - (aUnsortFirst ? SORT_LOOKUP_TABLE[colId].dir : prevSortDir); - let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst]; - let expectedAnno = SORT_LOOKUP_TABLE[colId].anno || ""; - - // Test sorting by only a column. - setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, col); - checkSort(aPlaceContentTree, expectedSortMode, expectedAnno); - - // Test sorting by both a column and a direction. - ["ascending", "descending"].forEach(function (dir) { - let sortConst = - "SORT_BY_" + SORT_LOOKUP_TABLE[colId].key + "_" + dir.toUpperCase(); - let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst]; - setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, col, dir); - checkSort(aPlaceContentTree, expectedSortMode, expectedAnno); - }); - } -} - -/** - * Tests sorting aPlaceContentTree by direction only. - * - * @param aOrganizerWin - * the Places window - * @param aPlaceContentTree - * the placeContent tree in aOrganizerWin - * @param aUnsortFirst - * true if, before each sort we try, we should sort to SORT_BY_NONE - */ -function testSortByDir(aOrganizerWin, aPlaceContentTree, aUnsortFirst) { - ["ascending", "descending"].forEach(function (dir) { - let key = (aUnsortFirst ? DEFAULT_SORT_KEY : prevSortKey); - let sortConst = "SORT_BY_" + key + "_" + dir.toUpperCase(); - let expectedSortMode = Ci.nsINavHistoryQueryOptions[sortConst]; - setSort(aOrganizerWin, aPlaceContentTree, aUnsortFirst, false, null, dir); - checkSort(aPlaceContentTree, expectedSortMode, ""); - }); -} - -function test() { - waitForExplicitFinish(); - - openLibrary(function (win) { - let tree = win.document.getElementById("placeContent"); - isnot(tree, null, "sanity check: placeContent tree should exist"); - // Run the tests. - testSortByColAndDir(win, tree, true); - testSortByColAndDir(win, tree, false); - testSortByDir(win, tree, true); - testSortByDir(win, tree, false); - testInvalid(win, tree); - // Reset the sort to SORT_BY_NONE. - setSort(win, tree, false, false); - // Close the window and finish. - win.close(); - finish(); - }); -} diff --git a/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js b/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js deleted file mode 100644 index 7a0eec22f..000000000 --- a/browser/components/places/tests/browser/browser_toolbarbutton_menu_context.js +++ /dev/null @@ -1,53 +0,0 @@ -var bookmarksMenuButton = document.getElementById("bookmarks-menu-button"); -var BMB_menuPopup = document.getElementById("BMB_bookmarksPopup"); -var BMB_showAllBookmarks = document.getElementById("BMB_bookmarksShowAll"); -var contextMenu = document.getElementById("placesContext"); -var newBookmarkItem = document.getElementById("placesContext_new:bookmark"); - -waitForExplicitFinish(); -add_task(function* testPopup() { - info("Checking popup context menu before moving the bookmarks button"); - yield checkPopupContextMenu(); - let pos = CustomizableUI.getPlacementOfWidget("bookmarks-menu-button").position; - CustomizableUI.addWidgetToArea("bookmarks-menu-button", CustomizableUI.AREA_PANEL); - CustomizableUI.addWidgetToArea("bookmarks-menu-button", CustomizableUI.AREA_NAVBAR, pos); - info("Checking popup context menu after moving the bookmarks button"); - yield checkPopupContextMenu(); -}); - -function* checkPopupContextMenu() { - let dropmarker = document.getAnonymousElementByAttribute(bookmarksMenuButton, "anonid", "dropmarker"); - BMB_menuPopup.setAttribute("style", "transition: none;"); - let popupShownPromise = onPopupEvent(BMB_menuPopup, "shown"); - EventUtils.synthesizeMouseAtCenter(dropmarker, {}); - info("Waiting for bookmarks menu to be shown."); - yield popupShownPromise; - let contextMenuShownPromise = onPopupEvent(contextMenu, "shown"); - EventUtils.synthesizeMouseAtCenter(BMB_showAllBookmarks, {type: "contextmenu", button: 2 }); - info("Waiting for context menu on bookmarks menu to be shown."); - yield contextMenuShownPromise; - ok(!newBookmarkItem.hasAttribute("disabled"), "New bookmark item shouldn't be disabled"); - let contextMenuHiddenPromise = onPopupEvent(contextMenu, "hidden"); - contextMenu.hidePopup(); - BMB_menuPopup.removeAttribute("style"); - info("Waiting for context menu on bookmarks menu to be hidden."); - yield contextMenuHiddenPromise; - let popupHiddenPromise = onPopupEvent(BMB_menuPopup, "hidden"); - // Can't use synthesizeMouseAtCenter because the dropdown panel is in the way - EventUtils.synthesizeKey("VK_ESCAPE", {}); - info("Waiting for bookmarks menu to be hidden."); - yield popupHiddenPromise; -} - -function onPopupEvent(popup, evt) { - let fullEvent = "popup" + evt; - let deferred = new Promise.defer(); - let onPopupHandler = (e) => { - if (e.target == popup) { - popup.removeEventListener(fullEvent, onPopupHandler); - deferred.resolve(); - } - }; - popup.addEventListener(fullEvent, onPopupHandler); - return deferred.promise; -} diff --git a/browser/components/places/tests/browser/browser_views_liveupdate.js b/browser/components/places/tests/browser/browser_views_liveupdate.js deleted file mode 100644 index 735d6b168..000000000 --- a/browser/components/places/tests/browser/browser_views_liveupdate.js +++ /dev/null @@ -1,475 +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/. */ - -/** - * Tests Places views (menu, toolbar, tree) for liveupdate. - */ - -var toolbar = document.getElementById("PersonalToolbar"); -var wasCollapsed = toolbar.collapsed; - -function test() { - waitForExplicitFinish(); - - // Uncollapse the personal toolbar if needed. - if (wasCollapsed) { - promiseSetToolbarVisibility(toolbar, true).then(openBookmarksSidebar); - } else { - openBookmarksSidebar(); - } -} - -function openBookmarksSidebar() { - // Sanity checks. - ok(PlacesUtils, "PlacesUtils in context"); - ok(PlacesUIUtils, "PlacesUIUtils in context"); - - // Open bookmarks menu. - var popup = document.getElementById("bookmarksMenuPopup"); - ok(popup, "Menu popup element exists"); - fakeOpenPopup(popup); - - // Open bookmarks sidebar. - var sidebar = document.getElementById("sidebar"); - sidebar.addEventListener("load", function() { - sidebar.removeEventListener("load", arguments.callee, true); - // Need to executeSoon since the tree is initialized on sidebar load. - executeSoon(startTest); - }, true); - SidebarUI.show("viewBookmarksSidebar"); -} - -/** - * Simulates popup opening causing it to populate. - * We cannot just use menu.open, since it would not work on Mac due to native menubar. - */ -function fakeOpenPopup(aPopup) { - var popupEvent = document.createEvent("MouseEvent"); - popupEvent.initMouseEvent("popupshowing", true, true, window, 0, - 0, 0, 0, 0, false, false, false, false, - 0, null); - aPopup.dispatchEvent(popupEvent); -} - -/** - * Adds bookmarks observer, and executes a bunch of bookmarks operations. - */ -function startTest() { - var bs = PlacesUtils.bookmarks; - // Add observers. - bs.addObserver(bookmarksObserver, false); - PlacesUtils.annotations.addObserver(bookmarksObserver, false); - var addedBookmarks = []; - - // MENU - info("*** Acting on menu bookmarks"); - var id = bs.insertBookmark(bs.bookmarksMenuFolder, - PlacesUtils._uri("http://bm1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bm1"); - bs.setItemTitle(id, "bm1_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(bs.bookmarksMenuFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "bm2"); - bs.setItemTitle(id, ""); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.bookmarksMenuFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.bookmarksMenuFolder, - "bmf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "bmf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://bmf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bmf1"); - bs.setItemTitle(id, "bmf1_edited"); - addedBookmarks.push(id); - bs.moveItem(id, bs.bookmarksMenuFolder, 0); - - // TOOLBAR - info("*** Acting on toolbar bookmarks"); - id = bs.insertBookmark(bs.toolbarFolder, - PlacesUtils._uri("http://tb1.mozilla.org/"), - bs.DEFAULT_INDEX, - "tb1"); - bs.setItemTitle(id, "tb1_edited"); - addedBookmarks.push(id); - // Test live update of title. - bs.setItemTitle(id, "tb1_edited"); - id = bs.insertBookmark(bs.toolbarFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "tb2"); - bs.setItemTitle(id, ""); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.toolbarFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.toolbarFolder, - "tbf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "tbf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://tbf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "tbf1"); - bs.setItemTitle(id, "tbf1_edited"); - addedBookmarks.push(id); - bs.moveItem(id, bs.toolbarFolder, 0); - - // UNSORTED - info("*** Acting on unsorted bookmarks"); - id = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri("http://ub1.mozilla.org/"), - bs.DEFAULT_INDEX, - "ub1"); - bs.setItemTitle(id, "ub1_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(bs.unfiledBookmarksFolder, - PlacesUtils._uri("place:"), - bs.DEFAULT_INDEX, - "ub2"); - bs.setItemTitle(id, "ub2_edited"); - addedBookmarks.push(id); - id = bs.insertSeparator(bs.unfiledBookmarksFolder, bs.DEFAULT_INDEX); - addedBookmarks.push(id); - id = bs.createFolder(bs.unfiledBookmarksFolder, - "ubf", - bs.DEFAULT_INDEX); - bs.setItemTitle(id, "ubf_edited"); - addedBookmarks.push(id); - id = bs.insertBookmark(id, - PlacesUtils._uri("http://ubf1.mozilla.org/"), - bs.DEFAULT_INDEX, - "bubf1"); - bs.setItemTitle(id, "bubf1_edited"); - addedBookmarks.push(id); - bs.moveItem(id, bs.unfiledBookmarksFolder, 0); - - // Remove all added bookmarks. - addedBookmarks.forEach(function (aItem) { - // If we remove an item after its containing folder has been removed, - // this will throw, but we can ignore that. - try { - bs.removeItem(aItem); - } catch (ex) {} - }); - - // Remove observers. - bs.removeObserver(bookmarksObserver); - PlacesUtils.annotations.removeObserver(bookmarksObserver); - finishTest(); -} - -/** - * Restores browser state and calls finish. - */ -function finishTest() { - // Close bookmarks sidebar. - SidebarUI.hide(); - - // Collapse the personal toolbar if needed. - if (wasCollapsed) { - promiseSetToolbarVisibility(toolbar, false).then(finish); - } else { - finish(); - } -} - -/** - * The observer is where magic happens, for every change we do it will look for - * nodes positions in the affected views. - */ -var bookmarksObserver = { - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsINavBookmarkObserver - , Ci.nsIAnnotationObserver - ]), - - // nsIAnnotationObserver - onItemAnnotationSet: function() {}, - onItemAnnotationRemoved: function() {}, - onPageAnnotationSet: function() {}, - onPageAnnotationRemoved: function() {}, - - // nsINavBookmarkObserver - onItemAdded: function PSB_onItemAdded(aItemId, aFolderId, aIndex, - aItemType, aURI) { - var views = getViewsForFolder(aFolderId); - ok(views.length > 0, "Found affected views (" + views.length + "): " + views); - - // Check that item has been added in the correct position. - for (var i = 0; i < views.length; i++) { - var [node, index] = searchItemInView(aItemId, views[i]); - isnot(node, null, "Found new Places node in " + views[i]); - is(index, aIndex, "Node is at index " + index); - } - }, - - onItemRemoved: function PSB_onItemRemoved(aItemId, aFolderId, aIndex, - aItemType) { - var views = getViewsForFolder(aFolderId); - ok(views.length > 0, "Found affected views (" + views.length + "): " + views); - // Check that item has been removed. - for (var i = 0; i < views.length; i++) { - var node = null; - [node, ] = searchItemInView(aItemId, views[i]); - is(node, null, "Places node not found in " + views[i]); - } - }, - - onItemMoved: function(aItemId, - aOldFolderId, aOldIndex, - aNewFolderId, aNewIndex, - aItemType) { - var views = getViewsForFolder(aNewFolderId); - ok(views.length > 0, "Found affected views: " + views); - - // Check that item has been moved in the correct position. - for (var i = 0; i < views.length; i++) { - var node = null; - var index = null; - [node, index] = searchItemInView(aItemId, views[i]); - isnot(node, null, "Found new Places node in " + views[i]); - is(index, aNewIndex, "Node is at index " + index); - } - }, - - onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {}, - onEndUpdateBatch: function PSB_onEndUpdateBatch() {}, - onItemVisited: function() {}, - - onItemChanged: function PSB_onItemChanged(aItemId, aProperty, - aIsAnnotationProperty, aNewValue, - aLastModified, aItemType, - aParentId) { - if (aProperty !== "title") - return; - - var views = getViewsForFolder(aParentId); - ok(views.length > 0, "Found affected views (" + views.length + "): " + views); - - // Check that item has been moved in the correct position. - let validator = function(aElementOrTreeIndex) { - if (typeof(aElementOrTreeIndex) == "number") { - var sidebar = document.getElementById("sidebar"); - var tree = sidebar.contentDocument.getElementById("bookmarks-view"); - let cellText = tree.view.getCellText(aElementOrTreeIndex, - tree.columns.getColumnAt(0)); - if (!aNewValue) - return cellText == PlacesUIUtils.getBestTitle(tree.view.nodeForTreeIndex(aElementOrTreeIndex), true); - return cellText == aNewValue; - } - if (!aNewValue && aElementOrTreeIndex.localName != "toolbarbutton") { - return aElementOrTreeIndex.getAttribute("label") == PlacesUIUtils.getBestTitle(aElementOrTreeIndex._placesNode); - } - return aElementOrTreeIndex.getAttribute("label") == aNewValue; - }; - - for (var i = 0; i < views.length; i++) { - var [node, , valid] = searchItemInView(aItemId, views[i], validator); - isnot(node, null, "Found changed Places node in " + views[i]); - is(node.title, aNewValue, "Node has correct title: " + aNewValue); - ok(valid, "Node element has correct label: " + aNewValue); - } - } -}; - -/** - * Search an item id in a view. - * - * @param aItemId - * item id of the item to search. - * @param aView - * either "toolbar", "menu" or "sidebar" - * @param aValidator - * function to check validity of the found node element. - * @returns [node, index, valid] or [null, null, false] if not found. - */ -function searchItemInView(aItemId, aView, aValidator) { - switch (aView) { - case "toolbar": - return getNodeForToolbarItem(aItemId, aValidator); - case "menu": - return getNodeForMenuItem(aItemId, aValidator); - case "sidebar": - return getNodeForSidebarItem(aItemId, aValidator); - } - - return [null, null, false]; -} - -/** - * Get places node and index for an itemId in bookmarks toolbar view. - * - * @param aItemId - * item id of the item to search. - * @returns [node, index] or [null, null] if not found. - */ -function getNodeForToolbarItem(aItemId, aValidator) { - var toolbar = document.getElementById("PlacesToolbarItems"); - - function findNode(aContainer) { - var children = aContainer.childNodes; - for (var i = 0, staticNodes = 0; i < children.length; i++) { - var child = children[i]; - - // Is this a Places node? - if (!child._placesNode || child.hasAttribute("simulated-places-node")) { - staticNodes++; - continue; - } - - if (child._placesNode.itemId == aItemId) { - let valid = aValidator ? aValidator(child) : true; - return [child._placesNode, i - staticNodes, valid]; - } - - // Don't search in queries, they could contain our item in a - // different position. Search only folders - if (PlacesUtils.nodeIsFolder(child._placesNode)) { - var popup = child.lastChild; - popup.showPopup(popup); - var foundNode = findNode(popup); - popup.hidePopup(); - if (foundNode[0] != null) - return foundNode; - } - } - return [null, null]; - } - - return findNode(toolbar); -} - -/** - * Get places node and index for an itemId in bookmarks menu view. - * - * @param aItemId - * item id of the item to search. - * @returns [node, index] or [null, null] if not found. - */ -function getNodeForMenuItem(aItemId, aValidator) { - var menu = document.getElementById("bookmarksMenu"); - - function findNode(aContainer) { - var children = aContainer.childNodes; - for (var i = 0, staticNodes = 0; i < children.length; i++) { - var child = children[i]; - - // Is this a Places node? - if (!child._placesNode || child.hasAttribute("simulated-places-node")) { - staticNodes++; - continue; - } - - if (child._placesNode.itemId == aItemId) { - let valid = aValidator ? aValidator(child) : true; - return [child._placesNode, i - staticNodes, valid]; - } - - // Don't search in queries, they could contain our item in a - // different position. Search only folders - if (PlacesUtils.nodeIsFolder(child._placesNode)) { - var popup = child.lastChild; - fakeOpenPopup(popup); - var foundNode = findNode(popup); - - child.open = false; - if (foundNode[0] != null) - return foundNode; - } - } - return [null, null, false]; - } - - return findNode(menu.lastChild); -} - -/** - * Get places node and index for an itemId in sidebar tree view. - * - * @param aItemId - * item id of the item to search. - * @returns [node, index] or [null, null] if not found. - */ -function getNodeForSidebarItem(aItemId, aValidator) { - var sidebar = document.getElementById("sidebar"); - var tree = sidebar.contentDocument.getElementById("bookmarks-view"); - - function findNode(aContainerIndex) { - if (tree.view.isContainerEmpty(aContainerIndex)) - return [null, null, false]; - - // The rowCount limit is just for sanity, but we will end looping when - // we have checked the last child of this container or we have found node. - for (var i = aContainerIndex + 1; i < tree.view.rowCount; i++) { - var node = tree.view.nodeForTreeIndex(i); - - if (node.itemId == aItemId) { - // Minus one because we want relative index inside the container. - let valid = aValidator ? aValidator(i) : true; - return [node, i - tree.view.getParentIndex(i) - 1, valid]; - } - - if (PlacesUtils.nodeIsFolder(node)) { - // Open container. - tree.view.toggleOpenState(i); - // Search inside it. - var foundNode = findNode(i); - // Close container. - tree.view.toggleOpenState(i); - // Return node if found. - if (foundNode[0] != null) - return foundNode; - } - - // We have finished walking this container. - if (!tree.view.hasNextSibling(aContainerIndex + 1, i)) - break; - } - return [null, null, false] - } - - // Root node is hidden, so we need to manually walk the first level. - for (var i = 0; i < tree.view.rowCount; i++) { - // Open container. - tree.view.toggleOpenState(i); - // Search inside it. - var foundNode = findNode(i); - // Close container. - tree.view.toggleOpenState(i); - // Return node if found. - if (foundNode[0] != null) - return foundNode; - } - return [null, null, false]; -} - -/** - * Get views affected by changes to a folder. - * - * @param aFolderId: - * item id of the folder we have changed. - * @returns a subset of views: ["toolbar", "menu", "sidebar"] - */ -function getViewsForFolder(aFolderId) { - var rootId = aFolderId; - while (!PlacesUtils.isRootItem(rootId)) - rootId = PlacesUtils.bookmarks.getFolderIdForItem(rootId); - - switch (rootId) { - case PlacesUtils.toolbarFolderId: - return ["toolbar", "sidebar"] - case PlacesUtils.bookmarksMenuFolderId: - return ["menu", "sidebar"] - case PlacesUtils.unfiledBookmarksFolderId: - return ["sidebar"] - } - return new Array(); -} diff --git a/browser/components/places/tests/browser/frameLeft.html b/browser/components/places/tests/browser/frameLeft.html deleted file mode 100644 index 5a54fe353..000000000 --- a/browser/components/places/tests/browser/frameLeft.html +++ /dev/null @@ -1,8 +0,0 @@ -<html> - <head> - <title>Left frame</title> - </head> - <body> - <a id="clickme" href="frameRight.html" target="right">Open page in the right frame.</a> - </body> -</html> diff --git a/browser/components/places/tests/browser/frameRight.html b/browser/components/places/tests/browser/frameRight.html deleted file mode 100644 index 226accc34..000000000 --- a/browser/components/places/tests/browser/frameRight.html +++ /dev/null @@ -1,8 +0,0 @@ -<html> - <head> - <title>Right Frame</title> - </head> - <body> - This is the right frame. - </body> -</html> diff --git a/browser/components/places/tests/browser/framedPage.html b/browser/components/places/tests/browser/framedPage.html deleted file mode 100644 index d388562e6..000000000 --- a/browser/components/places/tests/browser/framedPage.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> - <head> - <title>Framed page</title> - </head> - <frameset cols="*,*"> - <frame name="left" src="frameLeft.html"> - <frame name="right" src="about:mozilla"> - </frameset> -</html> diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js deleted file mode 100644 index aaf78332e..000000000 --- a/browser/components/places/tests/browser/head.js +++ /dev/null @@ -1,460 +0,0 @@ -XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", - "resource://gre/modules/NetUtil.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Promise", - "resource://gre/modules/Promise.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); - -// We need to cache this before test runs... -var cachedLeftPaneFolderIdGetter; -var getter = PlacesUIUtils.__lookupGetter__("leftPaneFolderId"); -if (!cachedLeftPaneFolderIdGetter && typeof(getter) == "function") { - cachedLeftPaneFolderIdGetter = getter; -} - -// ...And restore it when test ends. -registerCleanupFunction(function() { - let getter = PlacesUIUtils.__lookupGetter__("leftPaneFolderId"); - if (cachedLeftPaneFolderIdGetter && typeof(getter) != "function") { - PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter); - } -}); - -function openLibrary(callback, aLeftPaneRoot) { - let library = window.openDialog("chrome://browser/content/places/places.xul", - "", "chrome,toolbar=yes,dialog=no,resizable", - aLeftPaneRoot); - waitForFocus(function () { - callback(library); - }, library); - - return library; -} - -/** - * Returns a handle to a Library window. - * If one is opens returns itm otherwise it opens a new one. - * - * @param aLeftPaneRoot - * Hierarchy to open and select in the left pane. - */ -function promiseLibrary(aLeftPaneRoot) { - return new Promise(resolve => { - let library = Services.wm.getMostRecentWindow("Places:Organizer"); - if (library && !library.closed) { - if (aLeftPaneRoot) { - library.PlacesOrganizer.selectLeftPaneContainerByHierarchy(aLeftPaneRoot); - } - resolve(library); - } - else { - openLibrary(resolve, aLeftPaneRoot); - } - }); -} - -function promiseLibraryClosed(organizer) { - return new Promise(resolve => { - // Wait for the Organizer window to actually be closed - organizer.addEventListener("unload", function onUnload() { - organizer.removeEventListener("unload", onUnload); - resolve(); - }); - - // Close Library window. - organizer.close(); - }); -} - -/** - * Waits for a clipboard operation to complete, looking for the expected type. - * - * @see waitForClipboard - * - * @param aPopulateClipboardFn - * Function to populate the clipboard. - * @param aFlavor - * Data flavor to expect. - */ -function promiseClipboard(aPopulateClipboardFn, aFlavor) { - return new Promise(resolve => { - waitForClipboard(data => !!data, aPopulateClipboardFn, resolve, aFlavor); - }); -} - -/** - * Waits for all pending async statements on the default connection, before - * proceeding with aCallback. - * - * @param aCallback - * Function to be called when done. - * @param aScope - * Scope for the callback. - * @param aArguments - * Arguments array for the callback. - * - * @note The result is achieved by asynchronously executing a query requiring - * a write lock. Since all statements on the same connection are - * serialized, the end of this write operation means that all writes are - * complete. Note that WAL makes so that writers don't block readers, but - * this is a problem only across different connections. - */ -function waitForAsyncUpdates(aCallback, aScope, aArguments) -{ - let scope = aScope || this; - let args = aArguments || []; - let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase) - .DBConnection; - let begin = db.createAsyncStatement("BEGIN EXCLUSIVE"); - begin.executeAsync(); - begin.finalize(); - - let commit = db.createAsyncStatement("COMMIT"); - commit.executeAsync({ - handleResult: function() {}, - handleError: function() {}, - handleCompletion: function(aReason) - { - aCallback.apply(scope, args); - } - }); - commit.finalize(); -} - -function synthesizeClickOnSelectedTreeCell(aTree, aOptions) { - let tbo = aTree.treeBoxObject; - if (tbo.view.selection.count != 1) - throw new Error("The test node should be successfully selected"); - // Get selection rowID. - let min = {}, max = {}; - tbo.view.selection.getRangeAt(0, min, max); - let rowID = min.value; - tbo.ensureRowIsVisible(rowID); - // Calculate the click coordinates. - var rect = tbo.getCoordsForCellItem(rowID, aTree.columns[0], "text"); - var x = rect.x + rect.width / 2; - var y = rect.y + rect.height / 2; - // Simulate the click. - EventUtils.synthesizeMouse(aTree.body, x, y, aOptions || {}, - aTree.ownerGlobal); -} - -/** - * Asynchronously check a url is visited. - * - * @param aURI The URI. - * @return {Promise} - * @resolves When the check has been added successfully. - * @rejects JavaScript exception. - */ -function promiseIsURIVisited(aURI) { - let deferred = Promise.defer(); - - PlacesUtils.asyncHistory.isURIVisited(aURI, function(aURI, aIsVisited) { - deferred.resolve(aIsVisited); - }); - - return deferred.promise; -} - -function promiseBookmarksNotification(notification, conditionFn) { - info(`promiseBookmarksNotification: waiting for ${notification}`); - return new Promise((resolve) => { - let proxifiedObserver = new Proxy({}, { - get: (target, name) => { - if (name == "QueryInterface") - return XPCOMUtils.generateQI([ Ci.nsINavBookmarkObserver ]); - info(`promiseBookmarksNotification: got ${name} notification`); - if (name == notification) - return (...args) => { - if (conditionFn.apply(this, args)) { - PlacesUtils.bookmarks.removeObserver(proxifiedObserver, false); - executeSoon(resolve); - } else { - info(`promiseBookmarksNotification: skip cause condition doesn't apply to ${JSON.stringify(args)}`); - } - } - return () => {}; - } - }); - PlacesUtils.bookmarks.addObserver(proxifiedObserver, false); - }); -} - -function promiseHistoryNotification(notification, conditionFn) { - info(`Waiting for ${notification}`); - return new Promise((resolve) => { - let proxifiedObserver = new Proxy({}, { - get: (target, name) => { - if (name == "QueryInterface") - return XPCOMUtils.generateQI([ Ci.nsINavHistoryObserver ]); - if (name == notification) - return (...args) => { - if (conditionFn.apply(this, args)) { - PlacesUtils.history.removeObserver(proxifiedObserver, false); - executeSoon(resolve); - } - } - return () => {}; - } - }); - PlacesUtils.history.addObserver(proxifiedObserver, false); - }); -} - -/** - * Makes the specified toolbar visible or invisible and returns a Promise object - * that is resolved when the toolbar has completed any animations associated - * with hiding or showing the toolbar. - * - * Note that this code assumes that changes to a toolbar's visibility trigger - * a transition on the max-height property of the toolbar element. - * Changes to this styling could cause the returned Promise object to be - * resolved too early or not at all. - * - * @param aToolbar - * The toolbar to update. - * @param aVisible - * True to make the toolbar visible, false to make it hidden. - * - * @return {Promise} - * @resolves Any animation associated with updating the toolbar's visibility has - * finished. - * @rejects Never. - */ -function promiseSetToolbarVisibility(aToolbar, aVisible, aCallback) { - return new Promise((resolve, reject) => { - function listener(event) { - if (event.propertyName == "max-height") { - aToolbar.removeEventListener("transitionend", listener); - resolve(); - } - } - - let transitionProperties = - window.getComputedStyle(aToolbar).transitionProperty.split(", "); - if (isToolbarVisible(aToolbar) != aVisible && - transitionProperties.some( - prop => prop == "max-height" || prop == "all" - )) { - // Just because max-height is a transitionable property doesn't mean - // a transition will be triggered, but it's more likely. - aToolbar.addEventListener("transitionend", listener); - setToolbarVisibility(aToolbar, aVisible); - return; - } - - // No animation to wait for - setToolbarVisibility(aToolbar, aVisible); - resolve(); - }); -} - -/** - * Helper function to determine if the given toolbar is in the visible - * state according to its autohide/collapsed attribute. - * - * @aToolbar The toolbar to query. - * - * @returns True if the relevant attribute on |aToolbar| indicates it is - * visible, false otherwise. - */ -function isToolbarVisible(aToolbar) { - let hidingAttribute = aToolbar.getAttribute("type") == "menubar" - ? "autohide" - : "collapsed"; - let hidingValue = aToolbar.getAttribute(hidingAttribute).toLowerCase(); - // Check for both collapsed="true" and collapsed="collapsed" - return hidingValue !== "true" && hidingValue !== hidingAttribute; -} - -/** - * Executes a task after opening the bookmarks dialog, then cancels the dialog. - * - * @param autoCancel - * whether to automatically cancel the dialog at the end of the task - * @param openFn - * generator function causing the dialog to open - * @param task - * the task to execute once the dialog is open - */ -var withBookmarksDialog = Task.async(function* (autoCancel, openFn, taskFn) { - let closed = false; - let dialogPromise = new Promise(resolve => { - Services.ww.registerNotification(function winObserver(subject, topic, data) { - if (topic == "domwindowopened") { - let win = subject.QueryInterface(Ci.nsIDOMWindow); - win.addEventListener("load", function load() { - win.removeEventListener("load", load); - ok(win.location.href.startsWith("chrome://browser/content/places/bookmarkProperties"), - "The bookmark properties dialog is open"); - // This is needed for the overlay. - waitForFocus(() => { - resolve(win); - }, win); - }); - } else if (topic == "domwindowclosed") { - Services.ww.unregisterNotification(winObserver); - closed = true; - } - }); - }); - - info("withBookmarksDialog: opening the dialog"); - // The dialog might be modal and could block our events loop, so executeSoon. - executeSoon(openFn); - - info("withBookmarksDialog: waiting for the dialog"); - let dialogWin = yield dialogPromise; - - // Ensure overlay is loaded - info("waiting for the overlay to be loaded"); - yield waitForCondition(() => dialogWin.gEditItemOverlay.initialized, - "EditItemOverlay should be initialized"); - - // Check the first textbox is focused. - let doc = dialogWin.document; - let elt = doc.querySelector("textbox:not([collapsed=true])"); - if (elt) { - info("waiting for focus on the first textfield"); - yield waitForCondition(() => doc.activeElement == elt.inputField, - "The first non collapsed textbox should have been focused"); - } - - info("withBookmarksDialog: executing the task"); - try { - yield taskFn(dialogWin); - } finally { - if (!closed) { - if (!autoCancel) { - ok(false, "The test should have closed the dialog!"); - } - info("withBookmarksDialog: canceling the dialog"); - doc.documentElement.cancelDialog(); - } - } -}); - -/** - * Opens the contextual menu on the element pointed by the given selector. - * - * @param selector - * Valid selector syntax - * @return Promise - * Returns a Promise that resolves once the context menu has been - * opened. - */ -var openContextMenuForContentSelector = Task.async(function* (browser, selector) { - info("wait for the context menu"); - let contextPromise = BrowserTestUtils.waitForEvent(document.getElementById("contentAreaContextMenu"), - "popupshown"); - yield ContentTask.spawn(browser, { selector }, function* (args) { - let doc = content.document; - let elt = doc.querySelector(args.selector) - dump(`openContextMenuForContentSelector: found ${elt}\n`); - - /* Open context menu so chrome can access the element */ - const domWindowUtils = - content.QueryInterface(Components.interfaces.nsIInterfaceRequestor) - .getInterface(Components.interfaces.nsIDOMWindowUtils); - let rect = elt.getBoundingClientRect(); - let left = rect.left + rect.width / 2; - let top = rect.top + rect.height / 2; - domWindowUtils.sendMouseEvent("contextmenu", left, top, 2, - 1, 0, false, 0, 0, true); - }); - yield contextPromise; -}); - -/** - * Waits for a specified condition to happen. - * - * @param conditionFn - * a Function or a generator function, returning a boolean for whether - * the condition is fulfilled. - * @param errorMsg - * Error message to use if the condition has not been satisfied after a - * meaningful amount of tries. - */ -var waitForCondition = Task.async(function* (conditionFn, errorMsg) { - for (let tries = 0; tries < 100; ++tries) { - if ((yield conditionFn())) - return; - yield new Promise(resolve => { - if (!waitForCondition._timers) { - waitForCondition._timers = new Set(); - registerCleanupFunction(() => { - is(waitForCondition._timers.size, 0, "All the wait timers have been removed"); - delete waitForCondition._timers; - }); - } - let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - waitForCondition._timers.add(timer); - timer.init(() => { - waitForCondition._timers.delete(timer); - resolve(); - }, 100, Ci.nsITimer.TYPE_ONE_SHOT); - }); - } - ok(false, errorMsg); -}); - -/** - * Fills a bookmarks dialog text field ensuring to cause expected edit events. - * - * @param id - * id of the text field - * @param text - * text to fill in - * @param win - * dialog window - * @param [optional] blur - * whether to blur at the end. - */ -function fillBookmarkTextField(id, text, win, blur = true) { - let elt = win.document.getElementById(id); - elt.focus(); - elt.select(); - for (let c of text.split("")) { - EventUtils.synthesizeKey(c, {}, win); - } - if (blur) - elt.blur(); -} - -/** - * Executes a task after opening the bookmarks or history sidebar. Takes care - * of closing the sidebar once done. - * - * @param type - * either "bookmarks" or "history". - * @param taskFn - * The task to execute once the sidebar is ready. Will get the Places - * tree view as input. - */ -var withSidebarTree = Task.async(function* (type, taskFn) { - let sidebar = document.getElementById("sidebar"); - info("withSidebarTree: waiting sidebar load"); - let sidebarLoadedPromise = new Promise(resolve => { - sidebar.addEventListener("load", function load() { - sidebar.removeEventListener("load", load, true); - resolve(); - }, true); - }); - let sidebarId = type == "bookmarks" ? "viewBookmarksSidebar" - : "viewHistorySidebar"; - SidebarUI.show(sidebarId); - yield sidebarLoadedPromise; - - let treeId = type == "bookmarks" ? "bookmarks-view" - : "historyTree"; - let tree = sidebar.contentDocument.getElementById(treeId); - - // Need to executeSoon since the tree is initialized on sidebar load. - info("withSidebarTree: executing the task"); - try { - yield taskFn(tree); - } finally { - SidebarUI.hide(); - } -}); diff --git a/browser/components/places/tests/browser/keyword_form.html b/browser/components/places/tests/browser/keyword_form.html deleted file mode 100644 index a881c0d5a..000000000 --- a/browser/components/places/tests/browser/keyword_form.html +++ /dev/null @@ -1,17 +0,0 @@ -<!DOCTYPE HTML> - -<html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html;charset=windows-1252"> -</head> -<body> - <form id="form1" method="POST" action="keyword_form.html"> - <input type="hidden" name="accenti" value="àèìòù"> - <input type="text" name="search"> - </form> - <form id="form2" method="POST" action="keyword_form.html"> - <input type="hidden" name="accenti" value="ùòìèà"> - <input type="text" name="search"> - </form> -</body> -</html> diff --git a/browser/components/places/tests/browser/pageopeningwindow.html b/browser/components/places/tests/browser/pageopeningwindow.html deleted file mode 100644 index 282f9c593..000000000 --- a/browser/components/places/tests/browser/pageopeningwindow.html +++ /dev/null @@ -1,9 +0,0 @@ -<meta charset="UTF-8"> -Hi, I was opened via a <script>document.write(location.search ? - "popup call from the opened window... uh oh, that shouldn't happen!" : - "bookmarklet, and I will open a new window myself.")</script><br> -<script> - if (!location.search) { - open(location.href + "?donotopen=true", '_blank'); - } -</script> diff --git a/browser/components/places/tests/browser/sidebarpanels_click_test_page.html b/browser/components/places/tests/browser/sidebarpanels_click_test_page.html deleted file mode 100644 index c73eaa540..000000000 --- a/browser/components/places/tests/browser/sidebarpanels_click_test_page.html +++ /dev/null @@ -1,7 +0,0 @@ -<html> -<head> - <title>browser_sidebarpanels_click.js test page</title> -</head> -<body onload="alert('test');"> -</body> -</html> diff --git a/browser/components/places/tests/chrome/.eslintrc.js b/browser/components/places/tests/chrome/.eslintrc.js deleted file mode 100644 index 8c0f4f574..000000000 --- a/browser/components/places/tests/chrome/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/chrome.eslintrc.js" - ] -}; diff --git a/browser/components/places/tests/chrome/chrome.ini b/browser/components/places/tests/chrome/chrome.ini deleted file mode 100644 index d7b4a55c8..000000000 --- a/browser/components/places/tests/chrome/chrome.ini +++ /dev/null @@ -1,15 +0,0 @@ -[DEFAULT] -support-files = head.js - -[test_0_bug510634.xul] -[test_0_multiple_left_pane.xul] -[test_bug1163447_selectItems_through_shortcut.xul] -[test_bug427633_no_newfolder_if_noip.xul] -[test_bug485100-change-case-loses-tag.xul] -[test_bug549192.xul] -[test_bug549491.xul] -[test_bug631374_tags_selector_scroll.xul] -[test_editBookmarkOverlay_keywords.xul] -[test_editBookmarkOverlay_tags_liveUpdate.xul] -[test_selectItems_on_nested_tree.xul] -[test_treeview_date.xul] diff --git a/browser/components/places/tests/chrome/head.js b/browser/components/places/tests/chrome/head.js deleted file mode 100644 index 26b97f6d7..000000000 --- a/browser/components/places/tests/chrome/head.js +++ /dev/null @@ -1,7 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); diff --git a/browser/components/places/tests/chrome/test_0_bug510634.xul b/browser/components/places/tests/chrome/test_0_bug510634.xul deleted file mode 100644 index 86e102180..000000000 --- a/browser/components/places/tests/chrome/test_0_bug510634.xul +++ /dev/null @@ -1,99 +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"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="510634: Wrong icons on bookmarks sidebar" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"> - <![CDATA[ - - /** - * Bug 510634 - Wrong icons on bookmarks sidebar - * https://bugzilla.mozilla.org/show_bug.cgi?id=510634 - * - * Ensures that properties for special queries are set on their tree nodes, - * even if PlacesUIUtils.leftPaneFolderId was not initialized. - */ - - SimpleTest.waitForExplicitFinish(); - - function runTest() { - // We need to cache and restore this getter in order to simulate - // Bug 510634 - let cachedLeftPaneFolderIdGetter = - PlacesUIUtils.__lookupGetter__("leftPaneFolderId"); - // Must also cache and restore this getter as it is affected by - // leftPaneFolderId, from bug 564900. - let cachedAllBookmarksFolderIdGetter = - PlacesUIUtils.__lookupGetter__("allBookmarksFolderId"); - - let leftPaneFolderId = PlacesUIUtils.leftPaneFolderId; - - // restore the getter - PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter); - - // Setup the places tree contents. - let tree = document.getElementById("tree"); - tree.place = "place:queryType=1&folder=" + leftPaneFolderId; - - // The query-property is set on the title column for each row. - let titleColumn = tree.treeBoxObject.columns.getColumnAt(0); - - // Open All Bookmarks - tree.selectItems([PlacesUIUtils.leftPaneQueries["AllBookmarks"]]); - PlacesUtils.asContainer(tree.selectedNode).containerOpen = true; - is(PlacesUIUtils.allBookmarksFolderId, tree.selectedNode.itemId, - "Opened All Bookmarks"); - - ["History", "Downloads", "Tags", "AllBookmarks", "BookmarksToolbar", - "BookmarksMenu", "UnfiledBookmarks"].forEach( - function(aQueryName, aRow) { - let found = false; - for (let i = 0; i < tree.view.rowCount && !found; i++) { - rowProperties = tree.view.getCellProperties(i, titleColumn).split(" "); - found = rowProperties.includes("OrganizerQuery_" + aQueryName); - } - ok(found, "OrganizerQuery_" + aQueryName + " is set"); - } - ); - - // Close the root node - tree.result.root.containerOpen = false; - - // Restore the getters for the next test. - PlacesUIUtils.__defineGetter__("leftPaneFolderId", cachedLeftPaneFolderIdGetter); - PlacesUIUtils.__defineGetter__("allBookmarksFolderId", - cachedAllBookmarksFolderIdGetter); - - SimpleTest.finish(); - } - - ]]> - </script> -</window> diff --git a/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul b/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul deleted file mode 100644 index 09a4d2054..000000000 --- a/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul +++ /dev/null @@ -1,85 +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/. --> - -<!-- Bug 466422: - - Check that we replace the left pane with a correct one if it gets corrupted - - and we end up having more than one. --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Test handling of multiple left pane folders" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml"> - <p id="display"></p> - <div id="content" style="display: none"></div> - <pre id="test"></pre> - </body> - - <script type="application/javascript"> - <![CDATA[ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - // Sanity checks. - ok(PlacesUtils, "PlacesUtils is running in chrome context"); - ok(PlacesUIUtils, "PlacesUIUtils is running in chrome context"); - ok(PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION > 0, - "Left pane version in chrome context, " + - "current version is: " + PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION ); - - let fakeLeftPanes = []; - // We need 2 left pane folders to simulate a corrupt profile. - do { - let leftPaneItems = PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - - // Create a fake left pane folder. - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.rootGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER - }); - - let fakeLeftPaneRoot = yield PlacesUtils.promiseItemId(folder.guid); - PlacesUtils.annotations.setItemAnnotation(fakeLeftPaneRoot, PlacesUIUtils.ORGANIZER_FOLDER_ANNO, - PlacesUIUtils.ORGANIZER_LEFTPANE_VERSION, 0, - PlacesUtils.annotations.EXPIRE_NEVER); - fakeLeftPanes.push(folder.guid); - } while (fakeLeftPanes.length < 2); - - // Initialize the left pane queries. - PlacesUIUtils.leftPaneFolderId; - - // Check left pane. - ok(PlacesUIUtils.leftPaneFolderId > 0, - "Left pane folder correctly created"); - let leftPaneItems = PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.ORGANIZER_FOLDER_ANNO); - is(leftPaneItems.length, 1, - "We correctly have only 1 left pane folder"); - - // Check that all old left pane items have been removed. - for (let guid of fakeLeftPanes) { - ok(!(yield PlacesUtils.bookmarks.fetch({guid})), "This folder should have been removed"); - } - }).then(() => SimpleTest.finish()); - } - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul b/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul deleted file mode 100644 index 8e3a99533..000000000 --- a/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul +++ /dev/null @@ -1,89 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Any copyright is dedicated to the Public Domain. - http://creativecommons.org/licenses/publicdomain/ - --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="1163447: selectItems in Places no longer selects items within Toolbar or Sidebar folders" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" src="head.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"><![CDATA[ - - /** - * Bug 1163447: places-tree should be able to select an item within the toolbar, and - * unfiled bookmarks. Yet not follow recursive folder-shortcuts infinitely. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - let bmu = PlacesUtils.bookmarks; - - yield bmu.insert({ - parentGuid: bmu.toolbarGuid, - index: bmu.DEFAULT_INDEX, - type: bmu.TYPE_BOOKMARK, - url: "place:folder=TOOLBAR", - title: "shortcut to self - causing infinite recursion if not handled properly" - }); - - yield bmu.insert({ - parentGuid: bmu.toolbarGuid, - index: bmu.DEFAULT_INDEX, - type: bmu.TYPE_BOOKMARK, - url: "place:folder=UNFILED_BOOKMARKS", - title: "shortcut to unfiled, within toolbar" - }); - - let folder = yield bmu.insert({ - parentGuid: bmu.unfiledGuid, - index: bmu.DEFAULT_INDEX, - type: bmu.TYPE_FOLDER, - title: "folder within unfiled" - }); - - // Setup the places tree contents. - let tree = document.getElementById("tree"); - tree.place = "place:folder=TOOLBAR"; - - // Select the folder via the selectItems(itemId) API being tested - let itemId = yield PlacesUtils.promiseItemId(folder.guid); - tree.selectItems([itemId]); - - is(tree.selectedNode && tree.selectedNode.itemId, itemId, "The node was selected through the shortcut"); - - // Cleanup - yield bmu.eraseEverything(); - - }).catch(err => { - ok(false, `Uncaught error: ${err}`); - }).then(SimpleTest.finish); - } - ]]></script> -</window> diff --git a/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul b/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul deleted file mode 100644 index b659b2b46..000000000 --- a/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul +++ /dev/null @@ -1,91 +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"?> - -<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?> -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> -<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?> - -<!DOCTYPE window [ - <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd"> - %editBookmarkOverlayDTD; -]> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Bug 427633 - Disable creating a New Folder in the bookmarks dialogs if insertionPoint is invalid" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" - src="chrome://browser/content/places/editBookmarkOverlay.js"/> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <vbox id="editBookmarkPanelContent"/> - - <script type="application/javascript"> - <![CDATA[ - - /** - * Bug 427633 - Disable creating a New Folder in the bookmarks dialogs if - * insertionPoint is invalid. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - // Add a bookmark. - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - url: "http://www.example.com/", - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - title: "mozilla" - }); - - // Init panel. - ok(gEditItemOverlay, "gEditItemOverlay is in context"); - let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm); - gEditItemOverlay.initPanel({ node }); - ok(gEditItemOverlay.initialized, "gEditItemOverlay is initialized"); - - let tree = gEditItemOverlay._element("folderTree"); - yield openFolderTree(tree); - - tree.view.selection.clearSelection(); - ok(document.getElementById("editBMPanel_newFolderButton").disabled, - "New folder button is disabled if there's no selection"); - - // Cleanup. - yield PlacesUtils.bookmarks.remove(bm.guid); - }).then(() => SimpleTest.finish()); - } - - function openFolderTree(tree) { - return new Promise(resolve => { - tree.addEventListener("DOMAttrModified", function onAttrModified(event) { - if (event.attrName == "place") { - tree.removeEventListener("DOMAttrModified", onAttrModified); - resolve(); - } - }); - - // Open the folder tree. - document.getElementById("editBMPanel_foldersExpander").doCommand(); - }); - } - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul b/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul deleted file mode 100644 index afad950cb..000000000 --- a/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul +++ /dev/null @@ -1,83 +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"?> - -<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?> -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> -<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?> - -<!DOCTYPE window [ - <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd"> - %editBookmarkOverlayDTD; -]> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="485100: Exchanging a letter of a tag name with its big/small equivalent removes tag from bookmark" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" - src="chrome://browser/content/places/editBookmarkOverlay.js"/> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <vbox id="editBookmarkPanelContent"/> - - <script type="application/javascript"> - <![CDATA[ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - let testTag = "foo"; - let testTagUpper = "Foo"; - let testURI = Services.io.newURI("http://www.example.com/", null, null); - - // Add a bookmark. - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - title: "mozilla", - url: testURI - }); - - // Init panel - ok(gEditItemOverlay, "gEditItemOverlay is in context"); - let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm); - gEditItemOverlay.initPanel({ node }); - - // add a tag - document.getElementById("editBMPanel_tagsField").value = testTag; - gEditItemOverlay.onTagsFieldChange(); - - // test that the tag has been added in the backend - is(PlacesUtils.tagging.getTagsForURI(testURI)[0], testTag, "tags match"); - - // change the tag - document.getElementById("editBMPanel_tagsField").value = testTagUpper; - gEditItemOverlay.onTagsFieldChange(); - - // test that the tag has been added in the backend - is(PlacesUtils.tagging.getTagsForURI(testURI)[0], testTagUpper, "tags match"); - - // Cleanup. - PlacesUtils.tagging.untagURI(testURI, [testTag]); - yield PlacesUtils.bookmarks.remove(bm.guid); - }).then(() => SimpleTest.finish()); - } - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_bug549192.xul b/browser/components/places/tests/chrome/test_bug549192.xul deleted file mode 100644 index 4e6a89bb1..000000000 --- a/browser/components/places/tests/chrome/test_bug549192.xul +++ /dev/null @@ -1,120 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Any copyright is dedicated to the Public Domain. - http://creativecommons.org/licenses/publicdomain/ - --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="549192: History view not updated after deleting entry" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" src="head.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flatList="true" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"><![CDATA[ - /** - * Bug 874407 - * Ensures that history views are updated properly after visits. - * Bug 549192 - * Ensures that history views are updated after deleting entries. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - yield PlacesTestUtils.clearHistory(); - - // Add some visits. - let timeInMicroseconds = PlacesUtils.toPRTime(Date.now() - 10000); - - function newTimeInMicroseconds() { - timeInMicroseconds = timeInMicroseconds + 1000; - return timeInMicroseconds; - } - - let vtime = Date.now() * 1000; - const ttype = PlacesUtils.history.TRANSITION_TYPED; - let places = - [{ uri: Services.io.newURI("http://example.tld/", null, null), - visitDate: newTimeInMicroseconds(), transition: ttype }, - { uri: Services.io.newURI("http://example2.tld/", null, null), - visitDate: newTimeInMicroseconds(), transition: ttype }, - { uri: Services.io.newURI("http://example3.tld/", null, null), - visitDate: newTimeInMicroseconds(), transition: ttype }]; - - yield PlacesTestUtils.addVisits(places); - - // Make a history query. - let query = PlacesUtils.history.getNewQuery(); - let opts = PlacesUtils.history.getNewQueryOptions(); - opts.sortingMode = opts.SORT_BY_DATE_DESCENDING; - let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts); - - // Setup the places tree contents. - var tree = document.getElementById("tree"); - tree.place = queryURI; - - // loop through the rows and check them. - let treeView = tree.view; - let selection = treeView.selection; - let rc = treeView.rowCount; - - for (let i = 0; i < rc; i++) { - selection.select(i); - let node = tree.selectedNode; - is(node.uri, places[rc - i - 1].uri.spec, - "Found expected node at position " + i + "."); - } - - is(rc, 3, "Found expected number of rows."); - - // First check live-update of the view when adding visits. - places.forEach(place => place.visitDate = newTimeInMicroseconds()); - yield PlacesTestUtils.addVisits(places); - - for (let i = 0; i < rc; i++) { - selection.select(i); - let node = tree.selectedNode; - is(node.uri, places[rc - i - 1].uri.spec, - "Found expected node at position " + i + "."); - } - - // Now remove the pages and verify live-update again. - for (let i = 0; i < rc; i++) { - selection.select(0); - let node = tree.selectedNode; - tree.controller.remove("Removing page"); - ok(treeView.treeIndexForNode(node) == Ci.nsINavHistoryResultTreeViewer.INDEX_INVISIBLE, - node.uri + " removed."); - ok(treeView.rowCount == rc - i - 1, "Rows count decreased"); - } - - // Cleanup. - yield PlacesTestUtils.clearHistory(); - }).then(() => SimpleTest.finish()); - } - ]]></script> -</window> diff --git a/browser/components/places/tests/chrome/test_bug549491.xul b/browser/components/places/tests/chrome/test_bug549491.xul deleted file mode 100644 index 5ec7a765a..000000000 --- a/browser/components/places/tests/chrome/test_bug549491.xul +++ /dev/null @@ -1,78 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Any copyright is dedicated to the Public Domain. - http://creativecommons.org/licenses/publicdomain/ - --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="549491: 'The root node is never visible' exception when details of the root node are modified " - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" src="head.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flatList="true" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - <splitter class="tree-splitter"/> - <treecol label="Date" anonid="date" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"><![CDATA[ - /** - * Bug 549491 - * https://bugzilla.mozilla.org/show_bug.cgi?id=549491 - * - * Ensures that changing the details of places tree's root-node doesn't - * throw. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - yield PlacesTestUtils.clearHistory(); - - yield PlacesTestUtils.addVisits({ - uri: Services.io.newURI("http://example.tld/", null, null), - transition: PlacesUtils.history.TRANSITION_TYPED - }); - - // Make a history query. - let query = PlacesUtils.history.getNewQuery(); - let opts = PlacesUtils.history.getNewQueryOptions(); - let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts); - - // Setup the places tree contents. - let tree = document.getElementById("tree"); - tree.place = queryURI; - - let rootNode = tree.result.root; - let obs = tree.view.QueryInterface(Ci.nsINavHistoryResultObserver); - obs.nodeHistoryDetailsChanged(rootNode, rootNode.time, rootNode.accessCount); - obs.nodeTitleChanged(rootNode, rootNode.title); - ok(true, "No exceptions thrown"); - - // Cleanup. - yield PlacesTestUtils.clearHistory(); - }).then(SimpleTest.finish); - } - ]]></script> -</window> diff --git a/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul b/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul deleted file mode 100644 index b1d73017f..000000000 --- a/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul +++ /dev/null @@ -1,170 +0,0 @@ -<?xml version="1.0"?> - -<!-- Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?> -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> -<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?> - -<!DOCTYPE window [ - <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd"> - %editBookmarkOverlayDTD; -]> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Bug 631374 - Editing tags in the selector scrolls up the listbox" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" - src="chrome://browser/content/places/editBookmarkOverlay.js"/> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <vbox id="editBookmarkPanelContent"/> - - <script type="application/javascript"> - <![CDATA[ - - /** - * This test checks that editing tags doesn't scroll the tags selector - * listbox to wrong positions. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - let bs = PlacesUtils.bookmarks; - - let tags = ["a", "b", "c", "d", "e", "f", "g", - "h", "i", "l", "m", "n", "o", "p"]; - - // Add a bookmark and tag it. - let uri1 = Services.io.newURI("http://www1.mozilla.org/", null, null); - let bm1 = yield bs.insert({ - parentGuid: bs.toolbarGuid, - index: bs.DEFAULT_INDEX, - type: bs.TYPE_BOOKMARK, - title: "mozilla", - url: uri1.spec - }); - PlacesUtils.tagging.tagURI(uri1, tags); - - // Add a second bookmark so that tags won't disappear when unchecked. - let uri2 = Services.io.newURI("http://www2.mozilla.org/", null, null); - let bm2 = yield bs.insert({ - parentGuid: bs.toolbarGuid, - index: bs.DEFAULT_INDEX, - type: bs.TYPE_BOOKMARK, - title: "mozilla", - url: uri2.spec - }); - PlacesUtils.tagging.tagURI(uri2, tags); - - // Init panel. - ok(gEditItemOverlay, "gEditItemOverlay is in context"); - let node1 = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm1); - gEditItemOverlay.initPanel({ node: node1 }); - ok(gEditItemOverlay.initialized, "gEditItemOverlay is initialized"); - - yield openTagSelector(); - let tagsSelector = document.getElementById("editBMPanel_tagsSelector"); - - // Go by two so there is some untouched tag in the middle. - for (let i = 8; i < tags.length; i += 2) { - tagsSelector.selectedIndex = i; - let listItem = tagsSelector.selectedItem; - isnot(listItem, null, "Valid listItem found"); - - tagsSelector.ensureElementIsVisible(listItem); - let visibleIndex = tagsSelector.getIndexOfFirstVisibleRow(); - - ok(listItem.checked, "Item is checked " + i); - let selectedTag = listItem.label; - - // Uncheck the tag. - listItem.checked = false; - is(visibleIndex, tagsSelector.getIndexOfFirstVisibleRow(), - "Scroll position did not change"); - - // The listbox is rebuilt, so we have to get the new element. - let newItem = tagsSelector.selectedItem; - isnot(newItem, null, "Valid new listItem found"); - ok(!newItem.checked, "New listItem is unchecked " + i); - is(newItem.label, selectedTag, "Correct tag is still selected"); - - // Check the tag. - newItem.checked = true; - is(visibleIndex, tagsSelector.getIndexOfFirstVisibleRow(), - "Scroll position did not change"); - } - - // Remove the second bookmark, then nuke some of the tags. - yield bs.remove(bm2.guid); - - // Doing this backwords tests more interesting paths. - for (let i = tags.length - 1; i >= 0 ; i -= 2) { - tagsSelector.selectedIndex = i; - let listItem = tagsSelector.selectedItem; - isnot(listItem, null, "Valid listItem found"); - - tagsSelector.ensureElementIsVisible(listItem); - let firstVisibleTag = tags[tagsSelector.getIndexOfFirstVisibleRow()]; - - ok(listItem.checked, "Item is checked " + i); - let selectedTag = listItem.label; - - // Uncheck the tag. - listItem.checked = false; - - // Ensure the first visible tag is still visible in the list. - let firstVisibleIndex = tagsSelector.getIndexOfFirstVisibleRow(); - let lastVisibleIndex = firstVisibleIndex + tagsSelector.getNumberOfVisibleRows() -1; - let expectedTagIndex = tags.indexOf(firstVisibleTag); - ok(expectedTagIndex >= firstVisibleIndex && - expectedTagIndex <= lastVisibleIndex, - "Scroll position is correct"); - - // The listbox is rebuilt, so we have to get the new element. - let newItem = tagsSelector.selectedItem; - isnot(newItem, null, "Valid new listItem found"); - ok(newItem.checked, "New listItem is checked " + i); - is(tagsSelector.selectedItem.label, - tags[Math.min(i + 1, tags.length - 2)], - "The next tag is now selected"); - } - - // Cleanup. - yield bs.remove(bm1.guid); - }).then(SimpleTest.finish).catch(alert); - } - - function openTagSelector() { - // Wait for the tags selector to be open. - let promise = new Promise(resolve => { - let row = document.getElementById("editBMPanel_tagsSelectorRow"); - row.addEventListener("DOMAttrModified", function onAttrModified() { - row.removeEventListener("DOMAttrModified", onAttrModified); - resolve(); - }); - }); - - // Open the tags selector. - document.getElementById("editBMPanel_tagsSelectorExpander").doCommand(); - - return promise; - } - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul b/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul deleted file mode 100644 index f553d018b..000000000 --- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul +++ /dev/null @@ -1,99 +0,0 @@ -<?xml version="1.0"?> - -<!-- Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?> -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> -<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?> - -<!DOCTYPE window [ - <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd"> - %editBookmarkOverlayDTD; -]> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Bug 1343256 - Bookmark keywords disappear from one bookmark when adding a keyword to another bookmark" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js"/> - <script type="application/javascript" - src="chrome://browser/content/places/editBookmarkOverlay.js"/> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <vbox id="editBookmarkPanelContent"/> - - <script type="application/javascript"> - <![CDATA[ - function runTest() { - SimpleTest.waitForExplicitFinish(); - Task.spawn(test.bind(this)) - .catch(ex => ok(false, ex)) - .then(() => PlacesUtils.bookmarks.eraseEverything()) - .then(SimpleTest.finish); - } - - function promiseOnItemChanged() { - return new Promise(resolve => { - PlacesUtils.bookmarks.addObserver({ - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onItemAdded() {}, - onItemRemoved() {}, - onItemVisited() {}, - onItemMoved() {}, - onItemChanged(id, property, isAnno, value) { - PlacesUtils.bookmarks.removeObserver(this); - resolve({ property, value }); - }, - QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver]) - }, false); - }); - } - - function* test() { - ok(gEditItemOverlay, "Sanity check: gEditItemOverlay is in context"); - let keywordField = document.getElementById("editBMPanel_keywordField"); - - for (let i = 0; i < 2; ++i) { - let bm = yield PlacesUtils.bookmarks.insert({ - url: `http://www.test${i}.me/`, - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - }); - info(`Init panel on bookmark #${i+1}`); - let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm); - gEditItemOverlay.initPanel({ node }); - is(document.getElementById("editBMPanel_keywordField").value, "", - "The keyword field should be empty"); - info("Add a keyword to the bookmark"); - let promise = promiseOnItemChanged(); - keywordField.focus(); - keywordField.value = "kw"; - synthesizeKey(i.toString(), {}); - synthesizeKey("VK_RETURN", {}); - keywordField.blur(); - let {property, value} = yield promise; - is(property, "keyword", "The keyword should have been changed"); - is(value, `kw${i}`, "The new keyword value is correct"); - } - - for (let i = 0; i < 2; ++i) { - let entry = yield PlacesUtils.keywords.fetch({ url: `http://www.test${i}.me/` }); - is(entry.keyword, `kw${i}`, `The keyword for http://www.test${i}.me/ is correct`); - } - }; - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul b/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul deleted file mode 100644 index 1b1cc6473..000000000 --- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul +++ /dev/null @@ -1,204 +0,0 @@ -<?xml version="1.0"?> - -<!-- Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?> -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> - -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> -<?xul-overlay href="chrome://browser/content/places/editBookmarkOverlay.xul"?> - -<!DOCTYPE window [ - <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd"> - %editBookmarkOverlayDTD; -]> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="485100: Exchanging a letter of a tag name with its big/small equivalent removes tag from bookmark" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" - src="chrome://browser/content/places/editBookmarkOverlay.js"/> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <vbox id="editBookmarkPanelContent"/> - - <script type="application/javascript"> - <![CDATA[ - function checkTagsSelector(aAvailableTags, aCheckedTags) { - is(PlacesUtils.tagging.allTags.length, aAvailableTags.length, - "tagging service is in sync."); - let tagsSelector = document.getElementById("editBMPanel_tagsSelector"); - let children = tagsSelector.childNodes; - is(children.length, aAvailableTags.length, - "Found expected number of tags in the tags selector"); - - Array.prototype.forEach.call(children, function (aChild) { - let tag = aChild.getAttribute("label"); - ok(true, "Found tag '" + tag + "' in the selector"); - ok(aAvailableTags.includes(tag), "Found expected tag"); - let checked = aChild.getAttribute("checked") == "true"; - is(checked, aCheckedTags.includes(tag), - "Tag is correctly marked"); - }); - } - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - const TEST_URI = Services.io.newURI("http://www.test.me/", null, null); - const TEST_URI2 = Services.io.newURI("http://www.test.again.me/", null, null); - const TEST_TAG = "test-tag"; - - ok(gEditItemOverlay, "Sanity check: gEditItemOverlay is in context"); - - // Open the tags selector. - document.getElementById("editBMPanel_tagsSelectorRow").collapsed = false; - - // Add a bookmark. - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: TEST_URI.spec, - title: "test.me" - }); - - // Init panel. - let node = yield PlacesUIUtils.promiseNodeLikeFromFetchInfo(bm); - gEditItemOverlay.initPanel({ node }); - - // Add a tag. - PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]); - - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG, - "Correctly added tag to a single bookmark"); - is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG, - "Editing a single bookmark shows the added tag"); - checkTagsSelector([TEST_TAG], [TEST_TAG]); - - // Remove tag. - PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined, - "The tag has been removed"); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing a single bookmark should not show any tag"); - checkTagsSelector([], []); - - // Add a second bookmark. - let bm2 = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - title: "test.again.me", - url: TEST_URI2.spec - }); - - // Init panel with multiple uris. - gEditItemOverlay.initPanel({ uris: [TEST_URI, TEST_URI2] }); - - // Add a tag to the first uri. - PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG, - "Correctly added a tag to the first bookmark."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple bookmarks without matching tags should not show any tag."); - checkTagsSelector([TEST_TAG], []); - - // Add a tag to the second uri. - PlacesUtils.tagging.tagURI(TEST_URI2, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], TEST_TAG, - "Correctly added a tag to the second bookmark."); - is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG, - "Editing multiple bookmarks should show matching tags."); - checkTagsSelector([TEST_TAG], [TEST_TAG]); - - // Remove tag from the first bookmark. - PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined, - "Correctly removed tag from the first bookmark."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple bookmarks without matching tags should not show any tag."); - checkTagsSelector([TEST_TAG], []); - - // Remove tag from the second bookmark. - PlacesUtils.tagging.untagURI(TEST_URI2, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], undefined, - "Correctly removed tag from the second bookmark."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple bookmarks without matching tags should not show any tag."); - checkTagsSelector([], []); - - // Init panel with a nsIURI entry. - gEditItemOverlay.initPanel({ uris: [TEST_URI] }); - - // Add a tag. - PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG, - "Correctly added tag to the first entry."); - is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG, - "Editing a single nsIURI entry shows the added tag"); - checkTagsSelector([TEST_TAG], [TEST_TAG]); - - // Remove tag. - PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined, - "Correctly removed tag from the nsIURI entry."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing a single nsIURI entry should not show any tag"); - checkTagsSelector([], []); - - // Init panel with multiple nsIURI entries. - gEditItemOverlay.initPanel({ uris: [TEST_URI, TEST_URI2] }); - - // Add a tag to the first entry. - PlacesUtils.tagging.tagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], TEST_TAG, - "Tag correctly added."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple nsIURIs without matching tags should not show any tag."); - checkTagsSelector([TEST_TAG], []); - - // Add a tag to the second entry. - PlacesUtils.tagging.tagURI(TEST_URI2, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], TEST_TAG, - "Tag correctly added."); - is(document.getElementById("editBMPanel_tagsField").value, TEST_TAG, - "Editing multiple nsIURIs should show matching tags"); - checkTagsSelector([TEST_TAG], [TEST_TAG]); - - // Remove tag from the first entry. - PlacesUtils.tagging.untagURI(TEST_URI, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI)[0], undefined, - "Correctly removed tag from the first entry."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple nsIURIs without matching tags should not show any tag."); - checkTagsSelector([TEST_TAG], []); - - // Remove tag from the second entry. - PlacesUtils.tagging.untagURI(TEST_URI2, [TEST_TAG]); - is(PlacesUtils.tagging.getTagsForURI(TEST_URI2)[0], undefined, - "Correctly removed tag from the second entry."); - is(document.getElementById("editBMPanel_tagsField").value, "", - "Editing multiple nsIURIs without matching tags should not show any tag."); - checkTagsSelector([], []); - - // Cleanup. - yield PlacesUtils.bookmarks.remove(bm.guid); - yield PlacesUtils.bookmarks.remove(bm2.guid); - }).then(SimpleTest.finish); - } - ]]> - </script> - -</window> diff --git a/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul b/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul deleted file mode 100644 index 032c7a258..000000000 --- a/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul +++ /dev/null @@ -1,86 +0,0 @@ -<?xml version="1.0"?> - -<!-- - Any copyright is dedicated to the Public Domain. - http://creativecommons.org/licenses/publicdomain/ - --> - -<?xml-stylesheet href="chrome://global/skin" type="text/css"?> -<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" - type="text/css"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="549192: History view not updated after deleting entry" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" src="head.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"><![CDATA[ - /** - * Ensure that selectItems doesn't recurse infinitely in nested trees. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - Task.spawn(function* () { - yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "place:folder=UNFILED_BOOKMARKS", - title: "shortcut" - }); - - yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "place:folder=UNFILED_BOOKMARKS&maxResults=10", - title: "query" - }); - - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER, - title: "folder" - }); - - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: folder.guid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "http://www.mozilla.org/", - title: "bookmark" - }); - - // Setup the places tree contents. - let tree = document.getElementById("tree"); - tree.place = "place:folder=UNFILED_BOOKMARKS"; - - // Select the last bookmark. - let itemId = yield PlacesUtils.promiseItemId(bm.guid); - tree.selectItems([itemId]); - is (tree.selectedNode.itemId, itemId, "The right node was selected"); - }).then(SimpleTest.finish); - } - ]]></script> -</window> diff --git a/browser/components/places/tests/chrome/test_treeview_date.xul b/browser/components/places/tests/chrome/test_treeview_date.xul deleted file mode 100644 index 559232611..000000000 --- a/browser/components/places/tests/chrome/test_treeview_date.xul +++ /dev/null @@ -1,159 +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"?> - -<?xml-stylesheet href="chrome://browser/content/places/places.css"?> -<?xml-stylesheet href="chrome://browser/skin/places/places.css"?> -<?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?> - -<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="435322: Places tree view's formatting" - onload="runTest();"> - - <script type="application/javascript" - src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" /> - <script type="application/javascript" src="head.js" /> - - <body xmlns="http://www.w3.org/1999/xhtml" /> - - <tree id="tree" - type="places" - flatList="true" - flex="1"> - <treecols> - <treecol label="Title" id="title" anonid="title" primary="true" ordinal="1" flex="1"/> - <splitter class="tree-splitter"/> - <treecol label="Tags" id="tags" anonid="tags" flex="1"/> - <splitter class="tree-splitter"/> - <treecol label="Url" id="url" anonid="url" flex="1"/> - <splitter class="tree-splitter"/> - <treecol label="Visit Date" id="date" anonid="date" flex="1"/> - <splitter class="tree-splitter"/> - <treecol label="Visit Count" id="visitCount" anonid="visitCount" flex="1"/> - </treecols> - <treechildren flex="1"/> - </tree> - - <script type="application/javascript"> - <![CDATA[ - - /** - * Bug 435322 - * https://bugzilla.mozilla.org/show_bug.cgi?id=435322 - * - * Ensures that date in places treeviews is correctly formatted. - */ - - function runTest() { - SimpleTest.waitForExplicitFinish(); - - function uri(spec) { - return Services.io.newURI(spec, null, null); - } - - Task.spawn(function* () { - yield PlacesTestUtils.clearHistory(); - - let midnight = new Date(); - midnight.setHours(0); - midnight.setMinutes(0); - midnight.setSeconds(0); - midnight.setMilliseconds(0); - - // Add a visit 1ms before midnight, a visit at midnight, and - // a visit 1ms after midnight. - yield PlacesTestUtils.addVisits([ - {uri: uri("http://before.midnight.com/"), - visitDate: (midnight.getTime() - 1) * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED}, - {uri: uri("http://at.midnight.com/"), - visitDate: (midnight.getTime()) * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED}, - {uri: uri("http://after.midnight.com/"), - visitDate: (midnight.getTime() + 1) * 1000, - transition: PlacesUtils.history.TRANSITION_TYPED} - ]); - - // add a bookmark to the midnight visit - let bm = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - url: "http://at.midnight.com/", - title: "A bookmark at midnight", - type: PlacesUtils.bookmarks.TYPE_BOOKMARK - }); - - // Make a history query. - let query = PlacesUtils.history.getNewQuery(); - let opts = PlacesUtils.history.getNewQueryOptions(); - let queryURI = PlacesUtils.history.queriesToQueryString([query], 1, opts); - - // Setup the places tree contents. - let tree = document.getElementById("tree"); - tree.place = queryURI; - - // loop through the rows and check formatting - let treeView = tree.view; - let rc = treeView.rowCount; - ok(rc >= 3, "Rows found"); - let columns = tree.columns; - ok(columns.count > 0, "Columns found"); - const locale = Cc["@mozilla.org/chrome/chrome-registry;1"] - .getService(Ci.nsIXULChromeRegistry) - .getSelectedLocale("global", true); - for (let r = 0; r < rc; r++) { - let node = treeView.nodeForTreeIndex(r); - ok(node, "Places node found"); - for (let ci = 0; ci < columns.count; ci++) { - let c = columns.getColumnAt(ci); - let text = treeView.getCellText(r, c); - switch (c.element.getAttribute("anonid")) { - case "title": - // The title can differ, we did not set any title so we would - // expect null, but in such a case the view will generate a title - // through PlacesUIUtils.getBestTitle. - if (node.title) - is(text, node.title, "Title is correct"); - break; - case "url": - is(text, node.uri, "Uri is correct"); - break; - case "date": - let timeObj = new Date(node.time / 1000); - // Default is short date format. - let dtOptions = { year: 'numeric', month: 'numeric', day: 'numeric', - hour: 'numeric', minute: 'numeric' }; - // For today's visits we don't show date portion. - if (node.uri == "http://at.midnight.com/" || - node.uri == "http://after.midnight.com/") { - dtOptions = { hour: 'numeric', minute: 'numeric' }; - } else if (node.uri != "http://before.midnight.com/") { - // Avoid to test spurious uris, due to how the test works - // a redirecting uri could be put in the tree while we test. - break; - } - let timeStr = timeObj.toLocaleString(locale, dtOptions); - - is(text, timeStr, "Date format is correct"); - break; - case "visitCount": - is(text, 1, "Visit count is correct"); - break; - } - } - } - - // Cleanup. - yield PlacesUtils.bookmarks.remove(bm.guid); - yield PlacesTestUtils.clearHistory(); - }).then(SimpleTest.finish); - } - ]]> - </script> -</window> diff --git a/browser/components/places/tests/unit/.eslintrc.js b/browser/components/places/tests/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/places/tests/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/places/tests/unit/bookmarks.glue.html b/browser/components/places/tests/unit/bookmarks.glue.html deleted file mode 100644 index 07b22e9b3..000000000 --- a/browser/components/places/tests/unit/bookmarks.glue.html +++ /dev/null @@ -1,16 +0,0 @@ -<!DOCTYPE NETSCAPE-Bookmark-file-1> -<!-- This is an automatically generated file. - It will be read and overwritten. - DO NOT EDIT! --> -<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> -<TITLE>Bookmarks</TITLE> -<H1>Bookmarks Menu</H1> - -<DL><p> - <DT><A HREF="http://example.com/" ADD_DATE="1233157972" LAST_MODIFIED="1233157984">example</A> - <DT><H3 ADD_DATE="1233157910" LAST_MODIFIED="1233157972" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks Toolbar</H3> -<DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar - <DL><p> - <DT><A HREF="http://example.com/" ADD_DATE="1233157972" LAST_MODIFIED="1233157984">example</A> - </DL><p> -</DL><p> diff --git a/browser/components/places/tests/unit/bookmarks.glue.json b/browser/components/places/tests/unit/bookmarks.glue.json deleted file mode 100644 index 95900e176..000000000 --- a/browser/components/places/tests/unit/bookmarks.glue.json +++ /dev/null @@ -1 +0,0 @@ -{"title":"","id":1,"dateAdded":1233157910552624,"lastModified":1233157955206833,"type":"text/x-moz-place-container","root":"placesRoot","children":[{"title":"Bookmarks Menu","id":2,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157993171424,"type":"text/x-moz-place-container","root":"bookmarksMenuFolder","children":[{"title":"examplejson","id":27,"parent":2,"dateAdded":1233157972101126,"lastModified":1233157984999673,"type":"text/x-moz-place","uri":"http://example.com/"}]},{"index":1,"title":"Bookmarks Toolbar","id":3,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157972101126,"annos":[{"name":"bookmarkProperties/description","flags":0,"expires":4,"mimeType":null,"type":3,"value":"Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar"}],"type":"text/x-moz-place-container","root":"toolbarFolder","children":[{"title":"examplejson","id":26,"parent":3,"dateAdded":1233157972101126,"lastModified":1233157984999673,"type":"text/x-moz-place","uri":"http://example.com/"}]},{"index":2,"title":"Tags","id":4,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157910582667,"type":"text/x-moz-place-container","root":"tagsFolder","children":[]},{"index":3,"title":"Other Bookmarks","id":5,"parent":1,"dateAdded":1233157910552624,"lastModified":1233157911033315,"type":"text/x-moz-place-container","root":"unfiledBookmarksFolder","children":[]}]} diff --git a/browser/components/places/tests/unit/corruptDB.sqlite b/browser/components/places/tests/unit/corruptDB.sqlite Binary files differdeleted file mode 100644 index b234246ca..000000000 --- a/browser/components/places/tests/unit/corruptDB.sqlite +++ /dev/null diff --git a/browser/components/places/tests/unit/distribution.ini b/browser/components/places/tests/unit/distribution.ini deleted file mode 100644 index 93e73cb5c..000000000 --- a/browser/components/places/tests/unit/distribution.ini +++ /dev/null @@ -1,27 +0,0 @@ -# Distribution Configuration File -# Bug 516444 demo - -[Global] -id=516444 -version=1.0 -about=Test distribution file - -[BookmarksToolbar] -item.1.title=Toolbar Link Before -item.1.link=https://example.org/toolbar/before/ -item.1.keyword=e:t:b -item.1.icon=https://example.org/favicon.png -item.1.iconData=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg== -item.2.type=default -item.3.title=Toolbar Link After -item.3.link=https://example.org/toolbar/after/ -item.3.keyword=e:t:a - -[BookmarksMenu] -item.1.title=Menu Link Before -item.1.link=https://example.org/menu/before/ -item.1.icon=https://example.org/favicon.png -item.1.iconData=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg== -item.2.type=default -item.3.title=Menu Link After -item.3.link=https://example.org/menu/after/ diff --git a/browser/components/places/tests/unit/head_bookmarks.js b/browser/components/places/tests/unit/head_bookmarks.js deleted file mode 100644 index 460295f96..000000000 --- a/browser/components/places/tests/unit/head_bookmarks.js +++ /dev/null @@ -1,133 +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/. */ - -var Ci = Components.interfaces; -var Cc = Components.classes; -var Cr = Components.results; -var Cu = Components.utils; - -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/LoadContextInfo.jsm"); - -// Import common head. -var commonFile = do_get_file("../../../../../toolkit/components/places/tests/head_common.js", false); -if (commonFile) { - let uri = Services.io.newFileURI(commonFile); - Services.scriptloader.loadSubScript(uri.spec, this); -} - -// Put any other stuff relative to this test folder below. - -XPCOMUtils.defineLazyGetter(this, "PlacesUIUtils", function() { - Cu.import("resource:///modules/PlacesUIUtils.jsm"); - return PlacesUIUtils; -}); - -const ORGANIZER_FOLDER_ANNO = "PlacesOrganizer/OrganizerFolder"; -const ORGANIZER_QUERY_ANNO = "PlacesOrganizer/OrganizerQuery"; - -// Needed by some test that relies on having an app registered. -Cu.import("resource://testing-common/AppInfo.jsm", this); -updateAppInfo({ - name: "PlacesTest", - ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}", - version: "1", - platformVersion: "", -}); - -// Smart bookmarks constants. -const SMART_BOOKMARKS_VERSION = 8; -const SMART_BOOKMARKS_ON_TOOLBAR = 1; -const SMART_BOOKMARKS_ON_MENU = 2; // Takes into account the additional separator. - -// Default bookmarks constants. -const DEFAULT_BOOKMARKS_ON_TOOLBAR = 1; -const DEFAULT_BOOKMARKS_ON_MENU = 1; - -const SMART_BOOKMARKS_ANNO = "Places/SmartBookmark"; - -function checkItemHasAnnotation(guid, name) { - return PlacesUtils.promiseItemId(guid).then(id => { - let hasAnnotation = PlacesUtils.annotations.itemHasAnnotation(id, name); - Assert.ok(hasAnnotation, `Expected annotation ${name}`); - }); -} - -var createCorruptDB = Task.async(function* () { - let dbPath = OS.Path.join(OS.Constants.Path.profileDir, "places.sqlite"); - yield OS.File.remove(dbPath); - - // Create a corrupt database. - let dir = yield OS.File.getCurrentDirectory(); - let src = OS.Path.join(dir, "corruptDB.sqlite"); - yield OS.File.copy(src, dbPath); - - // Check there's a DB now. - Assert.ok((yield OS.File.exists(dbPath)), "should have a DB now"); -}); - -/** - * Rebuilds smart bookmarks listening to console output to report any message or - * exception generated. - * - * @return {Promise} - * Resolved when done. - */ -function rebuildSmartBookmarks() { - let consoleListener = { - observe(aMsg) { - if (aMsg.message.startsWith("[JavaScript Warning:")) { - // TODO (Bug 1300416): Ignore spurious strict warnings. - return; - } - do_throw("Got console message: " + aMsg.message); - }, - QueryInterface: XPCOMUtils.generateQI([ Ci.nsIConsoleListener ]), - }; - Services.console.reset(); - Services.console.registerListener(consoleListener); - do_register_cleanup(() => { - try { - Services.console.unregisterListener(consoleListener); - } catch (ex) { /* will likely fail */ } - }); - Cc["@mozilla.org/browser/browserglue;1"] - .getService(Ci.nsIObserver) - .observe(null, "browser-glue-test", "smart-bookmarks-init"); - return promiseTopicObserved("test-smart-bookmarks-done").then(() => { - Services.console.unregisterListener(consoleListener); - }); -} - -const SINGLE_TRY_TIMEOUT = 100; -const NUMBER_OF_TRIES = 30; - -/** - * Similar to waitForConditionPromise, but poll for an asynchronous value - * every SINGLE_TRY_TIMEOUT ms, for no more than tryCount times. - * - * @param promiseFn - * A function to generate a promise, which resolves to the expected - * asynchronous value. - * @param timeoutMsg - * The reason to reject the returned promise with. - * @param [optional] tryCount - * Maximum times to try before rejecting the returned promise with - * timeoutMsg, defaults to NUMBER_OF_TRIES. - * @return {Promise} - * @resolves to the asynchronous value being polled. - * @rejects if the asynchronous value is not available after tryCount attempts. - */ -var waitForResolvedPromise = Task.async(function* (promiseFn, timeoutMsg, tryCount=NUMBER_OF_TRIES) { - let tries = 0; - do { - try { - let value = yield promiseFn(); - return value; - } catch (ex) {} - yield new Promise(resolve => do_timeout(SINGLE_TRY_TIMEOUT, resolve)); - } while (++tries <= tryCount); - throw new Error(timeoutMsg); -}); diff --git a/browser/components/places/tests/unit/test_421483.js b/browser/components/places/tests/unit/test_421483.js deleted file mode 100644 index a0d138372..000000000 --- a/browser/components/places/tests/unit/test_421483.js +++ /dev/null @@ -1,103 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 SMART_BOOKMARKS_PREF = "browser.places.smartBookmarksVersion"; - -var gluesvc = Cc["@mozilla.org/browser/browserglue;1"]. - getService(Ci.nsIObserver); -// Avoid default bookmarks import. -gluesvc.observe(null, "initial-migration-will-import-default-bookmarks", ""); - -function run_test() { - run_next_test(); -} - -add_task(function* smart_bookmarks_disabled() { - Services.prefs.setIntPref("browser.places.smartBookmarksVersion", -1); - yield rebuildSmartBookmarks(); - - let smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - Assert.equal(smartBookmarkItemIds.length, 0); - - do_print("check that pref has not been bumped up"); - Assert.equal(Services.prefs.getIntPref("browser.places.smartBookmarksVersion"), -1); -}); - -add_task(function* create_smart_bookmarks() { - Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0); - yield rebuildSmartBookmarks(); - - let smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - Assert.notEqual(smartBookmarkItemIds.length, 0); - - do_print("check that pref has been bumped up"); - Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0); -}); - -add_task(function* remove_smart_bookmark_and_restore() { - let smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - let smartBookmarksCount = smartBookmarkItemIds.length; - do_print("remove one smart bookmark and restore"); - - let guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]); - yield PlacesUtils.bookmarks.remove(guid); - Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0); - - yield rebuildSmartBookmarks(); - smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - Assert.equal(smartBookmarkItemIds.length, smartBookmarksCount); - - do_print("check that pref has been bumped up"); - Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0); -}); - -add_task(function* move_smart_bookmark_rename_and_restore() { - let smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - let smartBookmarksCount = smartBookmarkItemIds.length; - do_print("smart bookmark should be restored in place"); - - let guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]); - let bm = yield PlacesUtils.bookmarks.fetch(guid); - let oldTitle = bm.title; - - // create a subfolder and move inside it - let subfolder = yield PlacesUtils.bookmarks.insert({ - parentGuid: bm.parentGuid, - title: "test", - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER - }); - - // change title and move into new subfolder - yield PlacesUtils.bookmarks.update({ - guid: guid, - parentGuid: subfolder.guid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - title: "new title" - }); - - // restore - Services.prefs.setIntPref("browser.places.smartBookmarksVersion", 0); - yield rebuildSmartBookmarks(); - - smartBookmarkItemIds = - PlacesUtils.annotations.getItemsWithAnnotation(SMART_BOOKMARKS_ANNO); - Assert.equal(smartBookmarkItemIds.length, smartBookmarksCount); - - guid = yield PlacesUtils.promiseItemGuid(smartBookmarkItemIds[0]); - bm = yield PlacesUtils.bookmarks.fetch(guid); - Assert.equal(bm.parentGuid, subfolder.guid); - Assert.equal(bm.title, oldTitle); - - do_print("check that pref has been bumped up"); - Assert.ok(Services.prefs.getIntPref("browser.places.smartBookmarksVersion") > 0); -}); diff --git a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js b/browser/components/places/tests/unit/test_PUIU_makeTransaction.js deleted file mode 100644 index c0626f53b..000000000 --- a/browser/components/places/tests/unit/test_PUIU_makeTransaction.js +++ /dev/null @@ -1,361 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function waitForBookmarkNotification(aNotification, aCallback, aProperty) -{ - PlacesUtils.bookmarks.addObserver({ - validate: function (aMethodName, aData) - { - if (aMethodName == aNotification && - (!aProperty || aProperty == aData.property)) { - PlacesUtils.bookmarks.removeObserver(this); - aCallback(aData); - } - }, - - // nsINavBookmarkObserver - QueryInterface: XPCOMUtils.generateQI([Ci.nsINavBookmarkObserver]), - onBeginUpdateBatch: function onBeginUpdateBatch() { - return this.validate(arguments.callee.name, arguments); - }, - onEndUpdateBatch: function onEndUpdateBatch() { - return this.validate(arguments.callee.name, arguments); - }, - onItemAdded: function onItemAdded(aItemId, aParentId, aIndex, aItemType, - aURI, aTitle) - { - return this.validate(arguments.callee.name, { id: aItemId, - index: aIndex, - type: aItemType, - url: aURI ? aURI.spec : null, - title: aTitle }); - }, - onItemRemoved: function onItemRemoved() { - return this.validate(arguments.callee.name, arguments); - }, - onItemChanged: function onItemChanged(id, property, aIsAnno, - aNewValue, aLastModified, type) - { - return this.validate(arguments.callee.name, - { id, - get index() { - return PlacesUtils.bookmarks.getItemIndex(this.id); - }, - type, - property, - get url() { - return type == PlacesUtils.bookmarks.TYPE_BOOKMARK ? - PlacesUtils.bookmarks.getBookmarkURI(this.id).spec : - null; - }, - get title() { - return PlacesUtils.bookmarks.getItemTitle(this.id); - }, - }); - }, - onItemVisited: function onItemVisited() { - return this.validate(arguments.callee.name, arguments); - }, - onItemMoved: function onItemMoved(aItemId, aOldParentId, aOldIndex, - aNewParentId, aNewIndex, aItemType) - { - this.validate(arguments.callee.name, { id: aItemId, - index: aNewIndex, - type: aItemType }); - } - }, false); -} - -function wrapNodeByIdAndParent(aItemId, aParentId) -{ - let wrappedNode; - let root = PlacesUtils.getFolderContents(aParentId, false, false).root; - for (let i = 0; i < root.childCount; ++i) { - let node = root.getChild(i); - if (node.itemId == aItemId) { - let type; - if (PlacesUtils.nodeIsContainer(node)) { - type = PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER; - } - else if (PlacesUtils.nodeIsURI(node)) { - type = PlacesUtils.TYPE_X_MOZ_PLACE; - } - else if (PlacesUtils.nodeIsSeparator(node)) { - type = PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR; - } - else { - do_throw("Unknown node type"); - } - wrappedNode = PlacesUtils.wrapNode(node, type); - } - } - root.containerOpen = false; - return JSON.parse(wrappedNode); -} - -add_test(function test_text_paste() -{ - const TEST_URL = "http://places.moz.org/" - const TEST_TITLE = "Places bookmark" - - waitForBookmarkNotification("onItemAdded", function(aData) - { - do_check_eq(aData.title, TEST_TITLE); - do_check_eq(aData.url, TEST_URL); - do_check_eq(aData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aData.index, 0); - run_next_test(); - }); - - let txn = PlacesUIUtils.makeTransaction( - { title: TEST_TITLE, uri: TEST_URL }, - PlacesUtils.TYPE_X_MOZ_URL, - PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX, - true // Unused for text. - ); - PlacesUtils.transactionManager.doTransaction(txn); -}); - -add_test(function test_container() -{ - const TEST_TITLE = "Places folder" - - waitForBookmarkNotification("onItemChanged", function(aChangedData) - { - do_check_eq(aChangedData.title, TEST_TITLE); - do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_FOLDER); - do_check_eq(aChangedData.index, 1); - - waitForBookmarkNotification("onItemAdded", function(aAddedData) - { - do_check_eq(aAddedData.title, TEST_TITLE); - do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_FOLDER); - do_check_eq(aAddedData.index, 2); - let id = aAddedData.id; - - waitForBookmarkNotification("onItemMoved", function(aMovedData) - { - do_check_eq(aMovedData.id, id); - do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_FOLDER); - do_check_eq(aMovedData.index, 1); - - run_next_test(); - }); - - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - 1, // Move to position 1. - false - ); - PlacesUtils.transactionManager.doTransaction(txn); - }); - - try { - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX, - true - ); - PlacesUtils.transactionManager.doTransaction(txn); - } catch (ex) { - do_throw(ex); - } - }, "random-anno"); - - let id = PlacesUtils.bookmarks.createFolder(PlacesUtils.unfiledBookmarksFolderId, - TEST_TITLE, - PlacesUtils.bookmarks.DEFAULT_INDEX); - PlacesUtils.annotations.setItemAnnotation(id, PlacesUIUtils.DESCRIPTION_ANNO, - "description", 0, - PlacesUtils.annotations.EXPIRE_NEVER); - PlacesUtils.annotations.setItemAnnotation(id, "random-anno", - "random-value", 0, - PlacesUtils.annotations.EXPIRE_NEVER); -}); - - -add_test(function test_separator() -{ - waitForBookmarkNotification("onItemChanged", function(aChangedData) - { - do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR); - do_check_eq(aChangedData.index, 3); - - waitForBookmarkNotification("onItemAdded", function(aAddedData) - { - do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR); - do_check_eq(aAddedData.index, 4); - let id = aAddedData.id; - - waitForBookmarkNotification("onItemMoved", function(aMovedData) - { - do_check_eq(aMovedData.id, id); - do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_SEPARATOR); - do_check_eq(aMovedData.index, 1); - - run_next_test(); - }); - - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - 1, // Move to position 1. - false - ); - PlacesUtils.transactionManager.doTransaction(txn); - }); - - try { - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX, - true - ); - PlacesUtils.transactionManager.doTransaction(txn); - } catch (ex) { - do_throw(ex); - } - }, "random-anno"); - - let id = PlacesUtils.bookmarks.insertSeparator(PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX); - PlacesUtils.annotations.setItemAnnotation(id, "random-anno", - "random-value", 0, - PlacesUtils.annotations.EXPIRE_NEVER); -}); - -add_test(function test_bookmark() -{ - const TEST_URL = "http://places.moz.org/" - const TEST_TITLE = "Places bookmark" - - waitForBookmarkNotification("onItemChanged", function(aChangedData) - { - do_check_eq(aChangedData.title, TEST_TITLE); - do_check_eq(aChangedData.url, TEST_URL); - do_check_eq(aChangedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aChangedData.index, 5); - - waitForBookmarkNotification("onItemAdded", function(aAddedData) - { - do_check_eq(aAddedData.title, TEST_TITLE); - do_check_eq(aAddedData.url, TEST_URL); - do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aAddedData.index, 6); - let id = aAddedData.id; - - waitForBookmarkNotification("onItemMoved", function(aMovedData) - { - do_check_eq(aMovedData.id, id); - do_check_eq(aMovedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aMovedData.index, 1); - - run_next_test(); - }); - - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - 1, // Move to position 1. - false - ); - PlacesUtils.transactionManager.doTransaction(txn); - }); - - try { - let txn = PlacesUIUtils.makeTransaction( - wrapNodeByIdAndParent(aChangedData.id, PlacesUtils.unfiledBookmarksFolderId), - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX, - true - ); - PlacesUtils.transactionManager.doTransaction(txn); - } catch (ex) { - do_throw(ex); - } - }, "random-anno"); - - let id = PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId, - NetUtil.newURI(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, - TEST_TITLE); - PlacesUtils.annotations.setItemAnnotation(id, PlacesUIUtils.DESCRIPTION_ANNO, - "description", 0, - PlacesUtils.annotations.EXPIRE_NEVER); - PlacesUtils.annotations.setItemAnnotation(id, "random-anno", - "random-value", 0, - PlacesUtils.annotations.EXPIRE_NEVER); -}); - -add_test(function test_visit() -{ - const TEST_URL = "http://places.moz.org/" - const TEST_TITLE = "Places bookmark" - - waitForBookmarkNotification("onItemAdded", function(aAddedData) - { - do_check_eq(aAddedData.title, TEST_TITLE); - do_check_eq(aAddedData.url, TEST_URL); - do_check_eq(aAddedData.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aAddedData.index, 7); - - waitForBookmarkNotification("onItemAdded", function(aAddedData2) - { - do_check_eq(aAddedData2.title, TEST_TITLE); - do_check_eq(aAddedData2.url, TEST_URL); - do_check_eq(aAddedData2.type, PlacesUtils.bookmarks.TYPE_BOOKMARK); - do_check_eq(aAddedData2.index, 8); - run_next_test(); - }); - - try { - let node = wrapNodeByIdAndParent(aAddedData.id, PlacesUtils.unfiledBookmarksFolderId); - // Simulate a not-bookmarked node, will copy it to a new bookmark. - node.id = -1; - let txn = PlacesUIUtils.makeTransaction( - node, - 0, // Unused for real nodes. - PlacesUtils.unfiledBookmarksFolderId, - PlacesUtils.bookmarks.DEFAULT_INDEX, - true - ); - PlacesUtils.transactionManager.doTransaction(txn); - } catch (ex) { - do_throw(ex); - } - }); - - PlacesUtils.bookmarks.insertBookmark(PlacesUtils.unfiledBookmarksFolderId, - NetUtil.newURI(TEST_URL), - PlacesUtils.bookmarks.DEFAULT_INDEX, - TEST_TITLE); -}); - -add_test(function check_annotations() { - // As last step check how many items for each annotation exist. - - // Copies should retain the description annotation. - let descriptions = - PlacesUtils.annotations.getItemsWithAnnotation(PlacesUIUtils.DESCRIPTION_ANNO, {}); - do_check_eq(descriptions.length, 4); - - // Only the original bookmarks should have this annotation. - let others = PlacesUtils.annotations.getItemsWithAnnotation("random-anno", {}); - do_check_eq(others.length, 3); - run_next_test(); -}); - -function run_test() -{ - run_next_test(); -} diff --git a/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js b/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js deleted file mode 100644 index 4db21555f..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_bookmarkshtml.js +++ /dev/null @@ -1,33 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue correctly exports bookmarks.html at shutdown if - * browser.bookmarks.autoExportHTML is set to true. - */ - -function run_test() { - run_next_test(); -} - -add_task(function* () { - remove_bookmarks_html(); - - Services.prefs.setBoolPref("browser.bookmarks.autoExportHTML", true); - do_register_cleanup(() => Services.prefs.clearUserPref("browser.bookmarks.autoExportHTML")); - - // Initialize nsBrowserGlue before Places. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports); - - // Initialize Places through the History Service. - Cc["@mozilla.org/browser/nav-history-service;1"] - .getService(Ci.nsINavHistoryService); - - Services.obs.addObserver(function observer() { - Services.obs.removeObserver(observer, "profile-before-change"); - check_bookmarks_html(); - }, "profile-before-change", false); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt.js b/browser/components/places/tests/unit/test_browserGlue_corrupt.js deleted file mode 100644 index 5b2a09068..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_corrupt.js +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue correctly restores bookmarks from a JSON backup if - * database is corrupt and one backup is available. - */ - -function run_test() { - // Create our bookmarks.html from bookmarks.glue.html. - create_bookmarks_html("bookmarks.glue.html"); - - remove_all_JSON_backups(); - - // Create our JSON backup from bookmarks.glue.json. - create_JSON_backup("bookmarks.glue.json"); - - run_next_test(); -} - -do_register_cleanup(function () { - remove_bookmarks_html(); - remove_all_JSON_backups(); - return PlacesUtils.bookmarks.eraseEverything(); -}); - -add_task(function* test_main() { - // Create a corrupt database. - yield createCorruptDB(); - - // Initialize nsBrowserGlue before Places. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports); - - // Check the database was corrupt. - // nsBrowserGlue uses databaseStatus to manage initialization. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CORRUPT); - - // The test will continue once restore has finished and smart bookmarks - // have been created. - yield promiseTopicObserved("places-browser-init-complete"); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Check that JSON backup has been restored. - // Notice restore from JSON notification is fired before smart bookmarks creation. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(bm.title, "examplejson"); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js b/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js deleted file mode 100644 index 7cb4e5e4c..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup.js +++ /dev/null @@ -1,52 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue correctly imports from bookmarks.html if database - * is corrupt but a JSON backup is not available. - */ - -function run_test() { - // Create our bookmarks.html from bookmarks.glue.html. - create_bookmarks_html("bookmarks.glue.html"); - - // Remove JSON backup from profile. - remove_all_JSON_backups(); - - run_next_test(); -} - -do_register_cleanup(remove_bookmarks_html); - -add_task(function* () { - // Create a corrupt database. - yield createCorruptDB(); - - // Initialize nsBrowserGlue before Places. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports); - - // Check the database was corrupt. - // nsBrowserGlue uses databaseStatus to manage initialization. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CORRUPT); - - // The test will continue once import has finished and smart bookmarks - // have been created. - yield promiseTopicObserved("places-browser-init-complete"); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Check that bookmarks html has been restored. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(bm.title, "example"); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js b/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js deleted file mode 100644 index 480420091..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_corrupt_nobackup_default.js +++ /dev/null @@ -1,55 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue correctly restores default bookmarks if database is - * corrupt, nor a JSON backup nor bookmarks.html are available. - */ - -Components.utils.import("resource://gre/modules/AppConstants.jsm"); - -function run_test() { - // Remove bookmarks.html from profile. - remove_bookmarks_html(); - - // Remove JSON backup from profile. - remove_all_JSON_backups(); - - run_next_test(); -} - -add_task(function* () { - // Create a corrupt database. - yield createCorruptDB(); - - // Initialize nsBrowserGlue before Places. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports); - - // Check the database was corrupt. - // nsBrowserGlue uses databaseStatus to manage initialization. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CORRUPT); - - // The test will continue once import has finished and smart bookmarks - // have been created. - yield promiseTopicObserved("places-browser-init-complete"); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Check that default bookmarks have been restored. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - - // Bug 1283076: Nightly bookmark points to Get Involved page, not Getting Started one - let chanTitle = AppConstants.NIGHTLY_BUILD ? "Get Involved" : "Getting Started"; - do_check_eq(bm.title, chanTitle); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_distribution.js b/browser/components/places/tests/unit/test_browserGlue_distribution.js deleted file mode 100644 index c3d6e1d9e..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_distribution.js +++ /dev/null @@ -1,125 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that nsBrowserGlue correctly imports bookmarks from distribution.ini. - */ - -const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion"; -const PREF_BMPROCESSED = "distribution.516444.bookmarksProcessed"; -const PREF_DISTRIBUTION_ID = "distribution.id"; - -const TOPICDATA_DISTRIBUTION_CUSTOMIZATION = "force-distribution-customization"; -const TOPIC_CUSTOMIZATION_COMPLETE = "distribution-customization-complete"; -const TOPIC_BROWSERGLUE_TEST = "browser-glue-test"; - -function run_test() { - // Set special pref to load distribution.ini from the profile folder. - Services.prefs.setBoolPref("distribution.testing.loadFromProfile", true); - - // Copy distribution.ini file to the profile dir. - let distroDir = gProfD.clone(); - distroDir.leafName = "distribution"; - let iniFile = distroDir.clone(); - iniFile.append("distribution.ini"); - if (iniFile.exists()) { - iniFile.remove(false); - print("distribution.ini already exists, did some test forget to cleanup?"); - } - - let testDistributionFile = gTestDir.clone(); - testDistributionFile.append("distribution.ini"); - testDistributionFile.copyTo(distroDir, "distribution.ini"); - Assert.ok(testDistributionFile.exists()); - - run_next_test(); -} - -do_register_cleanup(function () { - // Remove the distribution file, even if the test failed, otherwise all - // next tests will import it. - let iniFile = gProfD.clone(); - iniFile.leafName = "distribution"; - iniFile.append("distribution.ini"); - if (iniFile.exists()) { - iniFile.remove(false); - } - Assert.ok(!iniFile.exists()); -}); - -add_task(function* () { - // Disable Smart Bookmarks creation. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1); - - // Initialize Places through the History Service and check that a new - // database has been created. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CREATE); - - // Force distribution. - let glue = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver) - glue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_DISTRIBUTION_CUSTOMIZATION); - - // Test will continue on customization complete notification. - yield promiseTopicObserved(TOPIC_CUSTOMIZATION_COMPLETE); - - // Check the custom bookmarks exist on menu. - let menuItem = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 0 - }); - Assert.equal(menuItem.title, "Menu Link Before"); - - menuItem = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 1 + DEFAULT_BOOKMARKS_ON_MENU - }); - Assert.equal(menuItem.title, "Menu Link After"); - - // Check no favicon or keyword exists for this bookmark - yield Assert.rejects(waitForResolvedPromise(() => { - return PlacesUtils.promiseFaviconData(menuItem.url.href); - }, "Favicon not found", 10), /Favicon\snot\sfound/, "Favicon not found"); - - let keywordItem = yield PlacesUtils.keywords.fetch({ - url: menuItem.url.href - }); - Assert.strictEqual(keywordItem, null); - - // Check the custom bookmarks exist on toolbar. - let toolbarItem = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - Assert.equal(toolbarItem.title, "Toolbar Link Before"); - - // Check the custom favicon and keyword exist for this bookmark - let faviconItem = yield waitForResolvedPromise(() => { - return PlacesUtils.promiseFaviconData(toolbarItem.url.href); - }, "Favicon not found", 10); - Assert.equal(faviconItem.uri.spec, "https://example.org/favicon.png"); - Assert.greater(faviconItem.dataLen, 0); - Assert.equal(faviconItem.mimeType, "image/png"); - - let base64Icon = "data:image/png;base64," + - base64EncodeString(String.fromCharCode.apply(String, faviconItem.data)); - Assert.equal(base64Icon, SMALLPNG_DATA_URI.spec); - - keywordItem = yield PlacesUtils.keywords.fetch({ - url: toolbarItem.url.href - }); - Assert.notStrictEqual(keywordItem, null); - Assert.equal(keywordItem.keyword, "e:t:b"); - - toolbarItem = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 1 + DEFAULT_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(toolbarItem.title, "Toolbar Link After"); - - // Check the bmprocessed pref has been created. - Assert.ok(Services.prefs.getBoolPref(PREF_BMPROCESSED)); - - // Check distribution prefs have been created. - Assert.equal(Services.prefs.getCharPref(PREF_DISTRIBUTION_ID), "516444"); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_migrate.js b/browser/components/places/tests/unit/test_browserGlue_migrate.js deleted file mode 100644 index 817f10c81..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_migrate.js +++ /dev/null @@ -1,70 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that nsBrowserGlue does not overwrite bookmarks imported from the - * migrators. They usually run before nsBrowserGlue, so if we find any - * bookmark on init, we should not try to import. - */ - -const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion"; - -function run_test() { - // Create our bookmarks.html from bookmarks.glue.html. - create_bookmarks_html("bookmarks.glue.html"); - - // Remove current database file. - clearDB(); - - run_next_test(); -} - -do_register_cleanup(remove_bookmarks_html); - -add_task(function* test_migrate_bookmarks() { - // Initialize Places through the History Service and check that a new - // database has been created. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CREATE); - - // A migrator would run before nsBrowserGlue Places initialization, so mimic - // that behavior adding a bookmark and notifying the migration. - let bg = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver); - bg.observe(null, "initial-migration-will-import-default-bookmarks", null); - - yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_BOOKMARK, - url: "http://mozilla.org/", - title: "migrated" - }); - - let promise = promiseTopicObserved("places-browser-init-complete"); - bg.observe(null, "initial-migration-did-import-default-bookmarks", null); - yield promise; - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Check the created bookmark still exists. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: SMART_BOOKMARKS_ON_MENU - }); - Assert.equal(bm.title, "migrated"); - - // Check that we have not imported any new bookmark. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: SMART_BOOKMARKS_ON_MENU + 1 - }))); - - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_MENU - }))); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_prefs.js b/browser/components/places/tests/unit/test_browserGlue_prefs.js deleted file mode 100644 index 9f3504636..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_prefs.js +++ /dev/null @@ -1,240 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that nsBrowserGlue is correctly interpreting the preferences settable - * by the user or by other components. - */ - -const PREF_IMPORT_BOOKMARKS_HTML = "browser.places.importBookmarksHTML"; -const PREF_RESTORE_DEFAULT_BOOKMARKS = "browser.bookmarks.restore_default_bookmarks"; -const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion"; -const PREF_AUTO_EXPORT_HTML = "browser.bookmarks.autoExportHTML"; - -const TOPIC_BROWSERGLUE_TEST = "browser-glue-test"; -const TOPICDATA_FORCE_PLACES_INIT = "force-places-init"; - -var bg = Cc["@mozilla.org/browser/browserglue;1"]. - getService(Ci.nsIObserver); - -function run_test() { - // Create our bookmarks.html from bookmarks.glue.html. - create_bookmarks_html("bookmarks.glue.html"); - - remove_all_JSON_backups(); - - // Create our JSON backup from bookmarks.glue.json. - create_JSON_backup("bookmarks.glue.json"); - - run_next_test(); -} - -do_register_cleanup(function () { - remove_bookmarks_html(); - remove_all_JSON_backups(); - - return PlacesUtils.bookmarks.eraseEverything(); -}); - -function simulatePlacesInit() { - do_print("Simulate Places init"); - // Force nsBrowserGlue::_initPlaces(). - bg.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_FORCE_PLACES_INIT); - return promiseTopicObserved("places-browser-init-complete"); -} - -add_task(function* test_checkPreferences() { - // Initialize Places through the History Service and check that a new - // database has been created. - Assert.equal(PlacesUtils.history.databaseStatus, - PlacesUtils.history.DATABASE_STATUS_CREATE); - - // Wait for Places init notification. - yield promiseTopicObserved("places-browser-init-complete"); - - // Ensure preferences status. - Assert.ok(!Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML)); - - Assert.throws(() => Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); - Assert.throws(() => Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); -}); - -add_task(function* test_import() { - do_print("Import from bookmarks.html if importBookmarksHTML is true."); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been imported, and a smart bookmark has been - // created. - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(bm.title, "example"); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); -}); - -add_task(function* test_import_noSmartBookmarks() { - do_print("import from bookmarks.html, but don't create smart bookmarks " + - "if they are disabled"); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, -1); - Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been imported, but smart bookmarks have not - // been created. - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - Assert.equal(bm.title, "example"); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); -}); - -add_task(function* test_import_autoExport_updatedSmartBookmarks() { - do_print("Import from bookmarks.html, but don't create smart bookmarks " + - "if autoExportHTML is true and they are at latest version"); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 999); - Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true); - Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been imported, but smart bookmarks have not - // been created. - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - Assert.equal(bm.title, "example"); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); - - Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false); -}); - -add_task(function* test_import_autoExport_oldSmartBookmarks() { - do_print("Import from bookmarks.html, and create smart bookmarks if " + - "autoExportHTML is true and they are not at latest version."); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0); - Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, true); - Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been imported, but smart bookmarks have not - // been created. - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(bm.title, "example"); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); - - Services.prefs.setBoolPref(PREF_AUTO_EXPORT_HTML, false); -}); - -add_task(function* test_restore() { - do_print("restore from default bookmarks.html if " + - "restore_default_bookmarks is true."); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been restored. - Assert.ok(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - })); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); -}); - -add_task(function* test_restore_import() { - do_print("setting both importBookmarksHTML and " + - "restore_default_bookmarks should restore defaults."); - - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check: we should not have any bookmark on the toolbar. - Assert.ok(!(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }))); - - // Set preferences. - Services.prefs.setBoolPref(PREF_IMPORT_BOOKMARKS_HTML, true); - Services.prefs.setBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS, true); - - yield simulatePlacesInit(); - - // Check bookmarks.html has been restored. - Assert.ok(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - })); - - // Check preferences have been reverted. - Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); - Assert.ok(!Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_restore.js b/browser/components/places/tests/unit/test_browserGlue_restore.js deleted file mode 100644 index 9d7ac5ac1..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_restore.js +++ /dev/null @@ -1,62 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue correctly restores bookmarks from a JSON backup if - * database has been created and one backup is available. - */ - -function run_test() { - // Create our bookmarks.html from bookmarks.glue.html. - create_bookmarks_html("bookmarks.glue.html"); - - remove_all_JSON_backups(); - - // Create our JSON backup from bookmarks.glue.json. - create_JSON_backup("bookmarks.glue.json"); - - // Remove current database file. - clearDB(); - - run_next_test(); -} - -do_register_cleanup(function () { - remove_bookmarks_html(); - remove_all_JSON_backups(); - return PlacesUtils.bookmarks.eraseEverything(); -}); - -add_task(function* test_main() { - // Initialize nsBrowserGlue before Places. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsISupports); - - // Initialize Places through the History Service. - let hs = Cc["@mozilla.org/browser/nav-history-service;1"]. - getService(Ci.nsINavHistoryService); - - // Check a new database has been created. - // nsBrowserGlue uses databaseStatus to manage initialization. - Assert.equal(hs.databaseStatus, hs.DATABASE_STATUS_CREATE); - - // The test will continue once restore has finished and smart bookmarks - // have been created. - yield promiseTopicObserved("places-browser-init-complete"); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Check that JSON backup has been restored. - // Notice restore from JSON notification is fired before smart bookmarks creation. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: SMART_BOOKMARKS_ON_TOOLBAR - }); - Assert.equal(bm.title, "examplejson"); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js b/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js deleted file mode 100644 index 6ecaec4fe..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_smartBookmarks.js +++ /dev/null @@ -1,285 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that nsBrowserGlue is correctly interpreting the preferences settable - * by the user or by other components. - */ - -const PREF_SMART_BOOKMARKS_VERSION = "browser.places.smartBookmarksVersion"; -const PREF_AUTO_EXPORT_HTML = "browser.bookmarks.autoExportHTML"; -const PREF_IMPORT_BOOKMARKS_HTML = "browser.places.importBookmarksHTML"; -const PREF_RESTORE_DEFAULT_BOOKMARKS = "browser.bookmarks.restore_default_bookmarks"; - -function run_test() { - remove_bookmarks_html(); - remove_all_JSON_backups(); - run_next_test(); -} - -do_register_cleanup(() => PlacesUtils.bookmarks.eraseEverything()); - -function countFolderChildren(aFolderItemId) { - let rootNode = PlacesUtils.getFolderContents(aFolderItemId).root; - let cc = rootNode.childCount; - // Dump contents. - for (let i = 0; i < cc ; i++) { - let node = rootNode.getChild(i); - let title = PlacesUtils.nodeIsSeparator(node) ? "---" : node.title; - print("Found child(" + i + "): " + title); - } - rootNode.containerOpen = false; - return cc; -} - -add_task(function* setup() { - // Initialize browserGlue, but remove it's listener to places-init-complete. - Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver); - - // Initialize Places. - PlacesUtils.history; - - // Wait for Places init notification. - yield promiseTopicObserved("places-browser-init-complete"); - - // Ensure preferences status. - Assert.ok(!Services.prefs.getBoolPref(PREF_AUTO_EXPORT_HTML)); - Assert.ok(!Services.prefs.getBoolPref(PREF_RESTORE_DEFAULT_BOOKMARKS)); - Assert.throws(() => Services.prefs.getBoolPref(PREF_IMPORT_BOOKMARKS_HTML)); -}); - -add_task(function* test_version_0() { - do_print("All smart bookmarks are created if smart bookmarks version is 0."); - - // Sanity check: we should have default bookmark. - Assert.ok(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - })); - - Assert.ok(yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 0 - })); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0); - - yield rebuildSmartBookmarks(); - - // Count items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); - -add_task(function* test_version_change() { - do_print("An existing smart bookmark is replaced when version changes."); - - // Sanity check: we have a smart bookmark on the toolbar. - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - - // Change its title. - yield PlacesUtils.bookmarks.update({guid: bm.guid, title: "new title"}); - bm = yield PlacesUtils.bookmarks.fetch({guid: bm.guid}); - Assert.equal(bm.title, "new title"); - - // Sanity check items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1); - - yield rebuildSmartBookmarks(); - - // Count items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Check smart bookmark has been replaced, itemId has changed. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - Assert.notEqual(bm.title, "new title"); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); - -add_task(function* test_version_change_pos() { - do_print("bookmarks position is retained when version changes."); - - // Sanity check items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - let firstItemTitle = bm.title; - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1); - - yield rebuildSmartBookmarks(); - - // Count items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Check smart bookmarks are still in correct position. - bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm.guid, SMART_BOOKMARKS_ANNO); - Assert.equal(bm.title, firstItemTitle); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); - -add_task(function* test_version_change_pos_moved() { - do_print("moved bookmarks position is retained when version changes."); - - // Sanity check items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - let bm1 = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: 0 - }); - yield checkItemHasAnnotation(bm1.guid, SMART_BOOKMARKS_ANNO); - let firstItemTitle = bm1.title; - - // Move the first smart bookmark to the end of the menu. - yield PlacesUtils.bookmarks.update({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - guid: bm1.guid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX - }); - - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX - }); - Assert.equal(bm.guid, bm1.guid); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1); - - yield rebuildSmartBookmarks(); - - // Count items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - bm1 = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - index: PlacesUtils.bookmarks.DEFAULT_INDEX - }); - yield checkItemHasAnnotation(bm1.guid, SMART_BOOKMARKS_ANNO); - Assert.equal(bm1.title, firstItemTitle); - - // Move back the smart bookmark to the original position. - yield PlacesUtils.bookmarks.update({ - parentGuid: PlacesUtils.bookmarks.menuGuid, - guid: bm1.guid, - index: 1 - }); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); - -add_task(function* test_recreation() { - do_print("An explicitly removed smart bookmark should not be recreated."); - - // Remove toolbar's smart bookmarks - let bm = yield PlacesUtils.bookmarks.fetch({ - parentGuid: PlacesUtils.bookmarks.toolbarGuid, - index: 0 - }); - yield PlacesUtils.bookmarks.remove(bm.guid); - - // Sanity check items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 1); - - yield rebuildSmartBookmarks(); - - // Count items. - // We should not have recreated the smart bookmark on toolbar. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); - -add_task(function* test_recreation_version_0() { - do_print("Even if a smart bookmark has been removed recreate it if version is 0."); - - // Sanity check items. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Set preferences. - Services.prefs.setIntPref(PREF_SMART_BOOKMARKS_VERSION, 0); - - yield rebuildSmartBookmarks(); - - // Count items. - // We should not have recreated the smart bookmark on toolbar. - Assert.equal(countFolderChildren(PlacesUtils.toolbarFolderId), - SMART_BOOKMARKS_ON_TOOLBAR + DEFAULT_BOOKMARKS_ON_TOOLBAR); - Assert.equal(countFolderChildren(PlacesUtils.bookmarksMenuFolderId), - SMART_BOOKMARKS_ON_MENU + DEFAULT_BOOKMARKS_ON_MENU); - - // Check version has been updated. - Assert.equal(Services.prefs.getIntPref(PREF_SMART_BOOKMARKS_VERSION), - SMART_BOOKMARKS_VERSION); -}); diff --git a/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js b/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js deleted file mode 100644 index 072056b3f..000000000 --- a/browser/components/places/tests/unit/test_browserGlue_urlbar_defaultbehavior_migration.js +++ /dev/null @@ -1,150 +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 UI_VERSION = 26; -const TOPIC_BROWSERGLUE_TEST = "browser-glue-test"; -const TOPICDATA_BROWSERGLUE_TEST = "force-ui-migration"; -const DEFAULT_BEHAVIOR_PREF = "browser.urlbar.default.behavior"; -const AUTOCOMPLETE_PREF = "browser.urlbar.autocomplete.enabled"; - -var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"] - .getService(Ci.nsIObserver); -var gGetBoolPref = Services.prefs.getBoolPref; - -function run_test() { - run_next_test(); -} - -do_register_cleanup(cleanup); - -function cleanup() { - let prefix = "browser.urlbar.suggest."; - for (let type of ["history", "bookmark", "openpage", "history.onlyTyped"]) { - Services.prefs.clearUserPref(prefix + type); - } - Services.prefs.clearUserPref("browser.migration.version"); - Services.prefs.clearUserPref(AUTOCOMPLETE_PREF); -} - -function setupBehaviorAndMigrate(aDefaultBehavior, aAutocompleteEnabled = true) { - cleanup(); - // Migrate browser.urlbar.default.behavior preference. - Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1); - Services.prefs.setIntPref(DEFAULT_BEHAVIOR_PREF, aDefaultBehavior); - Services.prefs.setBoolPref(AUTOCOMPLETE_PREF, aAutocompleteEnabled); - // Simulate a migration. - gBrowserGlue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_BROWSERGLUE_TEST); -} - -add_task(function*() { - do_print("Migrate default.behavior = 0"); - setupBehaviorAndMigrate(0); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"), - "Bookmark preference should be true."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.openpage"), - "Openpage preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false."); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 1"); - setupBehaviorAndMigrate(1); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false, - "Bookmark preference should be false."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 2"); - setupBehaviorAndMigrate(2); - - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history"), false, - "History preference should be false."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"), - "Bookmark preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 3"); - setupBehaviorAndMigrate(3); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"), - "Bookmark preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 19"); - setupBehaviorAndMigrate(19); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.bookmark"), - "Bookmark preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 33"); - setupBehaviorAndMigrate(33); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false, - "Bookmark preference should be false."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), - "Typed preference should be true"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 129"); - setupBehaviorAndMigrate(129); - - Assert.ok(gGetBoolPref("browser.urlbar.suggest.history"), - "History preference should be true."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false, - "Bookmark preference should be false."); - Assert.ok(gGetBoolPref("browser.urlbar.suggest.openpage"), - "Openpage preference should be true"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); - -add_task(function*() { - do_print("Migrate default.behavior = 0, autocomplete.enabled = false"); - setupBehaviorAndMigrate(0, false); - - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history"), false, - "History preference should be false."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.bookmark"), false, - "Bookmark preference should be false."); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.openpage"), false, - "Openpage preference should be false"); - Assert.equal(gGetBoolPref("browser.urlbar.suggest.history.onlyTyped"), false, - "Typed preference should be false"); -}); diff --git a/browser/components/places/tests/unit/test_clearHistory_shutdown.js b/browser/components/places/tests/unit/test_clearHistory_shutdown.js deleted file mode 100644 index 0c1d78801..000000000 --- a/browser/components/places/tests/unit/test_clearHistory_shutdown.js +++ /dev/null @@ -1,181 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that requesting clear history at shutdown will really clear history. - */ - -const URIS = [ - "http://a.example1.com/" -, "http://b.example1.com/" -, "http://b.example2.com/" -, "http://c.example3.com/" -]; - -const TOPIC_CONNECTION_CLOSED = "places-connection-closed"; - -var EXPECTED_NOTIFICATIONS = [ - "places-shutdown" -, "places-will-close-connection" -, "places-expiration-finished" -, "places-connection-closed" -]; - -const UNEXPECTED_NOTIFICATIONS = [ - "xpcom-shutdown" -]; - -const FTP_URL = "ftp://localhost/clearHistoryOnShutdown/"; - -// Send the profile-after-change notification to the form history component to ensure -// that it has been initialized. -var formHistoryStartup = Cc["@mozilla.org/satchel/form-history-startup;1"]. - getService(Ci.nsIObserver); -formHistoryStartup.observe(null, "profile-after-change", null); -XPCOMUtils.defineLazyModuleGetter(this, "FormHistory", - "resource://gre/modules/FormHistory.jsm"); - -var timeInMicroseconds = Date.now() * 1000; - -function run_test() { - run_next_test(); -} - -add_task(function* test_execute() { - do_print("Initialize browserglue before Places"); - - // Avoid default bookmarks import. - let glue = Cc["@mozilla.org/browser/browserglue;1"]. - getService(Ci.nsIObserver); - glue.observe(null, "initial-migration-will-import-default-bookmarks", null); - glue.observe(null, "test-initialize-sanitizer", null); - - - Services.prefs.setBoolPref("privacy.clearOnShutdown.cache", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.cookies", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.offlineApps", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.history", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.downloads", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.cookies", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.formData", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.sessions", true); - Services.prefs.setBoolPref("privacy.clearOnShutdown.siteSettings", true); - - Services.prefs.setBoolPref("privacy.sanitize.sanitizeOnShutdown", true); - - do_print("Add visits."); - for (let aUrl of URIS) { - yield PlacesTestUtils.addVisits({ - uri: uri(aUrl), visitDate: timeInMicroseconds++, - transition: PlacesUtils.history.TRANSITION_TYPED - }); - } - do_print("Add cache."); - yield storeCache(FTP_URL, "testData"); - do_print("Add form history."); - yield addFormHistory(); - Assert.equal((yield getFormHistoryCount()), 1, "Added form history"); - - do_print("Simulate and wait shutdown."); - yield shutdownPlaces(); - - Assert.equal((yield getFormHistoryCount()), 0, "Form history cleared"); - - let stmt = DBConn(true).createStatement( - "SELECT id FROM moz_places WHERE url = :page_url " - ); - - try { - URIS.forEach(function(aUrl) { - stmt.params.page_url = aUrl; - do_check_false(stmt.executeStep()); - stmt.reset(); - }); - } finally { - stmt.finalize(); - } - - do_print("Check cache"); - // Check cache. - yield checkCache(FTP_URL); -}); - -function addFormHistory() { - return new Promise(resolve => { - let now = Date.now() * 1000; - FormHistory.update({ op: "add", - fieldname: "testfield", - value: "test", - timesUsed: 1, - firstUsed: now, - lastUsed: now - }, - { handleCompletion(reason) { resolve(); } }); - }); -} - -function getFormHistoryCount() { - return new Promise((resolve, reject) => { - let count = -1; - FormHistory.count({ fieldname: "testfield" }, - { handleResult(result) { count = result; }, - handleCompletion(reason) { resolve(count); } - }); - }); -} - -function storeCache(aURL, aContent) { - let cache = Services.cache2; - let storage = cache.diskCacheStorage(LoadContextInfo.default, false); - - return new Promise(resolve => { - let storeCacheListener = { - onCacheEntryCheck: function (entry, appcache) { - return Ci.nsICacheEntryOpenCallback.ENTRY_WANTED; - }, - - onCacheEntryAvailable: function (entry, isnew, appcache, status) { - do_check_eq(status, Cr.NS_OK); - - entry.setMetaDataElement("servertype", "0"); - var os = entry.openOutputStream(0); - - var written = os.write(aContent, aContent.length); - if (written != aContent.length) { - do_throw("os.write has not written all data!\n" + - " Expected: " + written + "\n" + - " Actual: " + aContent.length + "\n"); - } - os.close(); - entry.close(); - resolve(); - } - }; - - storage.asyncOpenURI(Services.io.newURI(aURL, null, null), "", - Ci.nsICacheStorage.OPEN_NORMALLY, - storeCacheListener); - }); -} - - -function checkCache(aURL) { - let cache = Services.cache2; - let storage = cache.diskCacheStorage(LoadContextInfo.default, false); - - return new Promise(resolve => { - let checkCacheListener = { - onCacheEntryAvailable: function (entry, isnew, appcache, status) { - do_check_eq(status, Cr.NS_ERROR_CACHE_KEY_NOT_FOUND); - resolve(); - } - }; - - storage.asyncOpenURI(Services.io.newURI(aURL, null, null), "", - Ci.nsICacheStorage.OPEN_READONLY, - checkCacheListener); - }); -} diff --git a/browser/components/places/tests/unit/test_leftpane_corruption_handling.js b/browser/components/places/tests/unit/test_leftpane_corruption_handling.js deleted file mode 100644 index 0af6f4e95..000000000 --- a/browser/components/places/tests/unit/test_leftpane_corruption_handling.js +++ /dev/null @@ -1,174 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 et: */ -/* 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 that we build a working leftpane in various corruption situations. - */ - -// Used to store the original leftPaneFolderId getter. -var gLeftPaneFolderIdGetter; -var gAllBookmarksFolderIdGetter; -// Used to store the original left Pane status as a JSON string. -var gReferenceHierarchy; -var gLeftPaneFolderId; - -add_task(function* () { - // We want empty roots. - yield PlacesUtils.bookmarks.eraseEverything(); - - // Sanity check. - Assert.ok(!!PlacesUIUtils); - - // Check getters. - gLeftPaneFolderIdGetter = Object.getOwnPropertyDescriptor(PlacesUIUtils, "leftPaneFolderId"); - Assert.equal(typeof(gLeftPaneFolderIdGetter.get), "function"); - gAllBookmarksFolderIdGetter = Object.getOwnPropertyDescriptor(PlacesUIUtils, "allBookmarksFolderId"); - Assert.equal(typeof(gAllBookmarksFolderIdGetter.get), "function"); - - do_register_cleanup(() => PlacesUtils.bookmarks.eraseEverything()); -}); - -add_task(function* () { - // Add a third party bogus annotated item. Should not be removed. - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - title: "test", - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER - }); - - let folderId = yield PlacesUtils.promiseItemId(folder.guid); - PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_QUERY_ANNO, - "test", 0, - PlacesUtils.annotations.EXPIRE_NEVER); - - // Create the left pane, and store its current status, it will be used - // as reference value. - gLeftPaneFolderId = PlacesUIUtils.leftPaneFolderId; - gReferenceHierarchy = folderIdToHierarchy(gLeftPaneFolderId); - - while (gTests.length) { - // Run current test. - yield Task.spawn(gTests.shift()); - - // Regenerate getters. - Object.defineProperty(PlacesUIUtils, "leftPaneFolderId", gLeftPaneFolderIdGetter); - gLeftPaneFolderId = PlacesUIUtils.leftPaneFolderId; - Object.defineProperty(PlacesUIUtils, "allBookmarksFolderId", gAllBookmarksFolderIdGetter); - - // Check the new left pane folder. - let leftPaneHierarchy = folderIdToHierarchy(gLeftPaneFolderId) - Assert.equal(gReferenceHierarchy, leftPaneHierarchy); - - folder = yield PlacesUtils.bookmarks.fetch({guid: folder.guid}); - Assert.equal(folder.title, "test"); - } -}); - -// Corruption cases. -var gTests = [ - - function* test1() { - print("1. Do nothing, checks test calibration."); - }, - - function* test2() { - print("2. Delete the left pane folder."); - let guid = yield PlacesUtils.promiseItemGuid(gLeftPaneFolderId); - yield PlacesUtils.bookmarks.remove(guid); - }, - - function* test3() { - print("3. Delete a child of the left pane folder."); - let guid = yield PlacesUtils.promiseItemGuid(gLeftPaneFolderId); - let bm = yield PlacesUtils.bookmarks.fetch({parentGuid: guid, index: 0}); - yield PlacesUtils.bookmarks.remove(bm.guid); - }, - - function* test4() { - print("4. Delete AllBookmarks."); - let guid = yield PlacesUtils.promiseItemGuid(PlacesUIUtils.allBookmarksFolderId); - yield PlacesUtils.bookmarks.remove(guid); - }, - - function* test5() { - print("5. Create a duplicated left pane folder."); - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - title: "PlacesRoot", - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER - }); - - let folderId = yield PlacesUtils.promiseItemId(folder.guid); - PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_FOLDER_ANNO, - "PlacesRoot", 0, - PlacesUtils.annotations.EXPIRE_NEVER); - }, - - function* test6() { - print("6. Create a duplicated left pane query."); - let folder = yield PlacesUtils.bookmarks.insert({ - parentGuid: PlacesUtils.bookmarks.unfiledGuid, - title: "AllBookmarks", - index: PlacesUtils.bookmarks.DEFAULT_INDEX, - type: PlacesUtils.bookmarks.TYPE_FOLDER - }); - - let folderId = yield PlacesUtils.promiseItemId(folder.guid); - PlacesUtils.annotations.setItemAnnotation(folderId, ORGANIZER_QUERY_ANNO, - "AllBookmarks", 0, - PlacesUtils.annotations.EXPIRE_NEVER); - }, - - function* test7() { - print("7. Remove the left pane folder annotation."); - PlacesUtils.annotations.removeItemAnnotation(gLeftPaneFolderId, - ORGANIZER_FOLDER_ANNO); - }, - - function* test8() { - print("8. Remove a left pane query annotation."); - PlacesUtils.annotations.removeItemAnnotation(PlacesUIUtils.allBookmarksFolderId, - ORGANIZER_QUERY_ANNO); - }, - - function* test9() { - print("9. Remove a child of AllBookmarks."); - let guid = yield PlacesUtils.promiseItemGuid(PlacesUIUtils.allBookmarksFolderId); - let bm = yield PlacesUtils.bookmarks.fetch({parentGuid: guid, index: 0}); - yield PlacesUtils.bookmarks.remove(bm.guid); - } - -]; - -/** - * Convert a folder item id to a JSON representation of it and its contents. - */ -function folderIdToHierarchy(aFolderId) { - let root = PlacesUtils.getFolderContents(aFolderId).root; - let hier = JSON.stringify(hierarchyToObj(root)); - root.containerOpen = false; - return hier; -} - -function hierarchyToObj(aNode) { - let o = {} - o.title = aNode.title; - o.annos = PlacesUtils.getAnnotationsForItem(aNode.itemId) - if (PlacesUtils.nodeIsURI(aNode)) { - o.uri = aNode.uri; - } - else if (PlacesUtils.nodeIsFolder(aNode)) { - o.children = []; - PlacesUtils.asContainer(aNode).containerOpen = true; - for (let i = 0; i < aNode.childCount; ++i) { - o.children.push(hierarchyToObj(aNode.getChild(i))); - } - aNode.containerOpen = false; - } - return o; -} diff --git a/browser/components/places/tests/unit/xpcshell.ini b/browser/components/places/tests/unit/xpcshell.ini deleted file mode 100644 index 1c40e1c53..000000000 --- a/browser/components/places/tests/unit/xpcshell.ini +++ /dev/null @@ -1,25 +0,0 @@ -[DEFAULT] -head = head_bookmarks.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' -support-files = - bookmarks.glue.html - bookmarks.glue.json - corruptDB.sqlite - distribution.ini - -[test_421483.js] -[test_browserGlue_bookmarkshtml.js] -[test_browserGlue_corrupt.js] -[test_browserGlue_corrupt_nobackup.js] -[test_browserGlue_corrupt_nobackup_default.js] -[test_browserGlue_distribution.js] -[test_browserGlue_migrate.js] -[test_browserGlue_prefs.js] -[test_browserGlue_restore.js] -[test_browserGlue_smartBookmarks.js] -[test_browserGlue_urlbar_defaultbehavior_migration.js] -[test_clearHistory_shutdown.js] -[test_leftpane_corruption_handling.js] -[test_PUIU_makeTransaction.js] diff --git a/browser/components/preferences/in-content/tests/.eslintrc.js b/browser/components/preferences/in-content/tests/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/preferences/in-content/tests/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/preferences/in-content/tests/browser.ini b/browser/components/preferences/in-content/tests/browser.ini deleted file mode 100644 index 6cba02599..000000000 --- a/browser/components/preferences/in-content/tests/browser.ini +++ /dev/null @@ -1,43 +0,0 @@ -[DEFAULT] -support-files = - head.js - privacypane_tests_perwindow.js - -[browser_advanced_update.js] -[browser_basic_rebuild_fonts_test.js] -[browser_bug410900.js] -[browser_bug705422.js] -[browser_bug731866.js] -[browser_bug795764_cachedisabled.js] -[browser_bug1018066_resetScrollPosition.js] -[browser_bug1020245_openPreferences_to_paneContent.js] -[browser_bug1184989_prevent_scrolling_when_preferences_flipped.js] -support-files = - browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul -[browser_change_app_handler.js] -skip-if = os != "win" # This test tests the windows-specific app selection dialog, so can't run on non-Windows -[browser_connection.js] -[browser_connection_bug388287.js] -[browser_cookies_exceptions.js] -[browser_defaultbrowser_alwayscheck.js] -[browser_healthreport.js] -skip-if = true || !healthreport # Bug 1185403 for the "true" -[browser_homepages_filter_aboutpreferences.js] -[browser_notifications_do_not_disturb.js] -[browser_permissions_urlFieldHidden.js] -[browser_proxy_backup.js] -[browser_privacypane_1.js] -[browser_privacypane_3.js] -[browser_privacypane_4.js] -[browser_privacypane_5.js] -[browser_privacypane_8.js] -[browser_sanitizeOnShutdown_prefLocked.js] -[browser_searchsuggestions.js] -[browser_security.js] -[browser_subdialogs.js] -support-files = - subdialog.xul - subdialog2.xul -[browser_telemetry.js] -# Skip this test on Android as FHR and Telemetry are separate systems there. -skip-if = !healthreport || !telemetry || (os == 'linux' && debug) || (os == 'android') diff --git a/browser/components/preferences/in-content/tests/browser_advanced_update.js b/browser/components/preferences/in-content/tests/browser_advanced_update.js deleted file mode 100644 index e9d0e8652..000000000 --- a/browser/components/preferences/in-content/tests/browser_advanced_update.js +++ /dev/null @@ -1,158 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const { classes: Cc, interfaces: Ci, manager: Cm, utils: Cu, results: Cr } = Components; - -Cu.import('resource://gre/modules/XPCOMUtils.jsm'); - -const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); - -const mockUpdateManager = { - contractId: "@mozilla.org/updates/update-manager;1", - - _mockClassId: uuidGenerator.generateUUID(), - - _originalClassId: "", - - _originalFactory: null, - - QueryInterface: XPCOMUtils.generateQI([Ci.nsIUpdateManager]), - - createInstance: function(outer, iiD) { - if (outer) { - throw Cr.NS_ERROR_NO_AGGREGATION; - } - return this.QueryInterface(iiD); - }, - - register: function () { - let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); - if (!registrar.isCIDRegistered(this._mockClassId)) { - this._originalClassId = registrar.contractIDToCID(this.contractId); - this._originalFactory = Cm.getClassObject(Cc[this.contractId], Ci.nsIFactory); - registrar.unregisterFactory(this._originalClassId, this._originalFactory); - registrar.registerFactory(this._mockClassId, "Unregister after testing", this.contractId, this); - } - }, - - unregister: function () { - let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); - registrar.unregisterFactory(this._mockClassId, this); - registrar.registerFactory(this._originalClassId, "", this.contractId, this._originalFactory); - }, - - get updateCount() { - return this._updates.length; - }, - - getUpdateAt: function (index) { - return this._updates[index]; - }, - - _updates: [ - { - name: "Firefox Developer Edition 49.0a2", - statusText: "The Update was successfully installed", - buildID: "20160728004010", - type: "minor", - installDate: 1469763105156, - detailsURL: "https://www.mozilla.org/firefox/aurora/" - }, - { - name: "Firefox Developer Edition 43.0a2", - statusText: "The Update was successfully installed", - buildID: "20150929004011", - type: "minor", - installDate: 1443585886224, - detailsURL: "https://www.mozilla.org/firefox/aurora/" - }, - { - name: "Firefox Developer Edition 42.0a2", - statusText: "The Update was successfully installed", - buildID: "20150920004018", - type: "major", - installDate: 1442818147544, - detailsURL: "https://www.mozilla.org/firefox/aurora/" - } - ] -}; - -function resetPreferences() { - Services.prefs.clearUserPref("browser.search.update"); -} - -function formatInstallDate(sec) { - var date = new Date(sec); - const locale = Cc["@mozilla.org/chrome/chrome-registry;1"] - .getService(Ci.nsIXULChromeRegistry) - .getSelectedLocale("global", true); - const dtOptions = { year: 'numeric', month: 'long', day: 'numeric', - hour: 'numeric', minute: 'numeric', second: 'numeric' }; - return date.toLocaleString(locale, dtOptions); -} - -registerCleanupFunction(resetPreferences); - -add_task(function*() { - yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab", { leaveOpen: true }); - resetPreferences(); - Services.prefs.setBoolPref("browser.search.update", false); - - let doc = gBrowser.selectedBrowser.contentDocument; - let enableSearchUpdate = doc.getElementById("enableSearchUpdate"); - is_element_visible(enableSearchUpdate, "Check search update preference is visible"); - - // Ensure that the update pref dialog reflects the actual pref value. - ok(!enableSearchUpdate.checked, "Ensure search updates are disabled"); - Services.prefs.setBoolPref("browser.search.update", true); - ok(enableSearchUpdate.checked, "Ensure search updates are enabled"); - - gBrowser.removeCurrentTab(); -}); - -add_task(function*() { - mockUpdateManager.register(); - - yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab", { leaveOpen: true }); - let doc = gBrowser.selectedBrowser.contentDocument; - - let showBtn = doc.getElementById("showUpdateHistory"); - let dialogOverlay = doc.getElementById("dialogOverlay"); - - // Test the dialog window opens - is(dialogOverlay.style.visibility, "", "The dialog should be invisible"); - showBtn.doCommand(); - yield promiseLoadSubDialog("chrome://mozapps/content/update/history.xul"); - is(dialogOverlay.style.visibility, "visible", "The dialog should be visible"); - - let dialogFrame = doc.getElementById("dialogFrame"); - let frameDoc = dialogFrame.contentDocument; - let updates = frameDoc.querySelectorAll("update"); - - // Test the update history numbers are correct - is(updates.length, mockUpdateManager.updateCount, "The update count is incorrect."); - - // Test the updates are displayed correctly - let update = null; - let updateData = null; - for (let i = 0; i < updates.length; ++i) { - update = updates[i]; - updateData = mockUpdateManager.getUpdateAt(i); - - is(update.name, updateData.name + " (" + updateData.buildID + ")", "Wrong update name"); - is(update.type, updateData.type == "major" ? "New Version" : "Security Update", "Wrong update type"); - is(update.installDate, formatInstallDate(updateData.installDate), "Wrong update installDate"); - is(update.detailsURL, updateData.detailsURL, "Wrong update detailsURL"); - is(update.status, updateData.statusText, "Wrong update status"); - } - - // Test the dialog window closes - let closeBtn = doc.getElementById("dialogClose"); - closeBtn.doCommand(); - is(dialogOverlay.style.visibility, "", "The dialog should be invisible"); - - mockUpdateManager.unregister(); - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js b/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js deleted file mode 100644 index 32c1bd726..000000000 --- a/browser/components/preferences/in-content/tests/browser_basic_rebuild_fonts_test.js +++ /dev/null @@ -1,76 +0,0 @@ -Services.prefs.setBoolPref("browser.preferences.instantApply", true); - -registerCleanupFunction(function() { - Services.prefs.clearUserPref("browser.preferences.instantApply"); -}); - -add_task(function*() { - yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true}); - let doc = gBrowser.contentDocument; - var langGroup = Services.prefs.getComplexValue("font.language.group", Ci.nsIPrefLocalizedString).data - is(doc.getElementById("font.language.group").value, langGroup, - "Language group should be set correctly."); - - let defaultFontType = Services.prefs.getCharPref("font.default." + langGroup); - let fontFamily = Services.prefs.getCharPref("font.name." + defaultFontType + "." + langGroup); - let fontFamilyField = doc.getElementById("defaultFont"); - is(fontFamilyField.value, fontFamily, "Font family should be set correctly."); - - let defaultFontSize = Services.prefs.getIntPref("font.size.variable." + langGroup); - let fontSizeField = doc.getElementById("defaultFontSize"); - is(fontSizeField.value, defaultFontSize, "Font size should be set correctly."); - - doc.getElementById("advancedFonts").click(); - let win = yield promiseLoadSubDialog("chrome://browser/content/preferences/fonts.xul"); - doc = win.document; - - // Simulate a dumb font backend. - win.FontBuilder._enumerator = { - _list: ["MockedFont1", "MockedFont2", "MockedFont3"], - EnumerateFonts: function(lang, type, list) { - return this._list; - }, - EnumerateAllFonts: function() { - return this._list; - }, - getDefaultFont: function() { return null; }, - getStandardFamilyName: function(name) { return name; }, - }; - win.FontBuilder._allFonts = null; - win.FontBuilder._langGroupSupported = false; - - let langGroupElement = doc.getElementById("font.language.group"); - let selectLangsField = doc.getElementById("selectLangs"); - let serifField = doc.getElementById("serif"); - let armenian = "x-armn"; - let western = "x-western"; - - langGroupElement.value = armenian; - selectLangsField.value = armenian; - is(serifField.value, "", "Font family should not be set."); - - langGroupElement.value = western; - selectLangsField.value = western; - - // Simulate a font backend supporting language-specific enumeration. - // NB: FontBuilder has cached the return value from EnumerateAllFonts(), - // so _allFonts will always have 3 elements regardless of subsequent - // _list changes. - win.FontBuilder._enumerator._list = ["MockedFont2"]; - - langGroupElement.value = armenian; - selectLangsField.value = armenian; - is(serifField.value, "MockedFont2", "Font family should be set."); - - langGroupElement.value = western; - selectLangsField.value = western; - - // Simulate a system that has no fonts for the specified language. - win.FontBuilder._enumerator._list = []; - - langGroupElement.value = armenian; - selectLangsField.value = armenian; - is(serifField.value, "", "Font family should not be set."); - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js b/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js deleted file mode 100644 index 9d938fdd4..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug1018066_resetScrollPosition.js +++ /dev/null @@ -1,24 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -var originalWindowHeight; -registerCleanupFunction(function() { - window.resizeTo(window.outerWidth, originalWindowHeight); - while (gBrowser.tabs[1]) - gBrowser.removeTab(gBrowser.tabs[1]); -}); - -add_task(function*() { - originalWindowHeight = window.outerHeight; - window.resizeTo(window.outerWidth, 300); - let prefs = yield openPreferencesViaOpenPreferencesAPI("paneApplications", undefined, {leaveOpen: true}); - is(prefs.selectedPane, "paneApplications", "Applications pane was selected"); - let mainContent = gBrowser.contentDocument.querySelector(".main-content"); - mainContent.scrollTop = 50; - is(mainContent.scrollTop, 50, "main-content should be scrolled 50 pixels"); - - gBrowser.contentWindow.gotoPref("paneGeneral"); - is(mainContent.scrollTop, 0, - "Switching to a different category should reset the scroll position"); -}); - diff --git a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js b/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js deleted file mode 100644 index bc2c6d800..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug1020245_openPreferences_to_paneContent.js +++ /dev/null @@ -1,43 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Services.prefs.setBoolPref("browser.preferences.instantApply", true); - -registerCleanupFunction(function() { - Services.prefs.clearUserPref("browser.preferences.instantApply"); -}); - -add_task(function*() { - let prefs = yield openPreferencesViaOpenPreferencesAPI("paneContent"); - is(prefs.selectedPane, "paneContent", "Content pane was selected"); - prefs = yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab"); - is(prefs.selectedPane, "paneAdvanced", "Advanced pane was selected"); - is(prefs.selectedAdvancedTab, "updateTab", "The update tab within the advanced prefs should be selected"); - prefs = yield openPreferencesViaHash("privacy"); - is(prefs.selectedPane, "panePrivacy", "Privacy pane is selected when hash is 'privacy'"); - prefs = yield openPreferencesViaOpenPreferencesAPI("nonexistant-category"); - is(prefs.selectedPane, "paneGeneral", "General pane is selected by default when a nonexistant-category is requested"); - prefs = yield openPreferencesViaHash("nonexistant-category"); - is(prefs.selectedPane, "paneGeneral", "General pane is selected when hash is a nonexistant-category"); - prefs = yield openPreferencesViaHash(); - is(prefs.selectedPane, "paneGeneral", "General pane is selected by default"); -}); - -function openPreferencesViaHash(aPane) { - let deferred = Promise.defer(); - gBrowser.selectedTab = gBrowser.addTab("about:preferences" + (aPane ? "#" + aPane : "")); - let newTabBrowser = gBrowser.selectedBrowser; - - newTabBrowser.addEventListener("Initialized", function PrefInit() { - newTabBrowser.removeEventListener("Initialized", PrefInit, true); - newTabBrowser.contentWindow.addEventListener("load", function prefLoad() { - newTabBrowser.contentWindow.removeEventListener("load", prefLoad); - let win = gBrowser.contentWindow; - let selectedPane = win.history.state; - gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane}); - }); - }, true); - - return deferred.promise; -} diff --git a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js b/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js deleted file mode 100644 index 0972b2de4..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.js +++ /dev/null @@ -1,92 +0,0 @@ -const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore); - -add_task(function* () { - waitForExplicitFinish(); - - const tabURL = getRootDirectory(gTestPath) + "browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul"; - - yield BrowserTestUtils.withNewTab({ gBrowser, url: tabURL }, function* (browser) { - let doc = browser.contentDocument; - let container = doc.getElementById("container"); - - // Test button - let button = doc.getElementById("button"); - button.focus(); - EventUtils.synthesizeKey(" ", {}); - yield checkPageScrolling(container, "button"); - - // Test checkbox - let checkbox = doc.getElementById("checkbox"); - checkbox.focus(); - EventUtils.synthesizeKey(" ", {}); - ok(checkbox.checked, "Checkbox is checked"); - yield checkPageScrolling(container, "checkbox"); - - // Test listbox - let listbox = doc.getElementById("listbox"); - let listitem = doc.getElementById("listitem"); - listbox.focus(); - EventUtils.synthesizeKey(" ", {}); - ok(listitem.selected, "Listitem is selected"); - yield checkPageScrolling(container, "listbox"); - - // Test radio - let radiogroup = doc.getElementById("radiogroup"); - radiogroup.focus(); - EventUtils.synthesizeKey(" ", {}); - yield checkPageScrolling(container, "radio"); - }); - - yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:preferences#search" }, function* (browser) { - let doc = browser.contentDocument; - let container = doc.getElementsByClassName("main-content")[0]; - - // Test search - let engineList = doc.getElementById("engineList"); - engineList.focus(); - EventUtils.synthesizeKey(" ", {}); - is(engineList.view.selection.currentIndex, 0, "Search engineList is selected"); - EventUtils.synthesizeKey(" ", {}); - yield checkPageScrolling(container, "search engineList"); - }); - - // Test session restore - const CRASH_URL = "about:mozilla"; - const CRASH_FAVICON = "chrome://branding/content/icon32.png"; - const CRASH_SHENTRY = {url: CRASH_URL}; - const CRASH_TAB = {entries: [CRASH_SHENTRY], image: CRASH_FAVICON}; - const CRASH_STATE = {windows: [{tabs: [CRASH_TAB]}]}; - - const TAB_URL = "about:sessionrestore"; - const TAB_FORMDATA = {url: TAB_URL, id: {sessionData: CRASH_STATE}}; - const TAB_SHENTRY = {url: TAB_URL}; - const TAB_STATE = {entries: [TAB_SHENTRY], formdata: TAB_FORMDATA}; - - let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank"); - - // Fake a post-crash tab - ss.setTabState(tab, JSON.stringify(TAB_STATE)); - - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - let doc = tab.linkedBrowser.contentDocument; - - // Make body scrollable - doc.body.style.height = (doc.body.clientHeight + 100) + "px"; - - let tabList = doc.getElementById("tabList"); - tabList.focus(); - EventUtils.synthesizeKey(" ", {}); - yield checkPageScrolling(doc.documentElement, "session restore"); - - gBrowser.removeCurrentTab(); - finish(); -}); - -function checkPageScrolling(container, type) { - return new Promise(resolve => { - setTimeout(() => { - is(container.scrollTop, 0, "Page should not scroll when " + type + " flipped"); - resolve(); - }, 0); - }); -} diff --git a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul b/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul deleted file mode 100644 index 59b644c8f..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0"?> -<!-- - XUL Widget Test for Bug 1184989 - --> -<page title="Bug 1184989 Test" - xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> - -<vbox id="container" style="height: 200px; overflow: auto;"> - <vbox style="height: 500px;"> - <hbox> - <button id="button" label="button" /> - </hbox> - - <hbox> - <checkbox id="checkbox" label="checkbox" /> - </hbox> - - <hbox style="height: 50px;"> - <listbox id="listbox"> - <listitem id="listitem" label="listitem" /> - <listitem label="listitem" /> - </listbox> - </hbox> - - <hbox> - <radiogroup id="radiogroup"> - <radio id="radio" label="radio" /> - </radiogroup> - </hbox> - </vbox> -</vbox> - -</page> diff --git a/browser/components/preferences/in-content/tests/browser_bug410900.js b/browser/components/preferences/in-content/tests/browser_bug410900.js deleted file mode 100644 index 5b100966d..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug410900.js +++ /dev/null @@ -1,46 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/PlacesUtils.jsm"); -Components.utils.import("resource://gre/modules/NetUtil.jsm"); - -function test() { - waitForExplicitFinish(); - - // Setup a phony handler to ensure the app pane will be populated. - var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"]. - createInstance(Ci.nsIWebHandlerApp); - handler.name = "App pane alive test"; - handler.uriTemplate = "http://test.mozilla.org/%s"; - - var extps = Cc["@mozilla.org/uriloader/external-protocol-service;1"]. - getService(Ci.nsIExternalProtocolService); - var info = extps.getProtocolHandlerInfo("apppanetest"); - info.possibleApplicationHandlers.appendElement(handler, false); - - var hserv = Cc["@mozilla.org/uriloader/handler-service;1"]. - getService(Ci.nsIHandlerService); - hserv.store(info); - - openPreferencesViaOpenPreferencesAPI("applications", null, {leaveOpen: true}).then( - () => runTest(gBrowser.selectedBrowser.contentWindow) - ); -} - -function runTest(win) { - var rbox = win.document.getElementById("handlersView"); - ok(rbox, "handlersView is present"); - - var items = rbox && rbox.getElementsByTagName("richlistitem"); - ok(items && items.length > 0, "App handler list populated"); - - var handlerAdded = false; - for (let i = 0; i < items.length; i++) { - if (items[i].getAttribute('type') == "apppanetest") - handlerAdded = true; - } - ok(handlerAdded, "apppanetest protocol handler was successfully added"); - - gBrowser.removeCurrentTab(); - finish(); -} diff --git a/browser/components/preferences/in-content/tests/browser_bug705422.js b/browser/components/preferences/in-content/tests/browser_bug705422.js deleted file mode 100644 index 24732083b..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug705422.js +++ /dev/null @@ -1,144 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - waitForExplicitFinish(); - // Allow all cookies, then actually set up the test - SpecialPowers.pushPrefEnv({"set": [["network.cookie.cookieBehavior", 0]]}, initTest); -} - -function initTest() { - const searchTerm = "example"; - const dummyTerm = "elpmaxe"; - - var cm = Components.classes["@mozilla.org/cookiemanager;1"] - .getService(Components.interfaces.nsICookieManager); - - // delete all cookies (might be left over from other tests) - cm.removeAll(); - - // data for cookies - var vals = [[searchTerm+".com", dummyTerm, dummyTerm], // match - [searchTerm+".org", dummyTerm, dummyTerm], // match - [dummyTerm+".com", searchTerm, dummyTerm], // match - [dummyTerm+".edu", searchTerm+dummyTerm, dummyTerm], // match - [dummyTerm+".net", dummyTerm, searchTerm], // match - [dummyTerm+".org", dummyTerm, searchTerm+dummyTerm], // match - [dummyTerm+".int", dummyTerm, dummyTerm]]; // no match - - // matches must correspond to above data - const matches = 6; - - var ios = Components.classes["@mozilla.org/network/io-service;1"] - .getService(Components.interfaces.nsIIOService); - var cookieSvc = Components.classes["@mozilla.org/cookieService;1"] - .getService(Components.interfaces.nsICookieService); - var v; - // inject cookies - for (v in vals) { - let [host, name, value] = vals[v]; - var cookieUri = ios.newURI("http://"+host, null, null); - cookieSvc.setCookieString(cookieUri, null, name+"="+value+";", null); - } - - // open cookie manager - var cmd = window.openDialog("chrome://browser/content/preferences/cookies.xul", - "Browser:Cookies", "", {}); - - // when it has loaded, run actual tests - cmd.addEventListener("load", function() { executeSoon(function() { runTest(cmd, searchTerm, vals.length, matches); }); }, false); -} - -function isDisabled(win, expectation) { - var disabled = win.document.getElementById("removeAllCookies").disabled; - is(disabled, expectation, "Remove all cookies button has correct state: "+(expectation?"disabled":"enabled")); -} - -function runTest(win, searchTerm, cookies, matches) { - var cm = Components.classes["@mozilla.org/cookiemanager;1"] - .getService(Components.interfaces.nsICookieManager); - - - // number of cookies should match injected cookies - var injectedCookies = 0, - injectedEnumerator = cm.enumerator; - while (injectedEnumerator.hasMoreElements()) { - injectedCookies++; - injectedEnumerator.getNext(); - } - is(injectedCookies, cookies, "Number of cookies match injected cookies"); - - // "delete all cookies" should be enabled - isDisabled(win, false); - - // filter cookies and count matches - win.gCookiesWindow.setFilter(searchTerm); - is(win.gCookiesWindow._view.rowCount, matches, "Correct number of cookies shown after filter is applied"); - - // "delete all cookies" should be enabled - isDisabled(win, false); - - - // select first cookie and delete - var tree = win.document.getElementById("cookiesList"); - var deleteButton = win.document.getElementById("removeSelectedCookies"); - var rect = tree.treeBoxObject.getCoordsForCellItem(0, tree.columns[0], "cell"); - EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {}, win); - EventUtils.synthesizeMouseAtCenter(deleteButton, {}, win); - - // count cookies should be matches-1 - is(win.gCookiesWindow._view.rowCount, matches-1, "Deleted selected cookie"); - - // select two adjacent cells and delete - EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, {}, win); - var eventObj = {}; - if (navigator.platform.indexOf("Mac") >= 0) - eventObj.metaKey = true; - else - eventObj.ctrlKey = true; - rect = tree.treeBoxObject.getCoordsForCellItem(1, tree.columns[0], "cell"); - EventUtils.synthesizeMouse(tree.body, rect.x + rect.width / 2, rect.y + rect.height / 2, eventObj, win); - EventUtils.synthesizeMouseAtCenter(deleteButton, {}, win); - - // count cookies should be matches-3 - is(win.gCookiesWindow._view.rowCount, matches-3, "Deleted selected two adjacent cookies"); - - // "delete all cookies" should be enabled - isDisabled(win, false); - - // delete all cookies and count - var deleteAllButton = win.document.getElementById("removeAllCookies"); - EventUtils.synthesizeMouseAtCenter(deleteAllButton, {}, win); - is(win.gCookiesWindow._view.rowCount, 0, "Deleted all matching cookies"); - - // "delete all cookies" should be disabled - isDisabled(win, true); - - // clear filter and count should be cookies-matches - win.gCookiesWindow.setFilter(""); - is(win.gCookiesWindow._view.rowCount, cookies-matches, "Unmatched cookies remain"); - - // "delete all cookies" should be enabled - isDisabled(win, false); - - // delete all cookies and count should be 0 - EventUtils.synthesizeMouseAtCenter(deleteAllButton, {}, win); - is(win.gCookiesWindow._view.rowCount, 0, "Deleted all cookies"); - - // check that datastore is also at 0 - var remainingCookies = 0, - remainingEnumerator = cm.enumerator; - while (remainingEnumerator.hasMoreElements()) { - remainingCookies++; - remainingEnumerator.getNext(); - } - is(remainingCookies, 0, "Zero cookies remain"); - - // "delete all cookies" should be disabled - isDisabled(win, true); - - // clean up - win.close(); - finish(); -} - diff --git a/browser/components/preferences/in-content/tests/browser_bug731866.js b/browser/components/preferences/in-content/tests/browser_bug731866.js deleted file mode 100644 index c1031d412..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug731866.js +++ /dev/null @@ -1,52 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/PlacesUtils.jsm"); -Components.utils.import("resource://gre/modules/NetUtil.jsm"); - -function test() { - waitForExplicitFinish(); - open_preferences(runTest); -} - -var gElements; - -function checkElements(expectedPane) { - for (let element of gElements) { - // keyset and preferences elements fail is_element_visible checks because they are never visible. - // special-case the drmGroup item because its visibility depends on pref + OS version - if (element.nodeName == "keyset" || - element.nodeName == "preferences" || - element.id === "drmGroup") { - continue; - } - let attributeValue = element.getAttribute("data-category"); - let suffix = " (id=" + element.id + ")"; - if (attributeValue == "pane" + expectedPane) { - is_element_visible(element, expectedPane + " elements should be visible" + suffix); - } else { - is_element_hidden(element, "Elements not in " + expectedPane + " should be hidden" + suffix); - } - } -} - -function runTest(win) { - is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded"); - - let tab = win.document; - gElements = tab.getElementById("mainPrefPane").children; - - let panes = [ - "General", "Search", "Content", "Applications", - "Privacy", "Security", "Sync", "Advanced", - ]; - - for (let pane of panes) { - win.gotoPref("pane" + pane); - checkElements(pane); - } - - gBrowser.removeCurrentTab(); - win.close(); - finish(); -} diff --git a/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js b/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js deleted file mode 100644 index 21f92db8d..000000000 --- a/browser/components/preferences/in-content/tests/browser_bug795764_cachedisabled.js +++ /dev/null @@ -1,52 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/PlacesUtils.jsm"); -Components.utils.import("resource://gre/modules/NetUtil.jsm"); - -function test() { - waitForExplicitFinish(); - - let prefs = [ - "browser.cache.offline.enable", - "browser.cache.disk.enable", - "browser.cache.memory.enable", - ]; - - registerCleanupFunction(function() { - for (let pref of prefs) { - Services.prefs.clearUserPref(pref); - } - }); - - for (let pref of prefs) { - Services.prefs.setBoolPref(pref, false); - } - - open_preferences(runTest); -} - -function runTest(win) { - is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded"); - - let tab = win.document; - let elements = tab.getElementById("mainPrefPane").children; - - // Test if advanced pane is opened correctly - win.gotoPref("paneAdvanced"); - for (let element of elements) { - if (element.nodeName == "preferences") { - continue; - } - let attributeValue = element.getAttribute("data-category"); - if (attributeValue == "paneAdvanced") { - is_element_visible(element, "Advanced elements should be visible"); - } else { - is_element_hidden(element, "Non-Advanced elements should be hidden"); - } - } - - gBrowser.removeCurrentTab(); - win.close(); - finish(); -} diff --git a/browser/components/preferences/in-content/tests/browser_change_app_handler.js b/browser/components/preferences/in-content/tests/browser_change_app_handler.js deleted file mode 100644 index f66cdfd37..000000000 --- a/browser/components/preferences/in-content/tests/browser_change_app_handler.js +++ /dev/null @@ -1,98 +0,0 @@ -var gMimeSvc = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService); -var gHandlerSvc = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService); - -SimpleTest.requestCompleteLog(); - -function setupFakeHandler() { - let info = gMimeSvc.getFromTypeAndExtension("text/plain", "foo.txt"); - ok(info.possibleLocalHandlers.length, "Should have at least one known handler"); - let handler = info.possibleLocalHandlers.queryElementAt(0, Ci.nsILocalHandlerApp); - - let infoToModify = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); - infoToModify.possibleApplicationHandlers.appendElement(handler, false); - - gHandlerSvc.store(infoToModify); -} - -add_task(function*() { - setupFakeHandler(); - yield openPreferencesViaOpenPreferencesAPI("applications", null, {leaveOpen: true}); - info("Preferences page opened on the applications pane."); - let win = gBrowser.selectedBrowser.contentWindow; - - let container = win.document.getElementById("handlersView"); - let ourItem = container.querySelector("richlistitem[type='text/x-test-handler']"); - ok(ourItem, "handlersView is present"); - ourItem.scrollIntoView(); - container.selectItem(ourItem); - ok(ourItem.selected, "Should be able to select our item."); - - let list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu")); - info("Got list after item was selected"); - - let chooseItem = list.firstChild.querySelector(".choose-app-item"); - let dialogLoadedPromise = promiseLoadSubDialog("chrome://global/content/appPicker.xul"); - let cmdEvent = win.document.createEvent("xulcommandevent"); - cmdEvent.initCommandEvent("command", true, true, win, 0, false, false, false, false, null); - chooseItem.dispatchEvent(cmdEvent); - - let dialog = yield dialogLoadedPromise; - info("Dialog loaded"); - - let dialogDoc = dialog.document; - let dialogList = dialogDoc.getElementById("app-picker-listbox"); - dialogList.selectItem(dialogList.firstChild); - let selectedApp = dialogList.firstChild.handlerApp; - dialogDoc.documentElement.acceptDialog(); - - // Verify results are correct in mime service: - let mimeInfo = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); - ok(mimeInfo.preferredApplicationHandler.equals(selectedApp), "App should be set as preferred."); - - // Check that we display this result: - list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu")); - info("Got list after item was selected"); - ok(list.selectedItem, "Should have a selected item"); - ok(mimeInfo.preferredApplicationHandler.equals(list.selectedItem.handlerApp), - "App should be visible as preferred item."); - - - // Now try to 'manage' this list: - dialogLoadedPromise = promiseLoadSubDialog("chrome://browser/content/preferences/applicationManager.xul"); - - let manageItem = list.firstChild.querySelector(".manage-app-item"); - cmdEvent = win.document.createEvent("xulcommandevent"); - cmdEvent.initCommandEvent("command", true, true, win, 0, false, false, false, false, null); - manageItem.dispatchEvent(cmdEvent); - - dialog = yield dialogLoadedPromise; - info("Dialog loaded the second time"); - - dialogDoc = dialog.document; - dialogList = dialogDoc.getElementById("appList"); - let itemToRemove = dialogList.querySelector('listitem[label="' + selectedApp.name + '"]'); - dialogList.selectItem(itemToRemove); - let itemsBefore = dialogList.children.length; - dialogDoc.getElementById("remove").click(); - ok(!itemToRemove.parentNode, "Item got removed from DOM"); - is(dialogList.children.length, itemsBefore - 1, "Item got removed"); - dialogDoc.documentElement.acceptDialog(); - - // Verify results are correct in mime service: - mimeInfo = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); - ok(!mimeInfo.preferredApplicationHandler, "App should no longer be set as preferred."); - - // Check that we display this result: - list = yield waitForCondition(() => win.document.getAnonymousElementByAttribute(ourItem, "class", "actionsMenu")); - ok(list.selectedItem, "Should have a selected item"); - ok(!list.selectedItem.handlerApp, - "No app should be visible as preferred item."); - - gBrowser.removeCurrentTab(); -}); - -registerCleanupFunction(function() { - let infoToModify = gMimeSvc.getFromTypeAndExtension("text/x-test-handler", null); - gHandlerSvc.remove(infoToModify); -}); - diff --git a/browser/components/preferences/in-content/tests/browser_connection.js b/browser/components/preferences/in-content/tests/browser_connection.js deleted file mode 100644 index 50438aed1..000000000 --- a/browser/components/preferences/in-content/tests/browser_connection.js +++ /dev/null @@ -1,99 +0,0 @@ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ -/* 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/. */ - -Components.utils.import("resource://gre/modules/Services.jsm"); -Components.utils.import("resource://gre/modules/Task.jsm"); - -function test() { - waitForExplicitFinish(); - - // network.proxy.type needs to be backed up and restored because mochitest - // changes this setting from the default - let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type"); - registerCleanupFunction(function() { - Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType); - Services.prefs.clearUserPref("network.proxy.no_proxies_on"); - Services.prefs.clearUserPref("browser.preferences.instantApply"); - }); - - let connectionURL = "chrome://browser/content/preferences/connection.xul"; - - /* - The connection dialog alone won't save onaccept since it uses type="child", - so it has to be opened as a sub dialog of the main pref tab. - Open the main tab here. - */ - open_preferences(Task.async(function* tabOpened(aContentWindow) { - is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded"); - let dialog = yield openAndLoadSubDialog(connectionURL); - let dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing"); - - ok(dialog, "connection window opened"); - runConnectionTests(dialog); - dialog.document.documentElement.acceptDialog(); - - let dialogClosingEvent = yield dialogClosingPromise; - ok(dialogClosingEvent, "connection window closed"); - // runConnectionTests will have changed this pref - make sure it was - // sanitized correctly when the dialog was accepted - is(Services.prefs.getCharPref("network.proxy.no_proxies_on"), - ".a.com,.b.com,.c.com", "no_proxies_on pref has correct value"); - gBrowser.removeCurrentTab(); - finish(); - })); -} - -// run a bunch of tests on the window containing connection.xul -function runConnectionTests(win) { - let doc = win.document; - let networkProxyNone = doc.getElementById("networkProxyNone"); - let networkProxyNonePref = doc.getElementById("network.proxy.no_proxies_on"); - let networkProxyTypePref = doc.getElementById("network.proxy.type"); - - // make sure the networkProxyNone textbox is formatted properly - is(networkProxyNone.getAttribute("multiline"), "true", - "networkProxyNone textbox is multiline"); - is(networkProxyNone.getAttribute("rows"), "2", - "networkProxyNone textbox has two rows"); - - // check if sanitizing the given input for the no_proxies_on pref results in - // expected string - function testSanitize(input, expected, errorMessage) { - networkProxyNonePref.value = input; - win.gConnectionsDialog.sanitizeNoProxiesPref(); - is(networkProxyNonePref.value, expected, errorMessage); - } - - // change this pref so proxy exceptions are actually configurable - networkProxyTypePref.value = 1; - is(networkProxyNone.disabled, false, "networkProxyNone textbox is enabled"); - - testSanitize(".a.com", ".a.com", - "sanitize doesn't mess up single filter"); - testSanitize(".a.com, .b.com, .c.com", ".a.com, .b.com, .c.com", - "sanitize doesn't mess up multiple comma/space sep filters"); - testSanitize(".a.com\n.b.com", ".a.com,.b.com", - "sanitize turns line break into comma"); - testSanitize(".a.com,\n.b.com", ".a.com,.b.com", - "sanitize doesn't add duplicate comma after comma"); - testSanitize(".a.com\n,.b.com", ".a.com,.b.com", - "sanitize doesn't add duplicate comma before comma"); - testSanitize(".a.com,\n,.b.com", ".a.com,,.b.com", - "sanitize doesn't add duplicate comma surrounded by commas"); - testSanitize(".a.com, \n.b.com", ".a.com, .b.com", - "sanitize doesn't add comma after comma/space"); - testSanitize(".a.com\n .b.com", ".a.com, .b.com", - "sanitize adds comma before space"); - testSanitize(".a.com\n\n\n;;\n;\n.b.com", ".a.com,.b.com", - "sanitize only adds one comma per substring of bad chars"); - testSanitize(".a.com,,.b.com", ".a.com,,.b.com", - "duplicate commas from user are untouched"); - testSanitize(".a.com\n.b.com\n.c.com,\n.d.com,\n.e.com", - ".a.com,.b.com,.c.com,.d.com,.e.com", - "sanitize replaces things globally"); - - // will check that this was sanitized properly after window closes - networkProxyNonePref.value = ".a.com;.b.com\n.c.com"; -} diff --git a/browser/components/preferences/in-content/tests/browser_connection_bug388287.js b/browser/components/preferences/in-content/tests/browser_connection_bug388287.js deleted file mode 100644 index 5a348876e..000000000 --- a/browser/components/preferences/in-content/tests/browser_connection_bug388287.js +++ /dev/null @@ -1,125 +0,0 @@ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/Services.jsm"); -Components.utils.import("resource://gre/modules/Task.jsm"); - -function test() { - waitForExplicitFinish(); - const connectionURL = "chrome://browser/content/preferences/connection.xul"; - let closeable = false; - let finalTest = false; - - // The changed preferences need to be backed up and restored because this mochitest - // changes them setting from the default - let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type"); - registerCleanupFunction(function() { - Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType); - Services.prefs.clearUserPref("network.proxy.share_proxy_settings"); - for (let proxyType of ["http", "ssl", "ftp", "socks"]) { - Services.prefs.clearUserPref("network.proxy." + proxyType); - Services.prefs.clearUserPref("network.proxy." + proxyType + "_port"); - if (proxyType == "http") { - continue; - } - Services.prefs.clearUserPref("network.proxy.backup." + proxyType); - Services.prefs.clearUserPref("network.proxy.backup." + proxyType + "_port"); - } - }); - - /* - The connection dialog alone won't save onaccept since it uses type="child", - so it has to be opened as a sub dialog of the main pref tab. - Open the main tab here. - */ - open_preferences(Task.async(function* tabOpened(aContentWindow) { - let dialog, dialogClosingPromise; - let doc, proxyTypePref, sharePref, httpPref, httpPortPref, ftpPref, ftpPortPref; - - // Convenient function to reset the variables for the new window - function* setDoc() { - if (closeable) { - let dialogClosingEvent = yield dialogClosingPromise; - ok(dialogClosingEvent, "Connection dialog closed"); - } - - if (finalTest) { - gBrowser.removeCurrentTab(); - finish(); - return; - } - - dialog = yield openAndLoadSubDialog(connectionURL); - dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing"); - - doc = dialog.document; - proxyTypePref = doc.getElementById("network.proxy.type"); - sharePref = doc.getElementById("network.proxy.share_proxy_settings"); - httpPref = doc.getElementById("network.proxy.http"); - httpPortPref = doc.getElementById("network.proxy.http_port"); - ftpPref = doc.getElementById("network.proxy.ftp"); - ftpPortPref = doc.getElementById("network.proxy.ftp_port"); - } - - // This batch of tests should not close the dialog - yield setDoc(); - - // Testing HTTP port 0 with share on - proxyTypePref.value = 1; - sharePref.value = true; - httpPref.value = "localhost"; - httpPortPref.value = 0; - doc.documentElement.acceptDialog(); - - // Testing HTTP port 0 + FTP port 80 with share off - sharePref.value = false; - ftpPref.value = "localhost"; - ftpPortPref.value = 80; - doc.documentElement.acceptDialog(); - - // Testing HTTP port 80 + FTP port 0 with share off - httpPortPref.value = 80; - ftpPortPref.value = 0; - doc.documentElement.acceptDialog(); - - // From now on, the dialog should close since we are giving it legitimate inputs. - // The test will timeout if the onbeforeaccept kicks in erroneously. - closeable = true; - - // Both ports 80, share on - httpPortPref.value = 80; - ftpPortPref.value = 80; - doc.documentElement.acceptDialog(); - - // HTTP 80, FTP 0, with share on - yield setDoc(); - proxyTypePref.value = 1; - sharePref.value = true; - ftpPref.value = "localhost"; - httpPref.value = "localhost"; - httpPortPref.value = 80; - ftpPortPref.value = 0; - doc.documentElement.acceptDialog(); - - // HTTP host empty, port 0 with share on - yield setDoc(); - proxyTypePref.value = 1; - sharePref.value = true; - httpPref.value = ""; - httpPortPref.value = 0; - doc.documentElement.acceptDialog(); - - // HTTP 0, but in no proxy mode - yield setDoc(); - proxyTypePref.value = 0; - sharePref.value = true; - httpPref.value = "localhost"; - httpPortPref.value = 0; - - // This is the final test, don't spawn another connection window - finalTest = true; - doc.documentElement.acceptDialog(); - yield setDoc(); - })); -} diff --git a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js b/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js deleted file mode 100644 index 89313d736..000000000 --- a/browser/components/preferences/in-content/tests/browser_cookies_exceptions.js +++ /dev/null @@ -1,348 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -requestLongerTimeout(2); - -function test() { - waitForExplicitFinish(); - requestLongerTimeout(3); - testRunner.runTests(); -} - -var testRunner = { - - tests: - [ - { - test: function(params) { - params.url.value = "test.com"; - params.btnAllow.doCommand(); - is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); - is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission text should be set correctly"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://test.com", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "test.com"; - params.btnBlock.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.denyText, - "permission should change to deny in UI"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://test.com", data: "changed", - capability: Ci.nsIPermissionManager.DENY_ACTION }], - }, - { - test: function(params) { - params.url.value = "test.com"; - params.btnAllow.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "http://test.com", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission should revert back to allow"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://test.com", data: "changed", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "test.com"; - params.btnRemove.doCommand(); - is(params.tree.view.rowCount, 0, "exception should be removed"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://test.com", data: "deleted" }], - }, - { - expectPermObservancesDuringTestFunction: true, - test: function(params) { - let uri = params.ioService.newURI("http://test.com", null, null); - params.pm.add(uri, "popup", Ci.nsIPermissionManager.DENY_ACTION); - is(params.tree.view.rowCount, 0, "adding unrelated permission should not change display"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "popup", origin: "http://test.com", data: "added", - capability: Ci.nsIPermissionManager.DENY_ACTION }], - cleanUp: function(params) { - let uri = params.ioService.newURI("http://test.com", null, null); - params.pm.remove(uri, "popup"); - }, - }, - { - test: function(params) { - params.url.value = "https://test.com:12345"; - params.btnAllow.doCommand(); - is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); - is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission text should be set correctly"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "https://test.com:12345", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "https://test.com:12345"; - params.btnBlock.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.denyText, - "permission should change to deny in UI"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "https://test.com:12345", data: "changed", - capability: Ci.nsIPermissionManager.DENY_ACTION }], - }, - { - test: function(params) { - params.url.value = "https://test.com:12345"; - params.btnAllow.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "https://test.com:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission should revert back to allow"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "https://test.com:12345", data: "changed", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "https://test.com:12345"; - params.btnRemove.doCommand(); - is(params.tree.view.rowCount, 0, "exception should be removed"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "https://test.com:12345", data: "deleted" }], - }, - { - test: function(params) { - params.url.value = "localhost:12345"; - params.btnAllow.doCommand(); - is(params.tree.view.rowCount, 1, "added exception shows up in treeview"); - is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission text should be set correctly"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://localhost:12345", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "localhost:12345"; - params.btnBlock.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.denyText, - "permission should change to deny in UI"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://localhost:12345", data: "changed", - capability: Ci.nsIPermissionManager.DENY_ACTION }], - }, - { - test: function(params) { - params.url.value = "localhost:12345"; - params.btnAllow.doCommand(); - is(params.tree.view.getCellText(0, params.nameCol), "http://localhost:12345", - "origin name should be set correctly"); - is(params.tree.view.getCellText(0, params.statusCol), params.allowText, - "permission should revert back to allow"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://localhost:12345", data: "changed", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - }, - { - test: function(params) { - params.url.value = "localhost:12345"; - params.btnRemove.doCommand(); - is(params.tree.view.rowCount, 0, "exception should be removed"); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://localhost:12345", data: "deleted" }], - }, - { - expectPermObservancesDuringTestFunction: true, - test(params) { - for (let URL of ["http://a", "http://z", "http://b"]) { - let URI = params.ioService.newURI(URL, null, null); - params.pm.add(URI, "cookie", Ci.nsIPermissionManager.ALLOW_ACTION); - } - - is(params.tree.view.rowCount, 3, "Three permissions should be present"); - is(params.tree.view.getCellText(0, params.nameCol), "http://a", - "site should be sorted. 'a' should be first"); - is(params.tree.view.getCellText(1, params.nameCol), "http://b", - "site should be sorted. 'b' should be second"); - is(params.tree.view.getCellText(2, params.nameCol), "http://z", - "site should be sorted. 'z' should be third"); - - // Sort descending then check results in cleanup since sorting isn't synchronous. - EventUtils.synthesizeMouseAtCenter(params.doc.getElementById("siteCol"), {}, - params.doc.defaultView); - params.btnApplyChanges.doCommand(); - }, - observances: [{ type: "cookie", origin: "http://a", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }, - { type: "cookie", origin: "http://z", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }, - { type: "cookie", origin: "http://b", data: "added", - capability: Ci.nsIPermissionManager.ALLOW_ACTION }], - cleanUp(params) { - is(params.tree.view.getCellText(0, params.nameCol), "http://z", - "site should be sorted. 'z' should be first"); - is(params.tree.view.getCellText(1, params.nameCol), "http://b", - "site should be sorted. 'b' should be second"); - is(params.tree.view.getCellText(2, params.nameCol), "http://a", - "site should be sorted. 'a' should be third"); - - for (let URL of ["http://a", "http://z", "http://b"]) { - let uri = params.ioService.newURI(URL, null, null); - params.pm.remove(uri, "cookie"); - } - }, - }, - ], - - _currentTest: -1, - - runTests: function() { - this._currentTest++; - - info("Running test #" + (this._currentTest + 1) + "\n"); - let that = this; - let p = this.runCurrentTest(this._currentTest + 1); - p.then(function() { - if (that._currentTest == that.tests.length - 1) { - finish(); - } - else { - that.runTests(); - } - }); - }, - - runCurrentTest: function(testNumber) { - return new Promise(function(resolve, reject) { - - let helperFunctions = { - windowLoad: function(win) { - let doc = win.document; - let params = { - doc, - tree: doc.getElementById("permissionsTree"), - nameCol: doc.getElementById("permissionsTree").treeBoxObject.columns.getColumnAt(0), - statusCol: doc.getElementById("permissionsTree").treeBoxObject.columns.getColumnAt(1), - url: doc.getElementById("url"), - btnAllow: doc.getElementById("btnAllow"), - btnBlock: doc.getElementById("btnBlock"), - btnApplyChanges: doc.getElementById("btnApplyChanges"), - btnRemove: doc.getElementById("removePermission"), - pm: Cc["@mozilla.org/permissionmanager;1"] - .getService(Ci.nsIPermissionManager), - ioService: Cc["@mozilla.org/network/io-service;1"] - .getService(Ci.nsIIOService), - allowText: win.gPermissionManager._getCapabilityString( - Ci.nsIPermissionManager.ALLOW_ACTION), - denyText: win.gPermissionManager._getCapabilityString( - Ci.nsIPermissionManager.DENY_ACTION), - allow: Ci.nsIPermissionManager.ALLOW_ACTION, - deny: Ci.nsIPermissionManager.DENY_ACTION, - }; - - let permObserver = { - observe: function(aSubject, aTopic, aData) { - if (aTopic != "perm-changed") - return; - - if (testRunner.tests[testRunner._currentTest].observances.length == 0) { - // Should fail here as we are not expecting a notification, but we don't. - // See bug 1063410. - return; - } - - let permission = aSubject.QueryInterface(Ci.nsIPermission); - let expected = testRunner.tests[testRunner._currentTest].observances.shift(); - - is(aData, expected.data, "type of message should be the same"); - for (let prop of ["type", "capability"]) { - if (expected[prop]) - is(permission[prop], expected[prop], - "property: \"" + prop + "\" should be equal"); - } - - if (expected.origin) { - is(permission.principal.origin, expected.origin, - "property: \"origin\" should be equal"); - } - - os.removeObserver(permObserver, "perm-changed"); - - let test = testRunner.tests[testRunner._currentTest]; - if (!test.expectPermObservancesDuringTestFunction) { - if (test.cleanUp) { - test.cleanUp(params); - } - - gBrowser.removeCurrentTab(); - resolve(); - } - }, - }; - - let os = Cc["@mozilla.org/observer-service;1"] - .getService(Ci.nsIObserverService); - - os.addObserver(permObserver, "perm-changed", false); - - if (testRunner._currentTest == 0) { - is(params.tree.view.rowCount, 0, "no cookie exceptions"); - } - - try { - let test = testRunner.tests[testRunner._currentTest]; - test.test(params); - if (test.expectPermObservancesDuringTestFunction) { - if (test.cleanUp) { - test.cleanUp(params); - } - - gBrowser.removeCurrentTab(); - resolve(); - } - } catch (ex) { - ok(false, "exception while running test #" + - testNumber + ": " + ex); - } - }, - }; - - openPreferencesViaOpenPreferencesAPI("panePrivacy", null, {leaveOpen: true}).then(function() { - let doc = gBrowser.contentDocument; - let historyMode = doc.getElementById("historyMode"); - historyMode.value = "custom"; - historyMode.doCommand(); - doc.getElementById("cookieExceptions").doCommand(); - - let subDialogURL = "chrome://browser/content/preferences/permissions.xul"; - promiseLoadSubDialog(subDialogURL).then(function(win) { - helperFunctions.windowLoad(win); - }); - }); - }); - }, -}; diff --git a/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js b/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js deleted file mode 100644 index b30b6d9e2..000000000 --- a/browser/components/preferences/in-content/tests/browser_defaultbrowser_alwayscheck.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; - -const CHECK_DEFAULT_INITIAL = Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"); - -add_task(function* clicking_make_default_checks_alwaysCheck_checkbox() { - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences"); - - yield test_with_mock_shellservice({isDefault: false}, function*() { - let setDefaultPane = content.document.getElementById("setDefaultPane"); - Assert.equal(setDefaultPane.selectedIndex, "0", - "The 'make default' pane should be visible when not default"); - let alwaysCheck = content.document.getElementById("alwaysCheckDefault"); - Assert.ok(!alwaysCheck.checked, "Always Check is unchecked by default"); - Assert.ok(!Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"), - "alwaysCheck pref should be false by default in test runs"); - - let setDefaultButton = content.document.getElementById("setDefaultButton"); - setDefaultButton.click(); - content.window.gMainPane.updateSetDefaultBrowser(); - - yield ContentTaskUtils.waitForCondition(() => alwaysCheck.checked, - "'Always Check' checkbox should get checked after clicking the 'Set Default' button"); - - Assert.ok(alwaysCheck.checked, - "Clicking 'Make Default' checks the 'Always Check' checkbox"); - Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"), - "Checking the checkbox should set the pref to true"); - Assert.ok(alwaysCheck.disabled, - "'Always Check' checkbox is locked with default browser and alwaysCheck=true"); - Assert.equal(setDefaultPane.selectedIndex, "1", - "The 'make default' pane should not be visible when default"); - Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"), - "checkDefaultBrowser pref is now enabled"); - }); - - gBrowser.removeCurrentTab(); - Services.prefs.clearUserPref("browser.shell.checkDefaultBrowser"); -}); - -add_task(function* clicking_make_default_checks_alwaysCheck_checkbox() { - Services.prefs.lockPref("browser.shell.checkDefaultBrowser"); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences"); - - yield test_with_mock_shellservice({isDefault: false}, function*() { - let setDefaultPane = content.document.getElementById("setDefaultPane"); - Assert.equal(setDefaultPane.selectedIndex, "0", - "The 'make default' pane should be visible when not default"); - let alwaysCheck = content.document.getElementById("alwaysCheckDefault"); - Assert.ok(alwaysCheck.disabled, "Always Check is disabled when locked"); - Assert.ok(alwaysCheck.checked, - "Always Check is checked because defaultPref is true and pref is locked"); - Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"), - "alwaysCheck pref should ship with 'true' by default"); - - let setDefaultButton = content.document.getElementById("setDefaultButton"); - setDefaultButton.click(); - content.window.gMainPane.updateSetDefaultBrowser(); - - yield ContentTaskUtils.waitForCondition(() => setDefaultPane.selectedIndex == "1", - "Browser is now default"); - - Assert.ok(alwaysCheck.checked, - "'Always Check' is still checked because it's locked"); - Assert.ok(alwaysCheck.disabled, - "'Always Check is disabled because it's locked"); - Assert.ok(Services.prefs.getBoolPref("browser.shell.checkDefaultBrowser"), - "The pref is locked and so doesn't get changed"); - }); - - Services.prefs.unlockPref("browser.shell.checkDefaultBrowser"); - gBrowser.removeCurrentTab(); -}); - -registerCleanupFunction(function() { - Services.prefs.unlockPref("browser.shell.checkDefaultBrowser"); - Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", CHECK_DEFAULT_INITIAL); -}); - -function* test_with_mock_shellservice(options, testFn) { - yield ContentTask.spawn(gBrowser.selectedBrowser, options, function*(options) { - let doc = content.document; - let win = doc.defaultView; - win.oldShellService = win.getShellService(); - let mockShellService = { - _isDefault: false, - isDefaultBrowser() { - return this._isDefault; - }, - setDefaultBrowser() { - this._isDefault = true; - }, - }; - win.getShellService = function() { - return mockShellService; - } - mockShellService._isDefault = options.isDefault; - win.gMainPane.updateSetDefaultBrowser(); - }); - - yield ContentTask.spawn(gBrowser.selectedBrowser, null, testFn); - - Services.prefs.setBoolPref("browser.shell.checkDefaultBrowser", CHECK_DEFAULT_INITIAL); -} diff --git a/browser/components/preferences/in-content/tests/browser_healthreport.js b/browser/components/preferences/in-content/tests/browser_healthreport.js deleted file mode 100644 index bbfae9707..000000000 --- a/browser/components/preferences/in-content/tests/browser_healthreport.js +++ /dev/null @@ -1,62 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. -* http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const FHR_UPLOAD_ENABLED = "datareporting.healthreport.uploadEnabled"; - -function runPaneTest(fn) { - open_preferences((win) => { - let doc = win.document; - win.gotoPref("paneAdvanced"); - let advancedPrefs = doc.getElementById("advancedPrefs"); - let tab = doc.getElementById("dataChoicesTab"); - advancedPrefs.selectedTab = tab; - fn(win, doc); - }); -} - -function test() { - waitForExplicitFinish(); - resetPreferences(); - registerCleanupFunction(resetPreferences); - runPaneTest(testBasic); -} - -function testBasic(win, doc) { - is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), true, - "Health Report upload enabled on app first run."); - - let checkbox = doc.getElementById("submitHealthReportBox"); - ok(checkbox); - is(checkbox.checked, true, "Health Report checkbox is checked on app first run."); - - checkbox.checked = false; - checkbox.doCommand(); - is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), false, - "Unchecking checkbox opts out of FHR upload."); - - checkbox.checked = true; - checkbox.doCommand(); - is(Services.prefs.getBoolPref(FHR_UPLOAD_ENABLED), true, - "Checking checkbox allows FHR upload."); - - win.close(); - Services.prefs.lockPref(FHR_UPLOAD_ENABLED); - runPaneTest(testUploadDisabled); -} - -function testUploadDisabled(win, doc) { - ok(Services.prefs.prefIsLocked(FHR_UPLOAD_ENABLED), "Upload enabled flag is locked."); - let checkbox = doc.getElementById("submitHealthReportBox"); - is(checkbox.getAttribute("disabled"), "true", "Checkbox is disabled if upload flag is locked."); - Services.prefs.unlockPref(FHR_UPLOAD_ENABLED); - - win.close(); - finish(); -} - -function resetPreferences() { - Services.prefs.clearUserPref(FHR_UPLOAD_ENABLED); -} - diff --git a/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js b/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js deleted file mode 100644 index 366454fcc..000000000 --- a/browser/components/preferences/in-content/tests/browser_homepages_filter_aboutpreferences.js +++ /dev/null @@ -1,20 +0,0 @@ -add_task(function*() { - is(gBrowser.currentURI.spec, "about:blank", "Test starts with about:blank open"); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:home"); - yield openPreferencesViaOpenPreferencesAPI("paneGeneral", null, {leaveOpen: true}); - let doc = gBrowser.contentDocument; - is(gBrowser.currentURI.spec, "about:preferences#general", - "#general should be in the URI for about:preferences"); - let oldHomepagePref = Services.prefs.getCharPref("browser.startup.homepage"); - - let useCurrent = doc.getElementById("useCurrent"); - useCurrent.click(); - - is(gBrowser.tabs.length, 3, "Three tabs should be open"); - is(Services.prefs.getCharPref("browser.startup.homepage"), "about:blank|about:home", - "about:blank and about:home should be the only homepages set"); - - Services.prefs.setCharPref("browser.startup.homepage", oldHomepagePref); - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); -}); diff --git a/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js b/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js deleted file mode 100644 index 68f9653f6..000000000 --- a/browser/components/preferences/in-content/tests/browser_notifications_do_not_disturb.js +++ /dev/null @@ -1,44 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - - -registerCleanupFunction(function() { - while (gBrowser.tabs[1]) - gBrowser.removeTab(gBrowser.tabs[1]); -}); - -add_task(function*() { - let prefs = yield openPreferencesViaOpenPreferencesAPI("paneContent", undefined, {leaveOpen: true}); - is(prefs.selectedPane, "paneContent", "Content pane was selected"); - - let doc = gBrowser.contentDocument; - let notificationsDoNotDisturbRow = doc.getElementById("notificationsDoNotDisturbRow"); - if (notificationsDoNotDisturbRow.hidden) { - todo(false, "Do not disturb is not available on this platform"); - return; - } - - let alertService; - try { - alertService = Cc["@mozilla.org/alerts-service;1"] - .getService(Ci.nsIAlertsService) - .QueryInterface(Ci.nsIAlertsDoNotDisturb); - } catch (ex) { - ok(true, "Do not disturb is not available on this platform: " + ex.message); - return; - } - - let checkbox = doc.getElementById("notificationsDoNotDisturb"); - ok(!checkbox.checked, "Checkbox should not be checked by default"); - ok(!alertService.manualDoNotDisturb, "Do not disturb should be off by default"); - - let checkboxChanged = waitForEvent(checkbox, "command") - checkbox.click(); - yield checkboxChanged; - ok(alertService.manualDoNotDisturb, "Do not disturb should be enabled when checked"); - - checkboxChanged = waitForEvent(checkbox, "command") - checkbox.click(); - yield checkboxChanged; - ok(!alertService.manualDoNotDisturb, "Do not disturb should be disabled when unchecked"); -}); diff --git a/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js b/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js deleted file mode 100644 index d9253735a..000000000 --- a/browser/components/preferences/in-content/tests/browser_permissions_urlFieldHidden.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -const PERMISSIONS_URL = "chrome://browser/content/preferences/permissions.xul"; - -add_task(function* urlFieldVisibleForPopupPermissions(finish) { - yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true}); - let win = gBrowser.selectedBrowser.contentWindow; - let doc = win.document; - let popupPolicyCheckbox = doc.getElementById("popupPolicy"); - ok(!popupPolicyCheckbox.checked, "popupPolicyCheckbox should be unchecked by default"); - popupPolicyCheckbox.click(); - let popupPolicyButton = doc.getElementById("popupPolicyButton"); - ok(popupPolicyButton, "popupPolicyButton found"); - let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL); - popupPolicyButton.click(); - let dialog = yield dialogPromise; - ok(dialog, "dialog loaded"); - - let urlLabel = dialog.document.getElementById("urlLabel"); - ok(!urlLabel.hidden, "urlLabel should be visible when one of block/session/allow visible"); - let url = dialog.document.getElementById("url"); - ok(!url.hidden, "url should be visible when one of block/session/allow visible"); - - popupPolicyCheckbox.click(); - gBrowser.removeCurrentTab(); -}); - -add_task(function* urlFieldHiddenForNotificationPermissions() { - yield openPreferencesViaOpenPreferencesAPI("paneContent", null, {leaveOpen: true}); - let win = gBrowser.selectedBrowser.contentWindow; - let doc = win.document; - let notificationsPolicyButton = doc.getElementById("notificationsPolicyButton"); - ok(notificationsPolicyButton, "notificationsPolicyButton found"); - let dialogPromise = promiseLoadSubDialog(PERMISSIONS_URL); - notificationsPolicyButton.click(); - let dialog = yield dialogPromise; - ok(dialog, "dialog loaded"); - - let urlLabel = dialog.document.getElementById("urlLabel"); - ok(urlLabel.hidden, "urlLabel should be hidden as requested"); - let url = dialog.document.getElementById("url"); - ok(url.hidden, "url should be hidden as requested"); - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_1.js b/browser/components/preferences/in-content/tests/browser_privacypane_1.js deleted file mode 100644 index 0df60c6ac..000000000 --- a/browser/components/preferences/in-content/tests/browser_privacypane_1.js +++ /dev/null @@ -1,18 +0,0 @@ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); - -let rootDir = getRootDirectory(gTestPath); -let jar = getJar(rootDir); -if (jar) { - let tmpdir = extractJarToTmp(jar); - rootDir = "file://" + tmpdir.path + '/'; -} -loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this); - -run_test_subset([ - test_pane_visibility, - test_dependent_elements, - test_dependent_cookie_elements, - test_dependent_clearonclose_elements, - test_dependent_prefs, -]); diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_3.js b/browser/components/preferences/in-content/tests/browser_privacypane_3.js deleted file mode 100644 index 8fe6f0825..000000000 --- a/browser/components/preferences/in-content/tests/browser_privacypane_3.js +++ /dev/null @@ -1,17 +0,0 @@ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -let rootDir = getRootDirectory(gTestPath); -let jar = getJar(rootDir); -if (jar) { - let tmpdir = extractJarToTmp(jar); - rootDir = "file://" + tmpdir.path + '/'; -} -loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this); - -run_test_subset([ - test_custom_retention("rememberHistory", "remember"), - test_custom_retention("rememberHistory", "custom"), - test_custom_retention("rememberForms", "remember"), - test_custom_retention("rememberForms", "custom"), - test_historymode_retention("remember", "remember"), -]); diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_4.js b/browser/components/preferences/in-content/tests/browser_privacypane_4.js deleted file mode 100644 index b7ef3deda..000000000 --- a/browser/components/preferences/in-content/tests/browser_privacypane_4.js +++ /dev/null @@ -1,25 +0,0 @@ -requestLongerTimeout(2); - -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -let rootDir = getRootDirectory(gTestPath); -let jar = getJar(rootDir); -if (jar) { - let tmpdir = extractJarToTmp(jar); - rootDir = "file://" + tmpdir.path + '/'; -} -loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this); -let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime); - -run_test_subset([ - test_custom_retention("acceptCookies", "remember"), - test_custom_retention("acceptCookies", "custom"), - test_custom_retention("acceptThirdPartyMenu", "remember", "visited"), - test_custom_retention("acceptThirdPartyMenu", "custom", "always"), - test_custom_retention("keepCookiesUntil", "remember", 1), - test_custom_retention("keepCookiesUntil", "custom", 2), - test_custom_retention("keepCookiesUntil", "custom", 0), - test_custom_retention("alwaysClear", "remember"), - test_custom_retention("alwaysClear", "custom"), - test_historymode_retention("remember", "remember"), -]); diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_5.js b/browser/components/preferences/in-content/tests/browser_privacypane_5.js deleted file mode 100644 index a07530010..000000000 --- a/browser/components/preferences/in-content/tests/browser_privacypane_5.js +++ /dev/null @@ -1,17 +0,0 @@ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -let rootDir = getRootDirectory(gTestPath); -let jar = getJar(rootDir); -if (jar) { - let tmpdir = extractJarToTmp(jar); - rootDir = "file://" + tmpdir.path + '/'; -} -loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this); - -run_test_subset([ - test_locbar_suggestion_retention("history", true), - test_locbar_suggestion_retention("bookmark", true), - test_locbar_suggestion_retention("openpage", false), - test_locbar_suggestion_retention("history", true), - test_locbar_suggestion_retention("history", false), -]); diff --git a/browser/components/preferences/in-content/tests/browser_privacypane_8.js b/browser/components/preferences/in-content/tests/browser_privacypane_8.js deleted file mode 100644 index 756b19a2f..000000000 --- a/browser/components/preferences/in-content/tests/browser_privacypane_8.js +++ /dev/null @@ -1,26 +0,0 @@ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -let rootDir = getRootDirectory(gTestPath); -let jar = getJar(rootDir); -if (jar) { - let tmpdir = extractJarToTmp(jar); - rootDir = "file://" + tmpdir.path + '/'; -} -loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this); - -run_test_subset([ - // history mode should be initialized to remember - test_historymode_retention("remember", undefined), - - // history mode should remain remember; toggle acceptCookies checkbox - test_custom_retention("acceptCookies", "remember"), - - // history mode should now be custom; set history mode to dontremember - test_historymode_retention("dontremember", "custom"), - - // history mode should remain custom; set history mode to remember - test_historymode_retention("remember", "custom"), - - // history mode should now be remember - test_historymode_retention("remember", "remember"), -]); diff --git a/browser/components/preferences/in-content/tests/browser_proxy_backup.js b/browser/components/preferences/in-content/tests/browser_proxy_backup.js deleted file mode 100644 index 3ad24c7ec..000000000 --- a/browser/components/preferences/in-content/tests/browser_proxy_backup.js +++ /dev/null @@ -1,65 +0,0 @@ -/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ -/* 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/. */ - -Components.utils.import("resource://gre/modules/Services.jsm"); -Components.utils.import("resource://gre/modules/Task.jsm"); - -function test() { - waitForExplicitFinish(); - - // network.proxy.type needs to be backed up and restored because mochitest - // changes this setting from the default - let oldNetworkProxyType = Services.prefs.getIntPref("network.proxy.type"); - registerCleanupFunction(function() { - Services.prefs.setIntPref("network.proxy.type", oldNetworkProxyType); - Services.prefs.clearUserPref("browser.preferences.instantApply"); - Services.prefs.clearUserPref("network.proxy.share_proxy_settings"); - for (let proxyType of ["http", "ssl", "ftp", "socks"]) { - Services.prefs.clearUserPref("network.proxy." + proxyType); - Services.prefs.clearUserPref("network.proxy." + proxyType + "_port"); - if (proxyType == "http") { - continue; - } - Services.prefs.clearUserPref("network.proxy.backup." + proxyType); - Services.prefs.clearUserPref("network.proxy.backup." + proxyType + "_port"); - } - }); - - let connectionURL = "chrome://browser/content/preferences/connection.xul"; - - // Set a shared proxy and a SOCKS backup - Services.prefs.setIntPref("network.proxy.type", 1); - Services.prefs.setBoolPref("network.proxy.share_proxy_settings", true); - Services.prefs.setCharPref("network.proxy.http", "example.com"); - Services.prefs.setIntPref("network.proxy.http_port", 1200); - Services.prefs.setCharPref("network.proxy.socks", "example.com"); - Services.prefs.setIntPref("network.proxy.socks_port", 1200); - Services.prefs.setCharPref("network.proxy.backup.socks", "127.0.0.1"); - Services.prefs.setIntPref("network.proxy.backup.socks_port", 9050); - - /* - The connection dialog alone won't save onaccept since it uses type="child", - so it has to be opened as a sub dialog of the main pref tab. - Open the main tab here. - */ - open_preferences(Task.async(function* tabOpened(aContentWindow) { - is(gBrowser.currentURI.spec, "about:preferences", "about:preferences loaded"); - let dialog = yield openAndLoadSubDialog(connectionURL); - let dialogClosingPromise = waitForEvent(dialog.document.documentElement, "dialogclosing"); - - ok(dialog, "connection window opened"); - dialog.document.documentElement.acceptDialog(); - - let dialogClosingEvent = yield dialogClosingPromise; - ok(dialogClosingEvent, "connection window closed"); - - // The SOCKS backup should not be replaced by the shared value - is(Services.prefs.getCharPref("network.proxy.backup.socks"), "127.0.0.1", "Shared proxy backup shouldn't be replaced"); - is(Services.prefs.getIntPref("network.proxy.backup.socks_port"), 9050, "Shared proxy port backup shouldn't be replaced"); - - gBrowser.removeCurrentTab(); - finish(); - })); -} diff --git a/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js b/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js deleted file mode 100644 index 6b587e036..000000000 --- a/browser/components/preferences/in-content/tests/browser_sanitizeOnShutdown_prefLocked.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; - -function switchToCustomHistoryMode(doc) { - // Select the last item in the menulist. - let menulist = doc.getElementById("historyMode"); - menulist.focus(); - EventUtils.sendKey("UP"); -} - -function testPrefStateMatchesLockedState() { - let win = gBrowser.contentWindow; - let doc = win.document; - switchToCustomHistoryMode(doc); - - let checkbox = doc.getElementById("alwaysClear"); - let preference = doc.getElementById("privacy.sanitize.sanitizeOnShutdown"); - is(checkbox.disabled, preference.locked, "Always Clear checkbox should be enabled when preference is not locked."); - - gBrowser.removeCurrentTab(); -} - -add_task(function setup() { - registerCleanupFunction(function resetPreferences() { - Services.prefs.unlockPref("privacy.sanitize.sanitizeOnShutdown"); - }); -}); - -add_task(function* test_preference_enabled_when_unlocked() { - yield openPreferencesViaOpenPreferencesAPI("panePrivacy", undefined, {leaveOpen: true}); - testPrefStateMatchesLockedState(); -}); - -add_task(function* test_preference_disabled_when_locked() { - Services.prefs.lockPref("privacy.sanitize.sanitizeOnShutdown"); - yield openPreferencesViaOpenPreferencesAPI("panePrivacy", undefined, {leaveOpen: true}); - testPrefStateMatchesLockedState(); -}); diff --git a/browser/components/preferences/in-content/tests/browser_searchsuggestions.js b/browser/components/preferences/in-content/tests/browser_searchsuggestions.js deleted file mode 100644 index 0185a23b9..000000000 --- a/browser/components/preferences/in-content/tests/browser_searchsuggestions.js +++ /dev/null @@ -1,43 +0,0 @@ -var original = Services.prefs.getBoolPref("browser.search.suggest.enabled"); - -registerCleanupFunction(() => { - Services.prefs.setBoolPref("browser.search.suggest.enabled", original); -}); - -// Open with suggestions enabled -add_task(function*() { - Services.prefs.setBoolPref("browser.search.suggest.enabled", true); - - yield openPreferencesViaOpenPreferencesAPI("search", undefined, { leaveOpen: true }); - - let doc = gBrowser.selectedBrowser.contentDocument; - let urlbarBox = doc.getElementById("urlBarSuggestion"); - ok(!urlbarBox.disabled, "Checkbox should be enabled"); - - Services.prefs.setBoolPref("browser.search.suggest.enabled", false); - - ok(urlbarBox.disabled, "Checkbox should be disabled"); - - gBrowser.removeCurrentTab(); -}); - -// Open with suggestions disabled -add_task(function*() { - Services.prefs.setBoolPref("browser.search.suggest.enabled", false); - - yield openPreferencesViaOpenPreferencesAPI("search", undefined, { leaveOpen: true }); - - let doc = gBrowser.selectedBrowser.contentDocument; - let urlbarBox = doc.getElementById("urlBarSuggestion"); - ok(urlbarBox.disabled, "Checkbox should be disabled"); - - Services.prefs.setBoolPref("browser.search.suggest.enabled", true); - - ok(!urlbarBox.disabled, "Checkbox should be enabled"); - - gBrowser.removeCurrentTab(); -}); - -add_task(function*() { - Services.prefs.setBoolPref("browser.search.suggest.enabled", original); -}); diff --git a/browser/components/preferences/in-content/tests/browser_security.js b/browser/components/preferences/in-content/tests/browser_security.js deleted file mode 100644 index e6eb2a91d..000000000 --- a/browser/components/preferences/in-content/tests/browser_security.js +++ /dev/null @@ -1,130 +0,0 @@ -const PREFS = [ - "browser.safebrowsing.phishing.enabled", - "browser.safebrowsing.malware.enabled", - - "browser.safebrowsing.downloads.enabled", - - "browser.safebrowsing.downloads.remote.block_potentially_unwanted", - "browser.safebrowsing.downloads.remote.block_uncommon" -]; - -let originals = PREFS.map(pref => [pref, Services.prefs.getBoolPref(pref)]) -let originalMalwareTable = Services.prefs.getCharPref("urlclassifier.malwareTable"); -registerCleanupFunction(function() { - originals.forEach(([pref, val]) => Services.prefs.setBoolPref(pref, val)) - Services.prefs.setCharPref("urlclassifier.malwareTable", originalMalwareTable); -}); - -// test the safebrowsing preference -add_task(function*() { - function* checkPrefSwitch(val1, val2) { - Services.prefs.setBoolPref("browser.safebrowsing.phishing.enabled", val1); - Services.prefs.setBoolPref("browser.safebrowsing.malware.enabled", val2); - - yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true }); - - let doc = gBrowser.selectedBrowser.contentDocument; - let checkbox = doc.getElementById("enableSafeBrowsing"); - let blockDownloads = doc.getElementById("blockDownloads"); - let blockUncommon = doc.getElementById("blockUncommonUnwanted"); - let checked = checkbox.checked; - is(checked, val1 && val2, "safebrowsing preference is initialized correctly"); - // should be disabled when checked is false (= pref is turned off) - is(blockDownloads.hasAttribute("disabled"), !checked, "block downloads checkbox is set correctly"); - is(blockUncommon.hasAttribute("disabled"), !checked, "block uncommon checkbox is set correctly"); - - // click the checkbox - EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow); - - // check that both settings are now turned on or off - is(Services.prefs.getBoolPref("browser.safebrowsing.phishing.enabled"), !checked, - "safebrowsing.enabled is set correctly"); - is(Services.prefs.getBoolPref("browser.safebrowsing.malware.enabled"), !checked, - "safebrowsing.malware.enabled is set correctly"); - - // check if the other checkboxes have updated - checked = checkbox.checked; - is(blockDownloads.hasAttribute("disabled"), !checked, "block downloads checkbox is set correctly"); - is(blockUncommon.hasAttribute("disabled"), !checked || !blockDownloads.checked, "block uncommon checkbox is set correctly"); - - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - } - - yield checkPrefSwitch(true, true); - yield checkPrefSwitch(false, true); - yield checkPrefSwitch(true, false); - yield checkPrefSwitch(false, false); -}); - -// test the download protection preference -add_task(function*() { - function* checkPrefSwitch(val) { - Services.prefs.setBoolPref("browser.safebrowsing.downloads.enabled", val); - - yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true }); - - let doc = gBrowser.selectedBrowser.contentDocument; - let checkbox = doc.getElementById("blockDownloads"); - let blockUncommon = doc.getElementById("blockUncommonUnwanted"); - let checked = checkbox.checked; - is(checked, val, "downloads preference is initialized correctly"); - // should be disabled when val is false (= pref is turned off) - is(blockUncommon.hasAttribute("disabled"), !val, "block uncommon checkbox is set correctly"); - - // click the checkbox - EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow); - - // check that setting is now turned on or off - is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.enabled"), !checked, - "safebrowsing.downloads preference is set correctly"); - - // check if the uncommon warning checkbox has updated - is(blockUncommon.hasAttribute("disabled"), val, "block uncommon checkbox is set correctly"); - - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - } - - yield checkPrefSwitch(true); - yield checkPrefSwitch(false); -}); - -// test the unwanted/uncommon software warning preference -add_task(function*() { - function* checkPrefSwitch(val1, val2) { - Services.prefs.setBoolPref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", val1); - Services.prefs.setBoolPref("browser.safebrowsing.downloads.remote.block_uncommon", val2); - - yield openPreferencesViaOpenPreferencesAPI("security", undefined, { leaveOpen: true }); - - let doc = gBrowser.selectedBrowser.contentDocument; - let checkbox = doc.getElementById("blockUncommonUnwanted"); - let checked = checkbox.checked; - is(checked, val1 && val2, "unwanted/uncommon preference is initialized correctly"); - - // click the checkbox - EventUtils.synthesizeMouseAtCenter(checkbox, {}, gBrowser.selectedBrowser.contentWindow); - - // check that both settings are now turned on or off - is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.remote.block_potentially_unwanted"), !checked, - "block_potentially_unwanted is set correctly"); - is(Services.prefs.getBoolPref("browser.safebrowsing.downloads.remote.block_uncommon"), !checked, - "block_uncommon is set correctly"); - - // when the preference is on, the malware table should include these ids - let malwareTable = Services.prefs.getCharPref("urlclassifier.malwareTable").split(","); - is(malwareTable.includes("goog-unwanted-shavar"), !checked, - "malware table doesn't include goog-unwanted-shavar"); - is(malwareTable.includes("test-unwanted-simple"), !checked, - "malware table doesn't include test-unwanted-simple"); - let sortedMalware = malwareTable.slice(0); - sortedMalware.sort(); - Assert.deepEqual(malwareTable, sortedMalware, "malware table has been sorted"); - - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); - } - - yield* checkPrefSwitch(true, true); - yield* checkPrefSwitch(false, true); - yield* checkPrefSwitch(true, false); - yield* checkPrefSwitch(false, false); -}); diff --git a/browser/components/preferences/in-content/tests/browser_subdialogs.js b/browser/components/preferences/in-content/tests/browser_subdialogs.js deleted file mode 100644 index ff0c1f8ae..000000000 --- a/browser/components/preferences/in-content/tests/browser_subdialogs.js +++ /dev/null @@ -1,293 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. -* http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * Tests for the sub-dialog infrastructure, not for actual sub-dialog functionality. - */ - -const gDialogURL = getRootDirectory(gTestPath) + "subdialog.xul"; -const gDialogURL2 = getRootDirectory(gTestPath) + "subdialog2.xul"; - -function* open_subdialog_and_test_generic_start_state(browser, domcontentloadedFn, url = gDialogURL) { - let domcontentloadedFnStr = domcontentloadedFn ? - "(" + domcontentloadedFn.toString() + ")()" : - ""; - return ContentTask.spawn(browser, {url, domcontentloadedFnStr}, function*(args) { - let {url, domcontentloadedFnStr} = args; - let rv = { acceptCount: 0 }; - let win = content.window; - let subdialog = win.gSubDialog; - subdialog.open(url, null, rv); - - info("waiting for subdialog DOMFrameContentLoaded"); - yield ContentTaskUtils.waitForEvent(win, "DOMFrameContentLoaded", true); - let result; - if (domcontentloadedFnStr) { - result = eval(domcontentloadedFnStr); - } - - info("waiting for subdialog load"); - yield ContentTaskUtils.waitForEvent(subdialog._frame, "load"); - info("subdialog window is loaded"); - - let expectedStyleSheetURLs = subdialog._injectedStyleSheets.slice(0); - for (let styleSheet of subdialog._frame.contentDocument.styleSheets) { - let index = expectedStyleSheetURLs.indexOf(styleSheet.href); - if (index >= 0) { - expectedStyleSheetURLs.splice(index, 1); - } - } - - Assert.ok(!!subdialog._frame.contentWindow, "The dialog should be non-null"); - Assert.notEqual(subdialog._frame.contentWindow.location.toString(), "about:blank", - "Subdialog URL should not be about:blank"); - Assert.equal(win.getComputedStyle(subdialog._overlay, "").visibility, "visible", - "Overlay should be visible"); - Assert.equal(expectedStyleSheetURLs.length, 0, - "No stylesheets that were expected are missing"); - return result; - }); -} - -function* close_subdialog_and_test_generic_end_state(browser, closingFn, closingButton, acceptCount, options) { - let dialogclosingPromise = ContentTask.spawn(browser, {closingButton, acceptCount}, function*(expectations) { - let win = content.window; - let subdialog = win.gSubDialog; - let frame = subdialog._frame; - info("waiting for dialogclosing"); - let closingEvent = - yield ContentTaskUtils.waitForEvent(frame.contentWindow, "dialogclosing"); - let closingButton = closingEvent.detail.button; - let actualAcceptCount = frame.contentWindow.arguments && - frame.contentWindow.arguments[0].acceptCount; - - info("waiting for about:blank load"); - yield ContentTaskUtils.waitForEvent(frame, "load"); - - Assert.notEqual(win.getComputedStyle(subdialog._overlay, "").visibility, "visible", - "overlay is not visible"); - Assert.equal(frame.getAttribute("style"), "", "inline styles should be cleared"); - Assert.equal(frame.contentWindow.location.href.toString(), "about:blank", - "sub-dialog should be unloaded"); - Assert.equal(closingButton, expectations.closingButton, - "closing event should indicate button was '" + expectations.closingButton + "'"); - Assert.equal(actualAcceptCount, expectations.acceptCount, - "should be 1 if accepted, 0 if canceled, undefined if closed w/out button"); - }); - - if (options && options.runClosingFnOutsideOfContentTask) { - yield closingFn(); - } else { - ContentTask.spawn(browser, null, closingFn); - } - - yield dialogclosingPromise; -} - -let tab; - -add_task(function* test_initialize() { - tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences"); -}); - -add_task(function* check_titlebar_focus_returnval_titlechanges_accepting() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - let domtitlechangedPromise = BrowserTestUtils.waitForEvent(tab.linkedBrowser, "DOMTitleChanged"); - yield ContentTask.spawn(tab.linkedBrowser, null, function*() { - let dialog = content.window.gSubDialog._frame.contentWindow; - let dialogTitleElement = content.document.getElementById("dialogTitle"); - Assert.equal(dialogTitleElement.textContent, "Sample sub-dialog", - "Title should be correct initially"); - Assert.equal(dialog.document.activeElement.value, "Default text", - "Textbox with correct text is focused"); - dialog.document.title = "Updated title"; - }); - - info("waiting for DOMTitleChanged event"); - yield domtitlechangedPromise; - - ContentTask.spawn(tab.linkedBrowser, null, function*() { - let dialogTitleElement = content.document.getElementById("dialogTitle"); - Assert.equal(dialogTitleElement.textContent, "Updated title", - "subdialog should have updated title"); - }); - - // Accept the dialog - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); }, - "accept", 1); -}); - -add_task(function* check_canceling_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentDocument.documentElement.cancelDialog(); }, - "cancel", 0); -}); - -add_task(function* check_reopening_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - info("opening another dialog which will close the first"); - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, "", gDialogURL2); - info("closing as normal"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); }, - "accept", 1); -}); - -add_task(function* check_opening_while_closing() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - info("closing"); - content.window.gSubDialog.close(); - info("reopening immediately after calling .close()"); - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentDocument.documentElement.acceptDialog(); }, - "accept", 1); - -}); - -add_task(function* window_close_on_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentWindow.window.close(); }, - null, 0); -}); - -add_task(function* click_close_button_on_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { return BrowserTestUtils.synthesizeMouseAtCenter("#dialogClose", {}, tab.linkedBrowser); }, - null, 0, {runClosingFnOutsideOfContentTask: true}); -}); - -add_task(function* back_navigation_on_subdialog_should_close_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.goBack(); }, - null, undefined); -}); - -add_task(function* back_navigation_on_browser_tab_should_close_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { tab.linkedBrowser.goBack(); }, - null, undefined, {runClosingFnOutsideOfContentTask: true}); -}); - -add_task(function* escape_should_close_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - info("canceling the dialog"); - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { return BrowserTestUtils.synthesizeKey("VK_ESCAPE", {}, tab.linkedBrowser); }, - "cancel", 0, {runClosingFnOutsideOfContentTask: true}); -}); - -add_task(function* correct_width_and_height_should_be_used_for_dialog() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser); - - yield ContentTask.spawn(tab.linkedBrowser, null, function*() { - let frameStyle = content.window.gSubDialog._frame.style; - Assert.equal(frameStyle.width, "32em", - "Width should be set on the frame from the dialog"); - Assert.equal(frameStyle.height, "5em", - "Height should be set on the frame from the dialog"); - }); - - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentWindow.window.close(); }, - null, 0); -}); - -add_task(function* wrapped_text_in_dialog_should_have_expected_scrollHeight() { - let oldHeight = yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() { - let frame = content.window.gSubDialog._frame; - let doc = frame.contentDocument; - let oldHeight = doc.documentElement.scrollHeight; - doc.documentElement.style.removeProperty("height"); - doc.getElementById("desc").textContent = ` - Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque - laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi - architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas - sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione - laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi - architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas - sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione - laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi - architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas - sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione - voluptatem sequi nesciunt.` - return oldHeight; - }); - - yield ContentTask.spawn(tab.linkedBrowser, oldHeight, function*(oldHeight) { - let frame = content.window.gSubDialog._frame; - let docEl = frame.contentDocument.documentElement; - Assert.equal(frame.style.width, "32em", - "Width should be set on the frame from the dialog"); - Assert.ok(docEl.scrollHeight > oldHeight, - "Content height increased (from " + oldHeight + " to " + docEl.scrollHeight + ")."); - Assert.equal(frame.style.height, docEl.scrollHeight + "px", - "Height on the frame should be higher now"); - }); - - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentWindow.window.close(); }, - null, 0); -}); - -add_task(function* dialog_too_tall_should_get_reduced_in_height() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() { - let frame = content.window.gSubDialog._frame; - frame.contentDocument.documentElement.style.height = '100000px'; - }); - - yield ContentTask.spawn(tab.linkedBrowser, null, function*() { - let frame = content.window.gSubDialog._frame; - Assert.equal(frame.style.width, "32em", "Width should be set on the frame from the dialog"); - Assert.ok(parseInt(frame.style.height, 10) < content.window.innerHeight, - "Height on the frame should be smaller than window's innerHeight"); - }); - - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentWindow.window.close(); }, - null, 0); -}); - -add_task(function* scrollWidth_and_scrollHeight_from_subdialog_should_size_the_browser() { - yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() { - let frame = content.window.gSubDialog._frame; - frame.contentDocument.documentElement.style.removeProperty("height"); - frame.contentDocument.documentElement.style.removeProperty("width"); - }); - - yield ContentTask.spawn(tab.linkedBrowser, null, function*() { - let frame = content.window.gSubDialog._frame; - Assert.ok(frame.style.width.endsWith("px"), - "Width (" + frame.style.width + ") should be set to a px value of the scrollWidth from the dialog"); - Assert.ok(frame.style.height.endsWith("px"), - "Height (" + frame.style.height + ") should be set to a px value of the scrollHeight from the dialog"); - }); - - yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser, - function() { content.window.gSubDialog._frame.contentWindow.window.close(); }, - null, 0); -}); - -add_task(function* test_shutdown() { - gBrowser.removeTab(tab); -}); diff --git a/browser/components/preferences/in-content/tests/browser_telemetry.js b/browser/components/preferences/in-content/tests/browser_telemetry.js deleted file mode 100644 index d8139d87a..000000000 --- a/browser/components/preferences/in-content/tests/browser_telemetry.js +++ /dev/null @@ -1,52 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. -* http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const PREF_TELEMETRY_ENABLED = "toolkit.telemetry.enabled"; - -function runPaneTest(fn) { - open_preferences((win) => { - let doc = win.document; - win.gotoPref("paneAdvanced"); - let advancedPrefs = doc.getElementById("advancedPrefs"); - let tab = doc.getElementById("dataChoicesTab"); - advancedPrefs.selectedTab = tab; - fn(win, doc); - }); -} - -function test() { - waitForExplicitFinish(); - resetPreferences(); - registerCleanupFunction(resetPreferences); - runPaneTest(testTelemetryState); -} - -function testTelemetryState(win, doc) { - let fhrCheckbox = doc.getElementById("submitHealthReportBox"); - Assert.ok(fhrCheckbox.checked, "Health Report checkbox is checked on app first run."); - - let telmetryCheckbox = doc.getElementById("submitTelemetryBox"); - Assert.ok(!telmetryCheckbox.disabled, - "Telemetry checkbox must be enabled if FHR is checked."); - Assert.ok(Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED), - "Telemetry must be enabled if the checkbox is ticked."); - - // Uncheck the FHR checkbox and make sure that Telemetry checkbox gets disabled. - fhrCheckbox.click(); - - Assert.ok(telmetryCheckbox.disabled, - "Telemetry checkbox must be disabled if FHR is unchecked."); - Assert.ok(!Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED), - "Telemetry must be disabled if the checkbox is unticked."); - - win.close(); - finish(); -} - -function resetPreferences() { - Services.prefs.clearUserPref("datareporting.healthreport.uploadEnabled"); - Services.prefs.clearUserPref(PREF_TELEMETRY_ENABLED); -} - diff --git a/browser/components/preferences/in-content/tests/head.js b/browser/components/preferences/in-content/tests/head.js deleted file mode 100644 index 0ed811e94..000000000 --- a/browser/components/preferences/in-content/tests/head.js +++ /dev/null @@ -1,165 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Components.utils.import("resource://gre/modules/Promise.jsm"); - -const kDefaultWait = 2000; - -function is_hidden(aElement) { - var style = aElement.ownerGlobal.getComputedStyle(aElement); - if (style.display == "none") - return true; - if (style.visibility != "visible") - return true; - - // Hiding a parent element will hide all its children - if (aElement.parentNode != aElement.ownerDocument) - return is_hidden(aElement.parentNode); - - return false; -} - -function is_element_visible(aElement, aMsg) { - isnot(aElement, null, "Element should not be null, when checking visibility"); - ok(!is_hidden(aElement), aMsg); -} - -function is_element_hidden(aElement, aMsg) { - isnot(aElement, null, "Element should not be null, when checking visibility"); - ok(is_hidden(aElement), aMsg); -} - -function open_preferences(aCallback) { - gBrowser.selectedTab = gBrowser.addTab("about:preferences"); - let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab); - newTabBrowser.addEventListener("Initialized", function () { - newTabBrowser.removeEventListener("Initialized", arguments.callee, true); - aCallback(gBrowser.contentWindow); - }, true); -} - -function openAndLoadSubDialog(aURL, aFeatures = null, aParams = null, aClosingCallback = null) { - let promise = promiseLoadSubDialog(aURL); - content.gSubDialog.open(aURL, aFeatures, aParams, aClosingCallback); - return promise; -} - -function promiseLoadSubDialog(aURL) { - return new Promise((resolve, reject) => { - content.gSubDialog._frame.addEventListener("load", function load(aEvent) { - if (aEvent.target.contentWindow.location == "about:blank") - return; - content.gSubDialog._frame.removeEventListener("load", load); - - is(content.gSubDialog._frame.contentWindow.location.toString(), aURL, - "Check the proper URL is loaded"); - - // Check visibility - is_element_visible(content.gSubDialog._overlay, "Overlay is visible"); - - // Check that stylesheets were injected - let expectedStyleSheetURLs = content.gSubDialog._injectedStyleSheets.slice(0); - for (let styleSheet of content.gSubDialog._frame.contentDocument.styleSheets) { - let i = expectedStyleSheetURLs.indexOf(styleSheet.href); - if (i >= 0) { - info("found " + styleSheet.href); - expectedStyleSheetURLs.splice(i, 1); - } - } - is(expectedStyleSheetURLs.length, 0, "All expectedStyleSheetURLs should have been found"); - - resolve(content.gSubDialog._frame.contentWindow); - }); - }); -} - -/** - * Waits a specified number of miliseconds for a specified event to be - * fired on a specified element. - * - * Usage: - * let receivedEvent = waitForEvent(element, "eventName"); - * // Do some processing here that will cause the event to be fired - * // ... - * // Now yield until the Promise is fulfilled - * yield receivedEvent; - * if (receivedEvent && !(receivedEvent instanceof Error)) { - * receivedEvent.msg == "eventName"; - * // ... - * } - * - * @param aSubject the element that should receive the event - * @param aEventName the event to wait for - * @param aTimeoutMs the number of miliseconds to wait before giving up - * @returns a Promise that resolves to the received event, or to an Error - */ -function waitForEvent(aSubject, aEventName, aTimeoutMs, aTarget) { - let eventDeferred = Promise.defer(); - let timeoutMs = aTimeoutMs || kDefaultWait; - let stack = new Error().stack; - let timerID = setTimeout(function wfe_canceller() { - aSubject.removeEventListener(aEventName, listener); - eventDeferred.reject(new Error(aEventName + " event timeout at " + stack)); - }, timeoutMs); - - var listener = function (aEvent) { - if (aTarget && aTarget !== aEvent.target) - return; - - // stop the timeout clock and resume - clearTimeout(timerID); - eventDeferred.resolve(aEvent); - }; - - function cleanup(aEventOrError) { - // unhook listener in case of success or failure - aSubject.removeEventListener(aEventName, listener); - return aEventOrError; - } - aSubject.addEventListener(aEventName, listener, false); - return eventDeferred.promise.then(cleanup, cleanup); -} - -function openPreferencesViaOpenPreferencesAPI(aPane, aAdvancedTab, aOptions) { - let deferred = Promise.defer(); - gBrowser.selectedTab = gBrowser.addTab("about:blank"); - openPreferences(aPane, aAdvancedTab ? {advancedTab: aAdvancedTab} : undefined); - let newTabBrowser = gBrowser.selectedBrowser; - - newTabBrowser.addEventListener("Initialized", function PrefInit() { - newTabBrowser.removeEventListener("Initialized", PrefInit, true); - newTabBrowser.contentWindow.addEventListener("load", function prefLoad() { - newTabBrowser.contentWindow.removeEventListener("load", prefLoad); - let win = gBrowser.contentWindow; - let selectedPane = win.history.state; - let doc = win.document; - let selectedAdvancedTab = aAdvancedTab && doc.getElementById("advancedPrefs").selectedTab.id; - if (!aOptions || !aOptions.leaveOpen) - gBrowser.removeCurrentTab(); - deferred.resolve({selectedPane: selectedPane, selectedAdvancedTab: selectedAdvancedTab}); - }); - }, true); - - return deferred.promise; -} - -function waitForCondition(aConditionFn, aMaxTries=50, aCheckInterval=100) { - return new Promise((resolve, reject) => { - function tryNow() { - tries++; - let rv = aConditionFn(); - if (rv) { - resolve(rv); - } else if (tries < aMaxTries) { - tryAgain(); - } else { - reject("Condition timed out: " + aConditionFn.toSource()); - } - } - function tryAgain() { - setTimeout(tryNow, aCheckInterval); - } - let tries = 0; - tryAgain(); - }); -} diff --git a/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js b/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js deleted file mode 100644 index 53c6d7d8a..000000000 --- a/browser/components/preferences/in-content/tests/privacypane_tests_perwindow.js +++ /dev/null @@ -1,330 +0,0 @@ -function* runTestOnPrivacyPrefPane(testFunc) { - info("runTestOnPrivacyPrefPane entered"); - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:preferences", true, true); - let browser = tab.linkedBrowser; - info("loaded about:preferences"); - browser.contentWindow.gotoPref("panePrivacy"); - info("viewing privacy pane, executing testFunc"); - testFunc(browser.contentWindow); - yield BrowserTestUtils.removeTab(tab); -} - -function controlChanged(element) { - element.doCommand(); -} - -// We can only test the panes that don't trigger a preference update -function test_pane_visibility(win) { - let modes = { - "remember": "historyRememberPane", - "custom": "historyCustomPane" - }; - - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - let historypane = win.document.getElementById("historyPane"); - ok(historypane, "history mode pane should exist"); - - for (let mode in modes) { - historymode.value = mode; - controlChanged(historymode); - is(historypane.selectedPanel, win.document.getElementById(modes[mode]), - "The correct pane should be selected for the " + mode + " mode"); - is_element_visible(historypane.selectedPanel, - "Correct pane should be visible for the " + mode + " mode"); - } -} - -function test_dependent_elements(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - let pbautostart = win.document.getElementById("privateBrowsingAutoStart"); - ok(pbautostart, "the private browsing auto-start checkbox should exist"); - let controls = [ - win.document.getElementById("rememberHistory"), - win.document.getElementById("rememberForms"), - win.document.getElementById("keepUntil"), - win.document.getElementById("keepCookiesUntil"), - win.document.getElementById("alwaysClear"), - ]; - controls.forEach(function(control) { - ok(control, "the dependent controls should exist"); - }); - let independents = [ - win.document.getElementById("acceptCookies"), - win.document.getElementById("acceptThirdPartyLabel"), - win.document.getElementById("acceptThirdPartyMenu") - ]; - independents.forEach(function(control) { - ok(control, "the independent controls should exist"); - }); - let cookieexceptions = win.document.getElementById("cookieExceptions"); - ok(cookieexceptions, "the cookie exceptions button should exist"); - let keepuntil = win.document.getElementById("keepCookiesUntil"); - ok(keepuntil, "the keep cookies until menulist should exist"); - let alwaysclear = win.document.getElementById("alwaysClear"); - ok(alwaysclear, "the clear data on close checkbox should exist"); - let rememberhistory = win.document.getElementById("rememberHistory"); - ok(rememberhistory, "the remember history checkbox should exist"); - let rememberforms = win.document.getElementById("rememberForms"); - ok(rememberforms, "the remember forms checkbox should exist"); - let alwaysclearsettings = win.document.getElementById("clearDataSettings"); - ok(alwaysclearsettings, "the clear data settings button should exist"); - - function expect_disabled(disabled) { - controls.forEach(function(control) { - is(control.disabled, disabled, - control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled"); - }); - is(keepuntil.value, disabled ? 2 : 0, - "the keep cookies until menulist value should be as expected"); - if (disabled) { - ok(!alwaysclear.checked, - "the clear data on close checkbox value should be as expected"); - ok(!rememberhistory.checked, - "the remember history checkbox value should be as expected"); - ok(!rememberforms.checked, - "the remember forms checkbox value should be as expected"); - } - } - function check_independents(expected) { - independents.forEach(function(control) { - is(control.disabled, expected, - control.getAttribute("id") + " should " + (expected ? "" : "not ") + "be disabled"); - }); - - ok(!cookieexceptions.disabled, - "the cookie exceptions button should never be disabled"); - ok(alwaysclearsettings.disabled, - "the clear data settings button should always be disabled"); - } - - // controls should only change in custom mode - historymode.value = "remember"; - controlChanged(historymode); - expect_disabled(false); - check_independents(false); - - // setting the mode to custom shouldn't change anything - historymode.value = "custom"; - controlChanged(historymode); - expect_disabled(false); - check_independents(false); -} - -function test_dependent_cookie_elements(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - let pbautostart = win.document.getElementById("privateBrowsingAutoStart"); - ok(pbautostart, "the private browsing auto-start checkbox should exist"); - let controls = [ - win.document.getElementById("acceptThirdPartyLabel"), - win.document.getElementById("acceptThirdPartyMenu"), - win.document.getElementById("keepUntil"), - win.document.getElementById("keepCookiesUntil"), - ]; - controls.forEach(function(control) { - ok(control, "the dependent cookie controls should exist"); - }); - let acceptcookies = win.document.getElementById("acceptCookies"); - ok(acceptcookies, "the accept cookies checkbox should exist"); - - function expect_disabled(disabled) { - controls.forEach(function(control) { - is(control.disabled, disabled, - control.getAttribute("id") + " should " + (disabled ? "" : "not ") + "be disabled"); - }); - } - - historymode.value = "custom"; - controlChanged(historymode); - pbautostart.checked = false; - controlChanged(pbautostart); - expect_disabled(false); - - acceptcookies.checked = false; - controlChanged(acceptcookies); - expect_disabled(true); - - acceptcookies.checked = true; - controlChanged(acceptcookies); - expect_disabled(false); - - let accessthirdparty = controls.shift(); - acceptcookies.checked = false; - controlChanged(acceptcookies); - expect_disabled(true); - ok(accessthirdparty.disabled, "access third party button should be disabled"); - - pbautostart.checked = false; - controlChanged(pbautostart); - expect_disabled(true); - ok(accessthirdparty.disabled, "access third party button should be disabled"); - - acceptcookies.checked = true; - controlChanged(acceptcookies); - expect_disabled(false); - ok(!accessthirdparty.disabled, "access third party button should be enabled"); -} - -function test_dependent_clearonclose_elements(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - let pbautostart = win.document.getElementById("privateBrowsingAutoStart"); - ok(pbautostart, "the private browsing auto-start checkbox should exist"); - let alwaysclear = win.document.getElementById("alwaysClear"); - ok(alwaysclear, "the clear data on close checkbox should exist"); - let alwaysclearsettings = win.document.getElementById("clearDataSettings"); - ok(alwaysclearsettings, "the clear data settings button should exist"); - - function expect_disabled(disabled) { - is(alwaysclearsettings.disabled, disabled, - "the clear data settings should " + (disabled ? "" : "not ") + "be disabled"); - } - - historymode.value = "custom"; - controlChanged(historymode); - pbautostart.checked = false; - controlChanged(pbautostart); - alwaysclear.checked = false; - controlChanged(alwaysclear); - expect_disabled(true); - - alwaysclear.checked = true; - controlChanged(alwaysclear); - expect_disabled(false); - - alwaysclear.checked = false; - controlChanged(alwaysclear); - expect_disabled(true); -} - -function test_dependent_prefs(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - let controls = [ - win.document.getElementById("rememberHistory"), - win.document.getElementById("rememberForms"), - win.document.getElementById("acceptCookies") - ]; - controls.forEach(function(control) { - ok(control, "the micro-management controls should exist"); - }); - - let thirdPartyCookieMenu = win.document.getElementById("acceptThirdPartyMenu"); - ok(thirdPartyCookieMenu, "the third-party cookie control should exist"); - - function expect_checked(checked) { - controls.forEach(function(control) { - is(control.checked, checked, - control.getAttribute("id") + " should " + (checked ? "not " : "") + "be checked"); - }); - - is(thirdPartyCookieMenu.value == "always" || thirdPartyCookieMenu.value == "visited", checked, "third-party cookies should " + (checked ? "not " : "") + "be limited"); - } - - // controls should be checked in remember mode - historymode.value = "remember"; - controlChanged(historymode); - expect_checked(true); - - // even if they're unchecked in custom mode - historymode.value = "custom"; - controlChanged(historymode); - thirdPartyCookieMenu.value = "never"; - controlChanged(thirdPartyCookieMenu); - controls.forEach(function(control) { - control.checked = false; - controlChanged(control); - }); - expect_checked(false); - historymode.value = "remember"; - controlChanged(historymode); - expect_checked(true); -} - -function test_historymode_retention(mode, expect) { - return function test_historymode_retention_fn(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - - if ((historymode.value == "remember" && mode == "dontremember") || - (historymode.value == "dontremember" && mode == "remember") || - (historymode.value == "custom" && mode == "dontremember")) { - return; - } - - if (expect !== undefined) { - is(historymode.value, expect, - "history mode is expected to remain " + expect); - } - - historymode.value = mode; - controlChanged(historymode); - }; -} - -function test_custom_retention(controlToChange, expect, valueIncrement) { - return function test_custom_retention_fn(win) { - let historymode = win.document.getElementById("historyMode"); - ok(historymode, "history mode menulist should exist"); - - if (expect !== undefined) { - is(historymode.value, expect, - "history mode is expected to remain " + expect); - } - - historymode.value = "custom"; - controlChanged(historymode); - - controlToChange = win.document.getElementById(controlToChange); - ok(controlToChange, "the control to change should exist"); - switch (controlToChange.localName) { - case "checkbox": - controlToChange.checked = !controlToChange.checked; - break; - case "textbox": - controlToChange.value = parseInt(controlToChange.value) + valueIncrement; - break; - case "menulist": - controlToChange.value = valueIncrement; - break; - } - controlChanged(controlToChange); - }; -} - -function test_locbar_suggestion_retention(suggestion, autocomplete) { - return function(win) { - let elem = win.document.getElementById(suggestion + "Suggestion"); - ok(elem, "Suggest " + suggestion + " checkbox should exist."); - elem.click(); - - is(Services.prefs.getBoolPref("browser.urlbar.autocomplete.enabled"), autocomplete, - "browser.urlbar.autocomplete.enabled pref should be " + autocomplete); - }; -} - -const gPrefCache = new Map(); - -function cache_preferences(win) { - let prefs = win.document.querySelectorAll("#privacyPreferences > preference"); - for (let pref of prefs) - gPrefCache.set(pref.name, pref.value); -} - -function reset_preferences(win) { - let prefs = win.document.querySelectorAll("#privacyPreferences > preference"); - for (let pref of prefs) - pref.value = gPrefCache.get(pref.name); -} - -function run_test_subset(subset) { - info("subset: " + Array.from(subset, x => x.name).join(",") + "\n"); - SpecialPowers.pushPrefEnv({"set": [["browser.preferences.instantApply", true]]}); - - let tests = [cache_preferences, ...subset, reset_preferences]; - for (let test of tests) { - add_task(runTestOnPrivacyPrefPane.bind(undefined, test)); - } -} diff --git a/browser/components/preferences/in-content/tests/subdialog.xul b/browser/components/preferences/in-content/tests/subdialog.xul deleted file mode 100644 index 48d297b73..000000000 --- a/browser/components/preferences/in-content/tests/subdialog.xul +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0"?> - -<!-- Any copyright is dedicated to the Public Domain. - - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> - -<dialog id="subDialog" - xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Sample sub-dialog" style="width: 32em; height: 5em;" - onload="document.getElementById('textbox').focus();" - ondialogaccept="acceptSubdialog();"> - <script> - function acceptSubdialog() { - window.arguments[0].acceptCount++; - } - </script> - - <description id="desc">A sample sub-dialog for testing</description> - - <textbox id="textbox" value="Default text" /> - - <separator class="thin"/> - - <button oncommand="close();" icon="close" label="Close" /> - -</dialog> diff --git a/browser/components/preferences/in-content/tests/subdialog2.xul b/browser/components/preferences/in-content/tests/subdialog2.xul deleted file mode 100644 index 89803c250..000000000 --- a/browser/components/preferences/in-content/tests/subdialog2.xul +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0"?> - -<!-- Any copyright is dedicated to the Public Domain. - - http://creativecommons.org/publicdomain/zero/1.0/ --> - -<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> - -<dialog id="subDialog" - xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" - title="Sample sub-dialog #2" style="width: 32em; height: 5em;" - onload="document.getElementById('textbox').focus();" - ondialogaccept="acceptSubdialog();"> - <script> - function acceptSubdialog() { - window.arguments[0].acceptCount++; - } - </script> - - <description id="desc">A sample sub-dialog for testing</description> - - <textbox id="textbox" value="Default text" /> - - <separator class="thin"/> - - <button oncommand="close();" icon="close" label="Close" /> - -</dialog> diff --git a/browser/components/privatebrowsing/test/browser/.eslintrc.js b/browser/components/privatebrowsing/test/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/privatebrowsing/test/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/privatebrowsing/test/browser/browser.ini b/browser/components/privatebrowsing/test/browser/browser.ini deleted file mode 100644 index 5efca4c0e..000000000 --- a/browser/components/privatebrowsing/test/browser/browser.ini +++ /dev/null @@ -1,54 +0,0 @@ -[DEFAULT] -tags = openwindow -support-files = - browser_privatebrowsing_concurrent_page.html - browser_privatebrowsing_geoprompt_page.html - browser_privatebrowsing_localStorage_before_after_page.html - browser_privatebrowsing_localStorage_before_after_page2.html - browser_privatebrowsing_localStorage_page1.html - browser_privatebrowsing_localStorage_page2.html - browser_privatebrowsing_placesTitleNoUpdate.html - browser_privatebrowsing_protocolhandler_page.html - browser_privatebrowsing_windowtitle_page.html - head.js - popup.html - title.sjs - empty_file.html - file_favicon.html - file_favicon.png - file_favicon.png^headers^ - -[browser_privatebrowsing_DownloadLastDirWithCPS.js] -[browser_privatebrowsing_about.js] -tags = trackingprotection -[browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js] -[browser_privatebrowsing_aboutSessionRestore.js] -[browser_privatebrowsing_cache.js] -[browser_privatebrowsing_certexceptionsui.js] -[browser_privatebrowsing_concurrent.js] -[browser_privatebrowsing_context_and_chromeFlags.js] -[browser_privatebrowsing_crh.js] -[browser_privatebrowsing_downloadLastDir.js] -[browser_privatebrowsing_downloadLastDir_c.js] -[browser_privatebrowsing_downloadLastDir_toggle.js] -[browser_privatebrowsing_favicon.js] -[browser_privatebrowsing_geoprompt.js] -[browser_privatebrowsing_lastpbcontextexited.js] -[browser_privatebrowsing_localStorage.js] -[browser_privatebrowsing_localStorage_before_after.js] -[browser_privatebrowsing_noSessionRestoreMenuOption.js] -[browser_privatebrowsing_nonbrowser.js] -[browser_privatebrowsing_opendir.js] -[browser_privatebrowsing_placesTitleNoUpdate.js] -[browser_privatebrowsing_placestitle.js] -[browser_privatebrowsing_popupblocker.js] -[browser_privatebrowsing_protocolhandler.js] -[browser_privatebrowsing_sidebar.js] -[browser_privatebrowsing_theming.js] -[browser_privatebrowsing_ui.js] -[browser_privatebrowsing_urlbarfocus.js] -[browser_privatebrowsing_windowtitle.js] -[browser_privatebrowsing_zoom.js] -[browser_privatebrowsing_zoomrestore.js] -[browser_privatebrowsing_newtab_from_popup.js] -[browser_privatebrowsing_blobUrl.js] diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js deleted file mode 100644 index bcd19b192..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_DownloadLastDirWithCPS.js +++ /dev/null @@ -1,282 +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/. */ - -var gTests; -function test() { - waitForExplicitFinish(); - requestLongerTimeout(2); - gTests = runTest(); - gTests.next(); -} - -/* - * ================ - * Helper functions - * ================ - */ - -function moveAlong(aResult) { - try { - gTests.send(aResult); - } catch (x if x instanceof StopIteration) { - finish(); - } -} - -function createWindow(aOptions) { - whenNewWindowLoaded(aOptions, function(win) { - moveAlong(win); - }); -} - -function getFile(downloadLastDir, aURI) { - downloadLastDir.getFileAsync(aURI, function(result) { - moveAlong(result); - }); -} - -function setFile(downloadLastDir, aURI, aValue) { - downloadLastDir.setFile(aURI, aValue); - executeSoon(moveAlong); -} - -function clearHistoryAndWait() { - clearHistory(); - executeSoon(() => executeSoon(moveAlong)); -} - -/* - * =================== - * Function with tests - * =================== - */ - -function runTest() { - let FileUtils = - Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils; - let DownloadLastDir = - Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir; - - let tmpDir = FileUtils.getDir("TmpD", [], true); - let dir1 = newDirectory(); - let dir2 = newDirectory(); - let dir3 = newDirectory(); - - let uri1 = Services.io.newURI("http://test1.com/", null, null); - let uri2 = Services.io.newURI("http://test2.com/", null, null); - let uri3 = Services.io.newURI("http://test3.com/", null, null); - let uri4 = Services.io.newURI("http://test4.com/", null, null); - - // cleanup functions registration - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.download.lastDir.savePerSite"); - Services.prefs.clearUserPref("browser.download.lastDir"); - [dir1, dir2, dir3].forEach(dir => dir.remove(true)); - win.close(); - pbWin.close(); - }); - - function checkDownloadLastDir(gDownloadLastDir, aLastDir) { - is(gDownloadLastDir.file.path, aLastDir.path, - "gDownloadLastDir should point to the expected last directory"); - getFile(gDownloadLastDir, uri1); - } - - function checkDownloadLastDirNull(gDownloadLastDir) { - is(gDownloadLastDir.file, null, "gDownloadLastDir should be null"); - getFile(gDownloadLastDir, uri1); - } - - /* - * ================================ - * Create a regular and a PB window - * ================================ - */ - - let win = yield createWindow({private: false}); - let pbWin = yield createWindow({private: true}); - - let downloadLastDir = new DownloadLastDir(win); - let pbDownloadLastDir = new DownloadLastDir(pbWin); - - /* - * ================== - * Beginning of tests - * ================== - */ - - is(typeof downloadLastDir, "object", - "downloadLastDir should be a valid object"); - is(downloadLastDir.file, null, - "LastDir pref should be null to start with"); - - // set up last dir - yield setFile(downloadLastDir, null, tmpDir); - is(downloadLastDir.file.path, tmpDir.path, - "LastDir should point to the tmpDir"); - isnot(downloadLastDir.file, tmpDir, - "downloadLastDir.file should not be pointing to tmpDir"); - - // set uri1 to dir1, all should now return dir1 - // also check that a new object is returned - yield setFile(downloadLastDir, uri1, dir1); - is(downloadLastDir.file.path, dir1.path, - "downloadLastDir should return dir1"); - isnot(downloadLastDir.file, dir1, - "downloadLastDir.file should not return dir1"); - is((yield getFile(downloadLastDir, uri1)).path, dir1.path, - "uri1 should return dir1"); // set in CPS - isnot((yield getFile(downloadLastDir, uri1)), dir1, - "getFile on uri1 should not return dir1"); - is((yield getFile(downloadLastDir, uri2)).path, dir1.path, - "uri2 should return dir1"); // fallback - isnot((yield getFile(downloadLastDir, uri2)), dir1, - "getFile on uri2 should not return dir1"); - is((yield getFile(downloadLastDir, uri3)).path, dir1.path, - "uri3 should return dir1"); // fallback - isnot((yield getFile(downloadLastDir, uri3)), dir1, - "getFile on uri3 should not return dir1"); - is((yield getFile(downloadLastDir, uri4)).path, dir1.path, - "uri4 should return dir1"); // fallback - isnot((yield getFile(downloadLastDir, uri4)), dir1, - "getFile on uri4 should not return dir1"); - - // set uri2 to dir2, all except uri1 should now return dir2 - yield setFile(downloadLastDir, uri2, dir2); - is(downloadLastDir.file.path, dir2.path, - "downloadLastDir should point to dir2"); - is((yield getFile(downloadLastDir, uri1)).path, dir1.path, - "uri1 should return dir1"); // set in CPS - is((yield getFile(downloadLastDir, uri2)).path, dir2.path, - "uri2 should return dir2"); // set in CPS - is((yield getFile(downloadLastDir, uri3)).path, dir2.path, - "uri3 should return dir2"); // fallback - is((yield getFile(downloadLastDir, uri4)).path, dir2.path, - "uri4 should return dir2"); // fallback - - // set uri3 to dir3, all except uri1 and uri2 should now return dir3 - yield setFile(downloadLastDir, uri3, dir3); - is(downloadLastDir.file.path, dir3.path, - "downloadLastDir should point to dir3"); - is((yield getFile(downloadLastDir, uri1)).path, dir1.path, - "uri1 should return dir1"); // set in CPS - is((yield getFile(downloadLastDir, uri2)).path, dir2.path, - "uri2 should return dir2"); // set in CPS - is((yield getFile(downloadLastDir, uri3)).path, dir3.path, - "uri3 should return dir3"); // set in CPS - is((yield getFile(downloadLastDir, uri4)).path, dir3.path, - "uri4 should return dir4"); // fallback - - // set uri1 to dir2, all except uri3 should now return dir2 - yield setFile(downloadLastDir, uri1, dir2); - is(downloadLastDir.file.path, dir2.path, - "downloadLastDir should point to dir2"); - is((yield getFile(downloadLastDir, uri1)).path, dir2.path, - "uri1 should return dir2"); // set in CPS - is((yield getFile(downloadLastDir, uri2)).path, dir2.path, - "uri2 should return dir2"); // set in CPS - is((yield getFile(downloadLastDir, uri3)).path, dir3.path, - "uri3 should return dir3"); // set in CPS - is((yield getFile(downloadLastDir, uri4)).path, dir2.path, - "uri4 should return dir2"); // fallback - - yield clearHistoryAndWait(); - - // check clearHistory removes all data - is(downloadLastDir.file, null, "clearHistory removes all data"); - //is(Services.contentPrefs.hasPref(uri1, "browser.download.lastDir", null), - // false, "LastDir preference should be absent"); - is((yield getFile(downloadLastDir, uri1)), null, "uri1 should point to null"); - is((yield getFile(downloadLastDir, uri2)), null, "uri2 should point to null"); - is((yield getFile(downloadLastDir, uri3)), null, "uri3 should point to null"); - is((yield getFile(downloadLastDir, uri4)), null, "uri4 should point to null"); - - yield setFile(downloadLastDir, null, tmpDir); - - // check data set outside PB mode is remembered - is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDir(downloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory"); - yield clearHistoryAndWait(); - - yield setFile(downloadLastDir, uri1, dir1); - - // check data set using CPS outside PB mode is remembered - is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory"); - yield clearHistoryAndWait(); - - // check data set inside PB mode is forgotten - yield setFile(pbDownloadLastDir, null, tmpDir); - - is((yield checkDownloadLastDir(pbDownloadLastDir, tmpDir)).path, tmpDir.path, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory"); - - yield clearHistoryAndWait(); - - // check data set using CPS inside PB mode is forgotten - yield setFile(pbDownloadLastDir, uri1, dir1); - - is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory"); - - // check data set outside PB mode but changed inside is remembered correctly - yield setFile(downloadLastDir, uri1, dir1); - yield setFile(pbDownloadLastDir, uri1, dir2); - is((yield checkDownloadLastDir(pbDownloadLastDir, dir2)).path, dir2.path, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDir(downloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory"); - - /* - * ==================== - * Create new PB window - * ==================== - */ - - // check that the last dir store got cleared in a new PB window - pbWin.close(); - // And give it time to close - executeSoon(moveAlong); - yield; - pbWin = yield createWindow({private: true}); - pbDownloadLastDir = new DownloadLastDir(pbWin); - - is((yield checkDownloadLastDir(pbDownloadLastDir, dir1)).path, dir1.path, "uri1 should return the expected last directory"); - - yield clearHistoryAndWait(); - - // check clearHistory inside PB mode clears data outside PB mode - yield setFile(pbDownloadLastDir, uri1, dir2); - - yield clearHistoryAndWait(); - - is((yield checkDownloadLastDirNull(downloadLastDir)), null, "uri1 should return the expected last directory"); - is((yield checkDownloadLastDirNull(pbDownloadLastDir)), null, "uri1 should return the expected last directory"); - - // check that disabling CPS works - Services.prefs.setBoolPref("browser.download.lastDir.savePerSite", false); - - yield setFile(downloadLastDir, uri1, dir1); - is(downloadLastDir.file.path, dir1.path, "LastDir should be set to dir1"); - is((yield getFile(downloadLastDir, uri1)).path, dir1.path, "uri1 should return dir1"); - is((yield getFile(downloadLastDir, uri2)).path, dir1.path, "uri2 should return dir1"); - is((yield getFile(downloadLastDir, uri3)).path, dir1.path, "uri3 should return dir1"); - is((yield getFile(downloadLastDir, uri4)).path, dir1.path, "uri4 should return dir1"); - - downloadLastDir.setFile(uri2, dir2); - is(downloadLastDir.file.path, dir2.path, "LastDir should be set to dir2"); - is((yield getFile(downloadLastDir, uri1)).path, dir2.path, "uri1 should return dir2"); - is((yield getFile(downloadLastDir, uri2)).path, dir2.path, "uri2 should return dir2"); - is((yield getFile(downloadLastDir, uri3)).path, dir2.path, "uri3 should return dir2"); - is((yield getFile(downloadLastDir, uri4)).path, dir2.path, "uri4 should return dir2"); - - Services.prefs.clearUserPref("browser.download.lastDir.savePerSite"); - - // check that passing null to setFile clears the stored value - yield setFile(downloadLastDir, uri3, dir3); - is((yield getFile(downloadLastDir, uri3)).path, dir3.path, "LastDir should be set to dir3"); - yield setFile(downloadLastDir, uri3, null); - is((yield getFile(downloadLastDir, uri3)), null, "uri3 should return null"); - - yield clearHistoryAndWait(); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js deleted file mode 100644 index e00f3f67a..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_about.js +++ /dev/null @@ -1,115 +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/. */ - -/** - * Opens a new private window and loads "about:privatebrowsing" there. - */ -function* openAboutPrivateBrowsing() { - let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - let tab = win.gBrowser.selectedBrowser; - tab.loadURI("about:privatebrowsing"); - yield BrowserTestUtils.browserLoaded(tab); - return { win, tab }; -} - -/** - * Clicks the given link and checks this opens a new tab with the given URI. - */ -function* testLinkOpensTab({ win, tab, elementId, expectedUrl }) { - let newTabPromise = BrowserTestUtils.waitForNewTab(win.gBrowser, expectedUrl); - yield ContentTask.spawn(tab, { elementId }, function* ({ elementId }) { - content.document.getElementById(elementId).click(); - }); - let newTab = yield newTabPromise; - ok(true, `Clicking ${elementId} opened ${expectedUrl} in a new tab.`); - yield BrowserTestUtils.removeTab(newTab); -} - -/** - * Clicks the given link and checks this opens the given URI in the same tab. - * - * This function does not return to the previous page. - */ -function* testLinkOpensUrl({ win, tab, elementId, expectedUrl }) { - let loadedPromise = BrowserTestUtils.browserLoaded(tab); - yield ContentTask.spawn(tab, { elementId }, function* ({ elementId }) { - content.document.getElementById(elementId).click(); - }); - yield loadedPromise; - is(tab.currentURI.spec, expectedUrl, - `Clicking ${elementId} opened ${expectedUrl} in the same tab.`); -} - -/** - * Tests the links in "about:privatebrowsing". - */ -add_task(function* test_links() { - // Use full version and change the remote URLs to prevent network access. - Services.prefs.setCharPref("app.support.baseURL", "https://example.com/"); - Services.prefs.setCharPref("privacy.trackingprotection.introURL", - "https://example.com/tour"); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("privacy.trackingprotection.introURL"); - Services.prefs.clearUserPref("app.support.baseURL"); - }); - - let { win, tab } = yield openAboutPrivateBrowsing(); - - yield testLinkOpensTab({ win, tab, - elementId: "learnMore", - expectedUrl: "https://example.com/private-browsing", - }); - - yield testLinkOpensUrl({ win, tab, - elementId: "startTour", - expectedUrl: "https://example.com/tour", - }); - - yield BrowserTestUtils.closeWindow(win); -}); - -/** - * Tests the action to disable and re-enable Tracking Protection in - * "about:privatebrowsing". - */ -add_task(function* test_toggleTrackingProtection() { - // Use tour version but disable Tracking Protection. - Services.prefs.setBoolPref("privacy.trackingprotection.pbmode.enabled", - true); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("privacy.trackingprotection.pbmode.enabled"); - }); - - let { win, tab } = yield openAboutPrivateBrowsing(); - - // Set up the observer for the preference change before triggering the action. - let prefBranch = - Services.prefs.getBranch("privacy.trackingprotection.pbmode."); - let waitForPrefChanged = () => new Promise(resolve => { - let prefObserver = { - QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), - observe: function () { - prefBranch.removeObserver("enabled", prefObserver); - resolve(); - }, - }; - prefBranch.addObserver("enabled", prefObserver, false); - }); - - let promisePrefChanged = waitForPrefChanged(); - yield ContentTask.spawn(tab, {}, function* () { - content.document.getElementById("tpButton").click(); - }); - yield promisePrefChanged; - ok(!prefBranch.getBoolPref("enabled"), "Tracking Protection is disabled."); - - promisePrefChanged = waitForPrefChanged(); - yield ContentTask.spawn(tab, {}, function* () { - content.document.getElementById("tpButton").click(); - }); - yield promisePrefChanged; - ok(prefBranch.getBoolPref("enabled"), "Tracking Protection is enabled."); - - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js deleted file mode 100644 index 6f52f7719..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutHomeButtonAfterWindowClose.js +++ /dev/null @@ -1,24 +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 test checks that the Session Restore "Restore Previous Session" -// button on about:home is disabled in private mode -add_task(function* test_no_sessionrestore_button() { - // Opening, then closing, a private window shouldn't create session data. - (yield BrowserTestUtils.openNewBrowserWindow({private: true})).close(); - - let win = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let tab = win.gBrowser.addTab("about:home"); - let browser = tab.linkedBrowser; - - yield BrowserTestUtils.browserLoaded(browser); - - yield ContentTask.spawn(browser, null, function* () { - let button = content.document.getElementById("restorePreviousSession"); - Assert.equal(content.getComputedStyle(button).display, "none", - "The Session Restore about:home button should be disabled"); - }); - - win.close(); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js deleted file mode 100644 index 5f6a91836..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_aboutSessionRestore.js +++ /dev/null @@ -1,23 +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 test checks that the session restore button from about:sessionrestore -// is disabled in private mode -add_task(function* testNoSessionRestoreButton() { - // Opening, then closing, a private window shouldn't create session data. - (yield BrowserTestUtils.openNewBrowserWindow({private: true})).close(); - - let win = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let tab = win.gBrowser.addTab("about:sessionrestore"); - let browser = tab.linkedBrowser; - - yield BrowserTestUtils.browserLoaded(browser); - - yield ContentTask.spawn(browser, null, function* () { - Assert.ok(content.document.getElementById("errorTryAgain").disabled, - "The Restore about:sessionrestore button should be disabled"); - }); - - win.close(); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js deleted file mode 100644 index 2ceb1032b..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_blobUrl.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -// Here we want to test that blob URLs are not available between private and -// non-private browsing. - -const BASE_URI = "http://mochi.test:8888/browser/browser/components/" - + "privatebrowsing/test/browser/empty_file.html"; - -add_task(function* test() { - info("Creating a normal window..."); - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let tab = win.gBrowser.selectedBrowser; - tab.loadURI(BASE_URI); - yield BrowserTestUtils.browserLoaded(tab); - - let blobURL; - - info("Creating a blob URL..."); - yield ContentTask.spawn(tab, null, function() { - return Promise.resolve(content.window.URL.createObjectURL(new content.window.Blob([123]))); - }).then(newURL => { blobURL = newURL }); - - info("Blob URL: " + blobURL); - - info("Creating a private window..."); - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - let privateTab = privateWin.gBrowser.selectedBrowser; - privateTab.loadURI(BASE_URI); - yield BrowserTestUtils.browserLoaded(privateTab); - - yield ContentTask.spawn(privateTab, blobURL, function(url) { - return new Promise(resolve => { - var xhr = new content.window.XMLHttpRequest(); - xhr.onerror = function() { resolve("SendErrored"); } - xhr.onload = function() { resolve("SendLoaded"); } - xhr.open("GET", url); - xhr.send(); - }); - }).then(status => { - is(status, "SendErrored", "Using a blob URI from one user context id in another should not work"); - }); - - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(privateWin); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js deleted file mode 100644 index 4990f6d3b..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js +++ /dev/null @@ -1,138 +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/. */ - -// Check about:cache after private browsing -// This test covers MozTrap test 6047 -// bug 880621 - -var {LoadContextInfo} = Cu.import("resource://gre/modules/LoadContextInfo.jsm", null); - -var tmp = {}; - -Cc["@mozilla.org/moz/jssubscript-loader;1"] - .getService(Ci.mozIJSSubScriptLoader) - .loadSubScript("chrome://browser/content/sanitize.js", tmp); - -var Sanitizer = tmp.Sanitizer; - -function test() { - - waitForExplicitFinish(); - - sanitizeCache(); - - let nrEntriesR1 = getStorageEntryCount("regular", function(nrEntriesR1) { - is(nrEntriesR1, 0, "Disk cache reports 0KB and has no entries"); - - get_cache_for_private_window(); - }); -} - -function cleanup() { - let prefs = Services.prefs.getBranch("privacy.cpd."); - - prefs.clearUserPref("history"); - prefs.clearUserPref("downloads"); - prefs.clearUserPref("cache"); - prefs.clearUserPref("cookies"); - prefs.clearUserPref("formdata"); - prefs.clearUserPref("offlineApps"); - prefs.clearUserPref("passwords"); - prefs.clearUserPref("sessions"); - prefs.clearUserPref("siteSettings"); -} - -function sanitizeCache() { - - let s = new Sanitizer(); - s.ignoreTimespan = false; - s.prefDomain = "privacy.cpd."; - - let prefs = gPrefService.getBranch(s.prefDomain); - prefs.setBoolPref("history", false); - prefs.setBoolPref("downloads", false); - prefs.setBoolPref("cache", true); - prefs.setBoolPref("cookies", false); - prefs.setBoolPref("formdata", false); - prefs.setBoolPref("offlineApps", false); - prefs.setBoolPref("passwords", false); - prefs.setBoolPref("sessions", false); - prefs.setBoolPref("siteSettings", false); - - s.sanitize(); -} - -function get_cache_service() { - return Components.classes["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Components.interfaces.nsICacheStorageService); -} - -function getStorageEntryCount(device, goon) { - var cs = get_cache_service(); - - var storage; - switch (device) { - case "private": - storage = cs.diskCacheStorage(LoadContextInfo.private, false); - break; - case "regular": - storage = cs.diskCacheStorage(LoadContextInfo.default, false); - break; - default: - throw "Unknown device " + device + " at getStorageEntryCount"; - } - - var visitor = { - entryCount: 0, - onCacheStorageInfo: function (aEntryCount, aConsumption) { - }, - onCacheEntryInfo: function(uri) - { - var urispec = uri.asciiSpec; - info(device + ":" + urispec + "\n"); - if (urispec.match(/^http:\/\/example.org\//)) - ++this.entryCount; - }, - onCacheEntryVisitCompleted: function() - { - goon(this.entryCount); - } - }; - - storage.asyncVisitStorage(visitor, true); -} - -function get_cache_for_private_window () { - let win = whenNewWindowLoaded({private: true}, function() { - - executeSoon(function() { - - ok(true, "The private window got loaded"); - - let tab = win.gBrowser.addTab("http://example.org"); - win.gBrowser.selectedTab = tab; - let newTabBrowser = win.gBrowser.getBrowserForTab(tab); - - newTabBrowser.addEventListener("load", function eventHandler() { - newTabBrowser.removeEventListener("load", eventHandler, true); - - executeSoon(function() { - - getStorageEntryCount("private", function(nrEntriesP) { - ok(nrEntriesP >= 1, "Memory cache reports some entries from example.org domain"); - - getStorageEntryCount("regular", function(nrEntriesR2) { - is(nrEntriesR2, 0, "Disk cache reports 0KB and has no entries"); - - cleanup(); - - win.close(); - finish(); - }); - }); - }); - }, true); - }); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js deleted file mode 100644 index 519f43475..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_certexceptionsui.js +++ /dev/null @@ -1,53 +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 test makes sure that certificate exceptions UI behaves correctly -// in private browsing windows, based on whether it's opened from the prefs -// window or from the SSL error page (see bug 461627). - -function test() { - const EXCEPTIONS_DLG_URL = 'chrome://pippki/content/exceptionDialog.xul'; - const EXCEPTIONS_DLG_FEATURES = 'chrome,centerscreen'; - const INVALID_CERT_LOCATION = 'https://nocert.example.com/'; - waitForExplicitFinish(); - - // open a private browsing window - var pbWin = OpenBrowserWindow({private: true}); - pbWin.addEventListener("load", function onLoad() { - pbWin.removeEventListener("load", onLoad, false); - doTest(); - }, false); - - // Test the certificate exceptions dialog - function doTest() { - let params = { - exceptionAdded : false, - location: INVALID_CERT_LOCATION, - prefetchCert: true, - }; - function testCheckbox() { - win.removeEventListener("load", testCheckbox, false); - Services.obs.addObserver(function onCertUI(aSubject, aTopic, aData) { - Services.obs.removeObserver(onCertUI, "cert-exception-ui-ready"); - ok(win.gCert, "The certificate information should be available now"); - - let checkbox = win.document.getElementById("permanent"); - ok(checkbox.hasAttribute("disabled"), - "the permanent checkbox should be disabled when handling the private browsing mode"); - ok(!checkbox.hasAttribute("checked"), - "the permanent checkbox should not be checked when handling the private browsing mode"); - win.close(); - cleanup(); - }, "cert-exception-ui-ready", false); - } - var win = pbWin.openDialog(EXCEPTIONS_DLG_URL, "", EXCEPTIONS_DLG_FEATURES, params); - win.addEventListener("load", testCheckbox, false); - } - - function cleanup() { - // close the private browsing window - pbWin.close(); - finish(); - } -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js deleted file mode 100644 index b73bbf219..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent.js +++ /dev/null @@ -1,88 +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 opening two tabs that share a localStorage, but keep one in private mode. -// Ensure that values from one don't leak into the other, and that values from -// earlier private storage sessions aren't visible later. - -// Step 1: create new tab, load a page that sets test=value in non-private storage -// Step 2: create a new tab, load a page that sets test2=value2 in private storage -// Step 3: load a page in the tab from step 1 that checks the value of test2 is value2 and the total count in non-private storage is 1 -// Step 4: load a page in the tab from step 2 that checks the value of test is value and the total count in private storage is 1 - -add_task(function* setup() { - yield SpecialPowers.pushPrefEnv({ - set: [["dom.ipc.processCount", 1]] - }); -}); - -add_task(function test() { - let prefix = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html'; - - function getElts(browser) { - return browser.contentTitle.split('|'); - }; - - // Step 1 - let non_private_browser = gBrowser.selectedBrowser; - non_private_browser.loadURI(prefix + '?action=set&name=test&value=value&initial=true'); - yield BrowserTestUtils.browserLoaded(non_private_browser); - - - // Step 2 - let private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : true }); - let private_browser = private_window.getBrowser().selectedBrowser; - private_browser.loadURI(prefix + '?action=set&name=test2&value=value2'); - yield BrowserTestUtils.browserLoaded(private_browser); - - - // Step 3 - non_private_browser.loadURI(prefix + '?action=get&name=test2'); - yield BrowserTestUtils.browserLoaded(non_private_browser); - let elts = yield getElts(non_private_browser); - isnot(elts[0], 'value2', "public window shouldn't see private storage"); - is(elts[1], '1', "public window should only see public items"); - - - // Step 4 - private_browser.loadURI(prefix + '?action=get&name=test'); - yield BrowserTestUtils.browserLoaded(private_browser); - elts = yield getElts(private_browser); - isnot(elts[0], 'value', "private window shouldn't see public storage"); - is(elts[1], '1', "private window should only see private items"); - - - // Reopen the private window again, without privateBrowsing, which should clear the - // the private storage. - private_window.close(); - private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : false }); - private_browser = null; - yield new Promise(resolve => Cu.schedulePreciseGC(resolve)); - private_browser = private_window.getBrowser().selectedBrowser; - - private_browser.loadURI(prefix + '?action=get&name=test2'); - yield BrowserTestUtils.browserLoaded(private_browser); - elts = yield getElts(private_browser); - isnot(elts[0], 'value2', "public window shouldn't see cleared private storage"); - is(elts[1], '1', "public window should only see public items"); - - - // Making it private again should clear the storage and it shouldn't - // be able to see the old private storage as well. - private_window.close(); - private_window = yield BrowserTestUtils.openNewBrowserWindow({ private : true }); - private_browser = null; - yield new Promise(resolve => Cu.schedulePreciseGC(resolve)); - private_browser = private_window.getBrowser().selectedBrowser; - - private_browser.loadURI(prefix + '?action=set&name=test3&value=value3'); - yield BrowserTestUtils.browserLoaded(private_browser); - elts = yield getElts(private_browser); - is(elts[1], '1', "private window should only see new private items"); - - // Cleanup. - non_private_browser.loadURI(prefix + '?final=true'); - yield BrowserTestUtils.browserLoaded(non_private_browser); - private_window.close(); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html deleted file mode 100644 index db35b114d..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html +++ /dev/null @@ -1,33 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<script type="text/javascript"> - var oGetVars = {}; - - if (window.location.search.length > 1) { - for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); - nKeyId < aCouples.length; - nKeyId++) { - aItKey = aCouples[nKeyId].split("="); - oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : ""; - } - } - - if (oGetVars.initial == 'true') { - localStorage.clear(); - } - - if (oGetVars.action == 'set') { - localStorage.setItem(oGetVars.name, oGetVars.value); - document.title = localStorage.getItem(oGetVars.name) + "|" + localStorage.length; - } else if (oGetVars.action == 'get') { - document.title = localStorage.getItem(oGetVars.name) + "|" + localStorage.length; - } - - if (oGetVars.final == 'true') { - localStorage.clear(); - } -</script> -</head> -<body> -</body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js deleted file mode 100644 index 30f7ee025..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_context_and_chromeFlags.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; - -/** - * Given some window in the parent process, ensure that - * the nsIXULWindow has the CHROME_PRIVATE_WINDOW chromeFlag, - * and that the usePrivateBrowsing property is set to true on - * both the window's nsILoadContext, as well as on the initial - * browser's content docShell nsILoadContext. - * - * @param win (nsIDOMWindow) - * An nsIDOMWindow in the parent process. - * @return Promise - */ -function assertWindowIsPrivate(win) { - let winDocShell = win.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDocShell); - let chromeFlags = winDocShell.QueryInterface(Ci.nsIDocShellTreeItem) - .treeOwner - .QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIXULWindow) - .chromeFlags; - - if (!win.gBrowser.selectedBrowser.hasContentOpener) { - Assert.ok(chromeFlags & Ci.nsIWebBrowserChrome.CHROME_PRIVATE_WINDOW, - "Should have the private window chrome flag"); - } - - let loadContext = winDocShell.QueryInterface(Ci.nsILoadContext); - Assert.ok(loadContext.usePrivateBrowsing, - "The parent window should be using private browsing"); - - return ContentTask.spawn(win.gBrowser.selectedBrowser, null, function*() { - let loadContext = docShell.QueryInterface(Ci.nsILoadContext); - Assert.ok(loadContext.usePrivateBrowsing, - "Content docShell should be using private browsing"); - }); -} - -/** - * Tests that chromeFlags bits and the nsILoadContext.usePrivateBrowsing - * attribute are properly set when opening a new private browsing - * window. - */ -add_task(function* test_context_and_chromeFlags() { - let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - yield assertWindowIsPrivate(win); - - let browser = win.gBrowser.selectedBrowser; - - let newWinPromise = BrowserTestUtils.waitForNewWindow(); - yield ContentTask.spawn(browser, null, function*() { - content.open("http://example.com", "_blank", "width=100,height=100"); - }); - - let win2 = yield newWinPromise; - yield assertWindowIsPrivate(win2); - - yield BrowserTestUtils.closeWindow(win2); - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js deleted file mode 100644 index cd316d1fb..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_crh.js +++ /dev/null @@ -1,42 +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 test makes sure that the Clear Recent History menu item and command -// is disabled inside the private browsing mode. - -add_task(function test() { - function checkDisableOption(aPrivateMode, aWindow) { - let crhCommand = aWindow.document.getElementById("Tools:Sanitize"); - ok(crhCommand, "The clear recent history command should exist"); - - is(PrivateBrowsingUtils.isWindowPrivate(aWindow), aPrivateMode, - "PrivateBrowsingUtils should report the correct per-window private browsing status"); - is(crhCommand.hasAttribute("disabled"), aPrivateMode, - "Clear Recent History command should be disabled according to the private browsing mode"); - }; - - let testURI = "http://mochi.test:8888/"; - - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let privateBrowser = privateWin.gBrowser.selectedBrowser; - privateBrowser.loadURI(testURI); - yield BrowserTestUtils.browserLoaded(privateBrowser); - - info("Test on private window"); - checkDisableOption(true, privateWin); - - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let browser = win.gBrowser.selectedBrowser; - browser.loadURI(testURI); - yield BrowserTestUtils.browserLoaded(browser); - - info("Test on public window"); - checkDisableOption(false, win); - - - // Cleanup - yield BrowserTestUtils.closeWindow(privateWin); - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js deleted file mode 100644 index 81b2943ee..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir.js +++ /dev/null @@ -1,93 +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/. */ - -function test() { - waitForExplicitFinish(); - - let FileUtils = - Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils; - let DownloadLastDir = - Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir; - let MockFilePicker = SpecialPowers.MockFilePicker; - let launcher = { - source: Services.io.newURI("http://test1.com/file", null, null) - }; - - MockFilePicker.init(window); - MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK; - - let prefs = Services.prefs.getBranch("browser.download."); - let launcherDialog = - Cc["@mozilla.org/helperapplauncherdialog;1"]. - getService(Ci.nsIHelperAppLauncherDialog); - let tmpDir = FileUtils.getDir("TmpD", [], true); - let dir1 = newDirectory(); - let dir2 = newDirectory(); - let dir3 = newDirectory(); - let file1 = newFileInDirectory(dir1); - let file2 = newFileInDirectory(dir2); - let file3 = newFileInDirectory(dir3); - - // cleanup functions registration - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.download.lastDir"); - [dir1, dir2, dir3].forEach(dir => dir.remove(true)); - MockFilePicker.cleanup(); - }); - prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir); - - function testOnWindow(aPrivate, aCallback) { - whenNewWindowLoaded({private: aPrivate}, function(win) { - let gDownloadLastDir = new DownloadLastDir(win); - aCallback(win, gDownloadLastDir); - gDownloadLastDir.cleanupPrivateFile(); - }); - } - - function testDownloadDir(aWin, gDownloadLastDir, aFile, aDisplayDir, aLastDir, - aGlobalLastDir, aCallback) { - // Check lastDir preference. - is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aDisplayDir.path, - "LastDir should be the expected display dir"); - // Check gDownloadLastDir value. - is(gDownloadLastDir.file.path, aDisplayDir.path, - "gDownloadLastDir should be the expected display dir"); - - MockFilePicker.returnFiles = [aFile]; - MockFilePicker.displayDirectory = null; - - launcher.saveDestinationAvailable = function (file) { - ok(!!file, "promptForSaveToFile correctly returned a file"); - - // File picker should start with expected display dir. - is(MockFilePicker.displayDirectory.path, aDisplayDir.path, - "File picker should start with browser.download.lastDir"); - // browser.download.lastDir should be modified on not private windows - is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aLastDir.path, - "LastDir should be the expected last dir"); - // gDownloadLastDir should be usable outside of private windows - is(gDownloadLastDir.file.path, aGlobalLastDir.path, - "gDownloadLastDir should be the expected global last dir"); - - launcher.saveDestinationAvailable = null; - aWin.close(); - aCallback(); - }; - - launcherDialog.promptForSaveToFileAsync(launcher, aWin, null, null, null); - } - - testOnWindow(false, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file1, tmpDir, dir1, dir1, function() { - testOnWindow(true, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file2, dir1, dir1, dir2, function() { - testOnWindow(false, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file3, dir1, dir3, dir3, finish); - }); - }); - }); - }); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js deleted file mode 100644 index 5a04d1999..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_c.js +++ /dev/null @@ -1,95 +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/. */ - -function test() { - waitForExplicitFinish(); - - let FileUtils = - Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils; - let DownloadLastDir = - Cu.import("resource://gre/modules/DownloadLastDir.jsm", {}).DownloadLastDir; - let MockFilePicker = SpecialPowers.MockFilePicker; - - MockFilePicker.init(window); - MockFilePicker.returnValue = Ci.nsIFilePicker.returnOK; - - let validateFileNameToRestore = validateFileName; - let prefs = Services.prefs.getBranch("browser.download."); - let tmpDir = FileUtils.getDir("TmpD", [], true); - let dir1 = newDirectory(); - let dir2 = newDirectory(); - let dir3 = newDirectory(); - let file1 = newFileInDirectory(dir1); - let file2 = newFileInDirectory(dir2); - let file3 = newFileInDirectory(dir3); - - // cleanup function registration - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.download.lastDir"); - [dir1, dir2, dir3].forEach(dir => dir.remove(true)); - MockFilePicker.cleanup(); - validateFileName = validateFileNameToRestore; - }); - - // Overwrite validateFileName to validate everything - validateFileName = foo => foo; - - let params = { - fileInfo: new FileInfo("test.txt", "test.txt", "test", "txt", "http://mozilla.org/test.txt"), - contentType: "text/plain", - saveMode: SAVEMODE_FILEONLY, - saveAsType: kSaveAsType_Complete, - file: null - }; - - prefs.setComplexValue("lastDir", Ci.nsIFile, tmpDir); - - function testOnWindow(aPrivate, aCallback) { - whenNewWindowLoaded({private: aPrivate}, function(win) { - let gDownloadLastDir = new DownloadLastDir(win); - aCallback(win, gDownloadLastDir); - }); - } - - function testDownloadDir(aWin, gDownloadLastDir, aFile, aDisplayDir, aLastDir, - aGlobalLastDir, aCallback) { - // Check lastDir preference. - is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aDisplayDir.path, - "LastDir should be the expected display dir"); - // Check gDownloadLastDir value. - is(gDownloadLastDir.file.path, aDisplayDir.path, - "gDownloadLastDir should be the expected display dir"); - - MockFilePicker.returnFiles = [aFile]; - MockFilePicker.displayDirectory = null; - aWin.promiseTargetFile(params).then(function() { - // File picker should start with expected display dir. - is(MockFilePicker.displayDirectory.path, aDisplayDir.path, - "File picker should start with browser.download.lastDir"); - // browser.download.lastDir should be modified on not private windows - is(prefs.getComplexValue("lastDir", Ci.nsIFile).path, aLastDir.path, - "LastDir should be the expected last dir"); - // gDownloadLastDir should be usable outside of private windows - is(gDownloadLastDir.file.path, aGlobalLastDir.path, - "gDownloadLastDir should be the expected global last dir"); - - gDownloadLastDir.cleanupPrivateFile(); - aWin.close(); - aCallback(); - }).then(null, function() { ok(false); }); - } - - testOnWindow(false, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file1, tmpDir, dir1, dir1, function() { - testOnWindow(true, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file2, dir1, dir1, dir2, function() { - testOnWindow(false, function(win, downloadDir) { - testDownloadDir(win, downloadDir, file3, dir1, dir3, dir3, finish); - }); - }); - }); - }); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js deleted file mode 100644 index b192c08f7..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_downloadLastDir_toggle.js +++ /dev/null @@ -1,105 +0,0 @@ -Cu.import("resource://gre/modules/FileUtils.jsm"); -Cu.import("resource://gre/modules/DownloadLastDir.jsm"); - -/** - * Tests how the browser remembers the last download folder - * from download to download, with a particular emphasis - * on how it behaves when private browsing windows open. - */ -add_task(function* test_downloads_last_dir_toggle() { - let tmpDir = FileUtils.getDir("TmpD", [], true); - let dir1 = newDirectory(); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.download.lastDir"); - dir1.remove(true); - }); - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let gDownloadLastDir = new DownloadLastDir(win); - is(typeof gDownloadLastDir, "object", - "gDownloadLastDir should be a valid object"); - is(gDownloadLastDir.file, null, - "gDownloadLastDir.file should be null to start with"); - - gDownloadLastDir.file = tmpDir; - is(gDownloadLastDir.file.path, tmpDir.path, - "LastDir should point to the temporary directory"); - isnot(gDownloadLastDir.file, tmpDir, - "gDownloadLastDir.file should not be pointing to the tmpDir"); - - gDownloadLastDir.file = 1; // not an nsIFile - is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null"); - - gDownloadLastDir.file = tmpDir; - clearHistory(); - is(gDownloadLastDir.file, null, "gDownloadLastDir.file should be null"); - - gDownloadLastDir.file = tmpDir; - yield BrowserTestUtils.closeWindow(win); - - info("Opening the first private window"); - yield testHelper({ private: true, expectedDir: tmpDir }); - info("Opening a non-private window"); - yield testHelper({ private: false, expectedDir: tmpDir }); - info("Opening a private window and setting download directory"); - yield testHelper({ private: true, setDir: dir1, expectedDir: dir1 }); - info("Opening a non-private window and checking download directory"); - yield testHelper({ private: false, expectedDir: tmpDir }); - info("Opening private window and clearing history"); - yield testHelper({ private: true, clearHistory: true, expectedDir: null }); - info("Opening a non-private window and checking download directory"); - yield testHelper({ private: true, expectedDir: null }); -}); - -/** - * Opens a new window and performs some test actions on it based - * on the options object that have been passed in. - * - * @param options (Object) - * An object with the following properties: - * - * clearHistory (bool, optional): - * Whether or not to simulate clearing session history. - * Defaults to false. - * - * setDir (nsIFile, optional): - * An nsIFile for setting the last download directory. - * If not set, the load download directory is not changed. - * - * expectedDir (nsIFile, expectedDir): - * An nsIFile for what we expect the last download directory - * should be. The nsIFile is not compared directly - only - * paths are compared. If expectedDir is not set, then the - * last download directory is expected to be null. - * - * @returns Promise - */ -function testHelper(options) { - return new Task.spawn(function() { - let win = yield BrowserTestUtils.openNewBrowserWindow(options); - let gDownloadLastDir = new DownloadLastDir(win); - - if (options.clearHistory) { - clearHistory(); - } - - if (options.setDir) { - gDownloadLastDir.file = options.setDir; - } - - let expectedDir = options.expectedDir; - - if (expectedDir) { - is(gDownloadLastDir.file.path, expectedDir.path, - "gDownloadLastDir should point to the expected last directory"); - isnot(gDownloadLastDir.file, expectedDir, - "gDownloadLastDir.file should not be pointing to the last directory"); - } else { - is(gDownloadLastDir.file, null, "gDownloadLastDir should be null"); - } - - gDownloadLastDir.cleanupPrivateFile(); - yield BrowserTestUtils.closeWindow(win); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js deleted file mode 100644 index 86f714082..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js +++ /dev/null @@ -1,293 +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 test make sure that the favicon of the private browsing is isolated. - -const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components; - -const TEST_SITE = "http://mochi.test:8888"; -const TEST_CACHE_SITE = "http://www.example.com"; -const TEST_DIRECTORY = "/browser/browser/components/privatebrowsing/test/browser/"; - -const TEST_PAGE = TEST_SITE + TEST_DIRECTORY + "file_favicon.html"; -const TEST_CACHE_PAGE = TEST_CACHE_SITE + TEST_DIRECTORY + "file_favicon.html"; -const FAVICON_URI = TEST_SITE + TEST_DIRECTORY + "file_favicon.png"; -const FAVICON_CACHE_URI = TEST_CACHE_SITE + TEST_DIRECTORY + "file_favicon.png"; - -let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); -let makeURI = Cu.import("resource://gre/modules/BrowserUtils.jsm", {}).BrowserUtils.makeURI; - -function clearAllImageCaches() { - let tools = SpecialPowers.Cc["@mozilla.org/image/tools;1"] - .getService(SpecialPowers.Ci.imgITools); - let imageCache = tools.getImgCacheForDocument(window.document); - imageCache.clearCache(true); // true=chrome - imageCache.clearCache(false); // false=content -} - -function clearAllPlacesFavicons() { - let faviconService = Cc["@mozilla.org/browser/favicon-service;1"] - .getService(Ci.nsIFaviconService); - - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - if (aTopic === "places-favicons-expired") { - resolve(); - Services.obs.removeObserver(observer, "places-favicons-expired", false); - } - } - }; - - Services.obs.addObserver(observer, "places-favicons-expired", false); - faviconService.expireAllFavicons(); - }); -} - -function observeFavicon(aIsPrivate, aExpectedCookie, aPageURI) { - let faviconReqXUL = false; - let faviconReqPlaces = false; - let attr = {}; - - if (aIsPrivate) { - attr.privateBrowsingId = 1; - } - - let expectedPrincipal = Services.scriptSecurityManager - .createCodebasePrincipal(aPageURI, attr); - - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - // Make sure that the topic is 'http-on-modify-request'. - if (aTopic === "http-on-modify-request") { - // We check the privateBrowsingId for the originAttributes of the loading - // channel. All requests for the favicon should contain the correct - // privateBrowsingId. There are two requests for a favicon loading, one - // from the Places library and one from the XUL image. The difference - // of them is the loading principal. The Places will use the content - // principal and the XUL image will use the system principal. - - let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel); - let reqLoadInfo = httpChannel.loadInfo; - let loadingPrincipal = reqLoadInfo.loadingPrincipal; - let triggeringPrincipal = reqLoadInfo.triggeringPrincipal; - - // Make sure this is a favicon request. - if (httpChannel.URI.spec !== FAVICON_URI) { - return; - } - - // Check the privateBrowsingId. - if (aIsPrivate) { - is(reqLoadInfo.originAttributes.privateBrowsingId, 1, "The loadInfo has correct privateBrowsingId"); - } else { - is(reqLoadInfo.originAttributes.privateBrowsingId, 0, "The loadInfo has correct privateBrowsingId"); - } - - if (loadingPrincipal.equals(systemPrincipal)) { - faviconReqXUL = true; - ok(triggeringPrincipal.equals(expectedPrincipal), - "The triggeringPrincipal of favicon loading from XUL should be the content principal."); - } else { - faviconReqPlaces = true; - ok(loadingPrincipal.equals(expectedPrincipal), - "The loadingPrincipal of favicon loading from Places should be the content prinicpal"); - } - - let faviconCookie = httpChannel.getRequestHeader("cookie"); - - is(faviconCookie, aExpectedCookie, "The cookie of the favicon loading is correct."); - } else { - ok(false, "Received unexpected topic: ", aTopic); - } - - if (faviconReqXUL && faviconReqPlaces) { - resolve(); - Services.obs.removeObserver(observer, "http-on-modify-request", false); - } - } - }; - - Services.obs.addObserver(observer, "http-on-modify-request", false); - }); -} - -function waitOnFaviconResponse(aFaviconURL) { - return new Promise(resolve => { - let observer = { - observe(aSubject, aTopic, aData) { - if (aTopic === "http-on-examine-response" || - aTopic === "http-on-examine-cached-response") { - - let httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel); - let loadInfo = httpChannel.loadInfo; - - if (httpChannel.URI.spec !== aFaviconURL) { - return; - } - - let result = { - topic: aTopic, - privateBrowsingId: loadInfo.originAttributes.privateBrowsingId - }; - - resolve(result); - Services.obs.removeObserver(observer, "http-on-examine-response", false); - Services.obs.removeObserver(observer, "http-on-examine-cached-response", false); - } - } - }; - - Services.obs.addObserver(observer, "http-on-examine-response", false); - Services.obs.addObserver(observer, "http-on-examine-cached-response", false); - }); -} - -function waitOnFaviconLoaded(aFaviconURL) { - return new Promise(resolve => { - let observer = { - onPageChanged(uri, attr, value, id) { - - if (attr === Ci.nsINavHistoryObserver.ATTRIBUTE_FAVICON && - value === aFaviconURL) { - resolve(); - PlacesUtils.history.removeObserver(observer, false); - } - }, - }; - - PlacesUtils.history.addObserver(observer, false); - }); -} - -function* assignCookies(aBrowser, aURL, aCookieValue){ - let tabInfo = yield openTab(aBrowser, aURL); - - yield ContentTask.spawn(tabInfo.browser, aCookieValue, function* (value) { - content.document.cookie = value; - }); - - yield BrowserTestUtils.removeTab(tabInfo.tab); -} - -function* openTab(aBrowser, aURL) { - let tab = aBrowser.addTab(aURL); - - // Select tab and make sure its browser is focused. - aBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = aBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return {tab, browser}; -} - -// A clean up function to prevent affecting other tests. -registerCleanupFunction(() => { - // Clear all cookies. - let cookieMgr = Cc["@mozilla.org/cookiemanager;1"] - .getService(Ci.nsICookieManager); - cookieMgr.removeAll(); - - // Clear all image caches and network caches. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); -}); - -add_task(function* test_favicon_privateBrowsing() { - // Clear all image caches before running the test. - clearAllImageCaches(); - - // Clear all favicons in Places. - yield clearAllPlacesFavicons(); - - // Create a private browsing window. - let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - let pageURI = makeURI(TEST_PAGE); - - // Generate two random cookies for non-private window and private window - // respectively. - let cookies = []; - cookies.push(Math.random().toString()); - cookies.push(Math.random().toString()); - - // Open a tab in private window and add a cookie into it. - yield assignCookies(privateWindow.gBrowser, TEST_SITE, cookies[0]); - - // Open a tab in non-private window and add a cookie into it. - yield assignCookies(gBrowser, TEST_SITE, cookies[1]); - - // Add the observer earlier in case we don't capture events in time. - let promiseObserveFavicon = observeFavicon(true, cookies[0], pageURI); - - // Open a tab for the private window. - let tabInfo = yield openTab(privateWindow.gBrowser, TEST_PAGE); - - // Waiting until favicon requests are all made. - yield promiseObserveFavicon; - - // Close the tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - - // Add the observer earlier in case we don't capture events in time. - promiseObserveFavicon = observeFavicon(false, cookies[1], pageURI); - - // Open a tab for the non-private window. - tabInfo = yield openTab(gBrowser, TEST_PAGE); - - // Waiting until favicon requests are all made. - yield promiseObserveFavicon; - - // Close the tab. - yield BrowserTestUtils.removeTab(tabInfo.tab); - yield BrowserTestUtils.closeWindow(privateWindow); -}); - -add_task(function* test_favicon_cache_privateBrowsing() { - // Clear all image cahces and network cache before running the test. - clearAllImageCaches(); - - let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"] - .getService(Ci.nsICacheStorageService); - networkCache.clear(); - - // Clear all favicons in Places. - yield clearAllPlacesFavicons(); - - // Add an observer for making sure the favicon has been loaded and cached. - let promiseFaviconLoaded = waitOnFaviconLoaded(FAVICON_CACHE_URI); - - // Open a tab for the non-private window. - let tabInfoNonPrivate = yield openTab(gBrowser, TEST_CACHE_PAGE); - - let response = yield waitOnFaviconResponse(FAVICON_CACHE_URI); - - yield promiseFaviconLoaded; - - // Check that the favicon response has come from the network and it has the - // correct privateBrowsingId. - is(response.topic, "http-on-examine-response", "The favicon image should be loaded through network."); - is(response.privateBrowsingId, 0, "We should observe the network response for the non-private tab."); - - // Create a private browsing window. - let privateWindow = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - - // Open a tab for the private window. - let tabInfoPrivate = yield openTab(privateWindow.gBrowser, TEST_CACHE_PAGE); - - // Wait for the favicon response of the private tab. - response = yield waitOnFaviconResponse(FAVICON_CACHE_URI); - - // Make sure the favicon is loaded through the network and its privateBrowsingId is correct. - is(response.topic, "http-on-examine-response", "The favicon image should be loaded through the network again."); - is(response.privateBrowsingId, 1, "We should observe the network response for the private tab."); - - yield BrowserTestUtils.removeTab(tabInfoPrivate.tab); - yield BrowserTestUtils.removeTab(tabInfoNonPrivate.tab); - yield BrowserTestUtils.closeWindow(privateWindow); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js deleted file mode 100644 index 3a078ffc1..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt.js +++ /dev/null @@ -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/. */ - -// This test makes sure that the geolocation prompt does not show a remember -// control inside the private browsing mode. - -add_task(function* test() { - const testPageURL = "http://mochi.test:8888/browser/" + - "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html"; - - function checkGeolocation(aPrivateMode, aWindow) { - return Task.spawn(function* () { - aWindow.gBrowser.selectedTab = aWindow.gBrowser.addTab(testPageURL); - yield BrowserTestUtils.browserLoaded(aWindow.gBrowser.selectedBrowser); - - let notification = aWindow.PopupNotifications.getNotification("geolocation"); - - // Wait until the notification is available. - while (!notification){ - yield new Promise(resolve => { executeSoon(resolve); }); - let notification = aWindow.PopupNotifications.getNotification("geolocation"); - } - - if (aPrivateMode) { - // Make sure the notification is correctly displayed without a remember control - is(notification.secondaryActions.length, 0, "Secondary actions shouldn't exist (always/never remember)"); - } else { - ok(notification.secondaryActions.length > 1, "Secondary actions should exist (always/never remember)"); - } - notification.remove(); - - aWindow.gBrowser.removeCurrentTab(); - }); - }; - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let browser = win.gBrowser.selectedBrowser; - browser.loadURI(testPageURL); - yield BrowserTestUtils.browserLoaded(browser); - - yield checkGeolocation(false, win); - - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let privateBrowser = privateWin.gBrowser.selectedBrowser; - privateBrowser.loadURI(testPageURL); - yield BrowserTestUtils.browserLoaded(privateBrowser); - - yield checkGeolocation(true, privateWin); - - // Cleanup - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(privateWin); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html deleted file mode 100644 index 36d5e3cec..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <title>Geolocation invoker</title> - </head> - <body> - <script type="text/javascript"> - navigator.geolocation.getCurrentPosition(function (pos) { - // ignore - }); - </script> - </body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js deleted file mode 100644 index dbe8ed060..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_lastpbcontextexited.js +++ /dev/null @@ -1,49 +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/. */ - -function test() { - // We need to open a new window for this so that its docshell would get destroyed - // when clearing the PB mode flag. - function runTest(aCloseWindow, aCallback) { - let newWin = OpenBrowserWindow({private: true}); - SimpleTest.waitForFocus(function() { - let expectedExiting = true; - let expectedExited = false; - let observerExiting = { - observe: function(aSubject, aTopic, aData) { - is(aTopic, "last-pb-context-exiting", "Correct topic should be dispatched (exiting)"); - is(expectedExiting, true, "notification not expected yet (exiting)"); - expectedExited = true; - Services.obs.removeObserver(observerExiting, "last-pb-context-exiting"); - } - }; - let observerExited = { - observe: function(aSubject, aTopic, aData) { - is(aTopic, "last-pb-context-exited", "Correct topic should be dispatched (exited)"); - is(expectedExited, true, "notification not expected yet (exited)"); - Services.obs.removeObserver(observerExited, "last-pb-context-exited"); - aCallback(); - } - }; - Services.obs.addObserver(observerExiting, "last-pb-context-exiting", false); - Services.obs.addObserver(observerExited, "last-pb-context-exited", false); - expectedExiting = true; - aCloseWindow(newWin); - newWin = null; - SpecialPowers.forceGC(); - }, newWin); - } - - waitForExplicitFinish(); - - runTest(function(newWin) { - // Simulate pressing the window close button - newWin.document.getElementById("cmd_closeWindow").doCommand(); - }, function () { - runTest(function(newWin) { - // Simulate closing the last tab - newWin.document.getElementById("cmd_close").doCommand(); - }, finish); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js deleted file mode 100644 index acccb5e2d..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage.js +++ /dev/null @@ -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/. */ - - add_task(function test() { - requestLongerTimeout(2); - const page1 = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/' + - 'browser_privatebrowsing_localStorage_page1.html' - - let win = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - - let tab = win.gBrowser.selectedTab = win.gBrowser.addTab(page1); - let browser = win.gBrowser.selectedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - browser.loadURI( - 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/' + - 'browser_privatebrowsing_localStorage_page2.html'); - yield BrowserTestUtils.browserLoaded(browser); - - is(browser.contentTitle, '2', "localStorage should contain 2 items"); - - // Cleanup - yield BrowserTestUtils.closeWindow(win); - }); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js deleted file mode 100644 index 3bcb6e5c9..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after.js +++ /dev/null @@ -1,36 +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/. */ - -// Ensure that a storage instance used by both private and public sessions at different times does not -// allow any data to leak due to cached values. - -// Step 1: Load browser_privatebrowsing_localStorage_before_after_page.html in a private tab, causing a storage -// item to exist. Close the tab. -// Step 2: Load the same page in a non-private tab, ensuring that the storage instance reports only one item -// existing. - -add_task(function test() { - let testURI = "about:blank"; - let prefix = 'http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/'; - - // Step 1. - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let privateBrowser = privateWin.gBrowser.addTab( - prefix + 'browser_privatebrowsing_localStorage_before_after_page.html').linkedBrowser; - yield BrowserTestUtils.browserLoaded(privateBrowser); - - is(privateBrowser.contentTitle, '1', "localStorage should contain 1 item"); - - // Step 2. - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let browser = win.gBrowser.addTab( - prefix + 'browser_privatebrowsing_localStorage_before_after_page2.html').linkedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - is(browser.contentTitle, 'null|0', 'localStorage should contain 0 items'); - - // Cleanup - yield BrowserTestUtils.closeWindow(privateWin); - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html deleted file mode 100644 index 143fea4e7..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html +++ /dev/null @@ -1,11 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<script type="text/javascript"> - localStorage.clear(); - localStorage.setItem('zzztest', 'zzzvalue'); - document.title = localStorage.length; -</script> -</head> -<body> -</body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html deleted file mode 100644 index 9a7e2da63..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html +++ /dev/null @@ -1,10 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<script type="text/javascript"> - document.title = localStorage.getItem('zzztest', 'zzzvalue') + '|' + localStorage.length; - localStorage.clear(); -</script> -</head> -<body> -</body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html deleted file mode 100644 index 3e79a01bf..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html +++ /dev/null @@ -1,10 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<script type="text/javascript"> - localStorage.clear(); - localStorage.setItem('test1', 'value1'); -</script> -</head> -<body> -</body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html deleted file mode 100644 index 8c9b28fd8..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html +++ /dev/null @@ -1,10 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<script type="text/javascript"> - localStorage.setItem('test2', 'value2'); - document.title = localStorage.length; -</script> -</head> -<body> -</body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js deleted file mode 100644 index b09ec0368..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_newtab_from_popup.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Tests that a popup window in private browsing window opens - * new tab links in the original private browsing window as - * new tabs. - * - * This is a regression test for bug 1202634. - */ - -// We're able to sidestep some quote-escaping issues when -// nesting data URI's by encoding the second data URI in -// base64. -const POPUP_BODY_BASE64 = btoa(`<a href="http://example.com/" target="_blank" - id="second"> - Now click this - </a>`); -const POPUP_LINK = `data:text/html;charset=utf-8;base64,${POPUP_BODY_BASE64}`; -const WINDOW_BODY = `data:text/html, - <a href="%23" id="first" - onclick="window.open('${POPUP_LINK}', '_blank', - 'width=630,height=500')"> - First click this. - </a>`; - -add_task(function* test_private_popup_window_opens_private_tabs() { - let privWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - - // Sanity check - this browser better be private. - ok(PrivateBrowsingUtils.isWindowPrivate(privWin), - "Opened a private browsing window."); - - // First, open a private browsing window, and load our - // testing page. - let privBrowser = privWin.gBrowser.selectedBrowser; - yield BrowserTestUtils.loadURI(privBrowser, WINDOW_BODY); - yield BrowserTestUtils.browserLoaded(privBrowser); - - // Next, click on the link in the testing page, and ensure - // that a private popup window is opened. - let openedPromise = BrowserTestUtils.waitForNewWindow(true, POPUP_LINK); - - yield BrowserTestUtils.synthesizeMouseAtCenter("#first", {}, privBrowser); - let popupWin = yield openedPromise; - ok(PrivateBrowsingUtils.isWindowPrivate(popupWin), - "Popup window was private."); - - // Now click on the link in the popup, and ensure that a new - // tab is opened in the original private browsing window. - let newTabPromise = BrowserTestUtils.waitForNewTab(privWin.gBrowser); - let popupBrowser = popupWin.gBrowser.selectedBrowser; - yield BrowserTestUtils.synthesizeMouseAtCenter("#second", {}, popupBrowser); - let newPrivTab = yield newTabPromise; - - // Ensure that the newly created tab's browser is private. - ok(PrivateBrowsingUtils.isBrowserPrivate(newPrivTab.linkedBrowser), - "Newly opened tab should be private."); - - // Clean up - yield BrowserTestUtils.removeTab(newPrivTab); - yield BrowserTestUtils.closeWindow(popupWin); - yield BrowserTestUtils.closeWindow(privWin); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js deleted file mode 100644 index ae6e8a6a3..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_noSessionRestoreMenuOption.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; - -/** - * Tests that if we open a tab within a private browsing window, and then - * close that private browsing window, that subsequent private browsing - * windows do not allow the command for restoring the last session. - */ -add_task(function* test_no_session_restore_menu_option() { - let win = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - ok(true, "The first private window got loaded"); - win.gBrowser.addTab("about:mozilla"); - yield BrowserTestUtils.closeWindow(win); - - win = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - let srCommand = win.document.getElementById("Browser:RestoreLastSession"); - ok(srCommand, "The Session Restore command should exist"); - is(PrivateBrowsingUtils.isWindowPrivate(win), true, - "PrivateBrowsingUtils should report the correct per-window private browsing status"); - is(srCommand.hasAttribute("disabled"), true, - "The Session Restore command should be disabled in private browsing mode"); - - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js deleted file mode 100644 index d2a69dd4e..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_nonbrowser.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; - -/** - * Tests that we fire the last-pb-context-exited observer notification - * when the last private browsing window closes, even if a chrome window - * was opened from that private browsing window. - */ -add_task(function* () { - let win = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - let chromeWin = win.open("chrome://browser/content/places/places.xul", "_blank", - "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar"); - yield BrowserTestUtils.waitForEvent(chromeWin, "load"); - let obsPromise = TestUtils.topicObserved("last-pb-context-exited"); - yield BrowserTestUtils.closeWindow(win); - yield obsPromise; - Assert.ok(true, "Got the last-pb-context-exited notification"); - chromeWin.close(); -}); - diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js deleted file mode 100644 index 0b1369b11..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_opendir.js +++ /dev/null @@ -1,133 +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 test makes sure that the last open directory used inside the private -// browsing mode is not remembered after leaving that mode. - -var windowsToClose = []; -function testOnWindow(options, callback) { - var win = OpenBrowserWindow(options); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - windowsToClose.push(win); - callback(win); - }, false); -} - -registerCleanupFunction(function() { - windowsToClose.forEach(function(win) { - win.close(); - }); -}); - -function test() { - // initialization - waitForExplicitFinish(); - let ds = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties); - let dir1 = ds.get("ProfD", Ci.nsIFile); - let dir2 = ds.get("TmpD", Ci.nsIFile); - let file = dir2.clone(); - file.append("pbtest.file"); - file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600); - - const kPrefName = "browser.open.lastDir"; - - function setupCleanSlate(win) { - win.gLastOpenDirectory.reset(); - gPrefService.clearUserPref(kPrefName); - } - - setupCleanSlate(window); - - // open one regular and one private window - testOnWindow(undefined, function(nonPrivateWindow) { - setupCleanSlate(nonPrivateWindow); - testOnWindow({private: true}, function(privateWindow) { - setupCleanSlate(privateWindow); - - // Test 1: general workflow test - - // initial checks - ok(!nonPrivateWindow.gLastOpenDirectory.path, - "Last open directory path should be initially empty"); - nonPrivateWindow.gLastOpenDirectory.path = dir2; - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir2.path, - "The path should be successfully set"); - nonPrivateWindow.gLastOpenDirectory.path = null; - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir2.path, - "The path should be not change when assigning it to null"); - nonPrivateWindow.gLastOpenDirectory.path = dir1; - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path, - "The path should be successfully outside of the private browsing mode"); - - // test the private window - is(privateWindow.gLastOpenDirectory.path.path, dir1.path, - "The path should not change when entering the private browsing mode"); - privateWindow.gLastOpenDirectory.path = dir2; - is(privateWindow.gLastOpenDirectory.path.path, dir2.path, - "The path should successfully change inside the private browsing mode"); - - // test the non-private window - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path, - "The path should be reset to the same path as before entering the private browsing mode"); - - setupCleanSlate(nonPrivateWindow); - setupCleanSlate(privateWindow); - - // Test 2: the user first tries to open a file inside the private browsing mode - - // test the private window - ok(!privateWindow.gLastOpenDirectory.path, - "No original path should exist inside the private browsing mode"); - privateWindow.gLastOpenDirectory.path = dir1; - is(privateWindow.gLastOpenDirectory.path.path, dir1.path, - "The path should be successfully set inside the private browsing mode"); - // test the non-private window - ok(!nonPrivateWindow.gLastOpenDirectory.path, - "The path set inside the private browsing mode should not leak when leaving that mode"); - - setupCleanSlate(nonPrivateWindow); - setupCleanSlate(privateWindow); - - // Test 3: the last open directory is set from a previous session, it should be used - // in normal mode - - gPrefService.setComplexValue(kPrefName, Ci.nsILocalFile, dir1); - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path, - "The pref set from last session should take effect outside the private browsing mode"); - - setupCleanSlate(nonPrivateWindow); - setupCleanSlate(privateWindow); - - // Test 4: the last open directory is set from a previous session, it should be used - // in private browsing mode mode - - gPrefService.setComplexValue(kPrefName, Ci.nsILocalFile, dir1); - // test the private window - is(privateWindow.gLastOpenDirectory.path.path, dir1.path, - "The pref set from last session should take effect inside the private browsing mode"); - // test the non-private window - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path, - "The pref set from last session should remain in effect after leaving the private browsing mode"); - - setupCleanSlate(nonPrivateWindow); - setupCleanSlate(privateWindow); - - // Test 5: setting the path to a file shouldn't work - - nonPrivateWindow.gLastOpenDirectory.path = file; - ok(!nonPrivateWindow.gLastOpenDirectory.path, - "Setting the path to a file shouldn't work when it's originally null"); - nonPrivateWindow.gLastOpenDirectory.path = dir1; - nonPrivateWindow.gLastOpenDirectory.path = file; - is(nonPrivateWindow.gLastOpenDirectory.path.path, dir1.path, - "Setting the path to a file shouldn't work when it's not originally null"); - - // cleanup - file.remove(false); - finish(); - }); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html deleted file mode 100644 index f5bb3212f..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <title>Title 1</title> - </head> - <body> - </body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js deleted file mode 100644 index 32436b3cc..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.js +++ /dev/null @@ -1,72 +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 to make sure that the visited page titles do not get updated inside the -// private browsing mode. -"use strict"; - -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/PlacesUtils.jsm"); - -add_task(function* test() { - const TEST_URL = "http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html" - const TEST_URI = Services.io.newURI(TEST_URL, null, null); - const TITLE_1 = "Title 1"; - const TITLE_2 = "Title 2"; - - function waitForTitleChanged() { - return new Promise(resolve => { - let historyObserver = { - onTitleChanged: function(uri, pageTitle) { - PlacesUtils.history.removeObserver(historyObserver, false); - resolve({uri: uri, pageTitle: pageTitle}); - }, - onBeginUpdateBatch: function () {}, - onEndUpdateBatch: function () {}, - onVisit: function () {}, - onDeleteURI: function () {}, - onClearHistory: function () {}, - onPageChanged: function () {}, - onDeleteVisits: function() {}, - QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]) - }; - - PlacesUtils.history.addObserver(historyObserver, false); - }); - }; - - yield PlacesTestUtils.clearHistory(); - - let tabToClose = gBrowser.selectedTab = gBrowser.addTab(TEST_URL); - yield waitForTitleChanged(); - is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_1, "The title matches the orignal title after first visit"); - - let place = { - uri: TEST_URI, - title: TITLE_2, - visits: [{ - visitDate: Date.now() * 1000, - transitionType: Ci.nsINavHistoryService.TRANSITION_LINK - }] - }; - PlacesUtils.asyncHistory.updatePlaces(place, { - handleError: () => ok(false, "Unexpected error in adding visit."), - handleResult: function () { }, - handleCompletion: function () {} - }); - - yield waitForTitleChanged(); - is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_2, "The title matches the updated title after updating visit"); - - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private:true}); - yield BrowserTestUtils.browserLoaded(privateWin.gBrowser.addTab(TEST_URL).linkedBrowser); - - is(PlacesUtils.history.getPageTitle(TEST_URI), TITLE_2, "The title remains the same after visiting in private window"); - yield PlacesTestUtils.clearHistory(); - - // Cleanup - BrowserTestUtils.closeWindow(privateWin); - gBrowser.removeTab(tabToClose); -}); - diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js deleted file mode 100644 index a70019976..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placestitle.js +++ /dev/null @@ -1,95 +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 test makes sure that the title of existing history entries does not -// change inside a private window. - -add_task(function* test() { - const TEST_URL = "http://mochi.test:8888/browser/browser/components/" + - "privatebrowsing/test/browser/title.sjs"; - let cm = Services.cookies; - - function cleanup() { - // delete all cookies - cm.removeAll(); - // delete all history items - return PlacesTestUtils.clearHistory(); - } - - yield cleanup(); - - let deferredFirst = PromiseUtils.defer(); - let deferredSecond = PromiseUtils.defer(); - let deferredThird = PromiseUtils.defer(); - - let testNumber = 0; - let historyObserver = { - onTitleChanged: function(aURI, aPageTitle) { - if (aURI.spec != TEST_URL) - return; - switch (++testNumber) { - case 1: - // The first time that the page is loaded - deferredFirst.resolve(aPageTitle); - break; - case 2: - // The second time that the page is loaded - deferredSecond.resolve(aPageTitle); - break; - case 3: - // After clean up - deferredThird.resolve(aPageTitle); - break; - default: - // Checks that opening the page in a private window should not fire a - // title change. - ok(false, "Title changed. Unexpected pass: " + testNumber); - } - }, - - onBeginUpdateBatch: function () {}, - onEndUpdateBatch: function () {}, - onVisit: function () {}, - onDeleteURI: function () {}, - onClearHistory: function () {}, - onPageChanged: function () {}, - onDeleteVisits: function() {}, - QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver]) - }; - PlacesUtils.history.addObserver(historyObserver, false); - - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL); - let aPageTitle = yield deferredFirst.promise; - // The first time that the page is loaded - is(aPageTitle, "No Cookie", - "The page should be loaded without any cookie for the first time"); - - win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL); - aPageTitle = yield deferredSecond.promise; - // The second time that the page is loaded - is(aPageTitle, "Cookie", - "The page should be loaded with a cookie for the second time"); - - yield cleanup(); - - win.gBrowser.selectedTab = win.gBrowser.addTab(TEST_URL); - aPageTitle = yield deferredThird.promise; - // After clean up - is(aPageTitle, "No Cookie", - "The page should be loaded without any cookie again"); - - let win2 = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - - let private_tab = win2.gBrowser.addTab(TEST_URL); - win2.gBrowser.selectedTab = private_tab; - yield BrowserTestUtils.browserLoaded(private_tab.linkedBrowser); - - // Cleanup - yield cleanup(); - PlacesUtils.history.removeObserver(historyObserver); - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(win2); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js deleted file mode 100644 index 71d85f296..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js +++ /dev/null @@ -1,70 +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 test makes sure that private browsing mode disables the remember option -// for the popup blocker menu. -add_task(function* test() { - let testURI = "http://mochi.test:8888/browser/browser/components/privatebrowsing/test/browser/popup.html"; - let oldPopupPolicy = gPrefService.getBoolPref("dom.disable_open_during_load"); - gPrefService.setBoolPref("dom.disable_open_during_load", true); - - registerCleanupFunction(() => { - gPrefService.setBoolPref("dom.disable_open_during_load", oldPopupPolicy); - }); - - function testPopupBlockerMenuItem(aExpectedDisabled, aWindow, aCallback) { - - aWindow.gBrowser.addEventListener("DOMUpdatePageReport", function() { - aWindow.gBrowser.removeEventListener("DOMUpdatePageReport", arguments.callee, false); - - executeSoon(function() { - let notification = aWindow.gBrowser.getNotificationBox().getNotificationWithValue("popup-blocked"); - ok(notification, "The notification box should be displayed"); - - function checkMenuItem(callback) { - dump("CMI: in\n"); - aWindow.document.addEventListener("popupshown", function(event) { - dump("CMI: popupshown\n"); - aWindow.document.removeEventListener("popupshown", arguments.callee, false); - - if (aExpectedDisabled) - is(aWindow.document.getElementById("blockedPopupAllowSite").getAttribute("disabled"), "true", - "The allow popups menu item should be disabled"); - - event.originalTarget.hidePopup(); - dump("CMI: calling back\n"); - callback(); - dump("CMI: called back\n"); - }, false); - dump("CMI: out\n"); - } - - checkMenuItem(function() { - aCallback(); - }); - notification.querySelector("button").doCommand(); - }); - - }, false); - - aWindow.gBrowser.selectedBrowser.loadURI(testURI); - } - - let win1 = yield BrowserTestUtils.openNewBrowserWindow(); - yield new Promise(resolve => waitForFocus(resolve, win1)); - yield new Promise(resolve => testPopupBlockerMenuItem(false, win1, resolve)); - - let win2 = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - yield new Promise(resolve => waitForFocus(resolve, win2)); - yield new Promise(resolve => testPopupBlockerMenuItem(true, win2, resolve)); - - let win3 = yield BrowserTestUtils.openNewBrowserWindow(); - yield new Promise(resolve => waitForFocus(resolve, win3)); - yield new Promise(resolve => testPopupBlockerMenuItem(false, win3, resolve)); - - // Cleanup - yield BrowserTestUtils.closeWindow(win1); - yield BrowserTestUtils.closeWindow(win2); - yield BrowserTestUtils.closeWindow(win3); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js deleted file mode 100644 index fe69a2234..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler.js +++ /dev/null @@ -1,47 +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 test makes sure that the web pages can't register protocol handlers -// inside the private browsing mode. - -add_task(function* test() { - let notificationValue = "Protocol Registration: testprotocol"; - let testURI = "http://example.com/browser/" + - "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html"; - - let doTest = Task.async(function* (aIsPrivateMode, aWindow) { - let tab = aWindow.gBrowser.selectedTab = aWindow.gBrowser.addTab(testURI); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - let promiseFinished = PromiseUtils.defer(); - setTimeout(function() { - let notificationBox = aWindow.gBrowser.getNotificationBox(); - let notification = notificationBox.getNotificationWithValue(notificationValue); - - if (aIsPrivateMode) { - // Make sure the notification is correctly displayed without a remember control - ok(!notification, "Notification box should not be displayed inside of private browsing mode"); - } else { - // Make sure the notification is correctly displayed with a remember control - ok(notification, "Notification box should be displaying outside of private browsing mode"); - } - - promiseFinished.resolve(); - }, 100); // remember control is added in a setTimeout(0) call - - yield promiseFinished.promise; - }); - - // test first when not on private mode - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield doTest(false, win); - - // then test when on private mode - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true}); - yield doTest(true, privateWin); - - // Cleanup - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(privateWin); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html deleted file mode 100644 index 74f846d54..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html +++ /dev/null @@ -1,13 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <title>Protocol registrar page</title> - </head> - <body> - <script type="text/javascript"> - navigator.registerProtocolHandler("testprotocol", - "https://example.com/foobar?uri=%s", - "Test Protocol"); - </script> - </body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js deleted file mode 100644 index dbd74029d..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_sidebar.js +++ /dev/null @@ -1,92 +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 test makes sure that Sidebars do not migrate across windows with -// different privacy states - -// See Bug 885054: https://bugzilla.mozilla.org/show_bug.cgi?id=885054 - -function test() { - waitForExplicitFinish(); - - let { utils: Cu } = Components; - - let { Promise: { defer } } = Cu.import("resource://gre/modules/Promise.jsm", {}); - - // opens a sidebar - function openSidebar(win) { - let { promise, resolve } = defer(); - let doc = win.document; - - let sidebarID = 'viewBookmarksSidebar'; - - let sidebar = doc.getElementById('sidebar'); - - let sidebarurl = doc.getElementById(sidebarID).getAttribute('sidebarurl'); - - sidebar.addEventListener('load', function onSidebarLoad() { - if (sidebar.contentWindow.location.href != sidebarurl) - return; - sidebar.removeEventListener('load', onSidebarLoad, true); - - resolve(win); - }, true); - - win.SidebarUI.show(sidebarID); - - return promise; - } - - let windowCache = []; - function cacheWindow(w) { - windowCache.push(w); - return w; - } - function closeCachedWindows () { - windowCache.forEach(w => w.close()); - } - - // Part 1: NON PRIVATE WINDOW -> PRIVATE WINDOW - openWindow(window, {}, 1). - then(cacheWindow). - then(openSidebar). - then(win => openWindow(win, { private: true })). - then(cacheWindow). - then(function({ document }) { - let sidebarBox = document.getElementById("sidebar-box"); - is(sidebarBox.hidden, true, 'Opening a private window from reg window does not open the sidebar'); - }). - // Part 2: NON PRIVATE WINDOW -> NON PRIVATE WINDOW - then(() => openWindow(window)). - then(cacheWindow). - then(openSidebar). - then(win => openWindow(win)). - then(cacheWindow). - then(function({ document }) { - let sidebarBox = document.getElementById("sidebar-box"); - is(sidebarBox.hidden, false, 'Opening a reg window from reg window does open the sidebar'); - }). - // Part 3: PRIVATE WINDOW -> NON PRIVATE WINDOW - then(() => openWindow(window, { private: true })). - then(cacheWindow). - then(openSidebar). - then(win => openWindow(win)). - then(cacheWindow). - then(function({ document }) { - let sidebarBox = document.getElementById("sidebar-box"); - is(sidebarBox.hidden, true, 'Opening a reg window from a private window does not open the sidebar'); - }). - // Part 4: PRIVATE WINDOW -> PRIVATE WINDOW - then(() => openWindow(window, { private: true })). - then(cacheWindow). - then(openSidebar). - then(win => openWindow(win, { private: true })). - then(cacheWindow). - then(function({ document }) { - let sidebarBox = document.getElementById("sidebar-box"); - is(sidebarBox.hidden, false, 'Opening a private window from private window does open the sidebar'); - }). - then(closeCachedWindows). - then(finish); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js deleted file mode 100644 index e2b8593d6..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_theming.js +++ /dev/null @@ -1,38 +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 test makes sure that privatebrowsingmode attribute of the window is correctly -// adjusted based on whether the window is a private window. - -var windowsToClose = []; -function testOnWindow(options, callback) { - var win = OpenBrowserWindow(options); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - windowsToClose.push(win); - executeSoon(() => callback(win)); - }, false); -} - -registerCleanupFunction(function() { - windowsToClose.forEach(function(win) { - win.close(); - }); -}); - -function test() { - // initialization - waitForExplicitFinish(); - - ok(!document.documentElement.hasAttribute("privatebrowsingmode"), - "privatebrowsingmode should not be present in normal mode"); - - // open a private window - testOnWindow({private: true}, function(win) { - is(win.document.documentElement.getAttribute("privatebrowsingmode"), "temporary", - "privatebrowsingmode should be \"temporary\" inside the private browsing mode"); - - finish(); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js deleted file mode 100644 index cbd2c60f8..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_ui.js +++ /dev/null @@ -1,82 +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 test makes sure that the gPrivateBrowsingUI object, the Private Browsing -// menu item and its XUL <command> element work correctly. - -function test() { - // initialization - waitForExplicitFinish(); - let windowsToClose = []; - let testURI = "about:blank"; - let pbMenuItem; - let cmd; - - function doTest(aIsPrivateMode, aWindow, aCallback) { - aWindow.gBrowser.selectedBrowser.addEventListener("load", function onLoad() { - aWindow.gBrowser.selectedBrowser.removeEventListener("load", onLoad, true); - - ok(aWindow.gPrivateBrowsingUI, "The gPrivateBrowsingUI object exists"); - - pbMenuItem = aWindow.document.getElementById("menu_newPrivateWindow"); - ok(pbMenuItem, "The Private Browsing menu item exists"); - - cmd = aWindow.document.getElementById("Tools:PrivateBrowsing"); - isnot(cmd, null, "XUL command object for the private browsing service exists"); - - is(pbMenuItem.getAttribute("label"), "New Private Window", - "The Private Browsing menu item should read \"New Private Window\""); - is(PrivateBrowsingUtils.isWindowPrivate(aWindow), aIsPrivateMode, - "PrivateBrowsingUtils should report the correct per-window private browsing status (privateBrowsing should be " + - aIsPrivateMode + ")"); - - aCallback(); - }, true); - - aWindow.gBrowser.selectedBrowser.loadURI(testURI); - }; - - function openPrivateBrowsingModeByUI(aWindow, aCallback) { - Services.obs.addObserver(function observer(aSubject, aTopic, aData) { - aSubject.addEventListener("load", function() { - aSubject.removeEventListener("load", arguments.callee); - Services.obs.removeObserver(observer, "domwindowopened"); - windowsToClose.push(aSubject); - aCallback(aSubject); - }, false); - }, "domwindowopened", false); - - cmd = aWindow.document.getElementById("Tools:PrivateBrowsing"); - var func = new Function("", cmd.getAttribute("oncommand")); - func.call(cmd); - }; - - function testOnWindow(aOptions, aCallback) { - whenNewWindowLoaded(aOptions, function(aWin) { - windowsToClose.push(aWin); - // execute should only be called when need, like when you are opening - // web pages on the test. If calling executeSoon() is not necesary, then - // call whenNewWindowLoaded() instead of testOnWindow() on your test. - executeSoon(() => aCallback(aWin)); - }); - }; - - // this function is called after calling finish() on the test. - registerCleanupFunction(function() { - windowsToClose.forEach(function(aWin) { - aWin.close(); - }); - }); - - // test first when not on private mode - testOnWindow({}, function(aWin) { - doTest(false, aWin, function() { - // then test when on private mode, opening a new private window from the - // user interface. - openPrivateBrowsingModeByUI(aWin, function(aPrivateWin) { - doTest(true, aPrivateWin, finish); - }); - }); - }); -} diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js deleted file mode 100644 index 2be701bcd..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_urlbarfocus.js +++ /dev/null @@ -1,43 +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 test makes sure that the URL bar is focused when entering the private window. - -"use strict"; -Components.utils.import("resource://gre/modules/Promise.jsm", this); -let aboutNewTabService = Components.classes["@mozilla.org/browser/aboutnewtab-service;1"] - .getService(Components.interfaces.nsIAboutNewTabService); - -function checkUrlbarFocus(win) { - let urlbar = win.gURLBar; - is(win.document.activeElement, urlbar.inputField, "URL Bar should be focused"); - is(urlbar.value, "", "URL Bar should be empty"); -} - -function openNewPrivateWindow() { - let deferred = Promise.defer(); - whenNewWindowLoaded({private: true}, win => { - executeSoon(() => deferred.resolve(win)); - }); - return deferred.promise; -} - -add_task(function* () { - let win = yield openNewPrivateWindow(); - checkUrlbarFocus(win); - win.close(); -}); - -add_task(function* () { - aboutNewTabService.newTabURL = "about:blank"; - registerCleanupFunction(() => { - aboutNewTabService.resetNewTabURL(); - }); - - let win = yield openNewPrivateWindow(); - checkUrlbarFocus(win); - win.close(); - - aboutNewTabService.resetNewTabURL(); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js deleted file mode 100644 index aca8d0c7b..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle.js +++ /dev/null @@ -1,77 +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 test makes sure that the window title changes correctly while switching -// from and to private browsing mode. - -add_task(function test() { - const testPageURL = "http://mochi.test:8888/browser/" + - "browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html"; - requestLongerTimeout(2); - - // initialization of expected titles - let test_title = "Test title"; - let app_name = document.documentElement.getAttribute("title"); - const isOSX = ("nsILocalFileMac" in Ci); - let page_with_title; - let page_without_title; - let about_pb_title; - let pb_page_with_title; - let pb_page_without_title; - let pb_about_pb_title; - if (isOSX) { - page_with_title = test_title; - page_without_title = app_name; - about_pb_title = "Open a private window?"; - pb_page_with_title = test_title + " - (Private Browsing)"; - pb_page_without_title = app_name + " - (Private Browsing)"; - pb_about_pb_title = "Private Browsing - (Private Browsing)"; - } - else { - page_with_title = test_title + " - " + app_name; - page_without_title = app_name; - about_pb_title = "Open a private window?" + " - " + app_name; - pb_page_with_title = test_title + " - " + app_name + " (Private Browsing)"; - pb_page_without_title = app_name + " (Private Browsing)"; - pb_about_pb_title = "Private Browsing - " + app_name + " (Private Browsing)"; - } - - function* testTabTitle(aWindow, url, insidePB, expected_title) { - let tab = (yield BrowserTestUtils.openNewForegroundTab(aWindow.gBrowser)); - yield BrowserTestUtils.loadURI(tab.linkedBrowser, url); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - yield BrowserTestUtils.waitForCondition(() => { - return aWindow.document.title === expected_title; - }, `Window title should be ${expected_title}, got ${aWindow.document.title}`); - - is(aWindow.document.title, expected_title, "The window title for " + url + - " is correct (" + (insidePB ? "inside" : "outside") + - " private browsing mode)"); - - let win = aWindow.gBrowser.replaceTabWithWindow(tab); - yield BrowserTestUtils.waitForEvent(win, "load", false); - - yield BrowserTestUtils.waitForCondition(() => { - return win.document.title === expected_title; - }, `Window title should be ${expected_title}, got ${aWindow.document.title}`); - - is(win.document.title, expected_title, "The window title for " + url + - " detached tab is correct (" + (insidePB ? "inside" : "outside") + - " private browsing mode)"); - - yield Promise.all([ BrowserTestUtils.closeWindow(win), - BrowserTestUtils.closeWindow(aWindow) ]); - } - - function openWin(private) { - return BrowserTestUtils.openNewBrowserWindow({ private }); - } - yield Task.spawn(testTabTitle((yield openWin(false)), "about:blank", false, page_without_title)); - yield Task.spawn(testTabTitle((yield openWin(false)), testPageURL, false, page_with_title)); - yield Task.spawn(testTabTitle((yield openWin(false)), "about:privatebrowsing", false, about_pb_title)); - yield Task.spawn(testTabTitle((yield openWin(true)), "about:blank", true, pb_page_without_title)); - yield Task.spawn(testTabTitle((yield openWin(true)), testPageURL, true, pb_page_with_title)); - yield Task.spawn(testTabTitle((yield openWin(true)), "about:privatebrowsing", true, pb_about_pb_title)); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html deleted file mode 100644 index 760bde7d1..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html +++ /dev/null @@ -1,9 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <title>Test title</title> - </head> - <body> - Test page for the window title test - </body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js deleted file mode 100644 index f5afcbd61..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoom.js +++ /dev/null @@ -1,37 +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 test makes sure that private browsing turns off doesn't cause zoom -// settings to be reset on tab switch (bug 464962) - -add_task(function* test() { - let win = (yield BrowserTestUtils.openNewBrowserWindow({ private: true })); - let tabAbout = (yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:")); - let tabMozilla = (yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:")); - - let mozillaZoom = win.ZoomManager.zoom; - - // change the zoom on the mozilla page - win.FullZoom.enlarge(); - // make sure the zoom level has been changed - isnot(win.ZoomManager.zoom, mozillaZoom, "Zoom level can be changed"); - mozillaZoom = win.ZoomManager.zoom; - - // switch to about: tab - yield BrowserTestUtils.switchTab(win.gBrowser, tabAbout); - - // switch back to mozilla tab - yield BrowserTestUtils.switchTab(win.gBrowser, tabMozilla); - - // make sure the zoom level has not changed - is(win.ZoomManager.zoom, mozillaZoom, - "Entering private browsing should not reset the zoom on a tab"); - - // cleanup - win.FullZoom.reset(); - yield Promise.all([ BrowserTestUtils.removeTab(tabMozilla), - BrowserTestUtils.removeTab(tabAbout) ]); - - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js deleted file mode 100644 index b67bfc229..000000000 --- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_zoomrestore.js +++ /dev/null @@ -1,64 +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 test makes sure that about:privatebrowsing does not appear zoomed in -// if there is already a zoom site pref for about:blank (bug 487656). - -add_task(function* test() { - // initialization - let windowsToClose = []; - let windowsToReset = []; - - function promiseLocationChange() { - return new Promise(resolve => { - Services.obs.addObserver(function onLocationChange(subj, topic, data) { - Services.obs.removeObserver(onLocationChange, topic); - resolve(); - }, "browser-fullZoom:location-change", false); - }); - } - - function promiseTestReady(aIsZoomedWindow, aWindow) { - // Need to wait on two things, the ordering of which is not guaranteed: - // (1) the page load, and (2) FullZoom's update to the new page's zoom - // level. FullZoom broadcasts "browser-fullZoom:location-change" when its - // update is done. (See bug 856366 for details.) - - - let browser = aWindow.gBrowser.selectedBrowser; - return BrowserTestUtils.loadURI(browser, "about:blank").then(() => { - return Promise.all([ BrowserTestUtils.browserLoaded(browser), - promiseLocationChange() ]); - }).then(() => doTest(aIsZoomedWindow, aWindow)); - } - - function doTest(aIsZoomedWindow, aWindow) { - if (aIsZoomedWindow) { - is(aWindow.ZoomManager.zoom, 1, - "Zoom level for freshly loaded about:blank should be 1"); - // change the zoom on the blank page - aWindow.FullZoom.enlarge(); - isnot(aWindow.ZoomManager.zoom, 1, "Zoom level for about:blank should be changed"); - return; - } - - // make sure the zoom level is set to 1 - is(aWindow.ZoomManager.zoom, 1, "Zoom level for about:privatebrowsing should be reset"); - } - - function testOnWindow(options, callback) { - return BrowserTestUtils.openNewBrowserWindow(options).then((win) => { - windowsToClose.push(win); - windowsToReset.push(win); - return win; - }); - } - - yield testOnWindow({}).then(win => promiseTestReady(true, win)); - yield testOnWindow({private: true}).then(win => promiseTestReady(false, win)); - - // cleanup - windowsToReset.forEach((win) => win.FullZoom.reset()); - yield Promise.all(windowsToClose.map(win => BrowserTestUtils.closeWindow(win))); -}); diff --git a/browser/components/privatebrowsing/test/browser/empty_file.html b/browser/components/privatebrowsing/test/browser/empty_file.html deleted file mode 100644 index 42682b474..000000000 --- a/browser/components/privatebrowsing/test/browser/empty_file.html +++ /dev/null @@ -1 +0,0 @@ -<html><body></body></html>
\ No newline at end of file diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.html b/browser/components/privatebrowsing/test/browser/file_favicon.html deleted file mode 100644 index b571134e1..000000000 --- a/browser/components/privatebrowsing/test/browser/file_favicon.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML> -<html> - <head> - <meta charset='utf-8'> - <title>Favicon Test for originAttributes</title> - <link rel="icon" type="image/png" href="file_favicon.png" /> - </head> - <body> - Favicon!! - </body> -</html>
\ No newline at end of file diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.png b/browser/components/privatebrowsing/test/browser/file_favicon.png Binary files differdeleted file mode 100644 index 5535363c9..000000000 --- a/browser/components/privatebrowsing/test/browser/file_favicon.png +++ /dev/null diff --git a/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^ b/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^ deleted file mode 100644 index 9e23c73b7..000000000 --- a/browser/components/privatebrowsing/test/browser/file_favicon.png^headers^ +++ /dev/null @@ -1 +0,0 @@ -Cache-Control: no-cache diff --git a/browser/components/privatebrowsing/test/browser/head.js b/browser/components/privatebrowsing/test/browser/head.js deleted file mode 100644 index c822ba8d1..000000000 --- a/browser/components/privatebrowsing/test/browser/head.js +++ /dev/null @@ -1,63 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -var {PromiseUtils} = Cu.import("resource://gre/modules/PromiseUtils.jsm", {}); -XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils", - "resource://testing-common/PlacesTestUtils.jsm"); - -function whenNewWindowLoaded(aOptions, aCallback) { - let win = OpenBrowserWindow(aOptions); - let focused = SimpleTest.promiseFocus(win); - let startupFinished = TestUtils.topicObserved("browser-delayed-startup-finished", - subject => subject == win).then(() => win); - Promise.all([focused, startupFinished]) - .then(results => executeSoon(() => aCallback(results[1]))); - - return win; -} - -function openWindow(aParent, aOptions, a3) { - let { Promise: { defer } } = Components.utils.import("resource://gre/modules/Promise.jsm", {}); - let { promise, resolve } = defer(); - - let win = aParent.OpenBrowserWindow(aOptions); - - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - resolve(win); - }, false); - - return promise; -} - -function newDirectory() { - let FileUtils = - Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils; - let tmpDir = FileUtils.getDir("TmpD", [], true); - let dir = tmpDir.clone(); - dir.append("testdir"); - dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - return dir; -} - -function newFileInDirectory(aDir) { - let FileUtils = - Cu.import("resource://gre/modules/FileUtils.jsm", {}).FileUtils; - let file = aDir.clone(); - file.append("testfile"); - file.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_FILE); - return file; -} - -function clearHistory() { - // simulate clearing the private data - Services.obs.notifyObservers(null, "browser:purge-session-history", ""); -} - -function _initTest() { - // Don't use about:home as the homepage for new windows - Services.prefs.setIntPref("browser.startup.page", 0); - registerCleanupFunction(() => Services.prefs.clearUserPref("browser.startup.page")); -} - -_initTest(); diff --git a/browser/components/privatebrowsing/test/browser/popup.html b/browser/components/privatebrowsing/test/browser/popup.html deleted file mode 100644 index 68bbbfa26..000000000 --- a/browser/components/privatebrowsing/test/browser/popup.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<html> - <head> - <meta charset="utf8"> - <title>Page creating a popup</title> - </head> - <body> - <script type="text/javascript"> - window.open("data:text/plain,test", "testwin"); - </script> - </body> -</html> diff --git a/browser/components/privatebrowsing/test/browser/title.sjs b/browser/components/privatebrowsing/test/browser/title.sjs deleted file mode 100644 index 568e235be..000000000 --- a/browser/components/privatebrowsing/test/browser/title.sjs +++ /dev/null @@ -1,22 +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 provides the tests with a page with different titles based on whether -// a cookie is present or not. - -function handleRequest(request, response) { - response.setStatusLine(request.httpVersion, 200, "OK"); - response.setHeader("Content-Type", "text/html", false); - - var cookie = "name=value"; - var title = "No Cookie"; - if (request.hasHeader("Cookie") && request.getHeader("Cookie") == cookie) - title = "Cookie"; - else - response.setHeader("Set-Cookie", cookie, false); - - response.write("<html><head><title>"); - response.write(title); - response.write("</title><body>test page</body></html>"); -} diff --git a/browser/components/safebrowsing/content/test/.eslintrc.js b/browser/components/safebrowsing/content/test/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/safebrowsing/content/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/safebrowsing/content/test/browser.ini b/browser/components/safebrowsing/content/test/browser.ini deleted file mode 100644 index 1ce19118e..000000000 --- a/browser/components/safebrowsing/content/test/browser.ini +++ /dev/null @@ -1,8 +0,0 @@ -[DEFAULT] -support-files = head.js - -[browser_bug400731.js] -[browser_bug415846.js] -# Disabled on Mac because of its bizarre special-and-unique snowflake of a help menu. -skip-if = os == "mac" || e10s # e10s: Bug 1248632 -[browser_whitelisted.js] diff --git a/browser/components/safebrowsing/content/test/browser_bug400731.js b/browser/components/safebrowsing/content/test/browser_bug400731.js deleted file mode 100644 index fac187753..000000000 --- a/browser/components/safebrowsing/content/test/browser_bug400731.js +++ /dev/null @@ -1,58 +0,0 @@ -/* Check presence of the "Ignore this warning" button */ - -function onDOMContentLoaded(callback) { - function complete({ data }) { - mm.removeMessageListener("Test:DOMContentLoaded", complete); - callback(data); - } - - let mm = gBrowser.selectedBrowser.messageManager; - mm.addMessageListener("Test:DOMContentLoaded", complete); - - function contentScript() { - let listener = function () { - removeEventListener("DOMContentLoaded", listener); - - let button = content.document.getElementById("ignoreWarningButton"); - - sendAsyncMessage("Test:DOMContentLoaded", { buttonPresent: !!button }); - }; - addEventListener("DOMContentLoaded", listener); - } - mm.loadFrameScript("data:,(" + contentScript.toString() + ")();", true); -} - -function test() { - waitForExplicitFinish(); - - gBrowser.selectedTab = gBrowser.addTab("http://www.itisatrap.org/firefox/its-an-attack.html"); - onDOMContentLoaded(testMalware); -} - -function testMalware(data) { - ok(data.buttonPresent, "Ignore warning button should be present for malware"); - - Services.prefs.setBoolPref("browser.safebrowsing.allowOverride", false); - - // Now launch the unwanted software test - onDOMContentLoaded(testUnwanted); - gBrowser.loadURI("http://www.itisatrap.org/firefox/unwanted.html"); -} - -function testUnwanted(data) { - // Confirm that "Ignore this warning" is visible - bug 422410 - ok(!data.buttonPresent, "Ignore warning button should be missing for unwanted software"); - - Services.prefs.setBoolPref("browser.safebrowsing.allowOverride", true); - - // Now launch the phishing test - onDOMContentLoaded(testPhishing); - gBrowser.loadURI("http://www.itisatrap.org/firefox/its-a-trap.html"); -} - -function testPhishing(data) { - ok(data.buttonPresent, "Ignore warning button should be present for phishing"); - - gBrowser.removeCurrentTab(); - finish(); -} diff --git a/browser/components/safebrowsing/content/test/browser_bug415846.js b/browser/components/safebrowsing/content/test/browser_bug415846.js deleted file mode 100644 index fc2e3472f..000000000 --- a/browser/components/safebrowsing/content/test/browser_bug415846.js +++ /dev/null @@ -1,86 +0,0 @@ -/* Check for the correct behaviour of the report web forgery/not a web forgery -menu items. - -Mac makes this astonishingly painful to test since their help menu is special magic, -but we can at least test it on the other platforms.*/ - -const NORMAL_PAGE = "http://example.com"; -const PHISH_PAGE = "http://www.itisatrap.org/firefox/its-a-trap.html"; - -/** - * Opens a new tab and browses to some URL, tests for the existence - * of the phishing menu items, and then runs a test function to check - * the state of the menu once opened. This function will take care of - * opening and closing the menu. - * - * @param url (string) - * The URL to browse the tab to. - * @param testFn (function) - * The function to run once the menu has been opened. This - * function will be passed the "reportMenu" and "errorMenu" - * DOM nodes as arguments, in that order. This function - * should not yield anything. - * @returns Promise - */ -function check_menu_at_page(url, testFn) { - return BrowserTestUtils.withNewTab({ - gBrowser, - url: "about:blank", - }, function*(browser) { - // We don't get load events when the DocShell redirects to error - // pages, but we do get DOMContentLoaded, so we'll wait for that. - let dclPromise = ContentTask.spawn(browser, null, function*() { - yield ContentTaskUtils.waitForEvent(this, "DOMContentLoaded", false); - }); - browser.loadURI(url); - yield dclPromise; - - let menu = document.getElementById("menu_HelpPopup"); - ok(menu, "Help menu should exist"); - - let reportMenu = - document.getElementById("menu_HelpPopup_reportPhishingtoolmenu"); - ok(reportMenu, "Report phishing menu item should exist"); - - let errorMenu = - document.getElementById("menu_HelpPopup_reportPhishingErrortoolmenu"); - ok(errorMenu, "Report phishing error menu item should exist"); - - let menuOpen = BrowserTestUtils.waitForEvent(menu, "popupshown"); - menu.openPopup(null, "", 0, 0, false, null); - yield menuOpen; - - testFn(reportMenu, errorMenu); - - let menuClose = BrowserTestUtils.waitForEvent(menu, "popuphidden"); - menu.hidePopup(); - yield menuClose; - }); -} - -/** - * Tests that we show the "Report this page" menu item at a normal - * page. - */ -add_task(function*() { - yield check_menu_at_page(NORMAL_PAGE, (reportMenu, errorMenu) => { - ok(!reportMenu.hidden, - "Report phishing menu should be visible on normal sites"); - ok(errorMenu.hidden, - "Report error menu item should be hidden on normal sites"); - }); -}); - -/** - * Tests that we show the "Report this page is okay" menu item at - * a reported attack site. - */ -add_task(function*() { - yield check_menu_at_page(PHISH_PAGE, (reportMenu, errorMenu) => { - ok(reportMenu.hidden, - "Report phishing menu should be hidden on phishing sites"); - ok(!errorMenu.hidden, - "Report error menu item should be visible on phishing sites"); - }); -}); - diff --git a/browser/components/safebrowsing/content/test/browser_whitelisted.js b/browser/components/safebrowsing/content/test/browser_whitelisted.js deleted file mode 100644 index afb647a81..000000000 --- a/browser/components/safebrowsing/content/test/browser_whitelisted.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Ensure that hostnames in the whitelisted pref are not blocked. */ - -const PREF_WHITELISTED_HOSTNAMES = "urlclassifier.skipHostnames"; -const TEST_PAGE = "http://www.itisatrap.org/firefox/its-an-attack.html"; -var tabbrowser = null; - -registerCleanupFunction(function() { - tabbrowser = null; - Services.prefs.clearUserPref(PREF_WHITELISTED_HOSTNAMES); - while (gBrowser.tabs.length > 1) { - gBrowser.removeCurrentTab(); - } -}); - -function testBlockedPage(window) { - info("Non-whitelisted pages must be blocked"); - ok(true, "about:blocked was shown"); -} - -function testWhitelistedPage(window) { - info("Whitelisted pages must be skipped"); - var getmeout_button = window.document.getElementById("getMeOutButton"); - var ignorewarning_button = window.document.getElementById("ignoreWarningButton"); - ok(!getmeout_button, "GetMeOut button not present"); - ok(!ignorewarning_button, "IgnoreWarning button not present"); -} - -add_task(function* testNormalBrowsing() { - tabbrowser = gBrowser; - let tab = tabbrowser.selectedTab = tabbrowser.addTab(); - - info("Load a test page that's whitelisted"); - Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, "example.com,www.ItIsaTrap.org,example.net"); - yield promiseTabLoadEvent(tab, TEST_PAGE, "load"); - testWhitelistedPage(tab.ownerGlobal); - - info("Load a test page that's no longer whitelisted"); - Services.prefs.setCharPref(PREF_WHITELISTED_HOSTNAMES, ""); - yield promiseTabLoadEvent(tab, TEST_PAGE, "AboutBlockedLoaded"); - testBlockedPage(tab.ownerGlobal); -}); diff --git a/browser/components/safebrowsing/content/test/head.js b/browser/components/safebrowsing/content/test/head.js deleted file mode 100644 index 90eef0a3f..000000000 --- a/browser/components/safebrowsing/content/test/head.js +++ /dev/null @@ -1,55 +0,0 @@ -Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); - -XPCOMUtils.defineLazyModuleGetter(this, "Promise", - "resource://gre/modules/Promise.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "Task", - "resource://gre/modules/Task.jsm"); - -/** - * Waits for a load (or custom) event to finish in a given tab. If provided - * load an uri into the tab. - * - * @param tab - * The tab to load into. - * @param [optional] url - * The url to load, or the current url. - * @param [optional] event - * The load event type to wait for. Defaults to "load". - * @return {Promise} resolved when the event is handled. - * @resolves to the received event - * @rejects if a valid load event is not received within a meaningful interval - */ -function promiseTabLoadEvent(tab, url, eventType="load") -{ - info(`Wait tab event: ${eventType}`); - - function handle(loadedUrl) { - if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) { - info(`Skipping spurious load event for ${loadedUrl}`); - return false; - } - - info("Tab event received: load"); - return true; - } - - let loaded; - if (eventType === "load") { - loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle); - } else { - // No need to use handle. - loaded = - BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, eventType, - true, undefined, true); - } - - if (url) - BrowserTestUtils.loadURI(tab.linkedBrowser, url); - - return loaded; -} - -Services.prefs.setCharPref("urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple"); -Services.prefs.setCharPref("urlclassifier.phishTable", "test-phish-simple"); -Services.prefs.setCharPref("urlclassifier.blockedTable", "test-block-simple"); -SafeBrowsing.init(); diff --git a/browser/components/search/test/.eslintrc.js b/browser/components/search/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/search/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/search/test/426329.xml b/browser/components/search/test/426329.xml deleted file mode 100644 index e4545cc77..000000000 --- a/browser/components/search/test/426329.xml +++ /dev/null @@ -1,11 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>Bug 426329</ShortName> - <Description>426329 Search</Description> - <InputEncoding>utf-8</InputEncoding> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/test.html"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/test.html</moz:SearchForm> -</OpenSearchDescription> diff --git a/browser/components/search/test/483086-1.xml b/browser/components/search/test/483086-1.xml deleted file mode 100644 index 9dbba4886..000000000 --- a/browser/components/search/test/483086-1.xml +++ /dev/null @@ -1,10 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>483086a</ShortName> - <Description>Bug 483086 Test 1</Description> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>foo://example.com</moz:SearchForm> -</OpenSearchDescription> diff --git a/browser/components/search/test/483086-2.xml b/browser/components/search/test/483086-2.xml deleted file mode 100644 index f130b9068..000000000 --- a/browser/components/search/test/483086-2.xml +++ /dev/null @@ -1,10 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>483086b</ShortName> - <Description>Bug 483086 Test 2</Description> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>http://example.com</moz:SearchForm> -</OpenSearchDescription> diff --git a/browser/components/search/test/browser.ini b/browser/components/search/test/browser.ini deleted file mode 100644 index f1070264d..000000000 --- a/browser/components/search/test/browser.ini +++ /dev/null @@ -1,44 +0,0 @@ -[DEFAULT] -support-files = - 426329.xml - 483086-1.xml - 483086-2.xml - head.js - opensearch.html - test.html - testEngine.xml - testEngine_diacritics.xml - testEngine_dupe.xml - testEngine_mozsearch.xml - webapi.html - -[browser_426329.js] -[browser_483086.js] -[browser_addEngine.js] -[browser_amazon.js] -[browser_amazon_behavior.js] -[browser_bing.js] -[browser_bing_behavior.js] -[browser_contextmenu.js] -[browser_contextSearchTabPosition.js] -skip-if = os == "mac" # bug 967013 -[browser_google.js] -[browser_google_codes.js] -[browser_google_behavior.js] -[browser_healthreport.js] -[browser_hiddenOneOffs_cleanup.js] -[browser_hiddenOneOffs_diacritics.js] -[browser_oneOffContextMenu.js] -[browser_oneOffContextMenu_setDefault.js] -[browser_oneOffHeader.js] -[browser_private_search_perwindowpb.js] -[browser_yahoo.js] -[browser_yahoo_behavior.js] -[browser_abouthome_behavior.js] -skip-if = true # Bug ??????, Bug 1100301 - leaks windows until shutdown when --run-by-dir -[browser_aboutSearchReset.js] -[browser_searchbar_openpopup.js] -skip-if = os == "linux" # Linux has different focus behaviours. -[browser_searchbar_keyboard_navigation.js] -[browser_searchbar_smallpanel_keyboard_navigation.js] -[browser_webapi.js] diff --git a/browser/components/search/test/browser_426329.js b/browser/components/search/test/browser_426329.js deleted file mode 100644 index d9cbd3f7a..000000000 --- a/browser/components/search/test/browser_426329.js +++ /dev/null @@ -1,250 +0,0 @@ -XPCOMUtils.defineLazyModuleGetter(this, "FormHistory", - "resource://gre/modules/FormHistory.jsm"); - -function expectedURL(aSearchTerms) { - const ENGINE_HTML_BASE = "http://mochi.test:8888/browser/browser/components/search/test/test.html"; - var textToSubURI = Cc["@mozilla.org/intl/texttosuburi;1"]. - getService(Ci.nsITextToSubURI); - var searchArg = textToSubURI.ConvertAndEscape("utf-8", aSearchTerms); - return ENGINE_HTML_BASE + "?test=" + searchArg; -} - -function simulateClick(aEvent, aTarget) { - var event = document.createEvent("MouseEvent"); - var ctrlKeyArg = aEvent.ctrlKey || false; - var altKeyArg = aEvent.altKey || false; - var shiftKeyArg = aEvent.shiftKey || false; - var metaKeyArg = aEvent.metaKey || false; - var buttonArg = aEvent.button || 0; - event.initMouseEvent("click", true, true, window, - 0, 0, 0, 0, 0, - ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, - buttonArg, null); - aTarget.dispatchEvent(event); -} - -// modified from toolkit/components/satchel/test/test_form_autocomplete.html -function checkMenuEntries(expectedValues) { - var actualValues = getMenuEntries(); - is(actualValues.length, expectedValues.length, "Checking length of expected menu"); - for (var i = 0; i < expectedValues.length; i++) - is(actualValues[i], expectedValues[i], "Checking menu entry #" + i); -} - -function getMenuEntries() { - var entries = []; - var autocompleteMenu = searchBar.textbox.popup; - // Could perhaps pull values directly from the controller, but it seems - // more reliable to test the values that are actually in the tree? - var column = autocompleteMenu.tree.columns[0]; - var numRows = autocompleteMenu.tree.view.rowCount; - for (var i = 0; i < numRows; i++) { - entries.push(autocompleteMenu.tree.view.getValueAt(i, column)); - } - return entries; -} - -function countEntries(name, value) { - return new Promise(resolve => { - let count = 0; - let obj = name && value ? {fieldname: name, value: value} : {}; - FormHistory.count(obj, - { handleResult: function(result) { count = result; }, - handleError: function(error) { throw error; }, - handleCompletion: function(reason) { - if (!reason) { - resolve(count); - } - } - }); - }); -} - -var searchBar; -var searchButton; -var searchEntries = ["test"]; -function promiseSetEngine() { - return new Promise(resolve => { - var ss = Services.search; - - function observer(aSub, aTopic, aData) { - switch (aData) { - case "engine-added": - var engine = ss.getEngineByName("Bug 426329"); - ok(engine, "Engine was added."); - ss.currentEngine = engine; - break; - case "engine-current": - ok(ss.currentEngine.name == "Bug 426329", "currentEngine set"); - searchBar = BrowserSearch.searchBar; - searchButton = document.getAnonymousElementByAttribute(searchBar, - "anonid", "search-go-button"); - ok(searchButton, "got search-go-button"); - searchBar.value = "test"; - - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - resolve(); - break; - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - ss.addEngine("http://mochi.test:8888/browser/browser/components/search/test/426329.xml", - null, "data:image/x-icon,%00", false); - }); -} - -function promiseRemoveEngine() { - return new Promise(resolve => { - var ss = Services.search; - - function observer(aSub, aTopic, aData) { - if (aData == "engine-removed") { - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - resolve(); - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - var engine = ss.getEngineByName("Bug 426329"); - ss.removeEngine(engine); - }); -} - - -var preSelectedBrowser; -var preTabNo; -function* prepareTest() { - preSelectedBrowser = gBrowser.selectedBrowser; - preTabNo = gBrowser.tabs.length; - searchBar = BrowserSearch.searchBar; - - yield SimpleTest.promiseFocus(); - - if (document.activeElement == searchBar) - return; - - let focusPromise = BrowserTestUtils.waitForEvent(searchBar, "focus"); - gURLBar.focus(); - searchBar.focus(); - yield focusPromise; -} - -add_task(function* testSetupEngine() { - yield promiseSetEngine(); -}); - -add_task(function* testReturn() { - yield* prepareTest(); - EventUtils.synthesizeKey("VK_RETURN", {}); - yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser); - - is(gBrowser.tabs.length, preTabNo, "Return key did not open new tab"); - is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testReturn opened correct search page"); -}); - -add_task(function* testAltReturn() { - yield* prepareTest(); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => { - EventUtils.synthesizeKey("VK_RETURN", { altKey: true }); - }); - - is(gBrowser.tabs.length, preTabNo + 1, "Alt+Return key added new tab"); - is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testAltReturn opened correct search page"); -}); - -// Shift key has no effect for now, so skip it -add_task(function* testShiftAltReturn() { - return; - /* - yield* prepareTest(); - - let url = expectedURL(searchBar.value); - - let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url); - EventUtils.synthesizeKey("VK_RETURN", { shiftKey: true, altKey: true }); - yield newTabPromise; - - is(gBrowser.tabs.length, preTabNo + 1, "Shift+Alt+Return key added new tab"); - is(gBrowser.currentURI.spec, url, "testShiftAltReturn opened correct search page"); - */ -}); - -add_task(function* testLeftClick() { - yield* prepareTest(); - simulateClick({ button: 0 }, searchButton); - yield BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser); - is(gBrowser.tabs.length, preTabNo, "LeftClick did not open new tab"); - is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testLeftClick opened correct search page"); -}); - -add_task(function* testMiddleClick() { - yield* prepareTest(); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => { - simulateClick({ button: 1 }, searchButton); - }); - is(gBrowser.tabs.length, preTabNo + 1, "MiddleClick added new tab"); - is(gBrowser.currentURI.spec, expectedURL(searchBar.value), "testMiddleClick opened correct search page"); -}); - -add_task(function* testShiftMiddleClick() { - yield* prepareTest(); - - let url = expectedURL(searchBar.value); - - let newTabPromise = BrowserTestUtils.waitForNewTab(gBrowser, url); - simulateClick({ button: 1, shiftKey: true }, searchButton); - let newTab = yield newTabPromise; - - is(gBrowser.tabs.length, preTabNo + 1, "Shift+MiddleClick added new tab"); - is(newTab.linkedBrowser.currentURI.spec, url, "testShiftMiddleClick opened correct search page"); -}); - -add_task(function* testRightClick() { - preTabNo = gBrowser.tabs.length; - gBrowser.selectedBrowser.loadURI("about:blank"); - yield new Promise(resolve => { - setTimeout(function() { - is(gBrowser.tabs.length, preTabNo, "RightClick did not open new tab"); - is(gBrowser.currentURI.spec, "about:blank", "RightClick did nothing"); - resolve(); - }, 5000); - simulateClick({ button: 2 }, searchButton); - }); - // The click in the searchbox focuses it, which opens the suggestion - // panel. Clean up after ourselves. - searchBar.textbox.popup.hidePopup(); -}); - -add_task(function* testSearchHistory() { - var textbox = searchBar._textbox; - for (var i = 0; i < searchEntries.length; i++) { - let count = yield countEntries(textbox.getAttribute("autocompletesearchparam"), searchEntries[i]); - ok(count > 0, "form history entry '" + searchEntries[i] + "' should exist"); - } -}); - -add_task(function* testAutocomplete() { - var popup = searchBar.textbox.popup; - let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown"); - searchBar.textbox.showHistoryPopup(); - yield popupShownPromise; - checkMenuEntries(searchEntries); -}); - -add_task(function* testClearHistory() { - let controller = searchBar.textbox.controllers.getControllerForCommand("cmd_clearhistory") - ok(controller.isCommandEnabled("cmd_clearhistory"), "Clear history command enabled"); - controller.doCommand("cmd_clearhistory"); - let count = yield countEntries(); - ok(count == 0, "History cleared"); -}); - -add_task(function* asyncCleanup() { - searchBar.value = ""; - while (gBrowser.tabs.length != 1) { - gBrowser.removeTab(gBrowser.tabs[0], {animate: false}); - } - gBrowser.selectedBrowser.loadURI("about:blank"); - yield promiseRemoveEngine(); -}); diff --git a/browser/components/search/test/browser_483086.js b/browser/components/search/test/browser_483086.js deleted file mode 100644 index 208add867..000000000 --- a/browser/components/search/test/browser_483086.js +++ /dev/null @@ -1,49 +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 gSS = Services.search; - -function test() { - waitForExplicitFinish(); - - function observer(aSubject, aTopic, aData) { - switch (aData) { - case "engine-added": - let engine = gSS.getEngineByName("483086a"); - ok(engine, "Test engine 1 installed"); - isnot(engine.searchForm, "foo://example.com", - "Invalid SearchForm URL dropped"); - gSS.removeEngine(engine); - break; - case "engine-removed": - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - test2(); - break; - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/483086-1.xml", - null, "data:image/x-icon;%00", false); -} - -function test2() { - function observer(aSubject, aTopic, aData) { - switch (aData) { - case "engine-added": - let engine = gSS.getEngineByName("483086b"); - ok(engine, "Test engine 2 installed"); - is(engine.searchForm, "http://example.com", "SearchForm is correct"); - gSS.removeEngine(engine); - break; - case "engine-removed": - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - finish(); - break; - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/483086-2.xml", - null, "data:image/x-icon;%00", false); -} diff --git a/browser/components/search/test/browser_aboutSearchReset.js b/browser/components/search/test/browser_aboutSearchReset.js deleted file mode 100644 index 64376d6da..000000000 --- a/browser/components/search/test/browser_aboutSearchReset.js +++ /dev/null @@ -1,159 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -const TELEMETRY_RESULT_ENUM = { - RESTORED_DEFAULT: 0, - KEPT_CURRENT: 1, - CHANGED_ENGINE: 2, - CLOSED_PAGE: 3, - OPENED_SETTINGS: 4 -}; - -const kSearchStr = "a search"; -const kSearchPurpose = "searchbar"; - -const kTestEngine = "testEngine.xml"; - -function checkTelemetryRecords(expectedValue) { - let histogram = Services.telemetry.getHistogramById("SEARCH_RESET_RESULT"); - let snapshot = histogram.snapshot(); - // The probe is declared with 5 values, but we get 6 back from .counts - let expectedCounts = [0, 0, 0, 0, 0, 0]; - if (expectedValue != null) { - expectedCounts[expectedValue] = 1; - } - Assert.deepEqual(snapshot.counts, expectedCounts, - "histogram has expected content"); - histogram.clear(); -} - -function promiseStoppedLoad(expectedURL) { - return new Promise(resolve => { - let browser = gBrowser.selectedBrowser; - let original = browser.loadURIWithFlags; - browser.loadURIWithFlags = function(URI) { - if (URI == expectedURL) { - browser.loadURIWithFlags = original; - ok(true, "loaded expected url: " + URI); - resolve(); - return; - } - - original.apply(browser, arguments); - }; - }); -} - -var gTests = [ - -{ - desc: "Test the 'Keep Current Settings' button.", - run: function* () { - let engine = yield promiseNewEngine(kTestEngine, {setAsCurrent: true}); - - let expectedURL = engine. - getSubmission(kSearchStr, null, kSearchPurpose). - uri.spec; - - let rawEngine = engine.wrappedJSObject; - let initialHash = rawEngine.getAttr("loadPathHash"); - rawEngine.setAttr("loadPathHash", "broken"); - - let loadPromise = promiseStoppedLoad(expectedURL); - gBrowser.contentDocument.getElementById("searchResetKeepCurrent").click(); - yield loadPromise; - - is(engine, Services.search.currentEngine, - "the custom engine is still default"); - is(rawEngine.getAttr("loadPathHash"), initialHash, - "the loadPathHash has been fixed"); - - checkTelemetryRecords(TELEMETRY_RESULT_ENUM.KEPT_CURRENT); - } -}, - -{ - desc: "Test the 'Restore Search Defaults' button.", - run: function* () { - let currentEngine = Services.search.currentEngine; - let originalEngine = Services.search.originalDefaultEngine; - let doc = gBrowser.contentDocument; - let defaultEngineSpan = doc.getElementById("defaultEngine"); - is(defaultEngineSpan.textContent, originalEngine.name, - "the name of the original default engine is displayed"); - - let expectedURL = originalEngine. - getSubmission(kSearchStr, null, kSearchPurpose). - uri.spec; - let loadPromise = promiseStoppedLoad(expectedURL); - let button = doc.getElementById("searchResetChangeEngine"); - is(doc.activeElement, button, - "the 'Change Search Engine' button is focused"); - button.click(); - yield loadPromise; - - is(originalEngine, Services.search.currentEngine, - "the default engine is back to the original one"); - - checkTelemetryRecords(TELEMETRY_RESULT_ENUM.RESTORED_DEFAULT); - Services.search.currentEngine = currentEngine; - } -}, - -{ - desc: "Click the settings link.", - run: function* () { - let loadPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, - false, - "about:preferences#search") - gBrowser.contentDocument.getElementById("linkSettingsPage").click(); - yield loadPromise; - - checkTelemetryRecords(TELEMETRY_RESULT_ENUM.OPENED_SETTINGS); - } -}, - -{ - desc: "Load another page without clicking any of the buttons.", - run: function* () { - yield promiseTabLoadEvent(gBrowser.selectedTab, "about:mozilla"); - - checkTelemetryRecords(TELEMETRY_RESULT_ENUM.CLOSED_PAGE); - } -}, - -]; - -function test() -{ - waitForExplicitFinish(); - Task.spawn(function* () { - let oldCanRecord = Services.telemetry.canRecordExtended; - Services.telemetry.canRecordExtended = true; - checkTelemetryRecords(); - - for (let test of gTests) { - info(test.desc); - - // Create a tab to run the test. - let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank"); - - // Start loading about:searchreset and wait for it to complete. - let url = "about:searchreset?data=" + encodeURIComponent(kSearchStr) + - "&purpose=" + kSearchPurpose; - yield promiseTabLoadEvent(tab, url); - - info("Running test"); - yield test.run(); - - info("Cleanup"); - gBrowser.removeCurrentTab(); - } - - Services.telemetry.canRecordExtended = oldCanRecord; - }).then(finish, ex => { - ok(false, "Unexpected Exception: " + ex); - finish(); - }); -} diff --git a/browser/components/search/test/browser_abouthome_behavior.js b/browser/components/search/test/browser_abouthome_behavior.js deleted file mode 100644 index 3291b41f4..000000000 --- a/browser/components/search/test/browser_abouthome_behavior.js +++ /dev/null @@ -1,144 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test home page search for all plugin URLs - */ - -"use strict"; - -function test() { - // Bug 992270: Ignore uncaught about:home exceptions (related to snippets from IndexedDB) - ignoreAllUncaughtExceptions(true); - - let previouslySelectedEngine = Services.search.currentEngine; - - function replaceUrl(base) { - return base; - } - - let gMutationObserver = null; - - function verify_about_home_search(engine_name) { - let engine = Services.search.getEngineByName(engine_name); - ok(engine, engine_name + " is installed"); - - Services.search.currentEngine = engine; - - // load about:home, but remove the listener first so it doesn't - // get in the way - gBrowser.removeProgressListener(listener); - gBrowser.loadURI("about:home"); - info("Waiting for about:home load"); - tab.linkedBrowser.addEventListener("load", function load(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank") { - info("skipping spurious load event"); - return; - } - tab.linkedBrowser.removeEventListener("load", load, true); - - // Observe page setup - let doc = gBrowser.contentDocument; - gMutationObserver = new MutationObserver(function (mutations) { - for (let mutation of mutations) { - if (mutation.attributeName == "searchEngineName") { - // Re-add the listener, and perform a search - gBrowser.addProgressListener(listener); - gMutationObserver.disconnect() - gMutationObserver = null; - executeSoon(function() { - doc.getElementById("searchText").value = "foo"; - doc.getElementById("searchSubmit").click(); - }); - } - } - }); - gMutationObserver.observe(doc.documentElement, { attributes: true }); - }, true); - } - waitForExplicitFinish(); - - let gCurrTest; - let gTests = [ - { - name: "Search with Bing from about:home", - searchURL: replaceUrl("http://www.bing.com/search?q=foo&pc=MOZI&form=MOZSPG"), - run: function () { - verify_about_home_search("Bing"); - } - }, - { - name: "Search with Yahoo from about:home", - searchURL: replaceUrl("https://search.yahoo.com/search?p=foo&ei=UTF-8&fr=moz35"), - run: function () { - verify_about_home_search("Yahoo"); - } - }, - { - name: "Search with Google from about:home", - searchURL: replaceUrl("https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8"), - run: function () { - verify_about_home_search("Google"); - } - }, - { - name: "Search with Amazon.com from about:home", - searchURL: replaceUrl("https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"), - run: function () { - verify_about_home_search("Amazon.com"); - } - } - ]; - - function nextTest() { - if (gTests.length) { - gCurrTest = gTests.shift(); - info("Running : " + gCurrTest.name); - executeSoon(gCurrTest.run); - } else { - // Make sure we listen again for uncaught exceptions in the next test or cleanup. - executeSoon(finish); - } - } - - let tab = gBrowser.selectedTab = gBrowser.addTab(); - - let listener = { - onStateChange: function onStateChange(webProgress, req, flags, status) { - info("onStateChange"); - // Only care about top-level document starts - let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | - Ci.nsIWebProgressListener.STATE_START; - if (!(flags & docStart) || !webProgress.isTopLevel) - return; - - if (req.originalURI.spec == "about:blank") - return; - - info("received document start"); - - ok(req instanceof Ci.nsIChannel, "req is a channel"); - is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded"); - info("Actual URI: " + req.URI.spec); - - req.cancel(Components.results.NS_ERROR_FAILURE); - - executeSoon(nextTest); - } - } - - registerCleanupFunction(function () { - Services.search.currentEngine = previouslySelectedEngine; - gBrowser.removeProgressListener(listener); - gBrowser.removeTab(tab); - if (gMutationObserver) - gMutationObserver.disconnect(); - }); - - tab.linkedBrowser.addEventListener("load", function load() { - tab.linkedBrowser.removeEventListener("load", load, true); - gBrowser.addProgressListener(listener); - nextTest(); - }, true); -} diff --git a/browser/components/search/test/browser_addEngine.js b/browser/components/search/test/browser_addEngine.js deleted file mode 100644 index b971ea5f7..000000000 --- a/browser/components/search/test/browser_addEngine.js +++ /dev/null @@ -1,105 +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 gSS = Services.search; - -function observer(aSubject, aTopic, aData) { - if (!gCurrentTest) { - info("Observer called with no test active"); - return; - } - - let engine = aSubject.QueryInterface(Ci.nsISearchEngine); - info("Observer: " + aData + " for " + engine.name); - let method; - switch (aData) { - case "engine-added": - if (gCurrentTest.added) - method = "added" - break; - case "engine-current": - if (gCurrentTest.current) - method = "current"; - break; - case "engine-removed": - if (gCurrentTest.removed) - method = "removed"; - break; - } - - if (method) - gCurrentTest[method](engine); -} - -function checkEngine(checkObj, engineObj) { - info("Checking engine"); - for (var prop in checkObj) - is(checkObj[prop], engineObj[prop], prop + " is correct"); -} - -var gTests = [ - { - name: "opensearch install", - engine: { - name: "Foo", - alias: null, - description: "Foo Search", - searchForm: "http://mochi.test:8888/browser/browser/components/search/test/" - }, - run: function () { - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - - gSS.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml", - null, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC", - false); - }, - added: function (engine) { - ok(engine, "engine was added."); - - checkEngine(this.engine, engine); - - let engineFromSS = gSS.getEngineByName(this.engine.name); - is(engine, engineFromSS, "engine is obtainable via getEngineByName"); - - let aEngine = gSS.getEngineByAlias("fooalias"); - ok(!aEngine, "Alias was not parsed from engine description"); - - gSS.currentEngine = engine; - }, - current: function (engine) { - let currentEngine = gSS.currentEngine; - is(engine, currentEngine, "engine is current"); - is(engine.name, this.engine.name, "current engine was changed successfully"); - - gSS.removeEngine(engine); - }, - removed: function (engine) { - // Remove the observer before calling the currentEngine getter, - // as that getter will set the currentEngine to the original default - // which will trigger a notification causing the test to loop over all - // engines. - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - - let currentEngine = gSS.currentEngine; - ok(currentEngine, "An engine is present."); - isnot(currentEngine.name, this.engine.name, "Current engine reset after removal"); - - nextTest(); - } - } -]; - -var gCurrentTest = null; -function nextTest() { - if (gTests.length) { - gCurrentTest = gTests.shift(); - info("Running " + gCurrentTest.name); - gCurrentTest.run(); - } else - executeSoon(finish); -} - -function test() { - waitForExplicitFinish(); - nextTest(); -} diff --git a/browser/components/search/test/browser_amazon.js b/browser/components/search/test/browser_amazon.js deleted file mode 100644 index 965a3dcf8..000000000 --- a/browser/components/search/test/browser_amazon.js +++ /dev/null @@ -1,82 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Amazon search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - -function test() { - let engine = Services.search.getEngineByName("Amazon.com"); - ok(engine, "Amazon.com"); - - let base = "https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base, "Check search URL for 'foo'"); - - // Check search suggestion URL. - url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec; - is(url, "https://completion.amazon.com/search/complete?q=foo&search-alias=aps&mkt=1", "Check search suggestion URL for 'foo'"); - - // Check all other engine properties. - const EXPECTED_ENGINE = { - name: "Amazon.com", - alias: null, - description: "Amazon.com Search", - searchForm: "https://www.amazon.com/exec/obidos/external-search/?field-keywords=&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search", - hidden: false, - wrappedJSObject: { - queryCharset: "UTF-8", - "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAAAAAC0AQAAJgAAACAgAAAAAAAA6QIAANoBAACJUE5HDQoaCgAAAA1JSERSAAAAEAAAABAIBgAAAB/z/2EAAAF7SURBVDjLlZPLasJAFIaFRF+iVV+h6hO0GF+gVB9AaHwDt64qCG03tQgtdCFIuyhUelmGli66MXThSt24kNiFBUlAYi6ezjnNxSuawB/ITP7v/HNmJgQAEaZzpgHs/gwcTyTEXuXl2U6nA8ViEbK5HKler28CVRAwnB9ptVrAh8MrQuCaZ4iA8fzIqSgCxwzpTIaSuN/RWGwdYLwCUBQFZFkGSZLgqdmEE7YEN8VOAKyaSKUW4nNBAFmnYiKZpDRX1WqwBBzP089n5f/NEQsFL4WqqtsBWJlzDAJr5PwSMM1awEzzdxIbGI3Hvc6jCZeVFgRQRwpY7Qcw3ktgfpR8wLRxCPaot/X4GS95MppfF6DX9n2A3f+kAZycaT8bAZjU6r6B/duD6d3BYg9wQq/tkYzHY1blEiz5lmQyGc95mrO6r2CxgpjCBXgNsJVviolpXJiraeOIjJRE10juUa4sR8V+mO17VvmGqtuOcdNlwut8zTQJcJ0njifyB2bgTdKh6w4BAAAAAElFTkSuQmCCiVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACsElEQVRYw71XQWsTURBe2LQgeNKLB+tVemt6txcteNSD/QGC6VEIGDx5s+eKPQqFgJhLNdFLBWMP7cU0oSAWjB70koC9WHbVQ5SO8+XtS14mr7svyaYDH9m87Jv55puZt1nPi4yIzjMeMj7T9OwjI88455nGC1cZX+nsDESumJmPFDwIAqrX6z00Gg1qt9vjkJgFgUeuO16Vy3RjeZkyMzM9+MY1fsM9I9h9zyV7ZAznZrA4FAoFVwJ1z+WuOysrg1lnMolkHJX4k0igzI5sARYWF7vEZEk0rvO6iyUSuJfLJUqM7zYSqRDIra4OOUZPmNZsNrsl8UVTpkJAjh1GzmaSpJ8mAWmYeZB5urHRhW5SNOfUCCDo47W1bvPZsp2qAhipy3Nz1kaLG8dUCEBqM5AvpgElqFar01NgIZsdco7Zb7VasU2YigIYL5tjqCL7Q5YkFQXKlcqQ7DbHthIALk/IWAKor82xPIhshxWABCYioDMz51sexcVi0XoG4DPLIyvJjkTArK3scDQnRvO0MdTrUHGiKZCP4tNgO6BAEI08EQH9Z2Qow0hyPypJGIa9p6JWKCn4SA8jSKmJIDgyRvPJkcRxjfUwNGr/i8+Mo32iHzWiThBD4NM60bet9P77/ubA728RlTjMiwiH6zEEfvIrwdZFtQmMJ7W/ofIDBZD5m3mVZGwJcOP2kmILIlCkE45HoPWurwCSg0+UQRD4ZyXxId+T7gQb9+4q9sioY5ltrOG3L5vqXiiJffDx/aUi83ZJ7jr2ohcEu8Hh6/m+I7OWGiVxbWKHsz+O3vSOakqFQdsFgQeJUiKD7Wv9YKXBgCeSUC3v2kM5EJhlHDh3NcgcPlG1BXZu98sDmTuBa4fsMnz9fniJUaGzs+eMC540XuR0aDO2L8Y3qPyMcdOM+R/8XcqRA3qp9gAAAABJRU5ErkJggg==", - _urls : [ - { - type: "application/x-suggestions+json", - method: "GET", - template: "https://completion.amazon.com/search/complete?q={searchTerms}&search-alias=aps&mkt=1", - params: "", - }, - { - type: "text/html", - method: "GET", - template: "https://www.amazon.com/exec/obidos/external-search/", - params: [ - { - name: "field-keywords", - value: "{searchTerms}", - purpose: undefined, - }, - { - name: "ie", - value: "{inputEncoding}", - purpose: undefined, - }, - { - name: "mode", - value: "blended", - purpose: undefined, - }, - { - name: "tag", - value: "mozilla-20", - purpose: undefined, - }, - { - name: "sourceid", - value: "Mozilla-search", - purpose: undefined, - }, - ], - mozparams: {}, - }, - ], - }, - }; - - isSubObjectOf(EXPECTED_ENGINE, engine, "Amazon"); -} diff --git a/browser/components/search/test/browser_amazon_behavior.js b/browser/components/search/test/browser_amazon_behavior.js deleted file mode 100644 index 22d16581a..000000000 --- a/browser/components/search/test/browser_amazon_behavior.js +++ /dev/null @@ -1,166 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Amazon search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - - -function test() { - let engine = Services.search.getEngineByName("Amazon.com"); - ok(engine, "Amazon is installed"); - - let previouslySelectedEngine = Services.search.currentEngine; - Services.search.currentEngine = engine; - engine.alias = "a"; - - let base = "https://www.amazon.com/exec/obidos/external-search/?field-keywords=foo&ie=UTF-8&mode=blended&tag=mozilla-20&sourceid=Mozilla-search"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base, "Check search URL for 'foo'"); - - waitForExplicitFinish(); - - var gCurrTest; - var gTests = [ - { - name: "context menu search", - searchURL: base, - run: function () { - // Simulate a contextmenu search - // FIXME: This is a bit "low-level"... - BrowserSearch.loadSearch("foo", false, "contextmenu"); - } - }, - { - name: "keyword search", - searchURL: base, - run: function () { - gURLBar.value = "? foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "keyword search", - searchURL: base, - run: function () { - gURLBar.value = "a foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "search bar search", - searchURL: base, - run: function () { - let sb = BrowserSearch.searchBar; - sb.focus(); - sb.value = "foo"; - registerCleanupFunction(function () { - sb.value = ""; - }); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "new tab search", - searchURL: base, - run: function () { - function doSearch(doc) { - // Re-add the listener, and perform a search - gBrowser.addProgressListener(listener); - doc.getElementById("newtab-search-text").value = "foo"; - doc.getElementById("newtab-search-submit").click(); - } - - // load about:newtab, but remove the listener first so it doesn't - // get in the way - gBrowser.removeProgressListener(listener); - gBrowser.loadURI("about:newtab"); - info("Waiting for about:newtab load"); - tab.linkedBrowser.addEventListener("load", function load(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank") { - info("skipping spurious load event"); - return; - } - tab.linkedBrowser.removeEventListener("load", load, true); - - // Observe page setup - let win = gBrowser.contentWindow; - if (win.gSearch.currentEngineName == - Services.search.currentEngine.name) { - doSearch(win.document); - } - else { - info("Waiting for newtab search init"); - win.addEventListener("ContentSearchService", function done(event) { - info("Got newtab search event " + event.detail.type); - if (event.detail.type == "State") { - win.removeEventListener("ContentSearchService", done); - // Let gSearch respond to the event before continuing. - executeSoon(() => doSearch(win.document)); - } - }); - } - }, true); - } - } - ]; - - function nextTest() { - if (gTests.length) { - gCurrTest = gTests.shift(); - info("Running : " + gCurrTest.name); - executeSoon(gCurrTest.run); - } else { - finish(); - } - } - - let tab = gBrowser.selectedTab = gBrowser.addTab(); - - let listener = { - onStateChange: function onStateChange(webProgress, req, flags, status) { - info("onStateChange"); - // Only care about top-level document starts - let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | - Ci.nsIWebProgressListener.STATE_START; - if (!(flags & docStart) || !webProgress.isTopLevel) - return; - - if (req.originalURI.spec == "about:blank") - return; - - info("received document start"); - - ok(req instanceof Ci.nsIChannel, "req is a channel"); - is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded"); - info("Actual URI: " + req.URI.spec); - - req.cancel(Components.results.NS_ERROR_FAILURE); - - executeSoon(nextTest); - } - } - - registerCleanupFunction(function () { - engine.alias = undefined; - gBrowser.removeProgressListener(listener); - gBrowser.removeTab(tab); - Services.search.currentEngine = previouslySelectedEngine; - }); - - tab.linkedBrowser.addEventListener("load", function load() { - tab.linkedBrowser.removeEventListener("load", load, true); - gBrowser.addProgressListener(listener); - nextTest(); - }, true); -} diff --git a/browser/components/search/test/browser_bing.js b/browser/components/search/test/browser_bing.js deleted file mode 100644 index 3a41ae0ac..000000000 --- a/browser/components/search/test/browser_bing.js +++ /dev/null @@ -1,118 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Bing search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - -function test() { - let engine = Services.search.getEngineByName("Bing"); - ok(engine, "Bing"); - - let base = "https://www.bing.com/search?q=foo&pc=MOZI"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base + "&form=MOZSBR", "Check search URL for 'foo'"); - url = engine.getSubmission("foo", null, "contextmenu").uri.spec; - is(url, base + "&form=MOZCON", "Check context menu search URL for 'foo'"); - url = engine.getSubmission("foo", null, "keyword").uri.spec; - is(url, base + "&form=MOZLBR", "Check keyword search URL for 'foo'"); - url = engine.getSubmission("foo", null, "searchbar").uri.spec; - is(url, base + "&form=MOZSBR", "Check search bar search URL for 'foo'"); - url = engine.getSubmission("foo", null, "homepage").uri.spec; - is(url, base + "&form=MOZSPG", "Check homepage search URL for 'foo'"); - url = engine.getSubmission("foo", null, "newtab").uri.spec; - is(url, base + "&form=MOZTSB", "Check newtab search URL for 'foo'"); - - // Check search suggestion URL. - url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec; - is(url, "https://www.bing.com/osjson.aspx?query=foo&form=OSDJAS&language=" + getLocale(), "Check search suggestion URL for 'foo'"); - - // Check all other engine properties. - const EXPECTED_ENGINE = { - name: "Bing", - alias: null, - description: "Bing. Search by Microsoft.", - searchForm: "https://www.bing.com/search?q=&pc=MOZI&form=MOZSBR", - hidden: false, - wrappedJSObject: { - queryCharset: "UTF-8", - "_iconURL": "data:image/x-icon;base64,AAABAAIAICAAAAEACACoCAAAJgAAABAQAAABAAgAaAUAAM4IAAAoAAAAIAAAAEAAAAABAAgAAAAAAIAEAAAAAAAAAAAAAAABAAAAAAAAhIQMAI+PIwCXlzEAn59BAKioUwCurl8AtbVuAL6+fwDJyZMA0tKlANjYsgDe3r4A5eXMAOzs2QDy8uUA+fnzAP///wAAGi8AAC1QAAA/cAAAUZAAAGOwAAB2zwAAiPAAEZj/ADGm/wBRs/8AccH/AJHP/wCx3f8A0ev/AP///wAAAAAAACwvAABLUAAAaHAAAIaQAAClsAAAw88AAOHwABHv/wAx8f8AUfP/AHH1/wCR9/8Asfn/ANH7/wD///8AAAAAAAAvIQAAUDcAAHBMAACQYwAAsHkAAM+PAADwpgAR/7QAMf++AFH/yABx/9MAkf/cALH/5QDR//AA////AAAAAAAALw4AAFAYAABwIgAAkCwAALA2AADPQAAA8EoAEf9bADH/cQBR/4cAcf+dAJH/sgCx/8kA0f/fAP///wAAAAAAAi8AAARQAAAGcAAACJAAAAqwAAALzwAADvAAACD/EgA9/zEAW/9RAHn/cQCY/5EAtf+xANT/0QD///8AAAAAABQvAAAiUAAAMHAAAD2QAABMsAAAWc8AAGfwAAB4/xEAiv8xAJz/UQCu/3EAwP+RANL/sQDk/9EA////AAAAAAAmLwAAQFAAAFpwAAB0kAAAjrAAAKnPAADC8AAA0f8RANj/MQDe/1EA4/9xAOn/kQDv/7EA9v/RAP///wAAAAAALyYAAFBBAABwWwAAkHQAALCOAADPqQAA8MMAAP/SEQD/2DEA/91RAP/kcQD/6pEA//CxAP/20QD///8AAAAAAC8UAABQIgAAcDAAAJA+AACwTQAAz1sAAPBpAAD/eREA/4oxAP+dUQD/r3EA/8GRAP/SsQD/5dEA////AAAAAAAvAwAAUAQAAHAGAACQCQAAsAoAAM8MAADwDgAA/yASAP8+MQD/XFEA/3pxAP+XkQD/trEA/9TRAP///wAAAAAALwAOAFAAFwBwACEAkAArALAANgDPAEAA8ABJAP8RWgD/MXAA/1GGAP9xnAD/kbIA/7HIAP/R3wD///8AAAAAAC8AIABQADYAcABMAJAAYgCwAHgAzwCOAPAApAD/EbMA/zG+AP9RxwD/cdEA/5HcAP+x5QD/0fAA////AAAAAAAsAC8ASwBQAGkAcACHAJAApQCwAMQAzwDhAPAA8BH/APIx/wD0Uf8A9nH/APeR/wD5sf8A+9H/AP///wAAAAAAGwAvAC0AUAA/AHAAUgCQAGMAsAB2AM8AiADwAJkR/wCmMf8AtFH/AMJx/wDPkf8A3LH/AOvR/wD///8AAAAAAAgALwAOAFAAFQBwABsAkAAhALAAJgDPACwA8AA+Ef8AWDH/AHFR/wCMcf8AppH/AL+x/wDa0f8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBggCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAsQEA0HAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwkPEBAQEBALBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEMEBAQEBAQEBAPCQMAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAQEBAQEBAQDQgBAAAAAAAAAAAAAAAAAAAAAAABDRAQEBAQEBAQEBAQEA0GAQAAAAAAAAAAAAAAAAAAAAENEBAQDgcLEBAQEBAQEBALBAAAAAAAAAAAAAAAAAAAAQ0QEBANAQEHDRAQEBAQEBAOCAAAAAAAAAAAAAAAAAABDRAQEA4BAAACCA4QEBAQEBANAQAAAAAAAAAAAAAAAAENEBAQDgEAAAAABAsQEBAQEA0BAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAABBw4QEBAQDQEAAAAAAAAAAAAAAAABDRAQEA4BAAABBw0QEBAQEBANAQAAAAAAAAAAAAAAAAENEBAQDgEAAAcQEBAQEBAQEA0BAAAAAAAAAAAAAAAAAQ0QEBAOAQABCxAQEBAQEBANBwAAAAAAAAAAAAAAAAABDRAQEA4BAAQPEBAQEA0IBAEAAAAAAAAAAAAAAAAAAAENEBAQDgEACRAQDQkGAQAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQILCgYCAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA4BAQIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEBAQDgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA4BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEBAQDgEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQ0QEBAOAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRAQEA0BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAENEA0IBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQcFAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgAAAAQAAAAIAAAAAEACAAAAAAAQAEAAAAAAAAAAAAAAAEAAAAAAACEhAAAjIwAAJKSFgCZmSgAqqpRALKyYgC+vnsAxsaKAM3NmQDU1KgA4ODBAOjozwDw8OEA+fnyAP///wD///8AAAAAAAAaLwAALVAAAD9wAABRkAAAY7AAAHbPAACI8AARmP8AMab/AFGz/wBxwf8Akc//ALHd/wDR6/8A////AAAAAAAALC8AAEtQAABocAAAhpAAAKWwAADDzwAA4fAAEe//ADHx/wBR8/8AcfX/AJH3/wCx+f8A0fv/AP///wAAAAAAAC8hAABQNwAAcEwAAJBjAACweQAAz48AAPCmABH/tAAx/74AUf/IAHH/0wCR/9wAsf/lANH/8AD///8AAAAAAAAvDgAAUBgAAHAiAACQLAAAsDYAAM9AAADwSgAR/1sAMf9xAFH/hwBx/50Akf+yALH/yQDR/98A////AAAAAAACLwAABFAAAAZwAAAIkAAACrAAAAvPAAAO8AAAIP8SAD3/MQBb/1EAef9xAJj/kQC1/7EA1P/RAP///wAAAAAAFC8AACJQAAAwcAAAPZAAAEywAABZzwAAZ/AAAHj/EQCK/zEAnP9RAK7/cQDA/5EA0v+xAOT/0QD///8AAAAAACYvAABAUAAAWnAAAHSQAACOsAAAqc8AAMLwAADR/xEA2P8xAN7/UQDj/3EA6f+RAO//sQD2/9EA////AAAAAAAvJgAAUEEAAHBbAACQdAAAsI4AAM+pAADwwwAA/9IRAP/YMQD/3VEA/+RxAP/qkQD/8LEA//bRAP///wAAAAAALxQAAFAiAABwMAAAkD4AALBNAADPWwAA8GkAAP95EQD/ijEA/51RAP+vcQD/wZEA/9KxAP/l0QD///8AAAAAAC8DAABQBAAAcAYAAJAJAACwCgAAzwwAAPAOAAD/IBIA/z4xAP9cUQD/enEA/5eRAP+2sQD/1NEA////AAAAAAAvAA4AUAAXAHAAIQCQACsAsAA2AM8AQADwAEkA/xFaAP8xcAD/UYYA/3GcAP+RsgD/scgA/9HfAP///wAAAAAALwAgAFAANgBwAEwAkABiALAAeADPAI4A8ACkAP8RswD/Mb4A/1HHAP9x0QD/kdwA/7HlAP/R8AD///8AAAAAACwALwBLAFAAaQBwAIcAkAClALAAxADPAOEA8ADwEf8A8jH/APRR/wD2cf8A95H/APmx/wD70f8A////AAAAAAAbAC8ALQBQAD8AcABSAJAAYwCwAHYAzwCIAPAAmRH/AKYx/wC0Uf8AwnH/AM+R/wDcsf8A69H/AP///wAAAAAACAAvAA4AUAAVAHAAGwCQACEAsAAmAM8ALADwAD4R/wBYMf8AcVH/AIxx/wCmkf8Av7H/ANrR/wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwMAAAAAAAAAAAAAAAACBgwMBwIAAAAAAAAAAAAABg4ODg4MBgIAAAAAAAAAAAYODQoODg4KBAAAAAAAAAAGDgwDBQsODg4FAAAAAAAABg4MAgADCg4OBgAAAAAAAAYODAICCg4ODgYAAAAAAAAGDgwCBg4OCwcCAAAAAAAABg4MAwkIBAIAAAAAAAAAAAYODAICAAAAAAAAAAAAAAAGDgwCAAAAAAAAAAAAAAAABg4MAgAAAAAAAAAAAAAAAAYMCAEAAAAAAAAAAAAAAAACAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", - _urls : [ - { - type: "application/x-suggestions+json", - method: "GET", - template: "https://www.bing.com/osjson.aspx", - params: [ - { - name: "query", - value: "{searchTerms}", - purpose: undefined, - }, - { - name: "form", - value: "OSDJAS", - purpose: undefined, - }, - { - name: "language", - value: "{moz:locale}", - purpose: undefined, - }, - ], - }, - { - type: "text/html", - method: "GET", - template: "https://www.bing.com/search", - params: [ - { - name: "q", - value: "{searchTerms}", - purpose: undefined, - }, - { - name: "pc", - value: "MOZI", - purpose: undefined, - }, - { - name: "form", - value: "MOZCON", - purpose: "contextmenu", - }, - { - name: "form", - value: "MOZSBR", - purpose: "searchbar", - }, - { - name: "form", - value: "MOZSPG", - purpose: "homepage", - }, - { - name: "form", - value: "MOZLBR", - purpose:"keyword", - }, - { - name: "form", - value: "MOZTSB", - purpose: "newtab", - }, - ], - mozparams: {}, - }, - ], - }, - }; - - isSubObjectOf(EXPECTED_ENGINE, engine, "Bing"); -} diff --git a/browser/components/search/test/browser_bing_behavior.js b/browser/components/search/test/browser_bing_behavior.js deleted file mode 100644 index bc9b187ec..000000000 --- a/browser/components/search/test/browser_bing_behavior.js +++ /dev/null @@ -1,166 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Bing search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - - -function test() { - let engine = Services.search.getEngineByName("Bing"); - ok(engine, "Bing is installed"); - - let previouslySelectedEngine = Services.search.currentEngine; - Services.search.currentEngine = engine; - engine.alias = "b"; - - let base = "https://www.bing.com/search?q=foo&pc=MOZI"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base + "&form=MOZSBR", "Check search URL for 'foo'"); - - waitForExplicitFinish(); - - var gCurrTest; - var gTests = [ - { - name: "context menu search", - searchURL: base + "&form=MOZCON", - run: function () { - // Simulate a contextmenu search - // FIXME: This is a bit "low-level"... - BrowserSearch.loadSearch("foo", false, "contextmenu"); - } - }, - { - name: "keyword search", - searchURL: base + "&form=MOZLBR", - run: function () { - gURLBar.value = "? foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "keyword search with alias", - searchURL: base + "&form=MOZLBR", - run: function () { - gURLBar.value = "b foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "search bar search", - searchURL: base + "&form=MOZSBR", - run: function () { - let sb = BrowserSearch.searchBar; - sb.focus(); - sb.value = "foo"; - registerCleanupFunction(function () { - sb.value = ""; - }); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "new tab search", - searchURL: base + "&form=MOZTSB", - run: function () { - function doSearch(doc) { - // Re-add the listener, and perform a search - gBrowser.addProgressListener(listener); - doc.getElementById("newtab-search-text").value = "foo"; - doc.getElementById("newtab-search-submit").click(); - } - - // load about:newtab, but remove the listener first so it doesn't - // get in the way - gBrowser.removeProgressListener(listener); - gBrowser.loadURI("about:newtab"); - info("Waiting for about:newtab load"); - tab.linkedBrowser.addEventListener("load", function load(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank") { - info("skipping spurious load event"); - return; - } - tab.linkedBrowser.removeEventListener("load", load, true); - - // Observe page setup - let win = gBrowser.contentWindow; - if (win.gSearch.currentEngineName == - Services.search.currentEngine.name) { - doSearch(win.document); - } - else { - info("Waiting for newtab search init"); - win.addEventListener("ContentSearchService", function done(event) { - info("Got newtab search event " + event.detail.type); - if (event.detail.type == "State") { - win.removeEventListener("ContentSearchService", done); - // Let gSearch respond to the event before continuing. - executeSoon(() => doSearch(win.document)); - } - }); - } - }, true); - } - } - ]; - - function nextTest() { - if (gTests.length) { - gCurrTest = gTests.shift(); - info("Running : " + gCurrTest.name); - executeSoon(gCurrTest.run); - } else { - finish(); - } - } - - let tab = gBrowser.selectedTab = gBrowser.addTab(); - - let listener = { - onStateChange: function onStateChange(webProgress, req, flags, status) { - info("onStateChange"); - // Only care about top-level document starts - let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | - Ci.nsIWebProgressListener.STATE_START; - if (!(flags & docStart) || !webProgress.isTopLevel) - return; - - if (req.originalURI.spec == "about:blank") - return; - - info("received document start"); - - ok(req instanceof Ci.nsIChannel, "req is a channel"); - is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded"); - info("Actual URI: " + req.URI.spec); - - req.cancel(Components.results.NS_ERROR_FAILURE); - - executeSoon(nextTest); - } - } - - registerCleanupFunction(function () { - engine.alias = undefined; - gBrowser.removeProgressListener(listener); - gBrowser.removeTab(tab); - Services.search.currentEngine = previouslySelectedEngine; - }); - - tab.linkedBrowser.addEventListener("load", function load() { - tab.linkedBrowser.removeEventListener("load", load, true); - gBrowser.addProgressListener(listener); - nextTest(); - }, true); -} diff --git a/browser/components/search/test/browser_contextSearchTabPosition.js b/browser/components/search/test/browser_contextSearchTabPosition.js deleted file mode 100644 index 21a8c1130..000000000 --- a/browser/components/search/test/browser_contextSearchTabPosition.js +++ /dev/null @@ -1,62 +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* test() { - yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]}); - let engine = yield promiseNewEngine("testEngine.xml"); - let histogramKey = "other-" + engine.name + ".contextmenu"; - let numSearchesBefore = 0; - - 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 tabs = []; - let tabsLoadedDeferred = new Deferred(); - - function tabAdded(event) { - let tab = event.target; - tabs.push(tab); - - // We wait for the blank tab and the two context searches tabs to open. - if (tabs.length == 3) { - tabsLoadedDeferred.resolve(); - } - } - - let container = gBrowser.tabContainer; - container.addEventListener("TabOpen", tabAdded, false); - - gBrowser.addTab("about:blank"); - BrowserSearch.loadSearchFromContext("mozilla"); - BrowserSearch.loadSearchFromContext("firefox"); - - // Wait for all the tabs to open. - yield tabsLoadedDeferred.promise; - - is(tabs[0], gBrowser.tabs[3], "blank tab has been pushed to the end"); - is(tabs[1], gBrowser.tabs[1], "first search tab opens next to the current tab"); - is(tabs[2], gBrowser.tabs[2], "second search tab opens next to the first search tab"); - - container.removeEventListener("TabOpen", tabAdded, false); - tabs.forEach(gBrowser.removeTab, gBrowser); - - // Make sure that the context searches are correctly recorded. - let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot(); - Assert.ok(histogramKey in hs, "The histogram must contain the correct key"); - Assert.equal(hs[histogramKey].sum, numSearchesBefore + 2, - "The histogram must contain the correct search count"); -}); - -function Deferred() { - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); -} diff --git a/browser/components/search/test/browser_contextmenu.js b/browser/components/search/test/browser_contextmenu.js deleted file mode 100644 index c485242b4..000000000 --- a/browser/components/search/test/browser_contextmenu.js +++ /dev/null @@ -1,101 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * * http://creativecommons.org/publicdomain/zero/1.0/ */ -/* - * Test searching for the selected text using the context menu - */ - -add_task(function* () { - const ss = Services.search; - const ENGINE_NAME = "Foo"; - var contextMenu; - - // We want select events to be fired. - yield new Promise(resolve => SpecialPowers.pushPrefEnv({"set": [["dom.select_events.enabled", true]]}, resolve)); - - let envService = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); - let originalValue = envService.get("XPCSHELL_TEST_PROFILE_DIR"); - envService.set("XPCSHELL_TEST_PROFILE_DIR", "1"); - - let url = "chrome://mochitests/content/browser/browser/components/search/test/"; - let resProt = Services.io.getProtocolHandler("resource") - .QueryInterface(Ci.nsIResProtocolHandler); - let originalSubstitution = resProt.getSubstitution("search-plugins"); - resProt.setSubstitution("search-plugins", - Services.io.newURI(url, null, null)); - - let searchDonePromise; - yield new Promise(resolve => { - function observer(aSub, aTopic, aData) { - switch (aData) { - case "engine-added": - var engine = ss.getEngineByName(ENGINE_NAME); - ok(engine, "Engine was added."); - ss.currentEngine = engine; - envService.set("XPCSHELL_TEST_PROFILE_DIR", originalValue); - resProt.setSubstitution("search-plugins", originalSubstitution); - break; - case "engine-current": - is(ss.currentEngine.name, ENGINE_NAME, "currentEngine set"); - resolve(); - break; - case "engine-removed": - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - if (searchDonePromise) { - searchDonePromise(); - } - break; - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - ss.addEngine("resource://search-plugins/testEngine_mozsearch.xml", - null, "data:image/x-icon,%00", false); - }); - - contextMenu = document.getElementById("contentAreaContextMenu"); - ok(contextMenu, "Got context menu XUL"); - - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/plain;charset=utf8,test%20search"); - - yield ContentTask.spawn(tab.linkedBrowser, "", function*() { - return new Promise(resolve => { - content.document.addEventListener("selectionchange", function selectionChanged() { - content.document.removeEventListener("selectionchange", selectionChanged); - resolve(); - }); - content.document.getSelection().selectAllChildren(content.document.body); - }); - }); - - var eventDetails = { type: "contextmenu", button: 2 }; - - let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - BrowserTestUtils.synthesizeMouseAtCenter("body", eventDetails, gBrowser.selectedBrowser); - yield popupPromise; - - info("checkContextMenu"); - var searchItem = contextMenu.getElementsByAttribute("id", "context-searchselect")[0]; - ok(searchItem, "Got search context menu item"); - is(searchItem.label, 'Search ' + ENGINE_NAME + ' for \u201ctest search\u201d', "Check context menu label"); - is(searchItem.disabled, false, "Check that search context menu item is enabled"); - - yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => { - searchItem.click(); - }); - - is(gBrowser.currentURI.spec, - "http://mochi.test:8888/browser/browser/components/search/test/?test=test+search&ie=utf-8&channel=contextsearch", - "Checking context menu search URL"); - - contextMenu.hidePopup(); - - // Remove the tab opened by the search - gBrowser.removeCurrentTab(); - - yield new Promise(resolve => { - searchDonePromise = resolve; - ss.removeEngine(ss.currentEngine); - }); - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/search/test/browser_google.js b/browser/components/search/test/browser_google.js deleted file mode 100644 index 2b0cabea7..000000000 --- a/browser/components/search/test/browser_google.js +++ /dev/null @@ -1,100 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Google search plugin URLs - */ - -"use strict"; - -function test() { - let engine = Services.search.getEngineByName("Google"); - ok(engine, "Google"); - - let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b"; - let keywordBase = base + "-ab"; - - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base, "Check search URL for 'foo'"); - url = engine.getSubmission("foo", null, "contextmenu").uri.spec; - is(url, base, "Check context menu search URL for 'foo'"); - url = engine.getSubmission("foo", null, "keyword").uri.spec; - is(url, keywordBase, "Check keyword search URL for 'foo'"); - url = engine.getSubmission("foo", null, "searchbar").uri.spec; - is(url, base, "Check search bar search URL for 'foo'"); - url = engine.getSubmission("foo", null, "homepage").uri.spec; - is(url, base, "Check homepage search URL for 'foo'"); - url = engine.getSubmission("foo", null, "newtab").uri.spec; - is(url, base, "Check newtab search URL for 'foo'"); - - // Check search suggestion URL. - url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec; - is(url, "https://www.google.com/complete/search?client=firefox&q=foo", "Check search suggestion URL for 'foo'"); - - // Check result parsing and alternate domains. - let alternateBase = base.replace("www.google.com", "www.google.fr"); - is(Services.search.parseSubmissionURL(base).terms, "foo", - "Check result parsing"); - is(Services.search.parseSubmissionURL(alternateBase).terms, "foo", - "Check alternate domain"); - - // Check all other engine properties. - const EXPECTED_ENGINE = { - name: "Google", - alias: null, - description: "Google Search", - searchForm: "https://www.google.com/search?q=&ie=utf-8&oe=utf-8&client=firefox-b", - hidden: false, - wrappedJSObject: { - queryCharset: "UTF-8", - "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///zD9/f2W/f392P39/fn9/f35/f391/39/ZT+/v4uAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v7+Cf39/Zn///////////////////////////////////////////39/ZX///8IAAAAAAAAAAAAAAAA/v7+Cf39/cH/////+v35/7TZp/92ul3/WKs6/1iqOv9yuFn/rNWd//j79v///////f39v////wgAAAAAAAAAAP39/Zn/////7PXp/3G3WP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP+Or1j//vDo///////9/f2VAAAAAP///zD/////+vz5/3G3V/9TqDT/WKo6/6LQkf/U6cz/1urO/6rUm/+Zo0r/8IZB//adZ////v7///////7+/i79/f2Y/////4nWzf9Lqkj/Vqo4/9Xqzv///////////////////////ebY//SHRv/0hUL//NjD///////9/f2U/f392v////8sxPH/Ebzt/43RsP/////////////////////////////////4roL/9IVC//i1jf///////f391/39/fr/////Cr37/wW8+/+16/7/////////////////9IVC//SFQv/0hUL/9IVC//SFQv/3pnX///////39/fn9/f36/////wu++/8FvPv/tuz+//////////////////SFQv/0hUL/9IVC//SFQv/0hUL/96p7///////9/f35/f392/////81yfz/CrL5/2uk9v///////////////////////////////////////////////////////f392P39/Zn/////ks/7/zdS7P84Rur/0NT6///////////////////////9/f////////////////////////39/Zb+/v4y//////n5/v9WYu3/NUPq/ztJ6/+VnPT/z9L6/9HU+v+WnfT/Ul7t/+Hj/P////////////////////8wAAAAAP39/Z3/////6Or9/1hj7v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v9sdvD////////////9/f2YAAAAAAAAAAD///8K/f39w//////5+f7/paz2/11p7v88Suv/Okfq/1pm7v+iqfX/+fn+///////9/f3B/v7+CQAAAAAAAAAAAAAAAP///wr9/f2d///////////////////////////////////////////9/f2Z/v7+CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/jL9/f2Z/f392/39/fr9/f36/f392v39/Zj///8wAAAAAAAAAAAAAAAAAAAAAPAPAADAAwAAgAEAAIABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAACAAQAAwAMAAPAPAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/g3+/v5X/f39mf39/cj9/f3q/f39+f39/fn9/f3q/f39yP39/Zn+/v5W////DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/iT9/f2c/f399f/////////////////////////////////////////////////////9/f31/f39mv7+/iMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/gn9/f2K/f39+////////////////////////////////////////////////////////////////////////////f39+v39/Yf///8IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+/v4k/f390v////////////////////////////////////////////////////////////////////////////////////////////////39/dD///8iAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////MP39/er//////////////////////////+r05v+v16H/gsBs/2WxSf9Wqjj/Vqk3/2OwRv99vWX/pdKV/97u2P////////////////////////////39/ej+/v4vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/iT9/f3q/////////////////////+v15/+Pxnv/VKk2/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/36+Z//d7tf///////////////////////39/ej///8iAAAAAAAAAAAAAAAAAAAAAAAAAAD///8K/f390//////////////////////E4bn/XKw+/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1apN/+x0pv///////////////////////39/dD///8IAAAAAAAAAAAAAAAAAAAAAP39/Yv/////////////////////sdij/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9TqDT/YKU1/8qOPv/5wZ////////////////////////39/YcAAAAAAAAAAAAAAAD+/v4l/f39+////////////////8Lgt/9TqDT/U6g0/1OoNP9TqDT/U6g0/1OoNP9utlT/n86N/7faqv+426v/pdKV/3u8ZP9UqDX/U6g0/3egN//jiUH/9IVC//SFQv/82MP//////////////////f39+v7+/iMAAAAAAAAAAP39/Z3////////////////q9Ob/W6w+/1OoNP9TqDT/U6g0/1OoNP9nskz/zOXC/////////////////////////////////+Dv2v+osWP/8YVC//SFQv/0hUL/9IVC//WQVP/++fb//////////////////f39mgAAAAD+/v4O/f399v///////////////4LHj/9TqDT/U6g0/1OoNP9TqDT/dblc//L58P/////////////////////////////////////////////8+v/3p3f/9IVC//SFQv/0hUL/9IVC//rIqf/////////////////9/f31////DP7+/ln////////////////f9v7/Cbz2/zOwhv9TqDT/U6g0/2KwRv/v9+z///////////////////////////////////////////////////////738//1kFT/9IVC//SFQv/0hUL/9plg///////////////////////+/v5W/f39nP///////////////4jf/f8FvPv/Bbz7/yG1s/9QqDz/vN2w//////////////////////////////////////////////////////////////////rHqP/0hUL/9IVC//SFQv/0hUL//vDn//////////////////39/Zn9/f3L////////////////R878/wW8+/8FvPv/Bbz7/y7C5P/7/fr//////////////////////////////////////////////////////////////////ere//SFQv/0hUL/9IVC//SFQv/718H//////////////////f39yP39/ez///////////////8cwvv/Bbz7/wW8+/8FvPv/WNL8///////////////////////////////////////0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//rIqv/////////////////9/f3q/f39+v///////////////we9+/8FvPv/Bbz7/wW8+/993P3///////////////////////////////////////SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/+cGf//////////////////39/fn9/f36////////////////B737/wW8+/8FvPv/Bbz7/33c/f//////////////////////////////////////9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/6xaX//////////////////f39+f39/e3///////////////8cwvv/Bbz7/wW8+/8FvPv/WdP8///////////////////////////////////////0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//SFQv/0hUL/9IVC//vVv//////////////////9/f3q/f39y////////////////0bN/P8FvPv/Bbz7/wW8+/8hrvn/+/v///////////////////////////////////////////////////////////////////////////////////////////////////////////////////39/cj9/f2c////////////////ht/9/wW8+/8FvPv/FZP1/zRJ6/+zuPf//////////////////////////////////////////////////////////////////////////////////////////////////////////////////f39mf7+/lr////////////////d9v7/B7n7/yB38f81Q+r/NUPq/0hV7P/u8P3////////////////////////////////////////////////////////////////////////////////////////////////////////////+/v5X////D/39/ff///////////////9tkPT/NUPq/zVD6v81Q+r/NUPq/2Fs7//y8v7////////////////////////////////////////////09f7//////////////////////////////////////////////////f399f7+/g0AAAAA/f39n////////////////+Tm/P89Suv/NUPq/zVD6v81Q+r/NUPq/1Bc7f/IzPn/////////////////////////////////x8v5/0xY7P+MlPP////////////////////////////////////////////9/f2cAAAAAAAAAAD+/v4n/f39/P///////////////7W69/81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v9ZZe7/k5v0/6609/+vtff/lJv0/1pm7v81Q+r/NUPq/zVD6v+GjvL//v7//////////////////////////////f39+/7+/iQAAAAAAAAAAAAAAAD9/f2N/////////////////////6Cn9f81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v+BivL////////////////////////////9/f2KAAAAAAAAAAAAAAAAAAAAAP7+/gv9/f3V/////////////////////7W69/8+S+v/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/P0zr/7q/+P///////////////////////f390v7+/gkAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/ib9/f3r/////////////////////+Xn/P94gfH/NkTq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NUPq/zVD6v81Q+r/NkTq/3Z/8f/l5/z///////////////////////39/er+/v4kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/jL9/f3r///////////////////////////k5vz/nqX1/2p08P9IVez/OEbq/zdF6v9GU+z/aHLv/5qh9f/i5Pz////////////////////////////9/f3q////MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/ib9/f3V/////////////////////////////////////////////////////////////////////////////////////////////////f390v7+/iQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wr9/f2N/f39/P///////////////////////////////////////////////////////////////////////////f39+/39/Yv+/v4JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD+/v4n/f39n/39/ff//////////////////////////////////////////////////////f399v39/Z3+/v4lAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v7+Dv7+/lr9/f2c/f39y/39/e39/f36/f39+v39/ez9/f3L/f39nP7+/ln+/v4OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/AA///AAD//AAAP/gAAB/wAAAP4AAAB8AAAAPAAAADgAAAAYAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAABgAAAAcAAAAPAAAAD4AAAB/AAAA/4AAAf/AAAP/8AAP//wAP/", - _urls : [ - { - type: "application/x-suggestions+json", - method: "GET", - template: "https://www.google.com/complete/search?client=firefox&q={searchTerms}", - params: "", - }, - { - type: "text/html", - method: "GET", - template: "https://www.google.com/search", - params: [ - { - "name": "q", - "value": "{searchTerms}", - "purpose": undefined, - }, - { - "name": "ie", - "value": "utf-8", - "purpose": undefined, - }, - { - "name": "oe", - "value": "utf-8", - "purpose": undefined, - }, - { - "name": "client", - "value": "firefox-b-ab", - "purpose": "keyword", - }, - { - "name": "client", - "value": "firefox-b", - "purpose": "searchbar", - }, - ], - mozparams: { - }, - }, - ], - }, - }; - - isSubObjectOf(EXPECTED_ENGINE, engine, "Google"); -} diff --git a/browser/components/search/test/browser_google_behavior.js b/browser/components/search/test/browser_google_behavior.js deleted file mode 100644 index 55405bb29..000000000 --- a/browser/components/search/test/browser_google_behavior.js +++ /dev/null @@ -1,165 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Google search plugin URLs - */ - -"use strict"; - -function test() { - let engine = Services.search.getEngineByName("Google"); - ok(engine, "Google is installed"); - - let previouslySelectedEngine = Services.search.currentEngine; - Services.search.currentEngine = engine; - engine.alias = "g"; - - let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b"; - let keywordBase = base + "-ab"; - - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base, "Check search URL for 'foo'"); - - waitForExplicitFinish(); - - var gCurrTest; - var gTests = [ - { - name: "context menu search", - searchURL: base, - run: function () { - // Simulate a contextmenu search - // FIXME: This is a bit "low-level"... - BrowserSearch.loadSearch("foo", false, "contextmenu"); - } - }, - { - name: "keyword search", - searchURL: keywordBase, - run: function () { - gURLBar.value = "? foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "keyword search", - searchURL: keywordBase, - run: function () { - gURLBar.value = "g foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "search bar search", - searchURL: base, - run: function () { - let sb = BrowserSearch.searchBar; - sb.focus(); - sb.value = "foo"; - registerCleanupFunction(function () { - sb.value = ""; - }); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "new tab search", - searchURL: base, - run: function () { - function doSearch(doc) { - // Re-add the listener, and perform a search - gBrowser.addProgressListener(listener); - doc.getElementById("newtab-search-text").value = "foo"; - doc.getElementById("newtab-search-submit").click(); - } - - // load about:newtab, but remove the listener first so it doesn't - // get in the way - gBrowser.removeProgressListener(listener); - gBrowser.loadURI("about:newtab"); - info("Waiting for about:newtab load"); - tab.linkedBrowser.addEventListener("load", function load(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank") { - info("skipping spurious load event"); - return; - } - tab.linkedBrowser.removeEventListener("load", load, true); - - // Observe page setup - let win = gBrowser.contentWindow; - if (win.gSearch.currentEngineName == - Services.search.currentEngine.name) { - doSearch(win.document); - } - else { - info("Waiting for newtab search init"); - win.addEventListener("ContentSearchService", function done(event) { - info("Got newtab search event " + event.detail.type); - if (event.detail.type == "State") { - win.removeEventListener("ContentSearchService", done); - // Let gSearch respond to the event before continuing. - executeSoon(() => doSearch(win.document)); - } - }); - } - }, true); - } - } - ]; - - function nextTest() { - if (gTests.length) { - gCurrTest = gTests.shift(); - info("Running : " + gCurrTest.name); - executeSoon(gCurrTest.run); - } else { - finish(); - } - } - - let tab = gBrowser.selectedTab = gBrowser.addTab(); - - let listener = { - onStateChange: function onStateChange(webProgress, req, flags, status) { - info("onStateChange"); - // Only care about top-level document starts - let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | - Ci.nsIWebProgressListener.STATE_START; - if (!(flags & docStart) || !webProgress.isTopLevel) - return; - - if (req.originalURI.spec == "about:blank") - return; - - info("received document start"); - - ok(req instanceof Ci.nsIChannel, "req is a channel"); - is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded"); - info("Actual URI: " + req.URI.spec); - - req.cancel(Components.results.NS_ERROR_FAILURE); - - executeSoon(nextTest); - } - } - - registerCleanupFunction(function () { - engine.alias = undefined; - gBrowser.removeProgressListener(listener); - gBrowser.removeTab(tab); - Services.search.currentEngine = previouslySelectedEngine; - }); - - tab.linkedBrowser.addEventListener("load", function load() { - tab.linkedBrowser.removeEventListener("load", load, true); - gBrowser.addProgressListener(listener); - nextTest(); - }, true); -} diff --git a/browser/components/search/test/browser_google_codes.js b/browser/components/search/test/browser_google_codes.js deleted file mode 100644 index e166b6868..000000000 --- a/browser/components/search/test/browser_google_codes.js +++ /dev/null @@ -1,161 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const kUrlPref = "geoSpecificDefaults.url"; -const BROWSER_SEARCH_PREF = "browser.search."; - -var originalGeoURL; - -/** - * Clean the profile of any cache file left from a previous run. - * Returns a boolean indicating if the cache file existed. - */ -function removeCacheFile() -{ - const CACHE_FILENAME = "search.json.mozlz4"; - - let file = Services.dirsvc.get("ProfD", Ci.nsIFile); - file.append(CACHE_FILENAME); - if (file.exists()) { - file.remove(false); - return true; - } - return false; -} - -/** - * Returns a promise that is resolved when an observer notification from the - * search service fires with the specified data. - * - * @param aExpectedData - * The value the observer notification sends that causes us to resolve - * the promise. - */ -function waitForSearchNotification(aExpectedData, aCallback) { - const SEARCH_SERVICE_TOPIC = "browser-search-service"; - Services.obs.addObserver(function observer(aSubject, aTopic, aData) { - if (aData != aExpectedData) - return; - - Services.obs.removeObserver(observer, SEARCH_SERVICE_TOPIC); - aCallback(); - }, SEARCH_SERVICE_TOPIC, false); -} - -function asyncInit() { - return new Promise(resolve => { - Services.search.init(function() { - ok(Services.search.isInitialized, "search service should be initialized"); - resolve(); - }); - }); -} - -function asyncReInit() { - const kLocalePref = "general.useragent.locale"; - - let promise = new Promise(resolve => { - waitForSearchNotification("reinit-complete", resolve); - }); - - Services.search.QueryInterface(Ci.nsIObserver) - .observe(null, "nsPref:changed", kLocalePref); - - return promise; -} - -let gEngineCount; - -add_task(function* preparation() { - // ContentSearch is interferring with our async re-initializations of the - // search service: once _initServicePromise has resolved, it will access - // the search service, thus causing unpredictable behavior due to - // synchronous initializations of the service. - let originalContentSearchPromise = ContentSearch._initServicePromise; - ContentSearch._initServicePromise = new Promise(resolve => { - registerCleanupFunction(() => { - ContentSearch._initServicePromise = originalContentSearchPromise; - resolve(); - }); - }); - - yield asyncInit(); - gEngineCount = Services.search.getVisibleEngines().length; - - waitForSearchNotification("uninit-complete", () => { - // Verify search service is not initialized - is(Services.search.isInitialized, false, "Search service should NOT be initialized"); - - removeCacheFile(); - - // Geo specific defaults won't be fetched if there's no country code. - Services.prefs.setCharPref("browser.search.geoip.url", - 'data:application/json,{"country_code": "US"}'); - - Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", true); - - // Make the new Google the only engine - originalGeoURL = Services.prefs.getCharPref(BROWSER_SEARCH_PREF + kUrlPref); - let geoUrl = 'data:application/json,{"interval": 31536000, "settings": {"searchDefault": "Google", "visibleDefaultEngines": ["google"]}}'; - Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, geoUrl); - }); - - yield asyncReInit(); - - yield new Promise(resolve => { - waitForSearchNotification("write-cache-to-disk-complete", resolve); - }); -}); - -add_task(function* tests() { - let engines = Services.search.getEngines(); - is(Services.search.currentEngine.name, "Google", "Search engine should be Google"); - is(engines.length, 1, "There should only be one engine"); - - let engine = Services.search.getEngineByName("Google"); - ok(engine, "Google"); - - let base = "https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b"; - - // Keyword uses a slightly different code - let keywordBase = base + "-ab"; - - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo", null, "contextmenu").uri.spec; - is(url, base, "Check context menu search URL for 'foo'"); - url = engine.getSubmission("foo", null, "keyword").uri.spec; - is(url, keywordBase, "Check keyword search URL for 'foo'"); - url = engine.getSubmission("foo", null, "searchbar").uri.spec; - is(url, base, "Check search bar search URL for 'foo'"); - url = engine.getSubmission("foo", null, "homepage").uri.spec; - is(url, base, "Check homepage search URL for 'foo'"); - url = engine.getSubmission("foo", null, "newtab").uri.spec; - is(url, base, "Check newtab search URL for 'foo'"); - url = engine.getSubmission("foo", null, "system").uri.spec; - is(url, base, "Check system search URL for 'foo'"); -}); - - -add_task(function* cleanup() { - waitForSearchNotification("uninit-complete", () => { - // Verify search service is not initialized - is(Services.search.isInitialized, false, - "Search service should NOT be initialized"); - removeCacheFile(); - - Services.prefs.clearUserPref("browser.search.geoip.url"); - - // We can't clear the pref because it's set to false by testing/profiles/prefs_general.js - Services.prefs.setBoolPref("browser.search.geoSpecificDefaults", false); - - Services.prefs.getDefaultBranch(BROWSER_SEARCH_PREF).setCharPref(kUrlPref, originalGeoURL); - }); - - yield asyncReInit(); - is(gEngineCount, Services.search.getVisibleEngines().length, - "correct engine count after cleanup"); -}); diff --git a/browser/components/search/test/browser_healthreport.js b/browser/components/search/test/browser_healthreport.js deleted file mode 100644 index c68ad174c..000000000 --- a/browser/components/search/test/browser_healthreport.js +++ /dev/null @@ -1,82 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences; - -function test() { - waitForExplicitFinish(); - resetPreferences(); - - function testTelemetry() { - // Find the right bucket for the "Foo" engine. - let engine = Services.search.getEngineByName("Foo"); - let histogramKey = (engine.identifier || "other-Foo") + ".searchbar"; - let numSearchesBefore = 0; - 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. - } - - // Now perform a search and ensure the count is incremented. - let tab = gBrowser.addTab(); - gBrowser.selectedTab = tab; - let searchBar = BrowserSearch.searchBar; - - searchBar.value = "firefox health report"; - searchBar.focus(); - - function afterSearch() { - searchBar.value = ""; - gBrowser.removeTab(tab); - - // Make sure that the context searches are correctly recorded. - let hs = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").snapshot(); - Assert.ok(histogramKey in hs, "The histogram must contain the correct key"); - Assert.equal(hs[histogramKey].sum, numSearchesBefore + 1, - "Performing a search increments the related SEARCH_COUNTS key by 1."); - - let engine = Services.search.getEngineByName("Foo"); - Services.search.removeEngine(engine); - } - - EventUtils.synthesizeKey("VK_RETURN", {}); - executeSoon(() => executeSoon(afterSearch)); - } - - function observer(subject, topic, data) { - switch (data) { - case "engine-added": - let engine = Services.search.getEngineByName("Foo"); - ok(engine, "Engine was added."); - Services.search.currentEngine = engine; - break; - - case "engine-current": - is(Services.search.currentEngine.name, "Foo", "Current engine is Foo"); - testTelemetry(); - break; - - case "engine-removed": - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - finish(); - break; - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]}).then(function() { - Services.search.addEngine("http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml", - null, "data:image/x-icon,%00", false); - }); -} - -function resetPreferences() { - Preferences.resetBranch("datareporting.policy."); - Preferences.set("datareporting.policy.dataSubmissionPolicyBypassNotification", true); -} diff --git a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js b/browser/components/search/test/browser_hiddenOneOffs_cleanup.js deleted file mode 100644 index 9a584feb6..000000000 --- a/browser/components/search/test/browser_hiddenOneOffs_cleanup.js +++ /dev/null @@ -1,99 +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 testPref = "Foo,FooDupe"; - -function promiseNewEngine(basename) { - return new Promise((resolve, reject) => { - info("Waiting for engine to be added: " + basename); - Services.search.init({ - onInitComplete: function() { - let url = getRootDirectory(gTestPath) + basename; - Services.search.addEngine(url, null, "", false, { - onSuccess: function (engine) { - info("Search engine added: " + basename); - resolve(engine); - }, - onError: function (errCode) { - ok(false, "addEngine failed with error code " + errCode); - reject(); - } - }); - } - }); - }); -} - -add_task(function* test_remove() { - yield promiseNewEngine("testEngine_dupe.xml"); - yield promiseNewEngine("testEngine.xml"); - Services.prefs.setCharPref("browser.search.hiddenOneOffs", testPref); - - info("Removing testEngine_dupe.xml"); - Services.search.removeEngine(Services.search.getEngineByName("FooDupe")); - - let hiddenOneOffs = - Services.prefs.getCharPref("browser.search.hiddenOneOffs").split(","); - - is(hiddenOneOffs.length, 1, - "hiddenOneOffs has the correct engine count post removal."); - is(hiddenOneOffs.some(x => x == "FooDupe"), false, - "Removed Engine is not in hiddenOneOffs after removal"); - is(hiddenOneOffs.some(x => x == "Foo"), true, - "Current hidden engine is not affected by removal."); - - info("Removing testEngine.xml"); - Services.search.removeEngine(Services.search.getEngineByName("Foo")); - - is(Services.prefs.getCharPref("browser.search.hiddenOneOffs"), "", - "hiddenOneOffs is empty after removing all hidden engines."); -}); - -add_task(function* test_add() { - yield promiseNewEngine("testEngine.xml"); - info("setting prefs to " + testPref); - Services.prefs.setCharPref("browser.search.hiddenOneOffs", testPref); - yield promiseNewEngine("testEngine_dupe.xml"); - - let hiddenOneOffs = - Services.prefs.getCharPref("browser.search.hiddenOneOffs").split(","); - - is(hiddenOneOffs.length, 1, - "hiddenOneOffs has the correct number of hidden engines present post add."); - is(hiddenOneOffs.some(x => x == "FooDupe"), false, - "Added engine is not present in hidden list."); - is(hiddenOneOffs.some(x => x == "Foo"), true, - "Adding an engine does not remove engines from hidden list."); -}); - -add_task(function* test_diacritics() { - const diacritic_engine = "Foo \u2661"; - let Preferences = - Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences; - - Preferences.set("browser.search.hiddenOneOffs", diacritic_engine); - yield promiseNewEngine("testEngine_diacritics.xml"); - - let hiddenOneOffs = - Preferences.get("browser.search.hiddenOneOffs").split(","); - is(hiddenOneOffs.some(x => x == diacritic_engine), false, - "Observer cleans up added hidden engines that include a diacritic."); - - Preferences.set("browser.search.hiddenOneOffs", diacritic_engine); - - info("Removing testEngine_diacritics.xml"); - Services.search.removeEngine(Services.search.getEngineByName(diacritic_engine)); - - hiddenOneOffs = - Preferences.get("browser.search.hiddenOneOffs").split(","); - is(hiddenOneOffs.some(x => x == diacritic_engine), false, - "Observer cleans up removed hidden engines that include a diacritic."); -}); - -registerCleanupFunction(() => { - info("Removing testEngine.xml"); - Services.search.removeEngine(Services.search.getEngineByName("Foo")); - info("Removing testEngine_dupe.xml"); - Services.search.removeEngine(Services.search.getEngineByName("FooDupe")); - Services.prefs.clearUserPref("browser.search.hiddenOneOffs"); -}); diff --git a/browser/components/search/test/browser_hiddenOneOffs_diacritics.js b/browser/components/search/test/browser_hiddenOneOffs_diacritics.js deleted file mode 100644 index db24c7192..000000000 --- a/browser/components/search/test/browser_hiddenOneOffs_diacritics.js +++ /dev/null @@ -1,59 +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/. */ -// Tests that keyboard navigation in the search panel works as designed. - -const searchbar = document.getElementById("searchbar"); -const textbox = searchbar._textbox; -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid", - "searchbar-search-button"); - -const diacritic_engine = "Foo \u2661"; - -var Preferences = - Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences; - -add_task(function* init() { - let currentEngine = Services.search.currentEngine; - yield promiseNewEngine("testEngine_diacritics.xml", {setAsCurrent: false}); - registerCleanupFunction(() => { - Services.search.currentEngine = currentEngine; - Services.prefs.clearUserPref("browser.search.hiddenOneOffs"); - }); -}); - -add_task(function* test_hidden() { - Preferences.set("browser.search.hiddenOneOffs", diacritic_engine); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; - - ok(!getOneOffs().some(x => x.getAttribute("tooltiptext") == diacritic_engine), - "Search engines with diacritics are hidden when added to hiddenOneOffs preference."); - - promise = promiseEvent(searchPopup, "popuphidden"); - info("Closing search panel"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; -}); - -add_task(function* test_shown() { - Preferences.set("browser.search.hiddenOneOffs", ""); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - }); - yield promise; - - ok(getOneOffs().some(x => x.getAttribute("tooltiptext") == diacritic_engine), - "Search engines with diacritics are shown when removed from hiddenOneOffs preference."); - - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; -}); diff --git a/browser/components/search/test/browser_oneOffContextMenu.js b/browser/components/search/test/browser_oneOffContextMenu.js deleted file mode 100644 index 69207923b..000000000 --- a/browser/components/search/test/browser_oneOffContextMenu.js +++ /dev/null @@ -1,105 +0,0 @@ -"use strict"; - -const TEST_ENGINE_NAME = "Foo"; -const TEST_ENGINE_BASENAME = "testEngine.xml"; - -const searchbar = document.getElementById("searchbar"); -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const searchIcon = document.getAnonymousElementByAttribute( - searchbar, "anonid", "searchbar-search-button" -); -const oneOffBinding = document.getAnonymousElementByAttribute( - searchPopup, "anonid", "search-one-off-buttons" -); -const contextMenu = document.getAnonymousElementByAttribute( - oneOffBinding, "anonid", "search-one-offs-context-menu" -); -const oneOffButtons = document.getAnonymousElementByAttribute( - oneOffBinding, "anonid", "search-panel-one-offs" -); -const searchInNewTabMenuItem = document.getAnonymousElementByAttribute( - oneOffBinding, "anonid", "search-one-offs-context-open-in-new-tab" -); - -add_task(function* init() { - yield promiseNewEngine(TEST_ENGINE_BASENAME, { - setAsCurrent: false, - }); -}); - -add_task(function* extendedTelemetryDisabled() { - yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", false]]}); - yield doTest(); - checkTelemetry("other"); -}); - -add_task(function* extendedTelemetryEnabled() { - yield SpecialPowers.pushPrefEnv({set: [["toolkit.telemetry.enabled", true]]}); - yield doTest(); - checkTelemetry("other-" + TEST_ENGINE_NAME); -}); - -function* doTest() { - // Open the popup. - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; - - // Get the one-off button for the test engine. - let oneOffButton; - for (let node of oneOffButtons.childNodes) { - if (node.engine && node.engine.name == TEST_ENGINE_NAME) { - oneOffButton = node; - break; - } - } - Assert.notEqual(oneOffButton, undefined, - "One-off for test engine should exist"); - - // Open the context menu on the one-off. - promise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - EventUtils.synthesizeMouseAtCenter(oneOffButton, { - type: "contextmenu", - button: 2, - }); - yield promise; - - // Click the Search in New Tab menu item. - promise = BrowserTestUtils.waitForNewTab(gBrowser); - EventUtils.synthesizeMouseAtCenter(searchInNewTabMenuItem, {}); - let tab = yield promise; - - // By default the search will open in the background and the popup will stay open: - promise = promiseEvent(searchPopup, "popuphidden"); - info("Closing search panel"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - // Check the loaded tab. - Assert.equal(tab.linkedBrowser.currentURI.spec, - "http://mochi.test:8888/browser/browser/components/search/test/", - "Expected search tab should have loaded"); - - yield BrowserTestUtils.removeTab(tab); - - // Move the cursor out of the panel area to avoid messing with other tests. - yield EventUtils.synthesizeNativeMouseMove(searchbar); -} - -function checkTelemetry(expectedEngineName) { - let propertyPath = [ - "countableEvents", - "__DEFAULT__", - "search-oneoff", - expectedEngineName + ".oneoff-context-searchbar", - "unknown", - "tab-background", - ]; - let telem = BrowserUITelemetry.getToolbarMeasures(); - for (let prop of propertyPath) { - Assert.ok(prop in telem, "Property " + prop + " should be in the telemetry"); - telem = telem[prop]; - } - Assert.equal(telem, 1, "Click count"); -} diff --git a/browser/components/search/test/browser_oneOffContextMenu_setDefault.js b/browser/components/search/test/browser_oneOffContextMenu_setDefault.js deleted file mode 100644 index ff49cb0c6..000000000 --- a/browser/components/search/test/browser_oneOffContextMenu_setDefault.js +++ /dev/null @@ -1,195 +0,0 @@ -"use strict"; - -const TEST_ENGINE_NAME = "Foo"; -const TEST_ENGINE_BASENAME = "testEngine.xml"; -const SEARCHBAR_BASE_ID = "searchbar-engine-one-off-item-"; -const URLBAR_BASE_ID = "urlbar-engine-one-off-item-"; -const ONEOFF_URLBAR_PREF = "browser.urlbar.oneOffSearches"; - -const searchbar = document.getElementById("searchbar"); -const urlbar = document.getElementById("urlbar"); -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const urlbarPopup = document.getElementById("PopupAutoCompleteRichResult"); -const searchIcon = document.getAnonymousElementByAttribute( - searchbar, "anonid", "searchbar-search-button" -); -const searchOneOffBinding = document.getAnonymousElementByAttribute( - searchPopup, "anonid", "search-one-off-buttons" -); -const urlBarOneOffBinding = document.getAnonymousElementByAttribute( - urlbarPopup, "anonid", "one-off-search-buttons" -); - -let originalEngine = Services.search.currentEngine; - -function resetEngine() { - Services.search.currentEngine = originalEngine; -} - -registerCleanupFunction(resetEngine); - -add_task(function* init() { - yield promiseNewEngine(TEST_ENGINE_BASENAME, { - setAsCurrent: false, - }); -}); - -add_task(function* test_searchBarChangeEngine() { - let oneOffButton = yield openPopupAndGetEngineButton(true, searchPopup, - searchOneOffBinding, - SEARCHBAR_BASE_ID); - - const setDefaultEngineMenuItem = document.getAnonymousElementByAttribute( - searchOneOffBinding, "anonid", "search-one-offs-context-set-default" - ); - - // Click the set default engine menu item. - let promise = promiseCurrentEngineChanged(); - EventUtils.synthesizeMouseAtCenter(setDefaultEngineMenuItem, {}); - - // This also checks the engine correctly changed. - yield promise; - - Assert.equal(oneOffButton.id, SEARCHBAR_BASE_ID + originalEngine.name, - "Should now have the original engine's id for the button"); - Assert.equal(oneOffButton.getAttribute("tooltiptext"), originalEngine.name, - "Should now have the original engine's name for the tooltip"); - Assert.equal(oneOffButton.image, originalEngine.iconURI.spec, - "Should now have the original engine's uri for the image"); - - yield promiseClosePopup(searchPopup); -}); - -add_task(function* test_urlBarChangeEngine() { - Services.prefs.setBoolPref(ONEOFF_URLBAR_PREF, true); - registerCleanupFunction(function* () { - Services.prefs.clearUserPref(ONEOFF_URLBAR_PREF); - }); - - // Ensure the engine is reset. - resetEngine(); - - let oneOffButton = yield openPopupAndGetEngineButton(false, urlbarPopup, - urlBarOneOffBinding, - URLBAR_BASE_ID); - - const setDefaultEngineMenuItem = document.getAnonymousElementByAttribute( - urlBarOneOffBinding, "anonid", "search-one-offs-context-set-default" - ); - - // Click the set default engine menu item. - let promise = promiseCurrentEngineChanged(); - EventUtils.synthesizeMouseAtCenter(setDefaultEngineMenuItem, {}); - - // This also checks the engine correctly changed. - yield promise; - - let currentEngine = Services.search.currentEngine; - - // For the urlbar, we should keep the new engine's icon. - Assert.equal(oneOffButton.id, URLBAR_BASE_ID + currentEngine.name, - "Should now have the original engine's id for the button"); - Assert.equal(oneOffButton.getAttribute("tooltiptext"), currentEngine.name, - "Should now have the original engine's name for the tooltip"); - Assert.equal(oneOffButton.image, currentEngine.iconURI.spec, - "Should now have the original engine's uri for the image"); - - yield promiseClosePopup(urlbarPopup); -}); - -/** - * Promises that an engine change has happened for the current engine, which - * has resulted in the test engine now being the current engine. - * - * @return {Promise} Resolved once the test engine is set as the current engine. - */ -function promiseCurrentEngineChanged() { - return new Promise(resolve => { - function observer(aSub, aTopic, aData) { - if (aData == "engine-current") { - Assert.ok(Services.search.currentEngine.name, TEST_ENGINE_NAME, "currentEngine set"); - Services.obs.removeObserver(observer, "browser-search-engine-modified"); - resolve(); - } - } - - Services.obs.addObserver(observer, "browser-search-engine-modified", false); - }); -} - -/** - * Opens the specified urlbar/search popup and gets the test engine from the - * one-off buttons. - * - * @param {Boolean} isSearch true if the search popup should be opened; false - * for the urlbar popup. - * @param {Object} popup The expected popup. - * @param {Object} oneOffBinding The expected one-off-binding for the popup. - * @param {String} baseId The expected string for the id of the current - * engine button, without the engine name. - * @return {Object} Returns an object that represents the one off button for the - * test engine. - */ -function* openPopupAndGetEngineButton(isSearch, popup, oneOffBinding, baseId) { - // Open the popup. - let promise = promiseEvent(popup, "popupshown"); - info("Opening panel"); - - // We have to open the popups in differnt ways. - if (isSearch) { - // Use the search icon to avoid hitting the network. - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - } else { - // There's no history at this stage, so we need to press a key. - urlbar.focus(); - EventUtils.synthesizeKey("a", {}); - } - yield promise; - - const contextMenu = document.getAnonymousElementByAttribute( - oneOffBinding, "anonid", "search-one-offs-context-menu" - ); - const oneOffButtons = document.getAnonymousElementByAttribute( - oneOffBinding, "anonid", "search-panel-one-offs" - ); - - // Get the one-off button for the test engine. - let oneOffButton; - for (let node of oneOffButtons.childNodes) { - if (node.engine && node.engine.name == TEST_ENGINE_NAME) { - oneOffButton = node; - break; - } - } - Assert.notEqual(oneOffButton, undefined, - "One-off for test engine should exist"); - Assert.equal(oneOffButton.getAttribute("tooltiptext"), TEST_ENGINE_NAME, - "One-off should have the tooltip set to the engine name"); - Assert.equal(oneOffButton.id, baseId + TEST_ENGINE_NAME, - "Should have the correct id"); - - // Open the context menu on the one-off. - promise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - EventUtils.synthesizeMouseAtCenter(oneOffButton, { - type: "contextmenu", - button: 2, - }); - yield promise; - - return oneOffButton; -} - -/** - * Closes the popup and moves the mouse away from it. - * - * @param {Button} popup The popup to close. - */ -function* promiseClosePopup(popup) { - // close the panel using the escape key. - let promise = promiseEvent(popup, "popuphidden"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - // Move the cursor out of the panel area to avoid messing with other tests. - yield EventUtils.synthesizeNativeMouseMove(popup); -} diff --git a/browser/components/search/test/browser_oneOffHeader.js b/browser/components/search/test/browser_oneOffHeader.js deleted file mode 100644 index 3a209bf56..000000000 --- a/browser/components/search/test/browser_oneOffHeader.js +++ /dev/null @@ -1,142 +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/. */ -// Tests that keyboard navigation in the search panel works as designed. - -const isMac = ("nsILocalFileMac" in Ci); - -const searchbar = document.getElementById("searchbar"); -const textbox = searchbar._textbox; -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid", - "searchbar-search-button"); - -const oneOffsContainer = - document.getAnonymousElementByAttribute(searchPopup, "anonid", - "search-one-off-buttons"); -const searchSettings = - document.getAnonymousElementByAttribute(oneOffsContainer, "anonid", - "search-settings"); -var header = - document.getAnonymousElementByAttribute(oneOffsContainer, "anonid", - "search-panel-one-offs-header"); -function getHeaderText() { - let headerChild = header.selectedPanel; - while (headerChild.hasChildNodes()) { - headerChild = headerChild.firstChild; - } - let headerStrings = []; - for (let label = headerChild; label; label = label.nextSibling) { - headerStrings.push(label.value); - } - return headerStrings.join(""); -} - -const msg = isMac ? 5 : 1; -const utils = window.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); -const scale = utils.screenPixelsPerCSSPixel; -function* synthesizeNativeMouseMove(aElement) { - let rect = aElement.getBoundingClientRect(); - let win = aElement.ownerGlobal; - let x = win.mozInnerScreenX + (rect.left + rect.right) / 2; - let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2; - - // Wait for the mouseup event to occur before continuing. - return new Promise((resolve, reject) => { - function eventOccurred(e) - { - aElement.removeEventListener("mouseover", eventOccurred, true); - resolve(); - } - - aElement.addEventListener("mouseover", eventOccurred, true); - - utils.sendNativeMouseEvent(x * scale, y * scale, msg, 0, null); - }); -} - - -add_task(function* init() { - yield promiseNewEngine("testEngine.xml"); -}); - -add_task(function* test_notext() { - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; - - is(header.getAttribute("selectedIndex"), 0, - "Header has the correct index selected with no search terms."); - - is(getHeaderText(), "Search with:", - "Search header string is correct when no search terms have been entered"); - - yield synthesizeNativeMouseMove(searchSettings); - is(header.getAttribute("selectedIndex"), 0, - "Header has the correct index when no search terms have been entered and the Change Search Settings button is selected."); - is(getHeaderText(), "Search with:", - "Header has the correct text when no search terms have been entered and the Change Search Settings button is selected."); - - let buttons = getOneOffs(); - yield synthesizeNativeMouseMove(buttons[0]); - is(header.getAttribute("selectedIndex"), 2, - "Header has the correct index selected when a search engine has been selected"); - is(getHeaderText(), "Search " + buttons[0].engine.name, - "Is the header text correct when a search engine is selected and no terms have been entered."); - - promise = promiseEvent(searchPopup, "popuphidden"); - info("Closing search panel"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; -}); - -add_task(function* test_text() { - textbox.value = "foo"; - registerCleanupFunction(() => { - textbox.value = ""; - }); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - }); - yield promise; - - is(header.getAttribute("selectedIndex"), 1, - "Header has the correct index selected with a search term."); - is(getHeaderText(), "Search for foo with:", - "Search header string is correct when a search term has been entered"); - - let buttons = getOneOffs(); - yield synthesizeNativeMouseMove(buttons[0]); - is(header.getAttribute("selectedIndex"), 2, - "Header has the correct index selected when a search engine has been selected"); - is(getHeaderText(), "Search " + buttons[0].engine.name, - "Is the header text correct when search terms are entered after a search engine has been selected."); - - yield synthesizeNativeMouseMove(searchSettings); - is(header.getAttribute("selectedIndex"), 1, - "Header has the correct index selected when search terms have been entered and the Change Search Settings button is selected."); - is(getHeaderText(), "Search for foo with:", - "Header has the correct text when search terms have been entered and the Change Search Settings button is selected."); - - // Click the "Foo Search" header at the top of the popup and make sure it - // loads the search results. - let searchbarEngine = - document.getAnonymousElementByAttribute(searchPopup, "anonid", - "searchbar-engine"); - - yield synthesizeNativeMouseMove(searchbarEngine); - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchbarEngine, {}); - }); - - let url = Services.search.currentEngine.getSubmission(textbox.value).uri.spec; - yield promiseTabLoadEvent(gBrowser.selectedTab, url); - - // Move the cursor out of the panel area to avoid messing with other tests. - yield synthesizeNativeMouseMove(searchbar); -}); diff --git a/browser/components/search/test/browser_private_search_perwindowpb.js b/browser/components/search/test/browser_private_search_perwindowpb.js deleted file mode 100644 index c0410371b..000000000 --- a/browser/components/search/test/browser_private_search_perwindowpb.js +++ /dev/null @@ -1,76 +0,0 @@ -// This test performs a search in a public window, then a different -// search in a private window, and then checks in the public window -// whether there is an autocomplete entry for the private search. - -add_task(function* () { - // Don't use about:home as the homepage for new windows - Services.prefs.setIntPref("browser.startup.page", 0); - registerCleanupFunction(() => Services.prefs.clearUserPref("browser.startup.page")); - - let windowsToClose = []; - - function performSearch(aWin, aIsPrivate) { - let searchBar = aWin.BrowserSearch.searchBar; - ok(searchBar, "got search bar"); - - let loadPromise = BrowserTestUtils.browserLoaded(aWin.gBrowser.selectedBrowser); - - searchBar.value = aIsPrivate ? "private test" : "public test"; - searchBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}, aWin); - - return loadPromise; - } - - function* testOnWindow(aIsPrivate) { - let win = yield BrowserTestUtils.openNewBrowserWindow({ private: aIsPrivate }); - yield SimpleTest.promiseFocus(win); - windowsToClose.push(win); - return win; - } - - yield promiseNewEngine("426329.xml", { iconURL: "data:image/x-icon,%00" }); - - let newWindow = yield* testOnWindow(false); - yield performSearch(newWindow, false); - - newWindow = yield* testOnWindow(true); - yield performSearch(newWindow, true); - - newWindow = yield* testOnWindow(false); - - let searchBar = newWindow.BrowserSearch.searchBar; - searchBar.value = "p"; - searchBar.focus(); - - let popup = searchBar.textbox.popup; - let popupPromise = BrowserTestUtils.waitForEvent(popup, "popupshown"); - searchBar.textbox.showHistoryPopup(); - yield popupPromise; - - let entries = getMenuEntries(searchBar); - for (let i = 0; i < entries.length; i++) { - isnot(entries[i], "private test", - "shouldn't see private autocomplete entries"); - } - - searchBar.textbox.toggleHistoryPopup(); - searchBar.value = ""; - - windowsToClose.forEach(function(win) { - win.close(); - }); -}); - -function getMenuEntries(searchBar) { - let entries = []; - let autocompleteMenu = searchBar.textbox.popup; - // Could perhaps pull values directly from the controller, but it seems - // more reliable to test the values that are actually in the tree? - let column = autocompleteMenu.tree.columns[0]; - let numRows = autocompleteMenu.tree.view.rowCount; - for (let i = 0; i < numRows; i++) { - entries.push(autocompleteMenu.tree.view.getValueAt(i, column)); - } - return entries; -} diff --git a/browser/components/search/test/browser_searchbar_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_keyboard_navigation.js deleted file mode 100644 index d395dfdc2..000000000 --- a/browser/components/search/test/browser_searchbar_keyboard_navigation.js +++ /dev/null @@ -1,425 +0,0 @@ -// Tests that keyboard navigation in the search panel works as designed. - -const searchbar = document.getElementById("searchbar"); -const textbox = searchbar._textbox; -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const oneOffsContainer = - document.getAnonymousElementByAttribute(searchPopup, "anonid", - "search-one-off-buttons"); - -const kValues = ["foo1", "foo2", "foo3"]; -const kUserValue = "foo"; - -function getOpenSearchItems() { - let os = []; - - let addEngineList = - document.getAnonymousElementByAttribute(oneOffsContainer, "anonid", - "add-engines"); - for (let item = addEngineList.firstChild; item; item = item.nextSibling) - os.push(item); - - return os; -} - -add_task(function* init() { - yield promiseNewEngine("testEngine.xml"); - - // First cleanup the form history in case other tests left things there. - yield new Promise((resolve, reject) => { - info("cleanup the search history"); - searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"}, - {handleCompletion: resolve, - handleError: reject}); - }); - - yield new Promise((resolve, reject) => { - info("adding search history values: " + kValues); - let ops = kValues.map(value => { return {op: "add", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops, { - handleCompletion: function() { - registerCleanupFunction(() => { - info("removing search history values: " + kValues); - let ops = - kValues.map(value => { return {op: "remove", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops); - }); - resolve(); - }, - handleError: reject - }); - }); - - textbox.value = kUserValue; - registerCleanupFunction(() => { textbox.value = ""; }); -}); - - -add_task(function* test_arrows() { - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - searchbar.focus(); - yield promise; - is(textbox.mController.searchString, kUserValue, "The search string should be 'foo'"); - - // Check the initial state of the panel before sending keyboard events. - is(searchPopup.view.rowCount, kValues.length, "There should be 3 suggestions"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - - // The tests will be less meaningful if the first, second, last, and - // before-last one-off buttons aren't different. We should always have more - // than 4 default engines, but it's safer to check this assumption. - let oneOffs = getOneOffs(); - ok(oneOffs.length >= 4, "we have at least 4 one-off buttons displayed") - - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // The down arrow should first go through the suggestions. - for (let i = 0; i < kValues.length; ++i) { - EventUtils.synthesizeKey("VK_DOWN", {}); - is(searchPopup.selectedIndex, i, - "the suggestion at index " + i + " should be selected"); - is(textbox.value, kValues[i], - "the textfield value should be " + kValues[i]); - } - - // Pressing down again should remove suggestion selection and change the text - // field value back to what the user typed, and select the first one-off. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, - "the textfield value should be back to initial value"); - - // now cycle through the one-off items, the first one is already selected. - for (let i = 0; i < oneOffs.length; ++i) { - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - } - - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - - // We should now be back to the initial situation. - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - info("now test the up arrow key"); - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // cycle through the one-off items, the first one is already selected. - for (let i = oneOffs.length; i; --i) { - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, oneOffs[i - 1], - "the one-off button #" + i + " should be selected"); - } - - // Another press on up should clear the one-off selection and select the - // last suggestion. - EventUtils.synthesizeKey("VK_UP", {}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - for (let i = kValues.length - 1; i >= 0; --i) { - is(searchPopup.selectedIndex, i, - "the suggestion at index " + i + " should be selected"); - is(textbox.value, kValues[i], - "the textfield value should be " + kValues[i]); - EventUtils.synthesizeKey("VK_UP", {}); - } - - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, - "the textfield value should be back to initial value"); -}); - -add_task(function* test_typing_clears_button_selection() { - is(Services.focus.focusedElement, textbox.inputField, - "the search bar should be focused"); // from the previous test. - ok(!textbox.selectedButton, "no button should be selected"); - - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // Type a character. - EventUtils.synthesizeKey("a", {}); - ok(!textbox.selectedButton, "the settings item should be de-selected"); - - // Remove the character. - EventUtils.synthesizeKey("VK_BACK_SPACE", {}); -}); - -add_task(function* test_tab() { - is(Services.focus.focusedElement, textbox.inputField, - "the search bar should be focused"); // from the previous test. - - let oneOffs = getOneOffs(); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // Pressing tab should select the first one-off without selecting suggestions. - // now cycle through the one-off items, the first one is already selected. - for (let i = 0; i < oneOffs.length; ++i) { - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - } - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, "the textfield value should be unmodified"); - - // One more <tab> selects the settings button. - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // Pressing tab again should close the panel... - let promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_TAB", {}); - yield promise; - - // ... and move the focus out of the searchbox. - isnot(Services.focus.focusedElement, textbox.inputField, - "the search bar no longer be focused"); -}); - -add_task(function* test_shift_tab() { - // First reopen the panel. - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - searchbar.focus(); - yield promise; - - let oneOffs = getOneOffs(); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // Press up once to select the last button. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // Press up again to select the last one-off button. - EventUtils.synthesizeKey("VK_UP", {}); - - // Pressing shift+tab should cycle through the one-off items. - for (let i = oneOffs.length - 1; i >= 0; --i) { - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - if (i) - EventUtils.synthesizeKey("VK_TAB", {shiftKey: true}); - } - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, "the textfield value should be unmodified"); - - // Pressing shift+tab again should close the panel... - promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_TAB", {shiftKey: true}); - yield promise; - - // ... and move the focus out of the searchbox. - isnot(Services.focus.focusedElement, textbox.inputField, - "the search bar no longer be focused"); -}); - -add_task(function* test_alt_down() { - // First refocus the panel. - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - searchbar.focus(); - yield promise; - - // close the panel using the escape key. - promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - // check that alt+down opens the panel... - promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - yield promise; - - // ... and does nothing else. - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, "the textfield value should be unmodified"); - - // Pressing alt+down should select the first one-off without selecting suggestions - // and cycle through the one-off items. - let oneOffs = getOneOffs(); - for (let i = 0; i < oneOffs.length; ++i) { - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - } - - // One more alt+down keypress and nothing should be selected. - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // another one and the first one-off should be selected. - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should be selected"); -}); - -add_task(function* test_alt_up() { - // close the panel using the escape key. - let promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - // check that alt+up opens the panel... - promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - yield promise; - - // ... and does nothing else. - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, "the textfield value should be unmodified"); - - // Pressing alt+up should select the last one-off without selecting suggestions - // and cycle up through the one-off items. - let oneOffs = getOneOffs(); - for (let i = oneOffs.length - 1; i >= 0; --i) { - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - } - - // One more alt+down keypress and nothing should be selected. - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // another one and the last one-off should be selected. - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - is(textbox.selectedButton, oneOffs[oneOffs.length - 1], - "the last one-off button should be selected"); - - // Cleanup for the next test. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - ok(!textbox.selectedButton, "no one-off should be selected anymore"); -}); - -add_task(function* test_tab_and_arrows() { - // Check the initial state is as expected. - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, "the textfield value should be unmodified"); - - // After pressing down, the first sugggestion should be selected. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(searchPopup.selectedIndex, 0, "first suggestion should be selected"); - is(textbox.value, kValues[0], "the textfield value should have changed"); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // After pressing tab, the first one-off should be selected, - // and the first suggestion still selected. - let oneOffs = getOneOffs(); - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should be selected"); - is(searchPopup.selectedIndex, 0, "first suggestion should still be selected"); - - // After pressing down, the second suggestion should be selected, - // and the first one-off still selected. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should still be selected"); - is(searchPopup.selectedIndex, 1, "second suggestion should be selected"); - - // After pressing up, the first suggestion should be selected again, - // and the first one-off still selected. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should still be selected"); - is(searchPopup.selectedIndex, 0, "second suggestion should be selected again"); - - // After pressing up again, we should have no suggestion selected anymore, - // the textfield value back to the user-typed value, and still the first one-off - // selected. - EventUtils.synthesizeKey("VK_UP", {}); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, kUserValue, - "the textfield value should be back to user typed value"); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should still be selected"); - - // Now pressing down should select the second one-off. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton, oneOffs[1], - "the second one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "there should still be no selected suggestion"); - - // Finally close the panel. - let promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; -}); - -add_task(function* test_open_search() { - let rootDir = getRootDirectory(gTestPath); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html"); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - searchbar.focus(); - yield promise; - - let engines = getOpenSearchItems(); - is(engines.length, 2, "the opensearch.html page exposes 2 engines") - - // Check that there's initially no selection. - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - ok(!textbox.selectedButton, "no button should be selected"); - - // Pressing up once selects the setting button... - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // ...and then pressing up selects open search engines. - for (let i = engines.length; i; --i) { - EventUtils.synthesizeKey("VK_UP", {}); - let selectedButton = textbox.selectedButton; - is(selectedButton, engines[i - 1], - "the engine #" + i + " should be selected"); - ok(selectedButton.classList.contains("addengine-item"), - "the button is themed as an engine item"); - } - - // Pressing up again should select the last one-off button. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, getOneOffs().pop(), - "the last one-off button should be selected"); - - info("now check that the down key navigates open search items as expected"); - for (let i = 0; i < engines.length; ++i) { - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton, engines[i], - "the engine #" + (i + 1) + " should be selected"); - } - - // Pressing down on the last engine item selects the settings button. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/search/test/browser_searchbar_openpopup.js b/browser/components/search/test/browser_searchbar_openpopup.js deleted file mode 100644 index befc8f142..000000000 --- a/browser/components/search/test/browser_searchbar_openpopup.js +++ /dev/null @@ -1,521 +0,0 @@ -// Tests that the suggestion popup appears at the right times in response to -// focus and user events (mouse, keyboard, drop). - -// Instead of loading EventUtils.js into the test scope in browser-test.js for all tests, -// we only need EventUtils.js for a few files which is why we are using loadSubScript. -var EventUtils = {}; -this._scriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]. - getService(Ci.mozIJSSubScriptLoader); -this._scriptLoader.loadSubScript("chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); - -const searchbar = document.getElementById("searchbar"); -const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid", "searchbar-search-button"); -const goButton = document.getAnonymousElementByAttribute(searchbar, "anonid", "search-go-button"); -const textbox = searchbar._textbox; -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const kValues = ["long text", "long text 2", "long text 3"]; - -const isWindows = Services.appinfo.OS == "WINNT"; -const mouseDown = isWindows ? 2 : 1; -const mouseUp = isWindows ? 4 : 2; -const utils = window.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); -const scale = utils.screenPixelsPerCSSPixel; - -function* synthesizeNativeMouseClick(aElement) { - let rect = aElement.getBoundingClientRect(); - let win = aElement.ownerGlobal; - let x = win.mozInnerScreenX + (rect.left + rect.right) / 2; - let y = win.mozInnerScreenY + (rect.top + rect.bottom) / 2; - - // Wait for the mouseup event to occur before continuing. - return new Promise((resolve, reject) => { - function eventOccurred(e) - { - aElement.removeEventListener("mouseup", eventOccurred, true); - resolve(); - } - - aElement.addEventListener("mouseup", eventOccurred, true); - - utils.sendNativeMouseEvent(x * scale, y * scale, mouseDown, 0, null); - utils.sendNativeMouseEvent(x * scale, y * scale, mouseUp, 0, null); - }); -} - -add_task(function* init() { - yield promiseNewEngine("testEngine.xml"); - - // First cleanup the form history in case other tests left things there. - yield new Promise((resolve, reject) => { - info("cleanup the search history"); - searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"}, - {handleCompletion: resolve, - handleError: reject}); - }); - - yield new Promise((resolve, reject) => { - info("adding search history values: " + kValues); - let ops = kValues.map(value => { return {op: "add", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops, { - handleCompletion: function() { - registerCleanupFunction(() => { - info("removing search history values: " + kValues); - let ops = - kValues.map(value => { return {op: "remove", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops); - }); - resolve(); - }, - handleError: reject - }); - }); -}); - -// Adds a task that shouldn't show the search suggestions popup. -function add_no_popup_task(task) { - add_task(function*() { - let sawPopup = false; - function listener() { - sawPopup = true; - } - - info("Entering test " + task.name); - searchPopup.addEventListener("popupshowing", listener, false); - yield Task.spawn(task); - searchPopup.removeEventListener("popupshowing", listener, false); - ok(!sawPopup, "Shouldn't have seen the suggestions popup"); - info("Leaving test " + task.name); - }); -} - -// Simulates the full set of events for a context click -function context_click(target) { - for (let event of ["mousedown", "contextmenu", "mouseup"]) - EventUtils.synthesizeMouseAtCenter(target, { type: event, button: 2 }); -} - -// Right clicking the icon should not open the popup. -add_no_popup_task(function* open_icon_context() { - gURLBar.focus(); - let toolbarPopup = document.getElementById("toolbar-context-menu"); - - let promise = promiseEvent(toolbarPopup, "popupshown"); - context_click(searchIcon); - yield promise; - - promise = promiseEvent(toolbarPopup, "popuphidden"); - toolbarPopup.hidePopup(); - yield promise; -}); - -// With no text in the search box left clicking the icon should open the popup. -// Clicking the icon again should hide the popup and not show it again. -add_task(function* open_empty() { - gURLBar.focus(); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Clicking icon"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; - is(searchPopup.getAttribute("showonlysettings"), "true", "Should only show the settings"); - is(textbox.mController.searchString, "", "Should be an empty search string"); - - // By giving the textbox some text any next attempt to open the search popup - // from the click handler will try to search for this text. - textbox.value = "foo"; - - promise = promiseEvent(searchPopup, "popuphidden"); - - info("Hiding popup"); - yield synthesizeNativeMouseClick(searchIcon); - yield promise; - - is(textbox.mController.searchString, "", "Should not have started to search for the new text"); - - // Cancel the search if it started. - if (textbox.mController.searchString != "") { - textbox.mController.stopSearch(); - } - - textbox.value = ""; -}); - -// With no text in the search box left clicking it should not open the popup. -add_no_popup_task(function* click_doesnt_open_popup() { - gURLBar.focus(); - - EventUtils.synthesizeMouseAtCenter(textbox, {}); - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 0, "Should have selected all of the text"); -}); - -// Left clicking in a non-empty search box when unfocused should focus it and open the popup. -add_task(function* click_opens_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; - - textbox.value = ""; -}); - -// Right clicking in a non-empty search box when unfocused should open the edit context menu. -add_no_popup_task(function* right_click_doesnt_open_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let contextPopup = document.getAnonymousElementByAttribute(textbox.inputField.parentNode, "anonid", "input-box-contextmenu"); - let promise = promiseEvent(contextPopup, "popupshown"); - context_click(textbox); - yield promise; - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(contextPopup, "popuphidden"); - contextPopup.hidePopup(); - yield promise; - - textbox.value = ""; -}); - -// Moving focus away from the search box should close the popup -add_task(function* focus_change_closes_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - let promise2 = promiseEvent(searchbar, "blur"); - EventUtils.synthesizeKey("VK_TAB", { shiftKey: true }); - yield promise; - yield promise2; - - textbox.value = ""; -}); - -// Moving focus away from the search box should close the small popup -add_task(function* focus_change_closes_small_popup() { - gURLBar.focus(); - - let promise = promiseEvent(searchPopup, "popupshown"); - // For some reason sending the mouse event immediately doesn't open the popup. - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - }); - yield promise; - is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - - promise = promiseEvent(searchPopup, "popuphidden"); - let promise2 = promiseEvent(searchbar, "blur"); - EventUtils.synthesizeKey("VK_TAB", { shiftKey: true }); - yield promise; - yield promise2; -}); - -// Pressing escape should close the popup. -add_task(function* escape_closes_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - textbox.value = ""; -}); - -// Pressing contextmenu should close the popup. -add_task(function* contextmenu_closes_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - - // synthesizeKey does not work with VK_CONTEXT_MENU (bug 1127368) - EventUtils.synthesizeMouseAtCenter(textbox, { type: "contextmenu", button: null }); - - yield promise; - - let contextPopup = - document.getAnonymousElementByAttribute(textbox.inputField.parentNode, - "anonid", "input-box-contextmenu"); - promise = promiseEvent(contextPopup, "popuphidden"); - contextPopup.hidePopup(); - yield promise; - - textbox.value = ""; -}); - -// Tabbing to the search box should open the popup if it contains text. -add_task(function* tab_opens_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeKey("VK_TAB", {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; - - textbox.value = ""; -}); - -// Tabbing to the search box should not open the popup if it doesn't contain text. -add_no_popup_task(function* tab_doesnt_open_popup() { - gURLBar.focus(); - textbox.value = "foo"; - - EventUtils.synthesizeKey("VK_TAB", {}); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - textbox.value = ""; -}); - -// Switching back to the window when the search box has focus from mouse should not open the popup. -add_task(function* refocus_window_doesnt_open_popup_mouse() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(searchbar, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - let newWin = OpenBrowserWindow(); - yield new Promise(resolve => waitForFocus(resolve, newWin)); - yield promise; - - function listener() { - ok(false, "Should not have shown the popup."); - } - searchPopup.addEventListener("popupshowing", listener, false); - - promise = promiseEvent(searchbar, "focus"); - newWin.close(); - yield promise; - - // Wait a few ticks to allow any focus handlers to show the popup if they are going to. - yield new Promise(resolve => executeSoon(resolve)); - yield new Promise(resolve => executeSoon(resolve)); - yield new Promise(resolve => executeSoon(resolve)); - - searchPopup.removeEventListener("popupshowing", listener, false); - textbox.value = ""; -}); - -// Switching back to the window when the search box has focus from keyboard should not open the popup. -add_task(function* refocus_window_doesnt_open_popup_keyboard() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeKey("VK_TAB", {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - let newWin = OpenBrowserWindow(); - yield new Promise(resolve => waitForFocus(resolve, newWin)); - yield promise; - - function listener() { - ok(false, "Should not have shown the popup."); - } - searchPopup.addEventListener("popupshowing", listener, false); - - promise = promiseEvent(searchbar, "focus"); - newWin.close(); - yield promise; - - // Wait a few ticks to allow any focus handlers to show the popup if they are going to. - yield new Promise(resolve => executeSoon(resolve)); - yield new Promise(resolve => executeSoon(resolve)); - yield new Promise(resolve => executeSoon(resolve)); - - searchPopup.removeEventListener("popupshowing", listener, false); - textbox.value = ""; -}); - -// Clicking the search go button shouldn't open the popup -add_no_popup_task(function* search_go_doesnt_open_popup() { - gBrowser.selectedTab = gBrowser.addTab(); - - gURLBar.focus(); - textbox.value = "foo"; - searchbar.updateGoButtonVisibility(); - - let promise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser); - EventUtils.synthesizeMouseAtCenter(goButton, {}); - yield promise; - - textbox.value = ""; - gBrowser.removeCurrentTab(); -}); - -// Clicks outside the search popup should close the popup but not consume the click. -add_task(function* dont_consume_clicks() { - gURLBar.focus(); - textbox.value = "foo"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - is(textbox.selectionStart, 0, "Should have selected all of the text"); - is(textbox.selectionEnd, 3, "Should have selected all of the text"); - - promise = promiseEvent(searchPopup, "popuphidden"); - yield synthesizeNativeMouseClick(gURLBar); - yield promise; - - is(Services.focus.focusedElement, gURLBar.inputField, "Should have focused the URL bar"); - - textbox.value = ""; -}); - -// Dropping text to the searchbar should open the popup -add_task(function* drop_opens_popup() { - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeDrop(searchIcon, textbox.inputField, [[ {type: "text/plain", data: "foo" } ]], "move", window); - yield promise; - - isnot(searchPopup.getAttribute("showonlysettings"), "true", "Should show the full popup"); - is(Services.focus.focusedElement, textbox.inputField, "Should have focused the search bar"); - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; - - textbox.value = ""; -}); - -// Moving the caret using the cursor keys should not close the popup. -add_task(function* dont_rollup_oncaretmove() { - gURLBar.focus(); - textbox.value = "long text"; - - let promise = promiseEvent(searchPopup, "popupshown"); - EventUtils.synthesizeMouseAtCenter(textbox, {}); - yield promise; - - // Deselect the text - EventUtils.synthesizeKey("VK_RIGHT", {}); - is(textbox.selectionStart, 9, "Should have moved the caret (selectionStart after deselect right)"); - is(textbox.selectionEnd, 9, "Should have moved the caret (selectionEnd after deselect right)"); - is(searchPopup.state, "open", "Popup should still be open"); - - EventUtils.synthesizeKey("VK_LEFT", {}); - is(textbox.selectionStart, 8, "Should have moved the caret (selectionStart after left)"); - is(textbox.selectionEnd, 8, "Should have moved the caret (selectionEnd after left)"); - is(searchPopup.state, "open", "Popup should still be open"); - - EventUtils.synthesizeKey("VK_RIGHT", {}); - is(textbox.selectionStart, 9, "Should have moved the caret (selectionStart after right)"); - is(textbox.selectionEnd, 9, "Should have moved the caret (selectionEnd after right)"); - is(searchPopup.state, "open", "Popup should still be open"); - - // Ensure caret movement works while a suggestion is selected. - is(textbox.popup.selectedIndex, -1, "No selected item in list"); - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.popup.selectedIndex, 0, "Selected item in list"); - is(textbox.selectionStart, 9, "Should have moved the caret to the end (selectionStart after selection)"); - is(textbox.selectionEnd, 9, "Should have moved the caret to the end (selectionEnd after selection)"); - - EventUtils.synthesizeKey("VK_LEFT", {}); - is(textbox.selectionStart, 8, "Should have moved the caret again (selectionStart after left)"); - is(textbox.selectionEnd, 8, "Should have moved the caret again (selectionEnd after left)"); - is(searchPopup.state, "open", "Popup should still be open"); - - EventUtils.synthesizeKey("VK_LEFT", {}); - is(textbox.selectionStart, 7, "Should have moved the caret (selectionStart after left)"); - is(textbox.selectionEnd, 7, "Should have moved the caret (selectionEnd after left)"); - is(searchPopup.state, "open", "Popup should still be open"); - - EventUtils.synthesizeKey("VK_RIGHT", {}); - is(textbox.selectionStart, 8, "Should have moved the caret (selectionStart after right)"); - is(textbox.selectionEnd, 8, "Should have moved the caret (selectionEnd after right)"); - is(searchPopup.state, "open", "Popup should still be open"); - - if (navigator.platform.indexOf("Mac") == -1) { - EventUtils.synthesizeKey("VK_HOME", {}); - is(textbox.selectionStart, 0, "Should have moved the caret (selectionStart after home)"); - is(textbox.selectionEnd, 0, "Should have moved the caret (selectionEnd after home)"); - is(searchPopup.state, "open", "Popup should still be open"); - } - - // Close the popup again - promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_ESCAPE", {}); - yield promise; - - textbox.value = ""; -}); diff --git a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js b/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js deleted file mode 100644 index 37ca32cf2..000000000 --- a/browser/components/search/test/browser_searchbar_smallpanel_keyboard_navigation.js +++ /dev/null @@ -1,354 +0,0 @@ -// Tests that keyboard navigation in the search panel works as designed. - -const searchbar = document.getElementById("searchbar"); -const textbox = searchbar._textbox; -const searchPopup = document.getElementById("PopupSearchAutoComplete"); -const oneOffsContainer = - document.getAnonymousElementByAttribute(searchPopup, "anonid", - "search-one-off-buttons"); -const searchIcon = document.getAnonymousElementByAttribute(searchbar, "anonid", - "searchbar-search-button"); - -const kValues = ["foo1", "foo2", "foo3"]; - -function getOpenSearchItems() { - let os = []; - - let addEngineList = - document.getAnonymousElementByAttribute(oneOffsContainer, "anonid", - "add-engines"); - for (let item = addEngineList.firstChild; item; item = item.nextSibling) - os.push(item); - - return os; -} - -add_task(function* init() { - yield promiseNewEngine("testEngine.xml"); - - // First cleanup the form history in case other tests left things there. - yield new Promise((resolve, reject) => { - info("cleanup the search history"); - searchbar.FormHistory.update({op: "remove", fieldname: "searchbar-history"}, - {handleCompletion: resolve, - handleError: reject}); - }); - - yield new Promise((resolve, reject) => { - info("adding search history values: " + kValues); - let ops = kValues.map(value => { return {op: "add", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops, { - handleCompletion: function() { - registerCleanupFunction(() => { - info("removing search history values: " + kValues); - let ops = - kValues.map(value => { return {op: "remove", - fieldname: "searchbar-history", - value: value} - }); - searchbar.FormHistory.update(ops); - }); - resolve(); - }, - handleError: reject - }); - }); -}); - - -add_task(function* test_arrows() { - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; -info("textbox.mController.searchString = " + textbox.mController.searchString); - is(textbox.mController.searchString, "", "The search string should be empty"); - - // Check the initial state of the panel before sending keyboard events. - is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup"); - // Having suggestions populated (but hidden) is important, because if there - // are none we can't ensure the keyboard events don't reach them. - is(searchPopup.view.rowCount, kValues.length, "There should be 3 suggestions"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - - // The tests will be less meaningful if the first, second, last, and - // before-last one-off buttons aren't different. We should always have more - // than 4 default engines, but it's safer to check this assumption. - let oneOffs = getOneOffs(); - ok(oneOffs.length >= 4, "we have at least 4 one-off buttons displayed") - - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // Pressing should select the first one-off. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // now cycle through the one-off items, the first one is already selected. - for (let i = 0; i < oneOffs.length; ++i) { - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - } - - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - - // We should now be back to the initial situation. - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - info("now test the up arrow key"); - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // cycle through the one-off items, the first one is already selected. - for (let i = oneOffs.length; i; --i) { - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, oneOffs[i - 1], - "the one-off button #" + i + " should be selected"); - } - - // Another press on up should clear the one-off selection. - EventUtils.synthesizeKey("VK_UP", {}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); -}); - -add_task(function* test_tab() { - is(Services.focus.focusedElement, textbox.inputField, - "the search bar should be focused"); // from the previous test. - - let oneOffs = getOneOffs(); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // Pressing tab should select the first one-off without selecting suggestions. - // now cycle through the one-off items, the first one is already selected. - for (let i = 0; i < oneOffs.length; ++i) { - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - } - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // One more <tab> selects the settings button. - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // Pressing tab again should close the panel... - let promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_TAB", {}); - yield promise; - - // ... and move the focus out of the searchbox. - isnot(Services.focus.focusedElement, textbox.inputField, - "the search bar no longer be focused"); -}); - -add_task(function* test_shift_tab() { - // First reopen the panel. - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - }); - yield promise; - - let oneOffs = getOneOffs(); - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup"); - - // Press up once to select the last button. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // Press up again to select the last one-off button. - EventUtils.synthesizeKey("VK_UP", {}); - - // Pressing shift+tab should cycle through the one-off items. - for (let i = oneOffs.length - 1; i >= 0; --i) { - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - if (i) - EventUtils.synthesizeKey("VK_TAB", {shiftKey: true}); - } - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // Pressing shift+tab again should close the panel... - promise = promiseEvent(searchPopup, "popuphidden"); - EventUtils.synthesizeKey("VK_TAB", {shiftKey: true}); - yield promise; - - // ... and move the focus out of the searchbox. - isnot(Services.focus.focusedElement, textbox.inputField, - "the search bar no longer be focused"); -}); - -add_task(function* test_alt_down() { - // First reopen the panel. - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - SimpleTest.executeSoon(() => { - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - }); - yield promise; - - // and check it's in a correct initial state. - is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup"); - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // Pressing alt+down should select the first one-off without selecting suggestions - // and cycle through the one-off items. - let oneOffs = getOneOffs(); - for (let i = 0; i < oneOffs.length; ++i) { - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - } - - // One more alt+down keypress and nothing should be selected. - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // another one and the first one-off should be selected. - EventUtils.synthesizeKey("VK_DOWN", {altKey: true}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should be selected"); - - // Clear the selection with an alt+up keypress - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - ok(!textbox.selectedButton, "no one-off button should be selected"); -}); - -add_task(function* test_alt_up() { - // Check the initial state of the panel - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // Pressing alt+up should select the last one-off without selecting suggestions - // and cycle up through the one-off items. - let oneOffs = getOneOffs(); - for (let i = oneOffs.length - 1; i >= 0; --i) { - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - is(textbox.selectedButton, oneOffs[i], - "the one-off button #" + (i + 1) + " should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - } - - // One more alt+down keypress and nothing should be selected. - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - ok(!textbox.selectedButton, "no one-off button should be selected"); - - // another one and the last one-off should be selected. - EventUtils.synthesizeKey("VK_UP", {altKey: true}); - is(textbox.selectedButton, oneOffs[oneOffs.length - 1], - "the last one-off button should be selected"); - - // Cleanup for the next test. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - EventUtils.synthesizeKey("VK_DOWN", {}); - ok(!textbox.selectedButton, "no one-off should be selected anymore"); -}); - -add_task(function* test_tab_and_arrows() { - // Check the initial state is as expected. - ok(!textbox.selectedButton, "no one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - is(textbox.value, "", "the textfield value should be unmodified"); - - // After pressing down, the first one-off should be selected. - let oneOffs = getOneOffs(); - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - - // After pressing tab, the second one-off should be selected. - EventUtils.synthesizeKey("VK_TAB", {}); - is(textbox.selectedButton, oneOffs[1], - "the second one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - - // After pressing up, the first one-off should be selected again. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, oneOffs[0], - "the first one-off button should be selected"); - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - - // Finally close the panel. - let promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; -}); - -add_task(function* test_open_search() { - let rootDir = getRootDirectory(gTestPath); - yield BrowserTestUtils.openNewForegroundTab(gBrowser, rootDir + "opensearch.html"); - - let promise = promiseEvent(searchPopup, "popupshown"); - info("Opening search panel"); - EventUtils.synthesizeMouseAtCenter(searchIcon, {}); - yield promise; - is(searchPopup.getAttribute("showonlysettings"), "true", "Should show the small popup"); - - let engines = getOpenSearchItems(); - is(engines.length, 2, "the opensearch.html page exposes 2 engines") - - // Check that there's initially no selection. - is(searchPopup.selectedIndex, -1, "no suggestion should be selected"); - ok(!textbox.selectedButton, "no button should be selected"); - - // Pressing up once selects the setting button... - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - // ...and then pressing up selects open search engines. - for (let i = engines.length; i; --i) { - EventUtils.synthesizeKey("VK_UP", {}); - let selectedButton = textbox.selectedButton; - is(selectedButton, engines[i - 1], - "the engine #" + i + " should be selected"); - ok(selectedButton.classList.contains("addengine-item"), - "the button is themed as an engine item"); - } - - // Pressing up again should select the last one-off button. - EventUtils.synthesizeKey("VK_UP", {}); - is(textbox.selectedButton, getOneOffs().pop(), - "the last one-off button should be selected"); - - info("now check that the down key navigates open search items as expected"); - for (let i = 0; i < engines.length; ++i) { - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton, engines[i], - "the engine #" + (i + 1) + " should be selected"); - } - - // Pressing down on the last engine item selects the settings button. - EventUtils.synthesizeKey("VK_DOWN", {}); - is(textbox.selectedButton.getAttribute("anonid"), "search-settings", - "the settings item should be selected"); - - promise = promiseEvent(searchPopup, "popuphidden"); - searchPopup.hidePopup(); - yield promise; - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/search/test/browser_webapi.js b/browser/components/search/test/browser_webapi.js deleted file mode 100644 index d8161ffbe..000000000 --- a/browser/components/search/test/browser_webapi.js +++ /dev/null @@ -1,92 +0,0 @@ -var ROOT = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com"); -const searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties"); -const brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties"); -const brandName = brandBundle.GetStringFromName("brandShortName"); - -function getString(key, ...params) { - return searchBundle.formatStringFromName(key, params, params.length); -} - -function AddSearchProvider(...args) { - return gBrowser.addTab(ROOT + "webapi.html?" + encodeURIComponent(JSON.stringify(args))); -} - -function promiseDialogOpened() { - return new Promise((resolve, reject) => { - Services.wm.addListener({ - onOpenWindow: function(xulWin) { - Services.wm.removeListener(this); - - let win = xulWin.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindow); - waitForFocus(() => { - if (win.location == "chrome://global/content/commonDialog.xul") - resolve(win) - else - reject(); - }, win); - } - }); - }); -} - -add_task(function* test_working() { - gBrowser.selectedTab = AddSearchProvider(ROOT + "testEngine.xml"); - - let dialog = yield promiseDialogOpened(); - is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog."); - is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"), - "Should have seen the right install message"); - dialog.document.documentElement.cancelDialog(); - - gBrowser.removeCurrentTab(); -}); - -add_task(function* test_HTTP() { - gBrowser.selectedTab = AddSearchProvider(ROOT.replace("http:", "HTTP:") + "testEngine.xml"); - - let dialog = yield promiseDialogOpened(); - is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog."); - is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"), - "Should have seen the right install message"); - dialog.document.documentElement.cancelDialog(); - - gBrowser.removeCurrentTab(); -}); - -add_task(function* test_relative() { - gBrowser.selectedTab = AddSearchProvider("testEngine.xml"); - - let dialog = yield promiseDialogOpened(); - is(dialog.args.promptType, "confirmEx", "Should see the confirmation dialog."); - is(dialog.args.text, getString("addEngineConfirmation", "Foo", "example.com"), - "Should have seen the right install message"); - dialog.document.documentElement.cancelDialog(); - - gBrowser.removeCurrentTab(); -}); - -add_task(function* test_invalid() { - gBrowser.selectedTab = AddSearchProvider("z://foobar"); - - let dialog = yield promiseDialogOpened(); - is(dialog.args.promptType, "alert", "Should see the alert dialog."); - is(dialog.args.text, getString("error_invalid_engine_msg", brandName), - "Should have seen the right error message") - dialog.document.documentElement.acceptDialog(); - - gBrowser.removeCurrentTab(); -}); - -add_task(function* test_missing() { - let url = ROOT + "foobar.xml"; - gBrowser.selectedTab = AddSearchProvider(url); - - let dialog = yield promiseDialogOpened(); - is(dialog.args.promptType, "alert", "Should see the alert dialog."); - is(dialog.args.text, getString("error_loading_engine_msg2", brandName, url), - "Should have seen the right error message") - dialog.document.documentElement.acceptDialog(); - - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/search/test/browser_yahoo.js b/browser/components/search/test/browser_yahoo.js deleted file mode 100644 index f45b47d0c..000000000 --- a/browser/components/search/test/browser_yahoo.js +++ /dev/null @@ -1,132 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Yahoo search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - -function test() { - let engine = Services.search.getEngineByName("Yahoo"); - ok(engine, "Yahoo"); - - let base = "https://search.yahoo.com/yhs/search?p=foo&ei=UTF-8&hspart=mozilla"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base + "&hsimp=yhs-001", "Check search URL for 'foo'"); - url = engine.getSubmission("foo", null, "searchbar").uri.spec; - is(url, base + "&hsimp=yhs-001", "Check search bar search URL for 'foo'"); - url = engine.getSubmission("foo", null, "keyword").uri.spec; - is(url, base + "&hsimp=yhs-002", "Check keyword search URL for 'foo'"); - url = engine.getSubmission("foo", null, "homepage").uri.spec; - is(url, base + "&hsimp=yhs-003", "Check homepage search URL for 'foo'"); - url = engine.getSubmission("foo", null, "newtab").uri.spec; - is(url, base + "&hsimp=yhs-004", "Check newtab search URL for 'foo'"); - url = engine.getSubmission("foo", null, "contextmenu").uri.spec; - is(url, base + "&hsimp=yhs-005", "Check context menu search URL for 'foo'"); - url = engine.getSubmission("foo", null, "system").uri.spec; - is(url, base + "&hsimp=yhs-007", "Check system search URL for 'foo'"); - url = engine.getSubmission("foo", null, "invalid").uri.spec; - is(url, base + "&hsimp=yhs-001", "Check invalid URL for 'foo'"); - - // Check search suggestion URL. - url = engine.getSubmission("foo", "application/x-suggestions+json").uri.spec; - is(url, "https://search.yahoo.com/sugg/ff?output=fxjson&appid=ffd&command=foo", "Check search suggestion URL for 'foo'"); - - // Check all other engine properties. - const EXPECTED_ENGINE = { - name: "Yahoo", - alias: null, - description: "Yahoo Search", - searchForm: "https://search.yahoo.com/yhs/search?p=&ei=UTF-8&hspart=mozilla&hsimp=yhs-001", - hidden: false, - wrappedJSObject: { - queryCharset: "UTF-8", - "_iconURL": "data:image/x-icon;base64,AAABAAIAEBAAAAEACAA8DQAAJgAAACAgAAABAAgAowsAAGINAACJUE5HDQoaCgAAAA1JSERSAAAAEAAAABAIBgAAAB/z/2EAAAAJcEhZcwAACxMAAAsTAQCanBgAAApPaUNDUFBob3Rvc2hvcCBJQ0MgcHJvZmlsZQAAeNqdU2dUU+kWPffe9EJLiICUS29SFQggUkKLgBSRJiohCRBKiCGh2RVRwRFFRQQbyKCIA46OgIwVUSwMigrYB+Qhoo6Do4iKyvvhe6Nr1rz35s3+tdc+56zznbPPB8AIDJZIM1E1gAypQh4R4IPHxMbh5C5AgQokcAAQCLNkIXP9IwEA+H48PCsiwAe+AAF40wsIAMBNm8AwHIf/D+pCmVwBgIQBwHSROEsIgBQAQHqOQqYAQEYBgJ2YJlMAoAQAYMtjYuMAUC0AYCd/5tMAgJ34mXsBAFuUIRUBoJEAIBNliEQAaDsArM9WikUAWDAAFGZLxDkA2C0AMElXZkgAsLcAwM4QC7IACAwAMFGIhSkABHsAYMgjI3gAhJkAFEbyVzzxK64Q5yoAAHiZsjy5JDlFgVsILXEHV1cuHijOSRcrFDZhAmGaQC7CeZkZMoE0D+DzzAAAoJEVEeCD8/14zg6uzs42jrYOXy3qvwb/ImJi4/7lz6twQAAA4XR+0f4sL7MagDsGgG3+oiXuBGheC6B194tmsg9AtQCg6dpX83D4fjw8RaGQudnZ5eTk2ErEQlthyld9/mfCX8BX/Wz5fjz89/XgvuIkgTJdgUcE+ODCzPRMpRzPkgmEYtzmj0f8twv//B3TIsRJYrlYKhTjURJxjkSajPMypSKJQpIpxSXS/2Ti3yz7Az7fNQCwaj4Be5EtqF1jA/ZLJxBYdMDi9wAA8rtvwdQoCAOAaIPhz3f/7z/9R6AlAIBmSZJxAABeRCQuVMqzP8cIAABEoIEqsEEb9MEYLMAGHMEF3MEL/GA2hEIkxMJCEEIKZIAccmAprIJCKIbNsB0qYC/UQB00wFFohpNwDi7CVbgOPXAP+mEInsEovIEJBEHICBNhIdqIAWKKWCOOCBeZhfghwUgEEoskIMmIFFEiS5E1SDFSilQgVUgd8j1yAjmHXEa6kTvIADKC/Ia8RzGUgbJRPdQMtUO5qDcahEaiC9BkdDGajxagm9BytBo9jDah59CraA/ajz5DxzDA6BgHM8RsMC7Gw0KxOCwJk2PLsSKsDKvGGrBWrAO7ifVjz7F3BBKBRcAJNgR3QiBhHkFIWExYTthIqCAcJDQR2gk3CQOEUcInIpOoS7QmuhH5xBhiMjGHWEgsI9YSjxMvEHuIQ8Q3JBKJQzInuZACSbGkVNIS0kbSblIj6SypmzRIGiOTydpka7IHOZQsICvIheSd5MPkM+Qb5CHyWwqdYkBxpPhT4ihSympKGeUQ5TTlBmWYMkFVo5pS3aihVBE1j1pCraG2Uq9Rh6gTNHWaOc2DFklLpa2ildMaaBdo92mv6HS6Ed2VHk6X0FfSy+lH6JfoA/R3DA2GFYPHiGcoGZsYBxhnGXcYr5hMphnTixnHVDA3MeuY55kPmW9VWCq2KnwVkcoKlUqVJpUbKi9Uqaqmqt6qC1XzVctUj6leU32uRlUzU+OpCdSWq1WqnVDrUxtTZ6k7qIeqZ6hvVD+kfln9iQZZw0zDT0OkUaCxX+O8xiALYxmzeCwhaw2rhnWBNcQmsc3ZfHYqu5j9HbuLPaqpoTlDM0ozV7NS85RmPwfjmHH4nHROCecop5fzforeFO8p4ikbpjRMuTFlXGuqlpeWWKtIq1GrR+u9Nq7tp52mvUW7WfuBDkHHSidcJ0dnj84FnedT2VPdpwqnFk09OvWuLqprpRuhu0R3v26n7pievl6Ankxvp955vef6HH0v/VT9bfqn9UcMWAazDCQG2wzOGDzFNXFvPB0vx9vxUUNdw0BDpWGVYZfhhJG50Tyj1UaNRg+MacZc4yTjbcZtxqMmBiYhJktN6k3umlJNuaYppjtMO0zHzczNos3WmTWbPTHXMueb55vXm9+3YFp4Wiy2qLa4ZUmy5FqmWe62vG6FWjlZpVhVWl2zRq2drSXWu627pxGnuU6TTque1mfDsPG2ybaptxmw5dgG2662bbZ9YWdiF2e3xa7D7pO9k326fY39PQcNh9kOqx1aHX5ztHIUOlY63prOnO4/fcX0lukvZ1jPEM/YM+O2E8spxGmdU5vTR2cXZ7lzg/OIi4lLgssulz4umxvG3ci95Ep09XFd4XrS9Z2bs5vC7ajbr+427mnuh9yfzDSfKZ5ZM3PQw8hD4FHl0T8Ln5Uwa9+sfk9DT4FntecjL2MvkVet17C3pXeq92HvFz72PnKf4z7jPDfeMt5ZX8w3wLfIt8tPw2+eX4XfQ38j/2T/ev/RAKeAJQFnA4mBQYFbAvv4enwhv44/Ottl9rLZ7UGMoLlBFUGPgq2C5cGtIWjI7JCtIffnmM6RzmkOhVB+6NbQB2HmYYvDfgwnhYeFV4Y/jnCIWBrRMZc1d9HcQ3PfRPpElkTem2cxTzmvLUo1Kj6qLmo82je6NLo/xi5mWczVWJ1YSWxLHDkuKq42bmy+3/zt84fineIL43sXmC/IXXB5oc7C9IWnFqkuEiw6lkBMiE44lPBBECqoFowl8hN3JY4KecIdwmciL9E20YjYQ1wqHk7ySCpNepLskbw1eSTFM6Us5bmEJ6mQvEwNTN2bOp4WmnYgbTI9Or0xg5KRkHFCqiFNk7Zn6mfmZnbLrGWFsv7Fbou3Lx6VB8lrs5CsBVktCrZCpuhUWijXKgeyZ2VXZr/Nico5lqueK83tzLPK25A3nO+f/+0SwhLhkralhktXLR1Y5r2sajmyPHF52wrjFQUrhlYGrDy4irYqbdVPq+1Xl65+vSZ6TWuBXsHKgsG1AWvrC1UK5YV969zX7V1PWC9Z37Vh+oadGz4ViYquFNsXlxV/2CjceOUbh2/Kv5nclLSpq8S5ZM9m0mbp5t4tnlsOlqqX5pcObg3Z2rQN31a07fX2Rdsvl80o27uDtkO5o788uLxlp8nOzTs/VKRU9FT6VDbu0t21Ydf4btHuG3u89jTs1dtbvPf9Psm+21UBVU3VZtVl+0n7s/c/romq6fiW+21drU5tce3HA9ID/QcjDrbXudTVHdI9VFKP1ivrRw7HH77+ne93LQ02DVWNnMbiI3BEeeTp9wnf9x4NOtp2jHus4QfTH3YdZx0vakKa8ppGm1Oa+1tiW7pPzD7R1ureevxH2x8PnDQ8WXlK81TJadrpgtOTZ/LPjJ2VnX1+LvncYNuitnvnY87fag9v77oQdOHSRf+L5zu8O85c8rh08rLb5RNXuFearzpfbep06jz+k9NPx7ucu5quuVxrue56vbV7ZvfpG543zt30vXnxFv/W1Z45Pd2983pv98X39d8W3X5yJ/3Oy7vZdyfurbxPvF/0QO1B2UPdh9U/W/7c2O/cf2rAd6Dz0dxH9waFg8/+kfWPD0MFj5mPy4YNhuueOD45OeI/cv3p/KdDz2TPJp4X/qL+y64XFi9++NXr187RmNGhl/KXk79tfKX96sDrGa/bxsLGHr7JeDMxXvRW++3Bd9x3He+j3w9P5Hwgfyj/aPmx9VPQp/uTGZOT/wQDmPP8YzMt2wAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAACZ0lEQVR42mzSP4icZRTF4ee+38xOkp2sG5cQxVJIIaaKkICxTkqJjQhpJFYiop2F1YKFQqoUVpEoCBYSS7dfOxVFWGIsokUE/0TEye7OzPe977XYNWk83b0cDoffvXHWGxkKYjt0N1fi+FaJIzNIFSJ0kDXn0z5nF1O9Sp5PzaizamLD2NELo5W4sOwXqqX/04o1R2wg9PYs/GXUmTjqpGNxwvWdFzz19Akvjj+XUkYTggylFLfml93due+tZ7+y577BrkJnbNWke8yHmzvgi/4lq+WU1XjCsThl2p1ya3GZ4KNrt03KuhXH0SkkkbTOL5+u2PnuZ/D8axtGMTaKsbOvrINP3v/W3Y9XhCJjQCrUWRedVpaq3nvn7oHXrz8jD8PfvnEGbL0716LXytIoxqizkups4R/VwhB7hpi7sXkbXNo86bkrazK5sXnbEHND7BvMLcykOotz3vlxvZw+faRb08VEiVC64rPdSw/pZ/Ly9EutNi3TkHOLOvN3u3OnHNx7MFio5qq5Ifdce/WHhwEfXPnekPuq/UPPQhrAKOV0MFdyRFQFRefr7Z9wRrb0zfYd1aCpGmr2BvtSTkcp1wZLnX0tx4oQjeHX+UF97P75QGspM7VMqTfopVwb0aY1F4ZWlFK1SCVDHQKUEvphj0ztkEdrvZoLtOkoNS2XlkHJIlroIky7Jw8atDSJdQ/aPTUdtJBaLqVmlJpqQataCZKhY/L4HwcEI/Qbv1v8tivbIdVG1UtNnPVmFmPEoT9l/Dc9Ujp42Mx4uGl6I5pmgdjGzaLbopsdJqZHWZnqtKkXcZU8D/8OAPAMQ4kD8KK1AAAAAElFTkSuQmCCiVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEJGlDQ1BJQ0MgUHJvZmlsZQAAOBGFVd9v21QUPolvUqQWPyBYR4eKxa9VU1u5GxqtxgZJk6XtShal6dgqJOQ6N4mpGwfb6baqT3uBNwb8AUDZAw9IPCENBmJ72fbAtElThyqqSUh76MQPISbtBVXhu3ZiJ1PEXPX6yznfOec7517bRD1fabWaGVWIlquunc8klZOnFpSeTYrSs9RLA9Sr6U4tkcvNEi7BFffO6+EdigjL7ZHu/k72I796i9zRiSJPwG4VHX0Z+AxRzNRrtksUvwf7+Gm3BtzzHPDTNgQCqwKXfZwSeNHHJz1OIT8JjtAq6xWtCLwGPLzYZi+3YV8DGMiT4VVuG7oiZpGzrZJhcs/hL49xtzH/Dy6bdfTsXYNY+5yluWO4D4neK/ZUvok/17X0HPBLsF+vuUlhfwX4j/rSfAJ4H1H0qZJ9dN7nR19frRTeBt4Fe9FwpwtN+2p1MXscGLHR9SXrmMgjONd1ZxKzpBeA71b4tNhj6JGoyFNp4GHgwUp9qplfmnFW5oTdy7NamcwCI49kv6fN5IAHgD+0rbyoBc3SOjczohbyS1drbq6pQdqumllRC/0ymTtej8gpbbuVwpQfyw66dqEZyxZKxtHpJn+tZnpnEdrYBbueF9qQn93S7HQGGHnYP7w6L+YGHNtd1FJitqPAR+hERCNOFi1i1alKO6RQnjKUxL1GNjwlMsiEhcPLYTEiT9ISbN15OY/jx4SMshe9LaJRpTvHr3C/ybFYP1PZAfwfYrPsMBtnE6SwN9ib7AhLwTrBDgUKcm06FSrTfSj187xPdVQWOk5Q8vxAfSiIUc7Z7xr6zY/+hpqwSyv0I0/QMTRb7RMgBxNodTfSPqdraz/sDjzKBrv4zu2+a2t0/HHzjd2Lbcc2sG7GtsL42K+xLfxtUgI7YHqKlqHK8HbCCXgjHT1cAdMlDetv4FnQ2lLasaOl6vmB0CMmwT/IPszSueHQqv6i/qluqF+oF9TfO2qEGTumJH0qfSv9KH0nfS/9TIp0Wboi/SRdlb6RLgU5u++9nyXYe69fYRPdil1o1WufNSdTTsp75BfllPy8/LI8G7AUuV8ek6fkvfDsCfbNDP0dvRh0CrNqTbV7LfEEGDQPJQadBtfGVMWEq3QWWdufk6ZSNsjG2PQjp3ZcnOWWing6noonSInvi0/Ex+IzAreevPhe+CawpgP1/pMTMDo64G0sTCXIM+KdOnFWRfQKdJvQzV1+Bt8OokmrdtY2yhVX2a+qrykJfMq4Ml3VR4cVzTQVz+UoNne4vcKLoyS+gyKO6EHe+75Fdt0Mbe5bRIf/wjvrVmhbqBN97RD1vxrahvBOfOYzoosH9bq94uejSOQGkVM6sN/7HelL4t10t9F4gPdVzydEOx83Gv+uNxo7XyL/FtFl8z9ZAHF4bBsrEwAAAAlwSFlzAAALEwAACxMBAJqcGAAAByVJREFUWAm1l1uIldcVx9d3ruMZZzRaay+pCjFJH6LSRqxQqA1NH0pBiH3Qp774kEAg4EOkxKdQSCjUFvpm6YsNVNoSaGjFtmga2yZgCIIawdv04g2kM7Uz6lzO+c758v/t/9lzTB/61Oxhn7332muv9V+3vb8pnooDVRkzZ4oY/LmK6mQZa05frX6yFJ9Ae7x4qd2IuV1FFM9WMfhaI9Z+pQBAL+aiEZ0QgNBm2YuZmxHF9VZMXqmivFaLweUyuteWYvHGVPWr2f+F7YvF/ola9DZGVJsHUXs8YvBEK1ZrXt9URDwqxY1BdGMQvWjGqkgA+iLUtazHuADUoowHYugKTilaR7SIpZjWqOMRfY090RbasS4JglpFtzWIcqwZa+pSqnWVcLLXijXpZCFpvbgb/VhMe8huMLPylWkci8/oSD8xJq7hj4WUWvXrlbqVrUyKtBYdpX3Bh9YbzsdErwRgbZKyFP+KdqxPssu4l2hDAOOxIj6bCHigKWRNCcpMCHHHB4TJLc+TXxKHnC51Ct+Qgxl/TZ0qE5Be/EdWTwjqQuJJAPIB8qAZk4kZoXJnvHH+27Hq0+0YX12PH+w7E3/8zbWkitN2M8pS7kCKZ761OV55c2fcm+nG7J1e7N/+e3m2nbyKQcAhnHWZLC86B1rxiFRvSIkIgJHFVWzZ+qk4fG5HEr4wV8buVb+Vuv5QeVZsi/HeW//eHZ1HbNfLT5+Jc2dndBav9KXugfqc+pLsv6Xxvk6kVheumnpDnXlTVMZWfHh+Li6cdOKvmGzEC69+WTskzwr1SfUJ9ZWp7z/0pWXlF9+ejQtnUdCWnAxQ+al5Tdz80lIVEP8x9eZQWCQwOTAhNc34Re+rUW8U0S+r2Ns8nWzBKgONBOeX3V3RaCpPRN7XeFcO7yYl+InML2U3VdBVHszHzbSXYLBJkuTSQzBuphoYZ7X/u8O30gFAHHxzi+Yop8ETcfDXW5JyKMd/fFuO9l3mYuwLAl5gbMg8QuKdYQg4Zjcxo7HikMeIn37vcizes9Ide9bGhs9NLPN9YX0ndnzHpbZ4vx9HXr6kc6Sobo2hIkuzOnIh0xMFRlvc0waWL+p3UePCQ/Myjjx/JSnl59CJbUkJgl75g+ZD/D978Yrc7EuMPe4ESo6OYsaasiiX7tADAyny5cGtyMHsDxzFnP0Tx6Z0SfsW27B1PHZ+c13seGZdbNo2Lo6Iu7e7cfznfxc/8ggNQBhZI9dSs2c5k+rFaHBXmZhd32xTGdlZPvzDvefj9XddlgeObYVpuf1o3zkpyrEnCJwBDjlmr9i7XP3jgrYkDamhEqRA8UOBxZ53tcOtBbgyzr53M65f8DU6sVZ1o067cfFBvP+XGzrDOa5s+JkTShIc+dBtlLOLlRpqAUDc+yqQMnViNq81edDVnPixno/vP/dXjn2svbbnPa1RiqXEHVkYQ06RWygnFEtpbZDLAJws2X1OHgfCv+hiRkZU8Y+pmbjwzjTE1D48PR1TV+5IMErgsjex2A8TJrqCHH9Cw6U0BGBkPUWrKTZnPq4L9WqIOFvEO8ml+vbRvyUB/Jw6OiUa9GydM58qQl6lTrNHyiENrwyTkOvXLziVkMlOOsesVKyIFtZB1zfDAGvdyj4xtkD7yHQ8Ynn4hCrwvYA+DOJCSlXAZl3MjNQobNzVPK7gJm0AiPsQyEg0c6s1cbEB5X08AmDz1TTLucApzHHyJgADvUqVysJMKOSicLRQl+emOIvbnaw+ot2pSTzl5zzJVjPaZ6ix7zCSN4E1shOAWnqbyYH8bOqd1h9AGJ0qtl6LRBubcBKxbo6xh60kWlbLjgG4NJ2ETkwqbl7SeUXVSCq+BF1C2bWEgEO4CxBGvOydGmu3ooXv7AEogLFqn2JtWKO8yc9xAmDxjhGiWMOQXe63zCvHtIjOpGOIwvGJlhRQepyzaiu0MQ4MnFhuT7CiJQC+sUg4jtOYO+1IH9OdCwgBSmOkP2r60CarHeXMjxw3PGyvOBnN670EgOPOc1yEYgDYCxbqTPDXki1srChi4R6lpQ+uDmVFDtkA5GH1qJEvQFgacqCFT37pyP+Y+DMJs0Y54NgbiIVn61jhEUrNARuNIi3vOQf8iUeQuNzILe4b/jFZ7RDYJhTbVRaJTxyWh8PgO93hQJCBsSa2GQyyoLlBzWDxgnm9l0JgADgNgVxElCH22xs4NCsaieSUyzWXaSTLDAPlGQB0Kt6JaqpzYjkJQT9id60aNwqZjVqlz9Kqp+JcfDjOAqhirNoCI6MelpVPAjZ/CbFv45Y9YNcicqDMKm/Xo/FPJdMlqZ9SIK7qSrrci9mbl6q3/DGQ5f7XuK347rgKeuMgiicEfLPmT0rGY1K5SdI/ryritlMbJrr/PZ8+I8qf9PF8qhMrT39QHfHLkhj/fz/bi+eb83F/VxX1b6jWvt6KdTs/AvvCmqXE235jAAAAAElFTkSuQmCC", - _urls : [ - { - type: "application/x-suggestions+json", - method: "GET", - template: "https://search.yahoo.com/sugg/ff", - params: [ - { - name: "output", - value: "fxjson", - purpose: undefined, - }, - { - name: "appid", - value: "ffd", - purpose: undefined, - }, - { - name: "command", - value: "{searchTerms}", - purpose: undefined, - }, - ], - }, - { - type: "text/html", - method: "GET", - template: "https://search.yahoo.com/yhs/search", - params: [ - { - name: "p", - value: "{searchTerms}", - purpose: undefined, - }, - { - name: "ei", - value: "UTF-8", - purpose: undefined, - }, - { - name: "hspart", - value: "mozilla", - purpose: undefined, - }, - { - name: "hsimp", - value: "yhs-001", - purpose: "searchbar", - }, - { - name: "hsimp", - value: "yhs-002", - purpose: "keyword", - }, - { - name: "hsimp", - value: "yhs-003", - purpose: "homepage", - }, - { - name: "hsimp", - value: "yhs-004", - purpose: "newtab", - }, - { - name: "hsimp", - value: "yhs-005", - purpose: "contextmenu", - }, - { - name: "hsimp", - value: "yhs-007", - purpose: "system", - }, - ], - mozparams: {}, - }, - ], - }, - }; - - isSubObjectOf(EXPECTED_ENGINE, engine, "Yahoo"); -} diff --git a/browser/components/search/test/browser_yahoo_behavior.js b/browser/components/search/test/browser_yahoo_behavior.js deleted file mode 100644 index 5b2d61422..000000000 --- a/browser/components/search/test/browser_yahoo_behavior.js +++ /dev/null @@ -1,166 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * Test Yahoo search plugin URLs - */ - -"use strict"; - -const BROWSER_SEARCH_PREF = "browser.search."; - - -function test() { - let engine = Services.search.getEngineByName("Yahoo"); - ok(engine, "Yahoo is installed"); - - let previouslySelectedEngine = Services.search.currentEngine; - Services.search.currentEngine = engine; - engine.alias = "y"; - - let base = "https://search.yahoo.com/yhs/search?p=foo&ei=UTF-8&hspart=mozilla"; - let url; - - // Test search URLs (including purposes). - url = engine.getSubmission("foo").uri.spec; - is(url, base + "&hsimp=yhs-001", "Check search URL for 'foo'"); - - waitForExplicitFinish(); - - var gCurrTest; - var gTests = [ - { - name: "context menu search", - searchURL: base + "&hsimp=yhs-005", - run: function () { - // Simulate a contextmenu search - // FIXME: This is a bit "low-level"... - BrowserSearch.loadSearch("foo", false, "contextmenu"); - } - }, - { - name: "keyword search", - searchURL: base + "&hsimp=yhs-002", - run: function () { - gURLBar.value = "? foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "keyword search with alias", - searchURL: base + "&hsimp=yhs-002", - run: function () { - gURLBar.value = "y foo"; - gURLBar.focus(); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "search bar search", - searchURL: base + "&hsimp=yhs-001", - run: function () { - let sb = BrowserSearch.searchBar; - sb.focus(); - sb.value = "foo"; - registerCleanupFunction(function () { - sb.value = ""; - }); - EventUtils.synthesizeKey("VK_RETURN", {}); - } - }, - { - name: "new tab search", - searchURL: base + "&hsimp=yhs-004", - run: function () { - function doSearch(doc) { - // Re-add the listener, and perform a search - gBrowser.addProgressListener(listener); - doc.getElementById("newtab-search-text").value = "foo"; - doc.getElementById("newtab-search-submit").click(); - } - - // load about:newtab, but remove the listener first so it doesn't - // get in the way - gBrowser.removeProgressListener(listener); - gBrowser.loadURI("about:newtab"); - info("Waiting for about:newtab load"); - tab.linkedBrowser.addEventListener("load", function load(event) { - if (event.originalTarget != tab.linkedBrowser.contentDocument || - event.target.location.href == "about:blank") { - info("skipping spurious load event"); - return; - } - tab.linkedBrowser.removeEventListener("load", load, true); - - // Observe page setup - let win = gBrowser.contentWindow; - if (win.gSearch.currentEngineName == - Services.search.currentEngine.name) { - doSearch(win.document); - } - else { - info("Waiting for newtab search init"); - win.addEventListener("ContentSearchService", function done(event) { - info("Got newtab search event " + event.detail.type); - if (event.detail.type == "State") { - win.removeEventListener("ContentSearchService", done); - // Let gSearch respond to the event before continuing. - executeSoon(() => doSearch(win.document)); - } - }); - } - }, true); - } - } - ]; - - function nextTest() { - if (gTests.length) { - gCurrTest = gTests.shift(); - info("Running : " + gCurrTest.name); - executeSoon(gCurrTest.run); - } else { - finish(); - } - } - - let tab = gBrowser.selectedTab = gBrowser.addTab(); - - let listener = { - onStateChange: function onStateChange(webProgress, req, flags, status) { - info("onStateChange"); - // Only care about top-level document starts - let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | - Ci.nsIWebProgressListener.STATE_START; - if (!(flags & docStart) || !webProgress.isTopLevel) - return; - - if (req.originalURI.spec == "about:blank") - return; - - info("received document start"); - - ok(req instanceof Ci.nsIChannel, "req is a channel"); - is(req.originalURI.spec, gCurrTest.searchURL, "search URL was loaded"); - info("Actual URI: " + req.URI.spec); - - req.cancel(Components.results.NS_ERROR_FAILURE); - - executeSoon(nextTest); - } - } - - registerCleanupFunction(function () { - engine.alias = undefined; - gBrowser.removeProgressListener(listener); - gBrowser.removeTab(tab); - Services.search.currentEngine = previouslySelectedEngine; - }); - - tab.linkedBrowser.addEventListener("load", function load() { - tab.linkedBrowser.removeEventListener("load", load, true); - gBrowser.addProgressListener(listener); - nextTest(); - }, true); -} diff --git a/browser/components/search/test/head.js b/browser/components/search/test/head.js deleted file mode 100644 index de27b5e1e..000000000 --- a/browser/components/search/test/head.js +++ /dev/null @@ -1,156 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -Cu.import("resource://gre/modules/Promise.jsm"); - -/** - * Recursively compare two objects and check that every property of expectedObj has the same value - * on actualObj. - */ -function isSubObjectOf(expectedObj, actualObj, name) { - for (let prop in expectedObj) { - if (typeof expectedObj[prop] == 'function') - continue; - if (expectedObj[prop] instanceof Object) { - is(actualObj[prop].length, expectedObj[prop].length, name + "[" + prop + "]"); - isSubObjectOf(expectedObj[prop], actualObj[prop], name + "[" + prop + "]"); - } else { - is(actualObj[prop], expectedObj[prop], name + "[" + prop + "]"); - } - } -} - -function getLocale() { - const localePref = "general.useragent.locale"; - return getLocalizedPref(localePref, Services.prefs.getCharPref(localePref)); -} - -/** - * Wrapper for nsIPrefBranch::getComplexValue. - * @param aPrefName - * The name of the pref to get. - * @returns aDefault if the requested pref doesn't exist. - */ -function getLocalizedPref(aPrefName, aDefault) { - try { - return Services.prefs.getComplexValue(aPrefName, Ci.nsIPrefLocalizedString).data; - } catch (ex) { - return aDefault; - } -} - -function promiseEvent(aTarget, aEventName, aPreventDefault) { - function cancelEvent(event) { - if (aPreventDefault) { - event.preventDefault(); - } - - return true; - } - - return BrowserTestUtils.waitForEvent(aTarget, aEventName, false, cancelEvent); -} - -/** - * Adds a new search engine to the search service and confirms it completes. - * - * @param {String} basename The file to load that contains the search engine - * details. - * @param {Object} [options] Options for the test: - * - {String} [iconURL] The icon to use for the search engine. - * - {Boolean} [setAsCurrent] Whether to set the new engine to be the - * current engine or not. - * - {String} [testPath] Used to override the current test path if this - * file is used from a different directory. - * @returns {Promise} The promise is resolved once the engine is added, or - * rejected if the addition failed. - */ -function promiseNewEngine(basename, options = {}) { - return new Promise((resolve, reject) => { - // Default the setAsCurrent option to true. - let setAsCurrent = - options.setAsCurrent == undefined ? true : options.setAsCurrent; - info("Waiting for engine to be added: " + basename); - Services.search.init({ - onInitComplete: function() { - let url = getRootDirectory(options.testPath || gTestPath) + basename; - let current = Services.search.currentEngine; - Services.search.addEngine(url, null, options.iconURL || "", false, { - onSuccess: function (engine) { - info("Search engine added: " + basename); - if (setAsCurrent) { - Services.search.currentEngine = engine; - } - registerCleanupFunction(() => { - if (setAsCurrent) { - Services.search.currentEngine = current; - } - Services.search.removeEngine(engine); - info("Search engine removed: " + basename); - }); - resolve(engine); - }, - onError: function (errCode) { - ok(false, "addEngine failed with error code " + errCode); - reject(); - } - }); - } - }); - }); -} - -/** - * Waits for a load (or custom) event to finish in a given tab. If provided - * load an uri into the tab. - * - * @param tab - * The tab to load into. - * @param [optional] url - * The url to load, or the current url. - * @return {Promise} resolved when the event is handled. - * @resolves to the received event - * @rejects if a valid load event is not received within a meaningful interval - */ -function promiseTabLoadEvent(tab, url) -{ - info("Wait tab event: load"); - - function handle(loadedUrl) { - if (loadedUrl === "about:blank" || (url && loadedUrl !== url)) { - info(`Skipping spurious load event for ${loadedUrl}`); - return false; - } - - info("Tab event received: load"); - return true; - } - - let loaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, handle); - - if (url) - BrowserTestUtils.loadURI(tab.linkedBrowser, url); - - return loaded; -} - -// Get an array of the one-off buttons. -function getOneOffs() { - let oneOffs = []; - let searchPopup = document.getElementById("PopupSearchAutoComplete"); - let oneOffsContainer = - document.getAnonymousElementByAttribute(searchPopup, "anonid", - "search-one-off-buttons"); - let oneOff = - document.getAnonymousElementByAttribute(oneOffsContainer, "anonid", - "search-panel-one-offs"); - for (oneOff = oneOff.firstChild; oneOff; oneOff = oneOff.nextSibling) { - if (oneOff.nodeType == Node.ELEMENT_NODE) { - if (oneOff.classList.contains("dummy") || - oneOff.classList.contains("search-setting-button-compact")) - break; - oneOffs.push(oneOff); - } - } - return oneOffs; -} diff --git a/browser/components/search/test/opensearch.html b/browser/components/search/test/opensearch.html deleted file mode 100644 index f4c0cc98e..000000000 --- a/browser/components/search/test/opensearch.html +++ /dev/null @@ -1,9 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<meta charset="UTF-8"> -<link rel="search" type="application/opensearchdescription+xml" title="engine1" href="http://mochi.test:8888/browser/browser/components/search/test/testEngine.xml"> -<link rel="search" type="application/opensearchdescription+xml" title="engine2" href="http://mochi.test:8888/browser/browser/components/search/test/testEngine_mozsearch.xml"> -</head> -<body></body> -</html> diff --git a/browser/components/search/test/test.html b/browser/components/search/test/test.html deleted file mode 100644 index a39bece4f..000000000 --- a/browser/components/search/test/test.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta charset="utf-8" /> - <title>Bug 426329</title> -</head> -<body></body> -</html> diff --git a/browser/components/search/test/testEngine.xml b/browser/components/search/test/testEngine.xml deleted file mode 100644 index 21ddc4b9a..000000000 --- a/browser/components/search/test/testEngine.xml +++ /dev/null @@ -1,12 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>Foo</ShortName> - <Description>Foo Search</Description> - <InputEncoding>utf-8</InputEncoding> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm> - <moz:Alias>fooalias</moz:Alias> -</OpenSearchDescription> diff --git a/browser/components/search/test/testEngine_diacritics.xml b/browser/components/search/test/testEngine_diacritics.xml deleted file mode 100644 index 0744921eb..000000000 --- a/browser/components/search/test/testEngine_diacritics.xml +++ /dev/null @@ -1,12 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>Foo ♡</ShortName> - <Description>Engine whose ShortName contains non-BMP Unicode characters</Description> - <InputEncoding>utf-8</InputEncoding> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm> - <moz:Alias>diacriticalias</moz:Alias> -</OpenSearchDescription> diff --git a/browser/components/search/test/testEngine_dupe.xml b/browser/components/search/test/testEngine_dupe.xml deleted file mode 100644 index d2db580c4..000000000 --- a/browser/components/search/test/testEngine_dupe.xml +++ /dev/null @@ -1,12 +0,0 @@ -<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" - xmlns:moz="http://www.mozilla.org/2006/browser/search/"> - <ShortName>FooDupe</ShortName> - <Description>Second Engine Search</Description> - <InputEncoding>utf-8</InputEncoding> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search"> - <Param name="test" value="{searchTerms}"/> - </Url> - <moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm> - <moz:Alias>secondalias</moz:Alias> -</OpenSearchDescription> diff --git a/browser/components/search/test/testEngine_mozsearch.xml b/browser/components/search/test/testEngine_mozsearch.xml deleted file mode 100644 index 9b4c02a0c..000000000 --- a/browser/components/search/test/testEngine_mozsearch.xml +++ /dev/null @@ -1,14 +0,0 @@ -<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> - <ShortName>Foo</ShortName> - <Description>Foo Search</Description> - <InputEncoding>utf-8</InputEncoding> - <Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image> - <Url type="application/x-suggestions+json" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?suggestions&locale={moz:locale}&test={searchTerms}"/> - <Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/"> - <Param name="test" value="{searchTerms}"/> - <Param name="ie" value="utf-8"/> - <MozParam name="channel" condition="purpose" purpose="keyword" value="keywordsearch"/> - <MozParam name="channel" condition="purpose" purpose="contextmenu" value="contextsearch"/> - </Url> - <SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</SearchForm> -</SearchPlugin> diff --git a/browser/components/search/test/webapi.html b/browser/components/search/test/webapi.html deleted file mode 100644 index 1ef38b895..000000000 --- a/browser/components/search/test/webapi.html +++ /dev/null @@ -1,16 +0,0 @@ -<!DOCTYPE html> - -<html> -<head> -<script> -function installEngine() { - var query = window.location.search.substring(1); - var args = JSON.parse(decodeURIComponent(query)); - - window.external.AddSearchProvider(...args); -} -</script> -</head> -<body onload="installEngine()"> -</body> -</html> diff --git a/browser/components/selfsupport/test/.eslintrc.js b/browser/components/selfsupport/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/selfsupport/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/selfsupport/test/browser.ini b/browser/components/selfsupport/test/browser.ini deleted file mode 100644 index ba56857b3..000000000 --- a/browser/components/selfsupport/test/browser.ini +++ /dev/null @@ -1,3 +0,0 @@ -[DEFAULT] - -[browser_selfsupportAPI.js] diff --git a/browser/components/selfsupport/test/browser_selfsupportAPI.js b/browser/components/selfsupport/test/browser_selfsupportAPI.js deleted file mode 100644 index 2a54d4ae6..000000000 --- a/browser/components/selfsupport/test/browser_selfsupportAPI.js +++ /dev/null @@ -1,88 +0,0 @@ -Cu.import("resource://gre/modules/Preferences.jsm"); - -function test_resetPref() { - const prefNewName = "browser.newpref.fake"; - Assert.ok(!Preferences.has(prefNewName), "pref should not exist"); - - const prefExistingName = "extensions.hotfix.id"; - Assert.ok(Preferences.has(prefExistingName), "pref should exist"); - Assert.ok(!Preferences.isSet(prefExistingName), "pref should not be user-set"); - let prefExistingOriginalValue = Preferences.get(prefExistingName); - - registerCleanupFunction(function() { - Preferences.set(prefExistingName, prefExistingOriginalValue); - Services.prefs.deleteBranch(prefNewName); - }); - - // 1. do nothing on an inexistent pref - MozSelfSupport.resetPref(prefNewName); - Assert.ok(!Preferences.has(prefNewName), "pref should still not exist"); - - // 2. creation of a new pref - Preferences.set(prefNewName, 10); - Assert.ok(Preferences.has(prefNewName), "pref should exist"); - Assert.equal(Preferences.get(prefNewName), 10, "pref value should be 10"); - - MozSelfSupport.resetPref(prefNewName); - Assert.ok(!Preferences.has(prefNewName), "pref should not exist any more"); - - // 3. do nothing on an unchanged existing pref - MozSelfSupport.resetPref(prefExistingName); - Assert.ok(Preferences.has(prefExistingName), "pref should still exist"); - Assert.equal(Preferences.get(prefExistingName), prefExistingOriginalValue, "pref value should be the same as original"); - - // 4. change the value of an existing pref - Preferences.set(prefExistingName, "anyone@mozilla.org"); - Assert.ok(Preferences.has(prefExistingName), "pref should exist"); - Assert.equal(Preferences.get(prefExistingName), "anyone@mozilla.org", "pref value should have changed"); - - MozSelfSupport.resetPref(prefExistingName); - Assert.ok(Preferences.has(prefExistingName), "pref should still exist"); - Assert.equal(Preferences.get(prefExistingName), prefExistingOriginalValue, "pref value should be the same as original"); - - // 5. delete an existing pref - // deleteBranch is implemented in such a way that - // clearUserPref can't undo its action - // see discussion in bug 1075160 -} - -function test_resetSearchEngines() -{ - const defaultEngineOriginal = Services.search.defaultEngine; - const visibleEnginesOriginal = Services.search.getVisibleEngines(); - - // 1. do nothing on unchanged search configuration - MozSelfSupport.resetSearchEngines(); - Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset"); - Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal, - "default visible engines set should be reset"); - - // 2. change the default search engine - const defaultEngineNew = visibleEnginesOriginal[3]; - Assert.notEqual(defaultEngineOriginal, defaultEngineNew, "new default engine should be different from original"); - Services.search.defaultEngine = defaultEngineNew; - Assert.equal(Services.search.defaultEngine, defaultEngineNew, "default engine should be set to new"); - MozSelfSupport.resetSearchEngines(); - Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset"); - Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal, - "default visible engines set should be reset"); - - // 3. remove an engine - const engineRemoved = visibleEnginesOriginal[2]; - Services.search.removeEngine(engineRemoved); - Assert.ok(Services.search.getVisibleEngines().indexOf(engineRemoved) == -1, - "removed engine should not be visible any more"); - MozSelfSupport.resetSearchEngines(); - Assert.equal(Services.search.defaultEngine, defaultEngineOriginal, "default engine should be reset"); - Assert.deepEqual(Services.search.getVisibleEngines(), visibleEnginesOriginal, - "default visible engines set should be reset"); - - // 4. add an angine - // we don't remove user-added engines as they are only used if selected -} - -function test() -{ - test_resetPref(); - test_resetSearchEngines(); -} diff --git a/browser/components/sessionstore/test/.eslintrc.js b/browser/components/sessionstore/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/sessionstore/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/sessionstore/test/browser.ini b/browser/components/sessionstore/test/browser.ini deleted file mode 100644 index 37154a0cc..000000000 --- a/browser/components/sessionstore/test/browser.ini +++ /dev/null @@ -1,242 +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/. - -# browser_506482.js is disabled because of frequent failures (bug 538672) -# browser_526613.js is disabled because of frequent failures (bug 534489) -# browser_589246.js is disabled for leaking browser windows (bug 752467) -# browser_580512.js is disabled for leaking browser windows (bug 752467) - -[DEFAULT] -support-files = - head.js - content.js - content-forms.js - browser_cookies.sjs - browser_formdata_sample.html - browser_formdata_xpath_sample.html - browser_frametree_sample.html - browser_frametree_sample_frameset.html - browser_frame_history_index.html - browser_frame_history_index2.html - browser_frame_history_index_blank.html - browser_frame_history_a.html - browser_frame_history_b.html - browser_frame_history_c.html - browser_frame_history_c1.html - browser_frame_history_c2.html - browser_form_restore_events_sample.html - browser_formdata_format_sample.html - browser_pageStyle_sample.html - browser_pageStyle_sample_nested.html - browser_sessionHistory_slow.sjs - browser_scrollPositions_sample.html - browser_scrollPositions_sample_frameset.html - browser_scrollPositions_readerModeArticle.html - browser_sessionStorage.html - browser_248970_b_sample.html - browser_339445_sample.html - browser_423132_sample.html - browser_447951_sample.html - browser_454908_sample.html - browser_456342_sample.xhtml - browser_463205_sample.html - browser_463206_sample.html - browser_466937_sample.html - browser_485482_sample.html - browser_637020_slow.sjs - browser_662743_sample.html - browser_739531_sample.html - browser_911547_sample.html - browser_911547_sample.html^headers^ - restore_redirect_http.html - restore_redirect_http.html^headers^ - restore_redirect_js.html - restore_redirect_target.html - browser_1234021_page.html - -#NB: the following are disabled -# browser_464620_a.html -# browser_464620_b.html -# browser_464620_xd.html - - -#disabled-for-intermittent-failures--bug-766044, browser_459906_empty.html -#disabled-for-intermittent-failures--bug-766044, browser_459906_sample.html -#disabled-for-intermittent-failures--bug-765389, browser_461743_sample.html - -[browser_aboutPrivateBrowsing.js] -[browser_aboutSessionRestore.js] -[browser_async_duplicate_tab.js] -[browser_async_flushes.js] -run-if = e10s && crashreporter -skip-if = debug # bug 1167933 -[browser_async_remove_tab.js] -run-if = e10s -skip-if = debug # bug 1211084 -[browser_attributes.js] -[browser_backup_recovery.js] -[browser_broadcast.js] -[browser_capabilities.js] -[browser_cleaner.js] -[browser_cookies.js] -[browser_crashedTabs.js] -skip-if = !e10s || !crashreporter -[browser_unrestored_crashedTabs.js] -skip-if = !e10s || !crashreporter -[browser_revive_crashed_bg_tabs.js] -skip-if = !e10s || !crashreporter -[browser_dying_cache.js] -[browser_dynamic_frames.js] -[browser_form_restore_events.js] -[browser_formdata.js] -[browser_formdata_cc.js] -[browser_formdata_format.js] -[browser_formdata_xpath.js] -[browser_frametree.js] -[browser_frame_history.js] -[browser_global_store.js] -[browser_history_persist.js] -[browser_label_and_icon.js] -[browser_merge_closed_tabs.js] -[browser_page_title.js] -[browser_pageStyle.js] -[browser_pending_tabs.js] -[browser_privatetabs.js] -[browser_purge_shistory.js] -skip-if = e10s # Bug 1271024 -[browser_replace_load.js] -[browser_restore_redirect.js] -[browser_restore_cookies_noOriginAttributes.js] -[browser_scrollPositions.js] -[browser_scrollPositionsReaderMode.js] -[browser_sessionHistory.js] -[browser_sessionStorage.js] -[browser_sessionStorage_size.js] -[browser_swapDocShells.js] -[browser_switch_remoteness.js] -run-if = e10s -[browser_upgrade_backup.js] -[browser_windowRestore_perwindowpb.js] -[browser_248970_b_perwindowpb.js] -# Disabled because of leaks. -# Re-enabling and rewriting this test is tracked in bug 936919. -skip-if = true -[browser_339445.js] -[browser_345898.js] -[browser_350525.js] -[browser_354894_perwindowpb.js] -[browser_367052.js] -[browser_393716.js] -[browser_394759_basic.js] -# Disabled for intermittent failures, bug 944372. -skip-if = true -[browser_394759_behavior.js] -[browser_394759_perwindowpb.js] -[browser_394759_purge.js] -[browser_423132.js] -[browser_447951.js] -[browser_454908.js] -[browser_456342.js] -[browser_461634.js] -[browser_463205.js] -[browser_463206.js] -[browser_464199.js] -[browser_465215.js] -[browser_465223.js] -[browser_466937.js] -[browser_467409-backslashplosion.js] -[browser_477657.js] -[browser_480893.js] -[browser_485482.js] -[browser_485563.js] -[browser_490040.js] -[browser_491168.js] -[browser_491577.js] -[browser_495495.js] -[browser_500328.js] -[browser_514751.js] -[browser_522375.js] -[browser_522545.js] -[browser_524745.js] -[browser_528776.js] -[browser_579868.js] -[browser_579879.js] -skip-if = (os == 'linux' && e10s && (debug||asan)) # Bug 1234404 -[browser_581937.js] -[browser_586147.js] -[browser_586068-apptabs.js] -[browser_586068-apptabs_ondemand.js] -[browser_586068-browser_state_interrupted.js] -[browser_586068-cascade.js] -[browser_586068-multi_window.js] -[browser_586068-reload.js] -[browser_586068-select.js] -[browser_586068-window_state.js] -[browser_586068-window_state_override.js] -[browser_588426.js] -[browser_590268.js] -[browser_590563.js] -[browser_595601-restore_hidden.js] -[browser_597071.js] -skip-if = true # Needs to be rewritten as Marionette test, bug 995916 -[browser_599909.js] -[browser_600545.js] -[browser_601955.js] -[browser_607016.js] -[browser_615394-SSWindowState_events.js] -[browser_618151.js] -[browser_623779.js] -[browser_624727.js] -[browser_628270.js] -[browser_635418.js] -[browser_636279.js] -[browser_637020.js] -[browser_644409-scratchpads.js] -[browser_645428.js] -[browser_659591.js] -[browser_662743.js] -[browser_662812.js] -[browser_665702-state_session.js] -[browser_682507.js] -[browser_687710.js] -[browser_687710_2.js] -[browser_694378.js] -[browser_701377.js] -[browser_705597.js] -[browser_707862.js] -[browser_739531.js] -[browser_739805.js] -[browser_819510_perwindowpb.js] -skip-if = (os == 'win' && bits == 64) # Bug 1284312 - -# Disabled for frequent intermittent failures -[browser_464620_a.js] -skip-if = true -[browser_464620_b.js] -skip-if = true - -# Disabled on OS X: -[browser_625016.js] -skip-if = os == "mac" - -[browser_911547.js] -[browser_send_async_message_oom.js] -[browser_multiple_navigateAndRestore.js] -run-if = e10s -[browser_async_window_flushing.js] -[browser_forget_async_closings.js] -[browser_newtab_userTypedValue.js] -[browser_parentProcessRestoreHash.js] -run-if = e10s -[browser_sessionStoreContainer.js] -[browser_windowStateContainer.js] -[browser_1234021.js] -[browser_remoteness_flip_on_restore.js] -run-if = e10s -[browser_background_tab_crash.js] -run-if = e10s && crashreporter - -# Disabled on debug for frequent intermittent failures: -[browser_undoCloseById.js] -skip-if = debug diff --git a/browser/components/sessionstore/test/browser_1234021.js b/browser/components/sessionstore/test/browser_1234021.js deleted file mode 100644 index a307d1e01..000000000 --- a/browser/components/sessionstore/test/browser_1234021.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -const PREF = 'network.cookie.cookieBehavior'; -const PAGE_URL = 'http://mochi.test:8888/browser/' + - 'browser/components/sessionstore/test/browser_1234021_page.html'; -const BEHAVIOR_REJECT = 2; - -add_task(function* test() { - yield pushPrefs([PREF, BEHAVIOR_REJECT]); - - yield BrowserTestUtils.withNewTab({ - gBrowser: gBrowser, - url: PAGE_URL - }, function* handler(aBrowser) { - yield TabStateFlusher.flush(aBrowser); - ok(true, "Flush didn't time out"); - }); -}); diff --git a/browser/components/sessionstore/test/browser_1234021_page.html b/browser/components/sessionstore/test/browser_1234021_page.html deleted file mode 100644 index 4a74fbc02..000000000 --- a/browser/components/sessionstore/test/browser_1234021_page.html +++ /dev/null @@ -1,6 +0,0 @@ -<!doctype html> -<html> - <script> - sessionStorage - </script> -</html> diff --git a/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js b/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js deleted file mode 100644 index f5775cd5b..000000000 --- a/browser/components/sessionstore/test/browser_248970_b_perwindowpb.js +++ /dev/null @@ -1,166 +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/. */ - -function test() { - /** Test (B) for Bug 248970 **/ - waitForExplicitFinish(); - - let windowsToClose = []; - let file = Services.dirsvc.get("TmpD", Ci.nsIFile); - let filePath = file.path; - let fieldList = { - "//input[@name='input']": Date.now().toString(), - "//input[@name='spaced 1']": Math.random().toString(), - "//input[3]": "three", - "//input[@type='checkbox']": true, - "//input[@name='uncheck']": false, - "//input[@type='radio'][1]": false, - "//input[@type='radio'][2]": true, - "//input[@type='radio'][3]": false, - "//select": 2, - "//select[@multiple]": [1, 3], - "//textarea[1]": "", - "//textarea[2]": "Some text... " + Math.random(), - "//textarea[3]": "Some more text\n" + new Date(), - "//input[@type='file']": filePath - }; - - registerCleanupFunction(function* () { - for (let win of windowsToClose) { - yield BrowserTestUtils.closeWindow(win); - } - }); - - function test(aLambda) { - try { - return aLambda() || true; - } catch(ex) { } - return false; - } - - function getElementByXPath(aTab, aQuery) { - let doc = aTab.linkedBrowser.contentDocument; - let xptype = Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE; - return doc.evaluate(aQuery, doc, null, xptype, null).singleNodeValue; - } - - function setFormValue(aTab, aQuery, aValue) { - let node = getElementByXPath(aTab, aQuery); - if (typeof aValue == "string") - node.value = aValue; - else if (typeof aValue == "boolean") - node.checked = aValue; - else if (typeof aValue == "number") - node.selectedIndex = aValue; - else - Array.forEach(node.options, (aOpt, aIx) => - (aOpt.selected = aValue.indexOf(aIx) > -1)); - } - - function compareFormValue(aTab, aQuery, aValue) { - let node = getElementByXPath(aTab, aQuery); - if (!node) - return false; - if (node instanceof Ci.nsIDOMHTMLInputElement) - return aValue == (node.type == "checkbox" || node.type == "radio" ? - node.checked : node.value); - if (node instanceof Ci.nsIDOMHTMLTextAreaElement) - return aValue == node.value; - if (!node.multiple) - return aValue == node.selectedIndex; - return Array.every(node.options, (aOpt, aIx) => - (aValue.indexOf(aIx) > -1) == aOpt.selected); - } - - ////////////////////////////////////////////////////////////////// - // Test (B) : Session data restoration between windows // - ////////////////////////////////////////////////////////////////// - - let rootDir = getRootDirectory(gTestPath); - const testURL = rootDir + "browser_248970_b_sample.html"; - const testURL2 = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_248970_b_sample.html"; - - whenNewWindowLoaded({ private: false }, function(aWin) { - windowsToClose.push(aWin); - - // get closed tab count - let count = ss.getClosedTabCount(aWin); - let max_tabs_undo = - Services.prefs.getIntPref("browser.sessionstore.max_tabs_undo"); - ok(0 <= count && count <= max_tabs_undo, - "getClosedTabCount should return zero or at most max_tabs_undo"); - - // setup a state for tab (A) so we can check later that is restored - let key = "key"; - let value = "Value " + Math.random(); - let state = { entries: [{ url: testURL }], extData: { key: value } }; - - // public session, add new tab: (A) - let tab_A = aWin.gBrowser.addTab(testURL); - ss.setTabState(tab_A, JSON.stringify(state)); - promiseBrowserLoaded(tab_A.linkedBrowser).then(() => { - // make sure that the next closed tab will increase getClosedTabCount - Services.prefs.setIntPref( - "browser.sessionstore.max_tabs_undo", max_tabs_undo + 1) - - // populate tab_A with form data - for (let i in fieldList) - setFormValue(tab_A, i, fieldList[i]); - - // public session, close tab: (A) - aWin.gBrowser.removeTab(tab_A); - - // verify that closedTabCount increased - ok(ss.getClosedTabCount(aWin) > count, - "getClosedTabCount has increased after closing a tab"); - - // verify tab: (A), in undo list - let tab_A_restored = test(() => ss.undoCloseTab(aWin, 0)); - ok(tab_A_restored, "a tab is in undo list"); - promiseTabRestored(tab_A_restored).then(() => { - is(testURL, tab_A_restored.linkedBrowser.currentURI.spec, - "it's the same tab that we expect"); - aWin.gBrowser.removeTab(tab_A_restored); - - whenNewWindowLoaded({ private: true }, function(aWin) { - windowsToClose.push(aWin); - - // setup a state for tab (B) so we can check that its duplicated - // properly - let key1 = "key1"; - let value1 = "Value " + Math.random(); - let state1 = { - entries: [{ url: testURL2 }], extData: { key1: value1 } - }; - - let tab_B = aWin.gBrowser.addTab(testURL2); - promiseTabState(tab_B, state1).then(() => { - // populate tab: (B) with different form data - for (let item in fieldList) - setFormValue(tab_B, item, fieldList[item]); - - // duplicate tab: (B) - let tab_C = aWin.gBrowser.duplicateTab(tab_B); - promiseTabRestored(tab_C).then(() => { - // verify the correctness of the duplicated tab - is(ss.getTabValue(tab_C, key1), value1, - "tab successfully duplicated - correct state"); - - for (let item in fieldList) - ok(compareFormValue(tab_C, item, fieldList[item]), - "The value for \"" + item + "\" was correctly duplicated"); - - // private browsing session, close tab: (C) and (B) - aWin.gBrowser.removeTab(tab_C); - aWin.gBrowser.removeTab(tab_B); - - finish(); - }); - }); - }); - }); - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_248970_b_sample.html b/browser/components/sessionstore/test/browser_248970_b_sample.html deleted file mode 100644 index 76c3ae1aa..000000000 --- a/browser/components/sessionstore/test/browser_248970_b_sample.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<meta charset="utf-8"> -<title>Test for bug 248970</title> - -<h3>Text Fields</h3> -<input type="text" name="input"> -<input type="text" name="spaced 1"> -<input> - -<h3>Checkboxes and Radio buttons</h3> -<input type="checkbox" name="check"> Check 1 -<input type="checkbox" name="uncheck" checked> Check 2 -<p> -<input type="radio" name="group" value="1"> Radio 1 -<input type="radio" name="group" value="some"> Radio 2 -<input type="radio" name="group" checked> Radio 3 - -<h3>Selects</h3> -<select name="any"> - <option value="1"> Select 1 - <option value="some"> Select 2 - <option>Select 3 -</select> -<select multiple="multiple"> - <option value=1> Multi-select 1 - <option value=2> Multi-select 2 - <option value=3> Multi-select 3 - <option value=4> Multi-select 4 -</select> - -<h3>Text Areas</h3> -<textarea name="testarea"></textarea> -<textarea name="sized one" rows="5" cols="25"></textarea> -<textarea></textarea> - -<h3>File Selector</h3> -<input type="file"> diff --git a/browser/components/sessionstore/test/browser_339445.js b/browser/components/sessionstore/test/browser_339445.js deleted file mode 100644 index c38a6cb18..000000000 --- a/browser/components/sessionstore/test/browser_339445.js +++ /dev/null @@ -1,32 +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* test() { - /** Test for Bug 339445 **/ - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_339445_sample.html"; - - let tab = gBrowser.addTab(testURL); - yield promiseBrowserLoaded(tab.linkedBrowser); - - yield ContentTask.spawn(tab.linkedBrowser, null, function() { - let doc = content.document; - is(doc.getElementById("storageTestItem").textContent, "PENDING", - "sessionStorage value has been set"); - }); - - let tab2 = gBrowser.duplicateTab(tab); - yield promiseTabRestored(tab2); - - yield ContentTask.spawn(tab2.linkedBrowser, null, function() { - let doc2 = content.document; - is(doc2.getElementById("storageTestItem").textContent, "SUCCESS", - "sessionStorage value has been duplicated"); - }); - - // clean up - yield Promise.all([ BrowserTestUtils.removeTab(tab2), - BrowserTestUtils.removeTab(tab) ]); -}); diff --git a/browser/components/sessionstore/test/browser_339445_sample.html b/browser/components/sessionstore/test/browser_339445_sample.html deleted file mode 100644 index 32656a8d9..000000000 --- a/browser/components/sessionstore/test/browser_339445_sample.html +++ /dev/null @@ -1,18 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<meta charset="utf-8"> -<title>Test for bug 339445</title> - -storageTestItem = <span id="storageTestItem">FAIL</span> - -<!-- - storageTestItem's textContent will be one of the following: - * FAIL : sessionStorage wasn't available - * PENDING : the test value has been initialized on first load - * SUCCESS : the test value was correctly retrieved ---> - -<script type="application/javascript"> - document.getElementById("storageTestItem").textContent = - sessionStorage["storageTestItem"] || "PENDING"; - sessionStorage["storageTestItem"] = "SUCCESS"; -</script> diff --git a/browser/components/sessionstore/test/browser_345898.js b/browser/components/sessionstore/test/browser_345898.js deleted file mode 100644 index bd4a46e69..000000000 --- a/browser/components/sessionstore/test/browser_345898.js +++ /dev/null @@ -1,44 +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/. */ - -function test() { - /** Test for Bug 345898 **/ - - function test(aLambda) { - try { - aLambda(); - return false; - } - catch (ex) { - return ex.name == "NS_ERROR_ILLEGAL_VALUE" || - ex.name == "NS_ERROR_FAILURE"; - } - } - - // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE - ok(test(() => ss.getWindowState({})), - "Invalid window for getWindowState throws"); - ok(test(() => ss.setWindowState({}, "", false)), - "Invalid window for setWindowState throws"); - ok(test(() => ss.getTabState({})), - "Invalid tab for getTabState throws"); - ok(test(() => ss.setTabState({}, "{}")), - "Invalid tab state for setTabState throws"); - ok(test(() => ss.setTabState({}, JSON.stringify({ entries: [] }))), - "Invalid tab for setTabState throws"); - ok(test(() => ss.duplicateTab({}, {})), - "Invalid tab for duplicateTab throws"); - ok(test(() => ss.duplicateTab({}, gBrowser.selectedTab)), - "Invalid window for duplicateTab throws"); - ok(test(() => ss.getClosedTabData({})), - "Invalid window for getClosedTabData throws"); - ok(test(() => ss.undoCloseTab({}, 0)), - "Invalid window for undoCloseTab throws"); - ok(test(() => ss.undoCloseTab(window, -1)), - "Invalid index for undoCloseTab throws"); - ok(test(() => ss.getWindowValue({}, "")), - "Invalid window for getWindowValue throws"); - ok(test(() => ss.setWindowValue({}, "", "")), - "Invalid window for setWindowValue throws"); -} diff --git a/browser/components/sessionstore/test/browser_350525.js b/browser/components/sessionstore/test/browser_350525.js deleted file mode 100644 index 1d87b3754..000000000 --- a/browser/components/sessionstore/test/browser_350525.js +++ /dev/null @@ -1,102 +0,0 @@ -"use strict"; - -add_task(function* setup() { - yield SpecialPowers.pushPrefEnv({ - set: [["dom.ipc.processCount", 1]] - }); -}) - -add_task(function* () { - /** Test for Bug 350525 **/ - - function test(aLambda) { - try { - return aLambda() || true; - } - catch (ex) { } - return false; - } - - //////////////////////////// - // setWindowValue, et al. // - //////////////////////////// - let key = "Unique name: " + Date.now(); - let value = "Unique value: " + Math.random(); - - // test adding - ok(test(() => ss.setWindowValue(window, key, value)), "set a window value"); - - // test retrieving - is(ss.getWindowValue(window, key), value, "stored window value matches original"); - - // test deleting - ok(test(() => ss.deleteWindowValue(window, key)), "delete the window value"); - - // value should not exist post-delete - is(ss.getWindowValue(window, key), "", "window value was deleted"); - - // test deleting a non-existent value - ok(test(() => ss.deleteWindowValue(window, key)), "delete non-existent window value"); - - ///////////////////////// - // setTabValue, et al. // - ///////////////////////// - key = "Unique name: " + Math.random(); - value = "Unique value: " + Date.now(); - let tab = gBrowser.addTab(); - tab.linkedBrowser.stop(); - - // test adding - ok(test(() => ss.setTabValue(tab, key, value)), "store a tab value"); - - // test retrieving - is(ss.getTabValue(tab, key), value, "stored tab value match original"); - - // test deleting - ok(test(() => ss.deleteTabValue(tab, key)), "delete the tab value"); - - // value should not exist post-delete - is(ss.getTabValue(tab, key), "", "tab value was deleted"); - - // test deleting a non-existent value - ok(test(() => ss.deleteTabValue(tab, key)), "delete non-existent tab value"); - - // clean up - yield promiseRemoveTab(tab); - - ///////////////////////////////////// - // getClosedTabCount, undoCloseTab // - ///////////////////////////////////// - - // get closed tab count - let count = ss.getClosedTabCount(window); - let max_tabs_undo = gPrefService.getIntPref("browser.sessionstore.max_tabs_undo"); - ok(0 <= count && count <= max_tabs_undo, - "getClosedTabCount returns zero or at most max_tabs_undo"); - - // create a new tab - let testURL = "about:"; - tab = gBrowser.addTab(testURL); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // make sure that the next closed tab will increase getClosedTabCount - gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", max_tabs_undo + 1); - registerCleanupFunction(() => gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo")); - - // remove tab - yield promiseRemoveTab(tab); - - // getClosedTabCount - let newcount = ss.getClosedTabCount(window); - ok(newcount > count, "after closing a tab, getClosedTabCount has been incremented"); - - // undoCloseTab - tab = test(() => ss.undoCloseTab(window, 0)); - ok(tab, "undoCloseTab doesn't throw") - - yield promiseTabRestored(tab); - is(tab.linkedBrowser.currentURI.spec, testURL, "correct tab was reopened"); - - // clean up - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_354894_perwindowpb.js b/browser/components/sessionstore/test/browser_354894_perwindowpb.js deleted file mode 100644 index bf80cd710..000000000 --- a/browser/components/sessionstore/test/browser_354894_perwindowpb.js +++ /dev/null @@ -1,474 +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/. */ - -/** - * Checks that restoring the last browser window in session is actually - * working. - * - * @see https://bugzilla.mozilla.org/show_bug.cgi?id=354894 - * @note It is implicitly tested that restoring the last window works when - * non-browser windows are around. The "Run Tests" window as well as the main - * browser window (wherein the test code gets executed) won't be considered - * browser windows. To achiveve this said main browser window has it's windowtype - * attribute modified so that it's not considered a browser window any longer. - * This is crucial, because otherwise there would be two browser windows around, - * said main test window and the one opened by the tests, and hence the new - * logic wouldn't be executed at all. - * @note Mac only tests the new notifications, as restoring the last window is - * not enabled on that platform (platform shim; the application is kept running - * although there are no windows left) - * @note There is a difference when closing a browser window with - * BrowserTryToCloseWindow() as opposed to close(). The former will make - * nsSessionStore restore a window next time it gets a chance and will post - * notifications. The latter won't. - */ - -// Some urls that might be opened in tabs and/or popups -// Do not use about:blank: -// That one is reserved for special purposes in the tests -const TEST_URLS = ["about:mozilla", "about:buildconfig"]; - -// Number of -request notifications to except -// remember to adjust when adding new tests -const NOTIFICATIONS_EXPECTED = 6; - -// Window features of popup windows -const POPUP_FEATURES = "toolbar=no,resizable=no,status=no"; - -// Window features of browser windows -const CHROME_FEATURES = "chrome,all,dialog=no"; - -const IS_MAC = navigator.platform.match(/Mac/); - -/** - * Returns an Object with two properties: - * open (int): - * A count of how many non-closed navigator:browser windows there are. - * winstates (int): - * A count of how many windows there are in the SessionStore state. - */ -function getBrowserWindowsCount() { - let open = 0; - let e = Services.wm.getEnumerator("navigator:browser"); - while (e.hasMoreElements()) { - if (!e.getNext().closed) - ++open; - } - - let winstates = JSON.parse(ss.getBrowserState()).windows.length; - - return { open, winstates }; -} - -add_task(function* setup() { - // Make sure we've only got one browser window to start with - let { open, winstates } = getBrowserWindowsCount(); - is(open, 1, "Should only be one open window"); - is(winstates, 1, "Should only be one window state in SessionStore"); - - // This test takes some time to run, and it could timeout randomly. - // So we require a longer timeout. See bug 528219. - requestLongerTimeout(3); - - // Make the main test window not count as a browser window any longer - let oldWinType = document.documentElement.getAttribute("windowtype"); - document.documentElement.setAttribute("windowtype", "navigator:testrunner"); - - registerCleanupFunction(() => { - document.documentElement.setAttribute("windowtype", "navigator:browser"); - }); -}); - -/** - * Sets up one of our tests by setting the right preferences, and - * then opening up a browser window preloaded with some tabs. - * - * @param options (Object) - * An object that can contain the following properties: - * - * private: - * Whether or not the opened window should be private. - * - * denyFirst: - * Whether or not the first window that attempts to close - * via closeWindowForRestoration should be denied. - * - * @param testFunction (Function*) - * A generator function that yields Promises to be run - * once the test has been set up. - * - * @returns Promise - * Resolves once the test has been cleaned up. - */ -let setupTest = Task.async(function*(options, testFunction) { - yield pushPrefs(["browser.startup.page", 3], - ["browser.tabs.warnOnClose", false]); - - // Observe these, and also use to count the number of hits - let observing = { - "browser-lastwindow-close-requested": 0, - "browser-lastwindow-close-granted": 0 - }; - - /** - * Helper: Will observe and handle the notifications for us - */ - let hitCount = 0; - function observer(aCancel, aTopic, aData) { - // count so that we later may compare - observing[aTopic]++; - - // handle some tests - if (options.denyFirst && ++hitCount == 1) { - aCancel.QueryInterface(Ci.nsISupportsPRBool).data = true; - } - } - - for (let o in observing) { - Services.obs.addObserver(observer, o, false); - } - - let private = options.private || false; - let newWin = yield promiseNewWindowLoaded({ private }); - - injectTestTabs(newWin); - - yield testFunction(newWin, observing); - - let count = getBrowserWindowsCount(); - is(count.open, 0, "Got right number of open windows"); - is(count.winstates, 1, "Got right number of stored window states"); - - for (let o in observing) { - Services.obs.removeObserver(observer, o); - } - - yield popPrefs(); -}); - -/** - * Loads a TEST_URLS into a browser window. - * - * @param win (Window) - * The browser window to load the tabs in - */ -function injectTestTabs(win) { - TEST_URLS.forEach(function (url) { - win.gBrowser.addTab(url); - }); -} - -/** - * Attempts to close a window via BrowserTryToCloseWindow so that - * we get the browser-lastwindow-close-requested and - * browser-lastwindow-close-granted observer notifications. - * - * @param win (Window) - * The window to try to close - * @returns Promise - * Resolves to true if the window closed, or false if the window - * was denied the ability to close. - */ -function closeWindowForRestoration(win) { - return new Promise((resolve) => { - let closePromise = BrowserTestUtils.windowClosed(win); - win.BrowserTryToCloseWindow(); - if (!win.closed) { - resolve(false); - return; - } - - closePromise.then(() => { - resolve(true); - }); - }); -} - -/** - * Normal in-session restore - * - * @note: Non-Mac only - * - * Should do the following: - * 1. Open a new browser window - * 2. Add some tabs - * 3. Close that window - * 4. Opening another window - * 5. Checks that state is restored - */ -add_task(function* test_open_close_normal() { - if (IS_MAC) { - return; - } - - yield setupTest({ denyFirst: true }, function*(newWin, obs) { - let closed = yield closeWindowForRestoration(newWin); - ok(!closed, "First close request should have been denied"); - - closed = yield closeWindowForRestoration(newWin); - ok(closed, "Second close request should be accepted"); - - newWin = yield promiseNewWindowLoaded(); - is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2, - "Restored window in-session with otherpopup windows around"); - - // Note that this will not result in the the browser-lastwindow-close - // notifications firing for this other newWin. - yield BrowserTestUtils.closeWindow(newWin); - - // setupTest gave us a window which was denied for closing once, and then - // closed. - is(obs["browser-lastwindow-close-requested"], 2, - "Got expected browser-lastwindow-close-requested notifications"); - is(obs["browser-lastwindow-close-granted"], 1, - "Got expected browser-lastwindow-close-granted notifications"); - }); -}); - -/** - * PrivateBrowsing in-session restore - * - * @note: Non-Mac only - * - * Should do the following: - * 1. Open a new browser window A - * 2. Add some tabs - * 3. Close the window A as the last window - * 4. Open a private browsing window B - * 5. Make sure that B didn't restore the tabs from A - * 6. Close private browsing window B - * 7. Open a new window C - * 8. Make sure that new window C has restored tabs from A - */ -add_task(function* test_open_close_private_browsing() { - if (IS_MAC) { - return; - } - - yield setupTest({}, function*(newWin, obs) { - let closed = yield closeWindowForRestoration(newWin); - ok(closed, "Should be able to close the window"); - - newWin = yield promiseNewWindowLoaded({private: true}); - is(newWin.gBrowser.browsers.length, 1, - "Did not restore in private browing mode"); - - closed = yield closeWindowForRestoration(newWin); - ok(closed, "Should be able to close the window"); - - newWin = yield promiseNewWindowLoaded(); - is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2, - "Restored tabs in a new non-private window"); - - // Note that this will not result in the the browser-lastwindow-close - // notifications firing for this other newWin. - yield BrowserTestUtils.closeWindow(newWin); - - // We closed two windows with closeWindowForRestoration, and both - // should have been successful. - is(obs["browser-lastwindow-close-requested"], 2, - "Got expected browser-lastwindow-close-requested notifications"); - is(obs["browser-lastwindow-close-granted"], 2, - "Got expected browser-lastwindow-close-granted notifications"); - }); -}); - -/** - * Open some popup windows to check those aren't restored, but the browser - * window is. - * - * @note: Non-Mac only - * - * Should do the following: - * 1. Open a new browser window - * 2. Add some tabs - * 3. Open some popups - * 4. Add another tab to one popup (so that it gets stored) and close it again - * 5. Close the browser window - * 6. Open another browser window - * 7. Make sure that the tabs of the closed browser window, but not the popup, - * are restored - */ -add_task(function* test_open_close_window_and_popup() { - if (IS_MAC) { - return; - } - - yield setupTest({}, function*(newWin, obs) { - let popupPromise = BrowserTestUtils.waitForNewWindow(); - openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[0]); - let popup = yield popupPromise; - - let popup2Promise = BrowserTestUtils.waitForNewWindow(); - openDialog(location, "popup2", POPUP_FEATURES, TEST_URLS[1]); - let popup2 = yield popup2Promise; - - popup2.gBrowser.addTab(TEST_URLS[0]); - - let closed = yield closeWindowForRestoration(newWin); - ok(closed, "Should be able to close the window"); - - yield BrowserTestUtils.closeWindow(popup2); - - newWin = yield promiseNewWindowLoaded(); - - is(newWin.gBrowser.browsers.length, TEST_URLS.length + 2, - "Restored window and associated tabs in session"); - - yield BrowserTestUtils.closeWindow(popup); - yield BrowserTestUtils.closeWindow(newWin); - - // We closed one window with closeWindowForRestoration, and it should - // have been successful. - is(obs["browser-lastwindow-close-requested"], 1, - "Got expected browser-lastwindow-close-requested notifications"); - is(obs["browser-lastwindow-close-granted"], 1, - "Got expected browser-lastwindow-close-granted notifications"); - }); -}); - -/** - * Open some popup window to check it isn't restored. Instead nothing at all - * should be restored - * - * @note: Non-Mac only - * - * Should do the following: - * 1. Open a popup - * 2. Add another tab to the popup (so that it gets stored) and close it again - * 3. Open a window - * 4. Check that nothing at all is restored - * 5. Open two browser windows and close them again - * 6. undoCloseWindow() one - * 7. Open another browser window - * 8. Check that nothing at all is restored - */ -add_task(function* test_open_close_only_popup() { - if (IS_MAC) { - return; - } - - yield setupTest({}, function*(newWin, obs) { - // We actually don't care about the initial window in this test. - yield BrowserTestUtils.closeWindow(newWin); - - // This will cause nsSessionStore to restore a window the next time it - // gets a chance. - let popupPromise = BrowserTestUtils.waitForNewWindow(); - openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[1]); - let popup = yield popupPromise; - - is(popup.gBrowser.browsers.length, 1, - "Did not restore the popup window (1)"); - - let closed = yield closeWindowForRestoration(popup); - ok(closed, "Should be able to close the window"); - - popupPromise = BrowserTestUtils.waitForNewWindow(); - openDialog(location, "popup", POPUP_FEATURES, TEST_URLS[1]); - popup = yield popupPromise; - - popup.gBrowser.addTab(TEST_URLS[0]); - is(popup.gBrowser.browsers.length, 2, - "Did not restore to the popup window (2)"); - - yield BrowserTestUtils.closeWindow(popup); - - newWin = yield promiseNewWindowLoaded(); - isnot(newWin.gBrowser.browsers.length, 2, - "Did not restore the popup window"); - is(TEST_URLS.indexOf(newWin.gBrowser.browsers[0].currentURI.spec), -1, - "Did not restore the popup window (2)"); - yield BrowserTestUtils.closeWindow(newWin); - - // We closed one popup window with closeWindowForRestoration, and popup - // windows should never fire the browser-lastwindow notifications. - is(obs["browser-lastwindow-close-requested"], 0, - "Got expected browser-lastwindow-close-requested notifications"); - is(obs["browser-lastwindow-close-granted"], 0, - "Got expected browser-lastwindow-close-granted notifications"); - }); -}); - -/** - * Open some windows and do undoCloseWindow. This should prevent any - * restoring later in the test - * - * @note: Non-Mac only - * - * Should do the following: - * 1. Open two browser windows and close them again - * 2. undoCloseWindow() one - * 3. Open another browser window - * 4. Make sure nothing at all is restored - */ -add_task(function* test_open_close_restore_from_popup() { - if (IS_MAC) { - return; - } - - yield setupTest({}, function*(newWin, obs) { - let newWin2 = yield promiseNewWindowLoaded(); - yield injectTestTabs(newWin2); - - let closed = yield closeWindowForRestoration(newWin); - ok(closed, "Should be able to close the window"); - closed = yield closeWindowForRestoration(newWin2); - ok(closed, "Should be able to close the window"); - - let counts = getBrowserWindowsCount(); - is(counts.open, 0, "Got right number of open windows"); - is(counts.winstates, 1, "Got right number of window states"); - - newWin = undoCloseWindow(0); - yield BrowserTestUtils.waitForEvent(newWin, "load"); - - // Make sure we wait until this window is restored. - yield BrowserTestUtils.waitForEvent(newWin.gBrowser.tabContainer, - "SSTabRestored"); - - newWin2 = yield promiseNewWindowLoaded(); - - is(newWin2.gBrowser.browsers.length, 1, - "Did not restore, as undoCloseWindow() was last called"); - is(TEST_URLS.indexOf(newWin2.gBrowser.browsers[0].currentURI.spec), -1, - "Did not restore, as undoCloseWindow() was last called (2)"); - - counts = getBrowserWindowsCount(); - is(counts.open, 2, "Got right number of open windows"); - is(counts.winstates, 3, "Got right number of window states"); - - yield BrowserTestUtils.closeWindow(newWin); - yield BrowserTestUtils.closeWindow(newWin2); - - counts = getBrowserWindowsCount(); - is(counts.open, 0, "Got right number of open windows"); - is(counts.winstates, 1, "Got right number of window states"); - }); -}); - -/** - * Test if closing can be denied on Mac. - * @note: Mac only - */ -add_task(function* test_mac_notifications() { - if (!IS_MAC) { - return; - } - - yield setupTest({ denyFirst: true }, function*(newWin, obs) { - let closed = yield closeWindowForRestoration(newWin); - ok(!closed, "First close attempt should be denied"); - closed = yield closeWindowForRestoration(newWin); - ok(closed, "Second close attempt should be granted"); - - // We tried closing once, and got denied. Then we tried again and - // succeeded. That means 2 close requests, and 1 close granted. - is(obs["browser-lastwindow-close-requested"], 2, - "Got expected browser-lastwindow-close-requested notifications"); - is(obs["browser-lastwindow-close-granted"], 1, - "Got expected browser-lastwindow-close-granted notifications"); - }); -}); - diff --git a/browser/components/sessionstore/test/browser_367052.js b/browser/components/sessionstore/test/browser_367052.js deleted file mode 100644 index 3cc89a66c..000000000 --- a/browser/components/sessionstore/test/browser_367052.js +++ /dev/null @@ -1,41 +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"; - -add_task(function* () { - // make sure that the next closed tab will increase getClosedTabCount - let max_tabs_undo = gPrefService.getIntPref("browser.sessionstore.max_tabs_undo"); - gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", max_tabs_undo + 1); - registerCleanupFunction(() => gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo")); - - // Empty the list of closed tabs. - while (ss.getClosedTabCount(window)) { - ss.forgetClosedTab(window, 0); - } - - // restore a blank tab - let tab = gBrowser.addTab("about:"); - yield promiseBrowserLoaded(tab.linkedBrowser); - - let count = yield promiseSHistoryCount(tab.linkedBrowser); - ok(count >= 1, "the new tab does have at least one history entry"); - - yield promiseTabState(tab, {entries: []}); - - // We may have a different sessionHistory object if the tab - // switched from non-remote to remote. - count = yield promiseSHistoryCount(tab.linkedBrowser); - is(count, 0, "the tab was restored without any history whatsoever"); - - yield promiseRemoveTab(tab); - is(ss.getClosedTabCount(window), 0, - "The closed blank tab wasn't added to Recently Closed Tabs"); -}); - -function promiseSHistoryCount(browser) { - return ContentTask.spawn(browser, null, function* () { - return docShell.QueryInterface(Ci.nsIWebNavigation).sessionHistory.count; - }); -} diff --git a/browser/components/sessionstore/test/browser_393716.js b/browser/components/sessionstore/test/browser_393716.js deleted file mode 100644 index c59bdcc8b..000000000 --- a/browser/components/sessionstore/test/browser_393716.js +++ /dev/null @@ -1,71 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = "about:config"; - -/** - * Bug 393716 - Basic tests for getTabState(), setTabState(), and duplicateTab(). - */ -add_task(function test_set_tabstate() { - let key = "Unique key: " + Date.now(); - let value = "Unique value: " + Math.random(); - - // create a new tab - let tab = gBrowser.addTab(URL); - ss.setTabValue(tab, key, value); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // get the tab's state - yield TabStateFlusher.flush(tab.linkedBrowser); - let state = ss.getTabState(tab); - ok(state, "get the tab's state"); - - // verify the tab state's integrity - state = JSON.parse(state); - ok(state instanceof Object && state.entries instanceof Array && state.entries.length > 0, - "state object seems valid"); - ok(state.entries.length == 1 && state.entries[0].url == URL, - "Got the expected state object (test URL)"); - ok(state.extData && state.extData[key] == value, - "Got the expected state object (test manually set tab value)"); - - // clean up - gBrowser.removeTab(tab); -}); - -add_task(function test_set_tabstate_and_duplicate() { - let key2 = "key2"; - let value2 = "Value " + Math.random(); - let value3 = "Another value: " + Date.now(); - let state = { entries: [{ url: URL }], extData: { key2: value2 } }; - - // create a new tab - let tab = gBrowser.addTab(); - // set the tab's state - ss.setTabState(tab, JSON.stringify(state)); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // verify the correctness of the restored tab - ok(ss.getTabValue(tab, key2) == value2 && tab.linkedBrowser.currentURI.spec == URL, - "the tab's state was correctly restored"); - - // add text data - yield setInputValue(tab.linkedBrowser, {id: "textbox", value: value3}); - - // duplicate the tab - let tab2 = ss.duplicateTab(window, tab); - yield promiseTabRestored(tab2); - - // verify the correctness of the duplicated tab - ok(ss.getTabValue(tab2, key2) == value2 && - tab2.linkedBrowser.currentURI.spec == URL, - "correctly duplicated the tab's state"); - let textbox = yield getInputValue(tab2.linkedBrowser, {id: "textbox"}); - is(textbox, value3, "also duplicated text data"); - - // clean up - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_394759_basic.js b/browser/components/sessionstore/test/browser_394759_basic.js deleted file mode 100644 index 1b1650e27..000000000 --- a/browser/components/sessionstore/test/browser_394759_basic.js +++ /dev/null @@ -1,92 +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_URL = "data:text/html;charset=utf-8,<input%20id=txt>" + - "<input%20type=checkbox%20id=chk>"; - -Cu.import("resource:///modules/sessionstore/SessionStore.jsm"); - -/** - * This test ensures that closing a window is a reversible action. We will - * close the the window, restore it and check that all data has been restored. - * This includes window-specific data as well as form data for tabs. - */ -function test() { - waitForExplicitFinish(); - - let uniqueKey = "bug 394759"; - let uniqueValue = "unik" + Date.now(); - let uniqueText = "pi != " + Math.random(); - - // Clear the list of closed windows. - forgetClosedWindows(); - - provideWindow(function onTestURLLoaded(newWin) { - newWin.gBrowser.addTab().linkedBrowser.stop(); - - // Mark the window with some unique data to be restored later on. - ss.setWindowValue(newWin, uniqueKey, uniqueValue); - let [txt, chk] = newWin.content.document.querySelectorAll("#txt, #chk"); - txt.value = uniqueText; - - let browser = newWin.gBrowser.selectedBrowser; - setInputChecked(browser, {id: "chk", checked: true}).then(() => { - BrowserTestUtils.closeWindow(newWin).then(() => { - is(ss.getClosedWindowCount(), 1, - "The closed window was added to Recently Closed Windows"); - - let data = SessionStore.getClosedWindowData(false); - - // Verify that non JSON serialized data is the same as JSON serialized data. - is(JSON.stringify(data), ss.getClosedWindowData(), - "Non-serialized data is the same as serialized data") - - ok(data[0].title == TEST_URL && JSON.stringify(data[0]).indexOf(uniqueText) > -1, - "The closed window data was stored correctly"); - - // Reopen the closed window and ensure its integrity. - let newWin2 = ss.undoCloseWindow(0); - - ok(newWin2 instanceof ChromeWindow, - "undoCloseWindow actually returned a window"); - is(ss.getClosedWindowCount(), 0, - "The reopened window was removed from Recently Closed Windows"); - - // SSTabRestored will fire more than once, so we need to make sure we count them. - let restoredTabs = 0; - let expectedTabs = data[0].tabs.length; - newWin2.addEventListener("SSTabRestored", function sstabrestoredListener(aEvent) { - ++restoredTabs; - info("Restored tab " + restoredTabs + "/" + expectedTabs); - if (restoredTabs < expectedTabs) { - return; - } - - is(restoredTabs, expectedTabs, "Correct number of tabs restored"); - newWin2.removeEventListener("SSTabRestored", sstabrestoredListener, true); - - is(newWin2.gBrowser.tabs.length, 2, - "The window correctly restored 2 tabs"); - is(newWin2.gBrowser.currentURI.spec, TEST_URL, - "The window correctly restored the URL"); - - let [txt, chk] = newWin2.content.document.querySelectorAll("#txt, #chk"); - ok(txt.value == uniqueText && chk.checked, - "The window correctly restored the form"); - is(ss.getWindowValue(newWin2, uniqueKey), uniqueValue, - "The window correctly restored the data associated with it"); - - // Clean up. - BrowserTestUtils.closeWindow(newWin2).then(finish); - }, true); - }); - }); - }, TEST_URL); -} - -function setInputChecked(browser, data) { - return sendMessage(browser, "ss-test:setInputChecked", data); -} diff --git a/browser/components/sessionstore/test/browser_394759_behavior.js b/browser/components/sessionstore/test/browser_394759_behavior.js deleted file mode 100644 index aa74dc061..000000000 --- a/browser/components/sessionstore/test/browser_394759_behavior.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Test helper function that opens a series of windows, closes them - * and then checks the closed window data from SessionStore against - * expected results. - * - * @param windowsToOpen (Array) - * An array of Objects, where each object must define a single - * property "isPopup" for whether or not the opened window should - * be a popup. - * @param expectedResults (Array) - * An Object with two properies: mac and other, where each points - * at yet another Object, with the following properties: - * - * popup (int): - * The number of popup windows we expect to be in the closed window - * data. - * normal (int): - * The number of normal windows we expect to be in the closed window - * data. - * @returns Promise - */ -function testWindows(windowsToOpen, expectedResults) { - return Task.spawn(function*() { - for (let winData of windowsToOpen) { - let features = "chrome,dialog=no," + - (winData.isPopup ? "all=no" : "all"); - let url = "http://example.com/?window=" + windowsToOpen.length; - - let openWindowPromise = BrowserTestUtils.waitForNewWindow(true, url); - openDialog(getBrowserURL(), "", features, url); - let win = yield openWindowPromise; - yield BrowserTestUtils.closeWindow(win); - } - - let closedWindowData = JSON.parse(ss.getClosedWindowData()); - let numPopups = closedWindowData.filter(function(el, i, arr) { - return el.isPopup; - }).length; - let numNormal = ss.getClosedWindowCount() - numPopups; - // #ifdef doesn't work in browser-chrome tests, so do a simple regex on platform - let oResults = navigator.platform.match(/Mac/) ? expectedResults.mac - : expectedResults.other; - is(numPopups, oResults.popup, - "There were " + oResults.popup + " popup windows to reopen"); - is(numNormal, oResults.normal, - "There were " + oResults.normal + " normal windows to repoen"); - }); -} - -add_task(function* test_closed_window_states() { - // This test takes quite some time, and timeouts frequently, so we require - // more time to run. - // See Bug 518970. - requestLongerTimeout(2); - - let windowsToOpen = [{isPopup: false}, - {isPopup: false}, - {isPopup: true}, - {isPopup: true}, - {isPopup: true}]; - let expectedResults = {mac: {popup: 3, normal: 0}, - other: {popup: 3, normal: 1}}; - - yield testWindows(windowsToOpen, expectedResults); - - - let windowsToOpen2 = [{isPopup: false}, - {isPopup: false}, - {isPopup: false}, - {isPopup: false}, - {isPopup: false}]; - let expectedResults2 = {mac: {popup: 0, normal: 3}, - other: {popup: 0, normal: 3}}; - - yield testWindows(windowsToOpen2, expectedResults2); -});
\ No newline at end of file diff --git a/browser/components/sessionstore/test/browser_394759_perwindowpb.js b/browser/components/sessionstore/test/browser_394759_perwindowpb.js deleted file mode 100644 index 83eec3070..000000000 --- a/browser/components/sessionstore/test/browser_394759_perwindowpb.js +++ /dev/null @@ -1,55 +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 TESTS = [ - { url: "about:config", - key: "bug 394759 Non-PB", - value: "uniq" + r() }, - { url: "about:mozilla", - key: "bug 394759 PB", - value: "uniq" + r() }, -]; - -function promiseTestOpenCloseWindow(aIsPrivate, aTest) { - return Task.spawn(function*() { - let win = yield BrowserTestUtils.openNewBrowserWindow({ "private": aIsPrivate }); - win.gBrowser.selectedBrowser.loadURI(aTest.url); - yield promiseBrowserLoaded(win.gBrowser.selectedBrowser); - yield Promise.resolve(); - // Mark the window with some unique data to be restored later on. - ss.setWindowValue(win, aTest.key, aTest.value); - yield TabStateFlusher.flushWindow(win); - // Close. - yield BrowserTestUtils.closeWindow(win); - }); -} - -function promiseTestOnWindow(aIsPrivate, aValue) { - return Task.spawn(function*() { - let win = yield BrowserTestUtils.openNewBrowserWindow({ "private": aIsPrivate }); - yield TabStateFlusher.flushWindow(win); - let data = JSON.parse(ss.getClosedWindowData())[0]; - is(ss.getClosedWindowCount(), 1, "Check that the closed window count hasn't changed"); - ok(JSON.stringify(data).indexOf(aValue) > -1, - "Check the closed window data was stored correctly"); - registerCleanupFunction(() => BrowserTestUtils.closeWindow(win)); - }); -} - -add_task(function* init() { - forgetClosedWindows(); - while (ss.getClosedTabCount(window) > 0) { - ss.forgetClosedTab(window, 0); - } -}); - -add_task(function* main() { - yield promiseTestOpenCloseWindow(false, TESTS[0]); - yield promiseTestOpenCloseWindow(true, TESTS[1]); - yield promiseTestOnWindow(false, TESTS[0].value); - yield promiseTestOnWindow(true, TESTS[0].value); -}); - diff --git a/browser/components/sessionstore/test/browser_394759_purge.js b/browser/components/sessionstore/test/browser_394759_purge.js deleted file mode 100644 index 75144aba1..000000000 --- a/browser/components/sessionstore/test/browser_394759_purge.js +++ /dev/null @@ -1,130 +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/. */ - -Components.utils.import("resource://gre/modules/ForgetAboutSite.jsm"); - -function waitForClearHistory(aCallback) { - let observer = { - observe: function(aSubject, aTopic, aData) { - Services.obs.removeObserver(this, "browser:purge-domain-data"); - setTimeout(aCallback, 0); - } - }; - Services.obs.addObserver(observer, "browser:purge-domain-data", false); -} - -function test() { - waitForExplicitFinish(); - // utility functions - function countClosedTabsByTitle(aClosedTabList, aTitle) { - return aClosedTabList.filter(aData => aData.title == aTitle).length; - } - - function countOpenTabsByTitle(aOpenTabList, aTitle) { - return aOpenTabList.filter(aData => aData.entries.some(aEntry => aEntry.title == aTitle)).length; - } - - // backup old state - let oldState = ss.getBrowserState(); - let oldState_wins = JSON.parse(oldState).windows.length; - if (oldState_wins != 1) - ok(false, "oldState in test_purge has " + oldState_wins + " windows instead of 1"); - - // create a new state for testing - const REMEMBER = Date.now(), FORGET = Math.random(); - let testState = { - windows: [ { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 } ], - _closedWindows : [ - // _closedWindows[0] - { - tabs: [ - { entries: [{ url: "http://example.com/", title: REMEMBER }] }, - { entries: [{ url: "http://mozilla.org/", title: FORGET }] } - ], - selected: 2, - title: "mozilla.org", - _closedTabs: [] - }, - // _closedWindows[1] - { - tabs: [ - { entries: [{ url: "http://mozilla.org/", title: FORGET }] }, - { entries: [{ url: "http://example.com/", title: REMEMBER }] }, - { entries: [{ url: "http://example.com/", title: REMEMBER }] }, - { entries: [{ url: "http://mozilla.org/", title: FORGET }] }, - { entries: [{ url: "http://example.com/", title: REMEMBER }] } - ], - selected: 5, - _closedTabs: [] - }, - // _closedWindows[2] - { - tabs: [ - { entries: [{ url: "http://example.com/", title: REMEMBER }] } - ], - selected: 1, - _closedTabs: [ - { - state: { - entries: [ - { url: "http://mozilla.org/", title: FORGET }, - { url: "http://mozilla.org/again", title: "doesn't matter" } - ] - }, - pos: 1, - title: FORGET - }, - { - state: { - entries: [ - { url: "http://example.com", title: REMEMBER } - ] - }, - title: REMEMBER - } - ] - } - ] - }; - - // set browser to test state - ss.setBrowserState(JSON.stringify(testState)); - - // purge domain & check that we purged correctly for closed windows - ForgetAboutSite.removeDataFromDomain("mozilla.org"); - waitForClearHistory(function() { - let closedWindowData = JSON.parse(ss.getClosedWindowData()); - - // First set of tests for _closedWindows[0] - tests basics - let win = closedWindowData[0]; - is(win.tabs.length, 1, "1 tab was removed"); - is(countOpenTabsByTitle(win.tabs, FORGET), 0, - "The correct tab was removed"); - is(countOpenTabsByTitle(win.tabs, REMEMBER), 1, - "The correct tab was remembered"); - is(win.selected, 1, "Selected tab has changed"); - is(win.title, REMEMBER, "The window title was correctly updated"); - - // Test more complicated case - win = closedWindowData[1]; - is(win.tabs.length, 3, "2 tabs were removed"); - is(countOpenTabsByTitle(win.tabs, FORGET), 0, - "The correct tabs were removed"); - is(countOpenTabsByTitle(win.tabs, REMEMBER), 3, - "The correct tabs were remembered"); - is(win.selected, 3, "Selected tab has changed"); - is(win.title, REMEMBER, "The window title was correctly updated"); - - // Tests handling of _closedTabs - win = closedWindowData[2]; - is(countClosedTabsByTitle(win._closedTabs, REMEMBER), 1, - "The correct number of tabs were removed, and the correct ones"); - is(countClosedTabsByTitle(win._closedTabs, FORGET), 0, - "All tabs to be forgotten were indeed removed"); - - // restore pre-test state - ss.setBrowserState(oldState); - finish(); - }); -} diff --git a/browser/components/sessionstore/test/browser_423132.js b/browser/components/sessionstore/test/browser_423132.js deleted file mode 100644 index 584002cff..000000000 --- a/browser/components/sessionstore/test/browser_423132.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; - -/** - * Tests that cookies are stored and restored correctly - * by sessionstore (bug 423132). - */ -add_task(function*() { - const testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_423132_sample.html"; - - Services.cookies.removeAll(); - // make sure that sessionstore.js can be forced to be created by setting - // the interval pref to 0 - yield SpecialPowers.pushPrefEnv({ - set: [["browser.sessionstore.interval", 0]] - }); - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let browser = win.gBrowser.selectedBrowser; - browser.loadURI(testURL); - yield BrowserTestUtils.browserLoaded(browser); - - yield TabStateFlusher.flush(browser); - - // get the sessionstore state for the window - let state = ss.getWindowState(win); - - // verify our cookie got set during pageload - let enumerator = Services.cookies.enumerator; - let cookie; - let i = 0; - while (enumerator.hasMoreElements()) { - cookie = enumerator.getNext().QueryInterface(Ci.nsICookie); - i++; - } - Assert.equal(i, 1, "expected one cookie"); - - // remove the cookie - Services.cookies.removeAll(); - - // restore the window state - ss.setWindowState(win, state, true); - - // at this point, the cookie should be restored... - enumerator = Services.cookies.enumerator; - let cookie2; - while (enumerator.hasMoreElements()) { - cookie2 = enumerator.getNext().QueryInterface(Ci.nsICookie); - if (cookie.name == cookie2.name) - break; - } - is(cookie.name, cookie2.name, "cookie name successfully restored"); - is(cookie.value, cookie2.value, "cookie value successfully restored"); - is(cookie.path, cookie2.path, "cookie path successfully restored"); - - // clean up - Services.cookies.removeAll(); - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/sessionstore/test/browser_423132_sample.html b/browser/components/sessionstore/test/browser_423132_sample.html deleted file mode 100644 index 6ff7e7aa3..000000000 --- a/browser/components/sessionstore/test/browser_423132_sample.html +++ /dev/null @@ -1,14 +0,0 @@ -<!DOCTYPE HTML> -<html> -<head> - <meta charset="utf-8"> - <script type="text/javascript"> - // generate an enormous random number... - var r = Math.floor(Math.random() * Math.pow(2, 62)).toString(); - - // ... and use it to set a randomly named cookie - document.cookie = r + "=value; path=/ohai"; - </script> -<body> -</body> -</html> diff --git a/browser/components/sessionstore/test/browser_447951.js b/browser/components/sessionstore/test/browser_447951.js deleted file mode 100644 index a7b6a5ee8..000000000 --- a/browser/components/sessionstore/test/browser_447951.js +++ /dev/null @@ -1,65 +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/. */ - -function test() { - /** Test for Bug 447951 **/ - - waitForExplicitFinish(); - const baseURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_447951_sample.html#"; - - // Make sure the functionality added in bug 943339 doesn't affect the results - gPrefService.setIntPref("browser.sessionstore.max_serialize_back", -1); - gPrefService.setIntPref("browser.sessionstore.max_serialize_forward", -1); - registerCleanupFunction(function () { - gPrefService.clearUserPref("browser.sessionstore.max_serialize_back"); - gPrefService.clearUserPref("browser.sessionstore.max_serialize_forward"); - }); - - let tab = gBrowser.addTab(); - promiseBrowserLoaded(tab.linkedBrowser).then(() => { - let tabState = { entries: [] }; - let max_entries = gPrefService.getIntPref("browser.sessionhistory.max_entries"); - for (let i = 0; i < max_entries; i++) - tabState.entries.push({ url: baseURL + i }); - - promiseTabState(tab, tabState).then(() => { - return TabStateFlusher.flush(tab.linkedBrowser); - }).then(() => { - tabState = JSON.parse(ss.getTabState(tab)); - is(tabState.entries.length, max_entries, "session history filled to the limit"); - is(tabState.entries[0].url, baseURL + 0, "... but not more"); - - // visit yet another anchor (appending it to session history) - ContentTask.spawn(tab.linkedBrowser, null, function() { - content.window.document.querySelector("a").click(); - }).then(flushAndCheck); - - function flushAndCheck() { - TabStateFlusher.flush(tab.linkedBrowser).then(check); - } - - function check() { - tabState = JSON.parse(ss.getTabState(tab)); - if (tab.linkedBrowser.currentURI.spec != baseURL + "end") { - // It may take a few passes through the event loop before we - // get the right URL. - executeSoon(flushAndCheck); - return; - } - - is(tab.linkedBrowser.currentURI.spec, baseURL + "end", - "the new anchor was loaded"); - is(tabState.entries[tabState.entries.length - 1].url, baseURL + "end", - "... and ignored"); - is(tabState.entries[0].url, baseURL + 1, - "... and the first item was removed"); - - // clean up - gBrowser.removeTab(tab); - finish(); - } - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_447951_sample.html b/browser/components/sessionstore/test/browser_447951_sample.html deleted file mode 100644 index 00282f25e..000000000 --- a/browser/components/sessionstore/test/browser_447951_sample.html +++ /dev/null @@ -1,5 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Testcase for bug 447951</title> - -<a href="#end">click me</a> diff --git a/browser/components/sessionstore/test/browser_454908.js b/browser/components/sessionstore/test/browser_454908.js deleted file mode 100644 index fb8206e2f..000000000 --- a/browser/components/sessionstore/test/browser_454908.js +++ /dev/null @@ -1,47 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_454908_sample.html"; -const PASS = "pwd-" + Math.random(); - -/** - * Bug 454908 - Don't save/restore values of password fields. - */ -add_task(function* test_dont_save_passwords() { - // Make sure we do save form data. - Services.prefs.clearUserPref("browser.sessionstore.privacy_level"); - - // Add a tab with a password field. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Fill in some values. - let usernameValue = "User " + Math.random(); - yield setInputValue(browser, {id: "username", value: usernameValue}); - yield setInputValue(browser, {id: "passwd", value: PASS}); - - // Close and restore the tab. - yield promiseRemoveTab(tab); - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that password fields aren't saved/restored. - let username = yield getInputValue(browser, {id: "username"}); - is(username, usernameValue, "username was saved/restored"); - let passwd = yield getInputValue(browser, {id: "passwd"}); - is(passwd, "", "password wasn't saved/restored"); - - // Write to disk and read our file. - yield forceSaveState(); - yield promiseForEachSessionRestoreFile((state, key) => - // Ensure that we have not saved our password. - ok(!state.includes(PASS), "password has not been written to file " + key) - ); - - // Cleanup. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_454908_sample.html b/browser/components/sessionstore/test/browser_454908_sample.html deleted file mode 100644 index 02f40bf20..000000000 --- a/browser/components/sessionstore/test/browser_454908_sample.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<title>Test for bug 454908</title> - -<h3>Dummy Login</h3> -<form> -<p>Username: <input type="text" id="username"> -<p>Password: <input type="password" id="passwd"> -</form> diff --git a/browser/components/sessionstore/test/browser_456342.js b/browser/components/sessionstore/test/browser_456342.js deleted file mode 100644 index d7ed33ee5..000000000 --- a/browser/components/sessionstore/test/browser_456342.js +++ /dev/null @@ -1,49 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_456342_sample.xhtml"; - -/** - * Bug 456342 - Restore values from non-standard input field types. - */ -add_task(function test_restore_nonstandard_input_values() { - // Add tab with various non-standard input field types. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Fill in form values. - let expectedValue = Math.random(); - yield setFormElementValues(browser, {value: expectedValue}); - - // Remove tab and check collected form data. - yield promiseRemoveTab(tab); - let undoItems = JSON.parse(ss.getClosedTabData(window)); - let savedFormData = undoItems[0].state.formdata; - - let countGood = 0, countBad = 0; - for (let id of Object.keys(savedFormData.id)) { - if (savedFormData.id[id] == expectedValue) { - countGood++; - } else { - countBad++; - } - } - - for (let exp of Object.keys(savedFormData.xpath)) { - if (savedFormData.xpath[exp] == expectedValue) { - countGood++; - } else { - countBad++; - } - } - - is(countGood, 4, "Saved text for non-standard input fields"); - is(countBad, 0, "Didn't save text for ignored field types"); -}); - -function setFormElementValues(browser, data) { - return sendMessage(browser, "ss-test:setFormElementValues", data); -} diff --git a/browser/components/sessionstore/test/browser_456342_sample.xhtml b/browser/components/sessionstore/test/browser_456342_sample.xhtml deleted file mode 100644 index a08777a8d..000000000 --- a/browser/components/sessionstore/test/browser_456342_sample.xhtml +++ /dev/null @@ -1,36 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> - -<head><title>Test for bug 456342</title></head> - -<body> -<form> -<h3>Non-standard <input>s</h3> -<p>Search <input type="search" id="searchTerm"/></p> -<p>Image Search: <input type="image search" /></p> -<p>Autocomplete: <input type="autocomplete" name="fill-in"/></p> -<p>Mistyped: <input type="txet" name="mistyped"/></p> - -<h3>Ignored types</h3> -<input type="hidden" name="hideme"/> -<input type="HIDDEN" name="hideme2"/> -<input type="submit" name="submit"/> -<input type="reset" name="reset"/> -<input type="image" name="image"/> -<input type="button" name="button"/> -<input type="password" name="password"/> -<input type="PassWord" name="password2"/> -<input type="PASSWORD" name="password3"/> -<input autocomplete="off" name="auto1"/> -<input type="text" autocomplete="OFF" name="auto2"/> -<textarea autocomplete="off" name="auto3"/> -<select autocomplete="off" name="auto4"> - <option value="1" selected="true"/> - <option value="2"/> - <option value="3"/> -</select> -</form> - -</body> -</html> diff --git a/browser/components/sessionstore/test/browser_459906.js b/browser/components/sessionstore/test/browser_459906.js deleted file mode 100644 index cadab3e5c..000000000 --- a/browser/components/sessionstore/test/browser_459906.js +++ /dev/null @@ -1,62 +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/. */ - -function test() { - /** Test for Bug 459906 **/ - - waitForExplicitFinish(); - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_459906_sample.html"; - let uniqueValue = "<b>Unique:</b> " + Date.now(); - - var frameCount = 0; - let tab = gBrowser.addTab(testURL); - tab.linkedBrowser.addEventListener("load", function(aEvent) { - // wait for all frames to load completely - if (frameCount++ < 2) - return; - tab.linkedBrowser.removeEventListener("load", arguments.callee, true); - - let iframes = tab.linkedBrowser.contentWindow.frames; - iframes[1].document.body.innerHTML = uniqueValue; - - frameCount = 0; - let tab2 = gBrowser.duplicateTab(tab); - tab2.linkedBrowser.addEventListener("load", function(aEvent) { - // wait for all frames to load (and reload!) completely - if (frameCount++ < 2) - return; - tab2.linkedBrowser.removeEventListener("load", arguments.callee, true); - - executeSoon(function() { - let iframes = tab2.linkedBrowser.contentWindow.frames; - if (iframes[1].document.body.innerHTML !== uniqueValue) { - // Poll again the value, since we can't ensure to run - // after SessionStore has injected innerHTML value. - // See bug 521802. - info("Polling for innerHTML value"); - setTimeout(arguments.callee, 100); - return; - } - - is(iframes[1].document.body.innerHTML, uniqueValue, - "rich textarea's content correctly duplicated"); - - let innerDomain = null; - try { - innerDomain = iframes[0].document.domain; - } - catch (ex) { /* throws for chrome: documents */ } - is(innerDomain, "mochi.test", "XSS exploit prevented!"); - - // clean up - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); - - finish(); - }); - }, true); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_459906_empty.html b/browser/components/sessionstore/test/browser_459906_empty.html deleted file mode 100644 index e01aaa339..000000000 --- a/browser/components/sessionstore/test/browser_459906_empty.html +++ /dev/null @@ -1,3 +0,0 @@ -<title>Cross Domain File for bug 459906</title> - -cheers from localhost diff --git a/browser/components/sessionstore/test/browser_459906_sample.html b/browser/components/sessionstore/test/browser_459906_sample.html deleted file mode 100644 index 39b789776..000000000 --- a/browser/components/sessionstore/test/browser_459906_sample.html +++ /dev/null @@ -1,41 +0,0 @@ -<!-- Testcase originally by David Bloom <bloom@google.com> --> - -<!DOCTYPE html> -<title>Test for bug 459906</title> - -<body> -<iframe src="data:text/html;charset=utf-8,not_on_localhost"></iframe> -<iframe></iframe> - -<script type="application/javascript"> - var loadCount = 0; - frames[0].addEventListener("DOMContentLoaded", handleLoad, false); - frames[1].addEventListener("DOMContentLoaded", handleLoad, false); - function handleLoad() { - if (++loadCount < 2) - return; - frames[0].removeEventListener("DOMContentLoaded", handleLoad, false); - frames[1].removeEventListener("DOMContentLoaded", handleLoad, false); - frames[0].document.designMode = "on"; - frames[0].document.__defineGetter__("designMode", function() { - // inject a cross domain file ... - var documentInjected = false; - document.getElementsByTagName("iframe")[0].onload = - function() { documentInjected = true; }; - frames[0].location = "browser_459906_empty.html"; - - // ... and ensure that it has time to load - for (var c = 0; !documentInjected && c < 20; c++) { - var r = new XMLHttpRequest(); - r.open("GET", location.href, false); - r.overrideMimeType("text/plain"); - r.send(null); - } - - return "on"; - }); - - frames[1].document.designMode = "on"; - }; -</script> -</body> diff --git a/browser/components/sessionstore/test/browser_461634.js b/browser/components/sessionstore/test/browser_461634.js deleted file mode 100644 index 01d3a4b0d..000000000 --- a/browser/components/sessionstore/test/browser_461634.js +++ /dev/null @@ -1,85 +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/. */ - -Cu.import("resource:///modules/sessionstore/SessionStore.jsm"); - -function test() { - /** Test for Bug 461634 **/ - - waitForExplicitFinish(); - - const REMEMBER = Date.now(), FORGET = Math.random(); - let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [ - { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER }, - { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://www.example.net/" }] }, title: REMEMBER }, - ] }] }; - let remember_count = 2; - - function countByTitle(aClosedTabList, aTitle) { - return aClosedTabList.filter(aData => aData.title == aTitle).length; - } - - function testForError(aFunction) { - try { - aFunction(); - return false; - } - catch (ex) { - return ex.name == "NS_ERROR_ILLEGAL_VALUE"; - } - } - - // Open a window and add the above closed tab list. - let newWin = openDialog(location, "", "chrome,all,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", - test_state.windows[0]._closedTabs.length); - ss.setWindowState(newWin, JSON.stringify(test_state), true); - - let closedTabs = SessionStore.getClosedTabData(newWin, false); - - // Verify that non JSON serialized data is the same as JSON serialized data. - is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin), - "Non-serialized data is the same as serialized data") - - is(closedTabs.length, test_state.windows[0]._closedTabs.length, - "Closed tab list has the expected length"); - is(countByTitle(closedTabs, FORGET), - test_state.windows[0]._closedTabs.length - remember_count, - "The correct amout of tabs are to be forgotten"); - is(countByTitle(closedTabs, REMEMBER), remember_count, - "Everything is set up"); - - // All of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE. - ok(testForError(() => ss.forgetClosedTab({}, 0)), - "Invalid window for forgetClosedTab throws"); - ok(testForError(() => ss.forgetClosedTab(newWin, -1)), - "Invalid tab for forgetClosedTab throws"); - ok(testForError(() => ss.forgetClosedTab(newWin, test_state.windows[0]._closedTabs.length + 1)), - "Invalid tab for forgetClosedTab throws"); - - // Remove third tab, then first tab. - ss.forgetClosedTab(newWin, 2); - ss.forgetClosedTab(newWin, null); - - closedTabs = SessionStore.getClosedTabData(newWin, false); - - // Verify that non JSON serialized data is the same as JSON serialized data. - is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin), - "Non-serialized data is the same as serialized data") - - is(closedTabs.length, remember_count, - "The correct amout of tabs was removed"); - is(countByTitle(closedTabs, FORGET), 0, - "All tabs specifically forgotten were indeed removed"); - is(countByTitle(closedTabs, REMEMBER), remember_count, - "... and tabs not specifically forgetten weren't"); - - // Clean up. - gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo"); - BrowserTestUtils.closeWindow(newWin).then(finish); - }); -} diff --git a/browser/components/sessionstore/test/browser_461743.js b/browser/components/sessionstore/test/browser_461743.js deleted file mode 100644 index 263fff5f2..000000000 --- a/browser/components/sessionstore/test/browser_461743.js +++ /dev/null @@ -1,39 +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/. */ - -function test() { - /** Test for Bug 461743 **/ - - waitForExplicitFinish(); - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_461743_sample.html"; - - let frameCount = 0; - let tab = gBrowser.addTab(testURL); - tab.linkedBrowser.addEventListener("load", function(aEvent) { - // Wait for all frames to load completely. - if (frameCount++ < 2) - return; - tab.linkedBrowser.removeEventListener("load", arguments.callee, true); - let tab2 = gBrowser.duplicateTab(tab); - tab2.linkedBrowser.addEventListener("461743", function(aEvent) { - tab2.linkedBrowser.removeEventListener("461743", arguments.callee, true); - is(aEvent.data, "done", "XSS injection was attempted"); - - executeSoon(function() { - let iframes = tab2.linkedBrowser.contentWindow.frames; - let innerHTML = iframes[1].document.body.innerHTML; - isnot(innerHTML, Components.utils.reportError.toString(), - "chrome access denied!"); - - // Clean up. - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); - - finish(); - }); - }, true, true); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_461743_sample.html b/browser/components/sessionstore/test/browser_461743_sample.html deleted file mode 100644 index 80c9e612a..000000000 --- a/browser/components/sessionstore/test/browser_461743_sample.html +++ /dev/null @@ -1,56 +0,0 @@ -<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> --> - -<!DOCTYPE html> -<title>Test for bug 461743</title> - -<body> -<iframe src="data:text/html;charset=utf-8,empty"></iframe> -<iframe></iframe> - -<script type="application/javascript"> - var chromeUrl = "chrome://global/content/mozilla.xhtml"; - var exploitUrl = "javascript:try { document.body.innerHTML = Components.utils.reportError; } catch (ex) { }"; - - var loadCount = 0; - frames[0].addEventListener("DOMContentLoaded", handleLoad, false); - frames[1].addEventListener("DOMContentLoaded", handleLoad, false); - function handleLoad() { - if (++loadCount < 2) - return; - frames[0].removeEventListener("DOMContentLoaded", handleLoad, false); - frames[1].removeEventListener("DOMContentLoaded", handleLoad, false); - - var flip = 0; - MutationEvent.prototype.toString = function() { - return flip++ == 0 ? chromeUrl : exploitUrl; - }; - - var href = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(frames[1].location), "href").get; - var loadChrome = { handleEvent: href }; - var loadExploit = { handleEvent: href }; - - function delay() { - var xhr = new XMLHttpRequest(); - xhr.open("GET", location.href, false); - xhr.send(null); - } - function done() { - var event = new MessageEvent('461743', { bubbles: true, cancelable: false, - data: "done", origin: location.href, - source: window }); - document.dispatchEvent(event); - frames[0].document.removeEventListener("DOMNodeInserted", loadChrome, true); - frames[0].document.removeEventListener("DOMNodeInserted", delay, true); - frames[0].document.removeEventListener("DOMNodeInserted", loadExploit, true); - frames[0].document.removeEventListener("DOMNodeInserted", done, true); - } - - frames[0].document.addEventListener("DOMNodeInserted", loadChrome, true); - frames[0].document.addEventListener("DOMNodeInserted", delay, true); - frames[0].document.addEventListener("DOMNodeInserted", loadExploit, true); - frames[0].document.addEventListener("DOMNodeInserted", done, true); - - frames[0].document.designMode = "on"; - }; -</script> -</body> diff --git a/browser/components/sessionstore/test/browser_463205.js b/browser/components/sessionstore/test/browser_463205.js deleted file mode 100644 index ad3f22794..000000000 --- a/browser/components/sessionstore/test/browser_463205.js +++ /dev/null @@ -1,40 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_463205_sample.html"; - -/** - * Bug 463205 - Check URLs before restoring form data to make sure a malicious - * website can't modify frame URLs and make us inject form data into the wrong - * web pages. - */ -add_task(function test_check_urls_before_restoring() { - // Add a blank tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Restore form data with a valid URL. - yield promiseTabState(tab, getState(URL)); - - let value = yield getInputValue(browser, {id: "text"}); - is(value, "foobar", "value was restored"); - - // Restore form data with an invalid URL. - yield promiseTabState(tab, getState("http://example.com/")); - - value = yield getInputValue(browser, {id: "text"}); - is(value, "", "value was not restored"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -function getState(url) { - return JSON.stringify({ - entries: [{url: URL}], - formdata: {url: url, id: {text: "foobar"}} - }); -} diff --git a/browser/components/sessionstore/test/browser_463205_sample.html b/browser/components/sessionstore/test/browser_463205_sample.html deleted file mode 100644 index 6591401b6..000000000 --- a/browser/components/sessionstore/test/browser_463205_sample.html +++ /dev/null @@ -1,7 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>bug 463205</title> - -<body> - <input type="text" id="text" /> -</body> diff --git a/browser/components/sessionstore/test/browser_463206.js b/browser/components/sessionstore/test/browser_463206.js deleted file mode 100644 index 99ee8373e..000000000 --- a/browser/components/sessionstore/test/browser_463206.js +++ /dev/null @@ -1,53 +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_URL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_463206_sample.html"; - -add_task(function* () { - // Add a new tab. - let tab = gBrowser.addTab(TEST_URL); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - // "Type in" some random values. - yield ContentTask.spawn(tab.linkedBrowser, null, function* () { - function typeText(aTextField, aValue) { - aTextField.value = aValue; - - let event = aTextField.ownerDocument.createEvent("UIEvents"); - event.initUIEvent("input", true, true, aTextField.ownerGlobal, 0); - aTextField.dispatchEvent(event); - } - - typeText(content.document.getElementById("out1"), Date.now()); - typeText(content.document.getElementsByName("1|#out2")[0], Math.random()); - typeText(content.frames[0].frames[1].document.getElementById("in1"), new Date()); - }); - - // Duplicate the tab. - let tab2 = gBrowser.duplicateTab(tab); - yield promiseTabRestored(tab2); - - // Query a few values from the top and its child frames. - yield ContentTask.spawn(tab2.linkedBrowser, null, function* () { - Assert.notEqual(content.document.getElementById("out1").value, - content.frames[1].document.getElementById("out1").value, - "text isn't reused for frames"); - Assert.notEqual(content.document.getElementsByName("1|#out2")[0].value, - "", "text containing | and # is correctly restored"); - Assert.equal(content.frames[1].document.getElementById("out2").value, - "", "id prefixes can't be faked"); - // Disabled for now, Bug 588077 - //Assert.equal(content.frames[0].frames[1].document.getElementById("in1").value, - // "", "id prefixes aren't mixed up"); - Assert.equal(content.frames[1].frames[0].document.getElementById("in1").value, - "", "id prefixes aren't mixed up"); - }); - - // Cleanup. - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_463206_sample.html b/browser/components/sessionstore/test/browser_463206_sample.html deleted file mode 100644 index 0d31f2906..000000000 --- a/browser/components/sessionstore/test/browser_463206_sample.html +++ /dev/null @@ -1,11 +0,0 @@ -<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> --> - -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Test for bug 463206</title> - -<iframe src="data:text/html;charset=utf-8,<iframe></iframe><iframe%20src='data:text/html;charset=utf-8,<input%2520id=%2522in1%2522>'></iframe>"></iframe> -<iframe src="data:text/html;charset=utf-8,<input%20id='out1'><input%20id='out2'><iframe%20src='data:text/html;charset=utf-8,<input%2520id=%2522in1%2522>'>"></iframe> - -<input id="out1"> -<input name="1|#out2"> diff --git a/browser/components/sessionstore/test/browser_464199.js b/browser/components/sessionstore/test/browser_464199.js deleted file mode 100644 index 36f07832c..000000000 --- a/browser/components/sessionstore/test/browser_464199.js +++ /dev/null @@ -1,85 +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/. */ - -Components.utils.import("resource://gre/modules/ForgetAboutSite.jsm"); - -function waitForClearHistory(aCallback) { - let observer = { - observe: function(aSubject, aTopic, aData) { - Services.obs.removeObserver(this, "browser:purge-domain-data"); - setTimeout(aCallback, 0); - } - }; - Services.obs.addObserver(observer, "browser:purge-domain-data", false); -} - -function test() { - /** Test for Bug 464199 **/ - - waitForExplicitFinish(); - - const REMEMBER = Date.now(), FORGET = Math.random(); - let test_state = { windows: [{ "tabs": [{ "entries": [] }], _closedTabs: [ - { state: { entries: [{ url: "http://www.example.net/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://www.example.org/" }] }, title: REMEMBER }, - { state: { entries: [{ url: "http://www.example.net/" }, - { url: "http://www.example.org/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://example.net/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://sub.example.net/" }] }, title: FORGET }, - { state: { entries: [{ url: "http://www.example.net:8080/" }] }, title: FORGET }, - { state: { entries: [{ url: "about:license" }] }, title: REMEMBER }, - { state: { entries: [{ url: "http://www.example.org/frameset", - children: [ - { url: "http://www.example.org/frame" }, - { url: "http://www.example.org:8080/frame2" } - ] }] }, title: REMEMBER }, - { state: { entries: [{ url: "http://www.example.org/frameset", - children: [ - { url: "http://www.example.org/frame" }, - { url: "http://www.example.net/frame" } - ] }] }, title: FORGET }, - { state: { entries: [{ url: "http://www.example.org/form", - formdata: { id: { "url": "http://www.example.net/" } } - }] }, title: REMEMBER }, - { state: { entries: [{ url: "http://www.example.org/form" }], - extData: { "setTabValue": "http://example.net:80" } }, title: REMEMBER } - ] }] }; - let remember_count = 5; - - function countByTitle(aClosedTabList, aTitle) { - return aClosedTabList.filter(aData => aData.title == aTitle).length; - } - - // open a window and add the above closed tab list - let newWin = openDialog(location, "", "chrome,all,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", - test_state.windows[0]._closedTabs.length); - ss.setWindowState(newWin, JSON.stringify(test_state), true); - - let closedTabs = JSON.parse(ss.getClosedTabData(newWin)); - is(closedTabs.length, test_state.windows[0]._closedTabs.length, - "Closed tab list has the expected length"); - is(countByTitle(closedTabs, FORGET), - test_state.windows[0]._closedTabs.length - remember_count, - "The correct amout of tabs are to be forgotten"); - is(countByTitle(closedTabs, REMEMBER), remember_count, - "Everything is set up."); - - ForgetAboutSite.removeDataFromDomain("example.net"); - waitForClearHistory(function() { - closedTabs = JSON.parse(ss.getClosedTabData(newWin)); - is(closedTabs.length, remember_count, - "The correct amout of tabs was removed"); - is(countByTitle(closedTabs, FORGET), 0, - "All tabs to be forgotten were indeed removed"); - is(countByTitle(closedTabs, REMEMBER), remember_count, - "... and tabs to be remembered weren't."); - - // clean up - gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo"); - BrowserTestUtils.closeWindow(newWin).then(finish); - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_464620_a.html b/browser/components/sessionstore/test/browser_464620_a.html deleted file mode 100644 index 1f03c92c7..000000000 --- a/browser/components/sessionstore/test/browser_464620_a.html +++ /dev/null @@ -1,54 +0,0 @@ -<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> --> - -<title>Test for bug 464620 (injection on input)</title> - -<iframe></iframe> -<iframe onload="setup()"></iframe> - -<script> - var targetUrl = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_464620_xd.html"; - var firstPass; - - function setup() { - if (firstPass !== undefined) - return; - firstPass = frames[1].location.href == "about:blank"; - if (firstPass) { - frames[0].location = 'data:text/html;charset=utf-8,<body onload="if (parent.firstPass) parent.step();"><input id="x" oninput="parent.xss()">XXX</body>'; - } - frames[1].location = targetUrl; - } - - function step() { - var x = frames[0].document.getElementById("x"); - if (x.value == "") - x.value = "ready"; - x.style.display = "none"; - frames[0].document.designMode = "on"; - } - - function xss() { - step(); - - var documentInjected = false; - document.getElementsByTagName("iframe")[0].onload = - function() { documentInjected = true; }; - frames[0].location = targetUrl; - - for (var c = 0; !documentInjected && c < 20; c++) { - var r = new XMLHttpRequest(); - r.open("GET", location.href, false); - r.overrideMimeType("text/plain"); - r.send(null); - } - document.getElementById("state").textContent = "done"; - - var event = new MessageEvent('464620_a', { bubbles: true, cancelable: false, - data: "done", origin: location.href, - source: window }); - document.dispatchEvent(event); - } -</script> - -<p id="state">pending</p> diff --git a/browser/components/sessionstore/test/browser_464620_a.js b/browser/components/sessionstore/test/browser_464620_a.js deleted file mode 100644 index 9756fa703..000000000 --- a/browser/components/sessionstore/test/browser_464620_a.js +++ /dev/null @@ -1,48 +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/. */ - -function test() { - /** Test for Bug 464620 (injection on input) **/ - - waitForExplicitFinish(); - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_464620_a.html"; - - var frameCount = 0; - let tab = gBrowser.addTab(testURL); - tab.linkedBrowser.addEventListener("load", function(aEvent) { - // wait for all frames to load completely - if (frameCount++ < 4) - return; - this.removeEventListener("load", arguments.callee, true); - - executeSoon(function() { - frameCount = 0; - let tab2 = gBrowser.duplicateTab(tab); - tab2.linkedBrowser.addEventListener("464620_a", function(aEvent) { - tab2.linkedBrowser.removeEventListener("464620_a", arguments.callee, true); - is(aEvent.data, "done", "XSS injection was attempted"); - - // let form restoration complete and take into account the - // setTimeout(..., 0) in sss_restoreDocument_proxy - executeSoon(function() { - setTimeout(function() { - let win = tab2.linkedBrowser.contentWindow; - isnot(win.frames[0].document.location, testURL, - "cross domain document was loaded"); - ok(!/XXX/.test(win.frames[0].document.body.innerHTML), - "no content was injected"); - - // clean up - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); - - finish(); - }, 0); - }); - }, true, true); - }); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_464620_b.html b/browser/components/sessionstore/test/browser_464620_b.html deleted file mode 100644 index 8c86d2152..000000000 --- a/browser/components/sessionstore/test/browser_464620_b.html +++ /dev/null @@ -1,58 +0,0 @@ -<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> --> - -<title>Test for bug 464620 (injection on DOM node insertion)</title> - -<iframe></iframe> -<iframe></iframe> -<iframe onload="setup()"></iframe> - -<script> - var targetUrl = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_464620_xd.html"; - var firstPass; - - function setup() { - if (firstPass !== undefined) - return; - firstPass = frames[2].location.href == "about:blank"; - if (firstPass) { - frames[0].location = 'data:text/html;charset=utf-8,<body onload="parent.step()">a</body>'; - frames[1].location = 'data:text/html;charset=utf-8,<body onload="document.designMode=\'on\';">XXX</body>'; - } - frames[2].location = targetUrl; - } - - function step() { - frames[0].document.designMode = "on"; - if (firstPass) - return; - - var body = frames[0].document.body; - body.addEventListener("DOMNodeInserted", function() { - body.removeEventListener("DOMNodeInserted", arguments.callee, true); - xss(); - }, true); - } - - function xss() { - var documentInjected = false; - document.getElementsByTagName("iframe")[1].onload = - function() { documentInjected = true; }; - frames[1].location = targetUrl; - - for (var c = 0; !documentInjected && c < 20; c++) { - var r = new XMLHttpRequest(); - r.open("GET", location.href, false); - r.overrideMimeType("text/plain"); - r.send(null); - } - document.getElementById("state").textContent = "done"; - - var event = new MessageEvent('464620_b', { bubbles: true, cancelable: false, - data: "done", origin: location.href, - source: window }); - document.dispatchEvent(event); - } -</script> - -<p id="state">pending</p> diff --git a/browser/components/sessionstore/test/browser_464620_b.js b/browser/components/sessionstore/test/browser_464620_b.js deleted file mode 100644 index cf23aa460..000000000 --- a/browser/components/sessionstore/test/browser_464620_b.js +++ /dev/null @@ -1,48 +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/. */ - -function test() { - /** Test for Bug 464620 (injection on DOM node insertion) **/ - - waitForExplicitFinish(); - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_464620_b.html"; - - var frameCount = 0; - let tab = gBrowser.addTab(testURL); - tab.linkedBrowser.addEventListener("load", function(aEvent) { - // wait for all frames to load completely - if (frameCount++ < 6) - return; - this.removeEventListener("load", arguments.callee, true); - - executeSoon(function() { - frameCount = 0; - let tab2 = gBrowser.duplicateTab(tab); - tab2.linkedBrowser.addEventListener("464620_b", function(aEvent) { - tab2.linkedBrowser.removeEventListener("464620_b", arguments.callee, true); - is(aEvent.data, "done", "XSS injection was attempted"); - - // let form restoration complete and take into account the - // setTimeout(..., 0) in sss_restoreDocument_proxy - executeSoon(function() { - setTimeout(function() { - let win = tab2.linkedBrowser.contentWindow; - isnot(win.frames[1].document.location, testURL, - "cross domain document was loaded"); - ok(!/XXX/.test(win.frames[1].document.body.innerHTML), - "no content was injected"); - - // clean up - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); - - finish(); - }, 0); - }); - }, true, true); - }); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_464620_xd.html b/browser/components/sessionstore/test/browser_464620_xd.html deleted file mode 100644 index 9ec51c4c7..000000000 --- a/browser/components/sessionstore/test/browser_464620_xd.html +++ /dev/null @@ -1,5 +0,0 @@ -<title>Cross Document File for bug 464620</title> - -<body onload="document.designMode='on';" bgcolor="red"> - This document is editable. -</body> diff --git a/browser/components/sessionstore/test/browser_465215.js b/browser/components/sessionstore/test/browser_465215.js deleted file mode 100644 index 3a0a7b9c5..000000000 --- a/browser/components/sessionstore/test/browser_465215.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; - -var uniqueName = "bug 465215"; -var uniqueValue1 = "as good as unique: " + Date.now(); -var uniqueValue2 = "as good as unique: " + Math.random(); - -add_task(function* () { - // set a unique value on a new, blank tab - let tab1 = gBrowser.addTab("about:blank"); - yield promiseBrowserLoaded(tab1.linkedBrowser); - ss.setTabValue(tab1, uniqueName, uniqueValue1); - - // duplicate the tab with that value - let tab2 = ss.duplicateTab(window, tab1); - yield promiseTabRestored(tab2); - is(ss.getTabValue(tab2, uniqueName), uniqueValue1, "tab value was duplicated"); - - ss.setTabValue(tab2, uniqueName, uniqueValue2); - isnot(ss.getTabValue(tab1, uniqueName), uniqueValue2, "tab values aren't sync'd"); - - // overwrite the tab with the value which should remove it - yield promiseTabState(tab1, {entries: []}); - is(ss.getTabValue(tab1, uniqueName), "", "tab value was cleared"); - - // clean up - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab1); -}); diff --git a/browser/components/sessionstore/test/browser_465223.js b/browser/components/sessionstore/test/browser_465223.js deleted file mode 100644 index 04f888b30..000000000 --- a/browser/components/sessionstore/test/browser_465223.js +++ /dev/null @@ -1,45 +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/. */ - -function test() { - /** Test for Bug 465223 **/ - - // test setup - waitForExplicitFinish(); - - let uniqueKey1 = "bug 465223.1"; - let uniqueKey2 = "bug 465223.2"; - let uniqueValue1 = "unik" + Date.now(); - let uniqueValue2 = "pi != " + Math.random(); - - // open a window and set a value on it - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - ss.setWindowValue(newWin, uniqueKey1, uniqueValue1); - - let newState = { windows: [{ tabs:[{ entries: [] }], extData: {} }] }; - newState.windows[0].extData[uniqueKey2] = uniqueValue2; - ss.setWindowState(newWin, JSON.stringify(newState), false); - - is(newWin.gBrowser.tabs.length, 2, - "original tab wasn't overwritten"); - is(ss.getWindowValue(newWin, uniqueKey1), uniqueValue1, - "window value wasn't overwritten when the tabs weren't"); - is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue2, - "new window value was correctly added"); - - newState.windows[0].extData[uniqueKey2] = uniqueValue1; - ss.setWindowState(newWin, JSON.stringify(newState), true); - - is(newWin.gBrowser.tabs.length, 1, - "original tabs were overwritten"); - is(ss.getWindowValue(newWin, uniqueKey1), "", - "window value was cleared"); - is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue1, - "window value was correctly overwritten"); - - // clean up - BrowserTestUtils.closeWindow(newWin).then(finish); - }); -} diff --git a/browser/components/sessionstore/test/browser_466937.js b/browser/components/sessionstore/test/browser_466937.js deleted file mode 100644 index 0a07caa0c..000000000 --- a/browser/components/sessionstore/test/browser_466937.js +++ /dev/null @@ -1,42 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_466937_sample.html"; - -/** - * Bug 466937 - Prevent file stealing with sessionstore. - */ -add_task(function test_prevent_file_stealing() { - // Add a tab with some file input fields. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Generate a path to a 'secret' file. - let file = Services.dirsvc.get("TmpD", Ci.nsIFile); - file.append("466937_test.file"); - file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666); - let testPath = file.path; - - // Fill in form values. - yield setInputValue(browser, {id: "reverse_thief", value: "/home/user/secret2"}); - yield setInputValue(browser, {id: "bystander", value: testPath}); - - // Duplicate and check form values. - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - let thief = yield getInputValue(browser2, {id: "thief"}); - is(thief, "", "file path wasn't set to text field value"); - let reverse_thief = yield getInputValue(browser2, {id: "reverse_thief"}); - is(reverse_thief, "", "text field value wasn't set to full file path"); - let bystander = yield getInputValue(browser2, {id: "bystander"}); - is(bystander, testPath, "normal case: file path was correctly preserved"); - - // Cleanup. - gBrowser.removeTab(tab); - gBrowser.removeTab(tab2); -}); diff --git a/browser/components/sessionstore/test/browser_466937_sample.html b/browser/components/sessionstore/test/browser_466937_sample.html deleted file mode 100644 index 1d46c649a..000000000 --- a/browser/components/sessionstore/test/browser_466937_sample.html +++ /dev/null @@ -1,22 +0,0 @@ -<!-- Testcase originally by <moz_bug_r_a4@yahoo.com> --> - -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Test for bug 466937</title> - -<input id="thief" value="/home/user/secret"> -<input type="file" id="reverse_thief"> -<input type="file" id="bystander"> - -<script> - window.addEventListener("DOMContentLoaded", function() { - window.removeEventListener("DOMContentLoaded", arguments.callee, false); - if (!document.location.hash) { - document.location.hash = "#ready"; - } - else { - document.getElementById("thief").type = "file"; - document.getElementById("reverse_thief").type = "text"; - } - }, false); -</script> diff --git a/browser/components/sessionstore/test/browser_467409-backslashplosion.js b/browser/components/sessionstore/test/browser_467409-backslashplosion.js deleted file mode 100644 index 0e990c614..000000000 --- a/browser/components/sessionstore/test/browser_467409-backslashplosion.js +++ /dev/null @@ -1,74 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -// Test Summary: -// 1. Open about:sessionrestore where formdata is a JS object, not a string -// 1a. Check that #sessionData on the page is readable after JSON.parse (skipped, checking formdata is sufficient) -// 1b. Check that there are no backslashes in the formdata -// 1c. Check that formdata doesn't require JSON.parse -// -// 2. Use the current state (currently about:sessionrestore with data) and then open that in a new instance of about:sessionrestore -// 2a. Check that there are no backslashes in the formdata -// 2b. Check that formdata doesn't require JSON.parse -// -// 3. [backwards compat] Use a stringified state as formdata when opening about:sessionrestore -// 3a. Make sure there are nodes in the tree on about:sessionrestore (skipped, checking formdata is sufficient) -// 3b. Check that there are no backslashes in the formdata -// 3c. Check that formdata doesn't require JSON.parse - -const CRASH_STATE = {windows: [{tabs: [{entries: [{url: "about:mozilla" }]}]}]}; -const STATE = createEntries(CRASH_STATE); -const STATE2 = createEntries({windows: [{tabs: [STATE]}]}); -const STATE3 = createEntries(JSON.stringify(CRASH_STATE)); - -function createEntries(sessionData) { - return { - entries: [{url: "about:sessionrestore"}], - formdata: {id: {sessionData: sessionData}, url: "about:sessionrestore"} - }; -} - -add_task(function test_nested_about_sessionrestore() { - // Prepare a blank tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // test 1 - yield promiseTabState(tab, STATE); - yield checkState("test1", tab); - - // test 2 - yield promiseTabState(tab, STATE2); - yield checkState("test2", tab); - - // test 3 - yield promiseTabState(tab, STATE3); - yield checkState("test3", tab); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -function* checkState(prefix, tab) { - // Flush and query tab state. - yield TabStateFlusher.flush(tab.linkedBrowser); - let {formdata} = JSON.parse(ss.getTabState(tab)); - - ok(formdata.id["sessionData"], prefix + ": we have form data for about:sessionrestore"); - - let sessionData_raw = JSON.stringify(formdata.id["sessionData"]); - ok(!/\\/.test(sessionData_raw), prefix + ": #sessionData contains no backslashes"); - info(sessionData_raw); - - let gotError = false; - try { - JSON.parse(formdata.id["sessionData"]); - } catch (e) { - info(prefix + ": got error: " + e); - gotError = true; - } - ok(gotError, prefix + ": attempting to JSON.parse form data threw error"); -} diff --git a/browser/components/sessionstore/test/browser_477657.js b/browser/components/sessionstore/test/browser_477657.js deleted file mode 100644 index 1a8ee3412..000000000 --- a/browser/components/sessionstore/test/browser_477657.js +++ /dev/null @@ -1,60 +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/. */ - -function test() { - /** Test for Bug 477657 **/ - waitForExplicitFinish(); - - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - let newState = { windows: [{ - tabs: [{ entries: [] }], - _closedTabs: [{ - state: { entries: [{ url: "about:" }]}, - title: "About:" - }], - sizemode: "maximized" - }] }; - - let uniqueKey = "bug 477657"; - let uniqueValue = "unik" + Date.now(); - - ss.setWindowValue(newWin, uniqueKey, uniqueValue); - is(ss.getWindowValue(newWin, uniqueKey), uniqueValue, - "window value was set before the window was overwritten"); - ss.setWindowState(newWin, JSON.stringify(newState), true); - - // use newWin.setTimeout(..., 0) to mirror sss_restoreWindowFeatures - newWin.setTimeout(function() { - is(ss.getWindowValue(newWin, uniqueKey), "", - "window value was implicitly cleared"); - - is(newWin.windowState, newWin.STATE_MAXIMIZED, - "the window was maximized"); - - is(JSON.parse(ss.getClosedTabData(newWin)).length, 1, - "the closed tab was added before the window was overwritten"); - delete newState.windows[0]._closedTabs; - delete newState.windows[0].sizemode; - ss.setWindowState(newWin, JSON.stringify(newState), true); - - newWin.setTimeout(function() { - is(JSON.parse(ss.getClosedTabData(newWin)).length, 0, - "closed tabs were implicitly cleared"); - - is(newWin.windowState, newWin.STATE_MAXIMIZED, - "the window remains maximized"); - newState.windows[0].sizemode = "normal"; - ss.setWindowState(newWin, JSON.stringify(newState), true); - - newWin.setTimeout(function() { - isnot(newWin.windowState, newWin.STATE_MAXIMIZED, - "the window was explicitly unmaximized"); - - BrowserTestUtils.closeWindow(newWin).then(finish); - }, 0); - }, 0); - }, 0); - }); -} diff --git a/browser/components/sessionstore/test/browser_480893.js b/browser/components/sessionstore/test/browser_480893.js deleted file mode 100644 index e3ddb39b7..000000000 --- a/browser/components/sessionstore/test/browser_480893.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; - -/** - * Tests that we get sent to the right page when the user clicks - * the "Close" button in about:sessionrestore - */ -add_task(function*() { - yield SpecialPowers.pushPrefEnv({ - "set": [ - ["browser.startup.page", 0], - ] - }); - - let tab = gBrowser.addTab("about:sessionrestore"); - gBrowser.selectedTab = tab; - let browser = tab.linkedBrowser; - yield BrowserTestUtils.browserLoaded(browser, false, "about:sessionrestore"); - - let doc = browser.contentDocument; - - // Click on the "Close" button after about:sessionrestore is loaded. - doc.getElementById("errorCancel").click(); - - yield BrowserTestUtils.browserLoaded(browser, false, "about:blank"); - - // Test that starting a new session loads the homepage (set to http://mochi.test:8888) - // if Firefox is configured to display a homepage at startup (browser.startup.page = 1) - let homepage = "http://mochi.test:8888/"; - yield SpecialPowers.pushPrefEnv({ - "set": [ - ["browser.startup.homepage", homepage], - ["browser.startup.page", 1], - ] - }); - - browser.loadURI("about:sessionrestore"); - yield BrowserTestUtils.browserLoaded(browser, false, "about:sessionrestore"); - doc = browser.contentDocument; - - // Click on the "Close" button after about:sessionrestore is loaded. - doc.getElementById("errorCancel").click(); - yield BrowserTestUtils.browserLoaded(browser); - - is(browser.currentURI.spec, homepage, "loaded page is the homepage"); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_485482.js b/browser/components/sessionstore/test/browser_485482.js deleted file mode 100644 index 68ec9941b..000000000 --- a/browser/components/sessionstore/test/browser_485482.js +++ /dev/null @@ -1,37 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_485482_sample.html"; - -/** - * Bug 485482 - Make sure that we produce valid XPath expressions even for very - * weird HTML documents. - */ -add_task(function test_xpath_exp_for_strange_documents() { - // Load a page with weird tag names. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Fill in some values. - let uniqueValue = Math.random(); - yield setInputValue(browser, {selector: "input[type=text]", value: uniqueValue}); - yield setInputChecked(browser, {selector: "input[type=checkbox]", checked: true}); - - // Duplicate the tab. - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - // Check that we generated valid XPath expressions to restore form values. - let text = yield getInputValue(browser2, {selector: "input[type=text]"}); - is(text, uniqueValue, "generated XPath expression was valid"); - let checkbox = yield getInputChecked(browser2, {selector: "input[type=checkbox]"}); - ok(checkbox, "generated XPath expression was valid"); - - // Cleanup. - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_485482_sample.html b/browser/components/sessionstore/test/browser_485482_sample.html deleted file mode 100644 index c2097b593..000000000 --- a/browser/components/sessionstore/test/browser_485482_sample.html +++ /dev/null @@ -1,12 +0,0 @@ -<!DOCTYPE html> -<title>Test for bug 485482</title> - -<bad=name> - <input type="text"> -</bad=name> - -<worse=name> - <l0c@l+na~e"'§> - <input type="checkbox" name="check"> Check - </l0c@l+na~e"'§> -</worse=name> diff --git a/browser/components/sessionstore/test/browser_485563.js b/browser/components/sessionstore/test/browser_485563.js deleted file mode 100644 index f4e6b31cc..000000000 --- a/browser/components/sessionstore/test/browser_485563.js +++ /dev/null @@ -1,26 +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/. */ - -function test() { - /** Test for Bug 485563 **/ - - waitForExplicitFinish(); - - let uniqueValue = Math.random() + "\u2028Second line\u2029Second paragraph\u2027"; - - let tab = gBrowser.addTab(); - promiseBrowserLoaded(tab.linkedBrowser).then(() => { - ss.setTabValue(tab, "bug485563", uniqueValue); - let tabState = JSON.parse(ss.getTabState(tab)); - is(tabState.extData["bug485563"], uniqueValue, - "unicode line separator wasn't over-encoded"); - ss.deleteTabValue(tab, "bug485563"); - ss.setTabState(tab, JSON.stringify(tabState)); - is(ss.getTabValue(tab, "bug485563"), uniqueValue, - "unicode line separator was correctly preserved"); - - gBrowser.removeTab(tab); - finish(); - }); -} diff --git a/browser/components/sessionstore/test/browser_490040.js b/browser/components/sessionstore/test/browser_490040.js deleted file mode 100644 index bc680c32f..000000000 --- a/browser/components/sessionstore/test/browser_490040.js +++ /dev/null @@ -1,65 +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/. */ - -// Only windows with open tabs are restorable. Windows where a lone tab is -// detached may have _closedTabs, but is left with just an empty tab. -const STATES = [{ - shouldBeAdded: true, - windowState: { - windows: [{ - tabs: [{ entries: [{ url: "http://example.com", title: "example.com" }] }], - selected: 1, - _closedTabs: [] - }] - } - }, { - shouldBeAdded: false, - windowState: { - windows: [{ - tabs: [{ entries: [] }], - _closedTabs: [] - }] - } - }, { - shouldBeAdded: false, - windowState: { - windows: [{ - tabs: [{ entries: [] }], - _closedTabs: [{ state: { entries: [{ url: "http://example.com", index: 1 }] } }] - }] - } - }, { - shouldBeAdded: false, - windowState: { - windows: [{ - tabs: [{ entries: [] }], - _closedTabs: [], - extData: { keyname: "pi != " + Math.random() } - }] - } - }]; - -add_task(function* test_bug_490040() { - for (let state of STATES) { - // Ensure we can store the window if needed. - let startingClosedWindowCount = ss.getClosedWindowCount(); - yield pushPrefs(["browser.sessionstore.max_windows_undo", - startingClosedWindowCount + 1]); - - let curClosedWindowCount = ss.getClosedWindowCount(); - let win = yield BrowserTestUtils.openNewBrowserWindow(); - - ss.setWindowState(win, JSON.stringify(state.windowState), true); - if (state.windowState.windows[0].tabs.length) { - yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - } - - yield BrowserTestUtils.closeWindow(win); - - is(ss.getClosedWindowCount(), - curClosedWindowCount + (state.shouldBeAdded ? 1 : 0), - "That window should " + (state.shouldBeAdded ? "" : "not ") + - "be restorable"); - } -}); diff --git a/browser/components/sessionstore/test/browser_491168.js b/browser/components/sessionstore/test/browser_491168.js deleted file mode 100644 index ae66afe77..000000000 --- a/browser/components/sessionstore/test/browser_491168.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; - -const REFERRER1 = "http://example.org/?" + Date.now(); -const REFERRER2 = "http://example.org/?" + Math.random(); - -add_task(function* () { - function* checkDocumentReferrer(referrer, msg) { - yield ContentTask.spawn(gBrowser.selectedBrowser, { referrer, msg }, function* (args) { - Assert.equal(content.document.referrer, args.referrer, args.msg); - }); - } - - // Add a new tab. - let tab = gBrowser.selectedTab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Load a new URI with a specific referrer. - let referrerURI = Services.io.newURI(REFERRER1, null, null); - browser.loadURI("http://example.org", referrerURI, null); - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - let tabState = JSON.parse(ss.getTabState(tab)); - is(tabState.entries[0].referrer, REFERRER1, - "Referrer retrieved via getTabState matches referrer set via loadURI."); - - tabState.entries[0].referrer = REFERRER2; - yield promiseTabState(tab, tabState); - - yield checkDocumentReferrer(REFERRER2, - "document.referrer matches referrer set via setTabState."); - gBrowser.removeCurrentTab(); - - // Restore the closed tab. - tab = ss.undoCloseTab(window, 0); - yield promiseTabRestored(tab); - - yield checkDocumentReferrer(REFERRER2, - "document.referrer is still correct after closing and reopening the tab."); - gBrowser.removeCurrentTab(); -}); diff --git a/browser/components/sessionstore/test/browser_491577.js b/browser/components/sessionstore/test/browser_491577.js deleted file mode 100644 index 0e088d702..000000000 --- a/browser/components/sessionstore/test/browser_491577.js +++ /dev/null @@ -1,120 +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/. */ - -function test() { - /** Test for Bug 491577 **/ - - // test setup - waitForExplicitFinish(); - - const REMEMBER = Date.now(), FORGET = Math.random(); - let test_state = { - windows: [ { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 } ], - _closedWindows : [ - // _closedWindows[0] - { - tabs: [ - { entries: [{ url: "http://example.com/", title: "title" }] }, - { entries: [{ url: "http://mozilla.org/", title: "title" }] } - ], - selected: 2, - title: FORGET, - _closedTabs: [] - }, - // _closedWindows[1] - { - tabs: [ - { entries: [{ url: "http://mozilla.org/", title: "title" }] }, - { entries: [{ url: "http://example.com/", title: "title" }] }, - { entries: [{ url: "http://mozilla.org/", title: "title" }] }, - ], - selected: 3, - title: REMEMBER, - _closedTabs: [] - }, - // _closedWindows[2] - { - tabs: [ - { entries: [{ url: "http://example.com/", title: "title" }] } - ], - selected: 1, - title: FORGET, - _closedTabs: [ - { - state: { - entries: [ - { url: "http://mozilla.org/", title: "title" }, - { url: "http://mozilla.org/again", title: "title" } - ] - }, - pos: 1, - title: "title" - }, - { - state: { - entries: [ - { url: "http://example.com", title: "title" } - ] - }, - title: "title" - } - ] - } - ] - }; - let remember_count = 1; - - function countByTitle(aClosedWindowList, aTitle) { - return aClosedWindowList.filter(aData => aData.title == aTitle).length; - } - - function testForError(aFunction) { - try { - aFunction(); - return false; - } - catch (ex) { - return ex.name == "NS_ERROR_ILLEGAL_VALUE"; - } - } - - // open a window and add the above closed window list - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - gPrefService.setIntPref("browser.sessionstore.max_windows_undo", - test_state._closedWindows.length); - ss.setWindowState(newWin, JSON.stringify(test_state), true); - - let closedWindows = JSON.parse(ss.getClosedWindowData()); - is(closedWindows.length, test_state._closedWindows.length, - "Closed window list has the expected length"); - is(countByTitle(closedWindows, FORGET), - test_state._closedWindows.length - remember_count, - "The correct amount of windows are to be forgotten"); - is(countByTitle(closedWindows, REMEMBER), remember_count, - "Everything is set up."); - - // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE - ok(testForError(() => ss.forgetClosedWindow(-1)), - "Invalid window for forgetClosedWindow throws"); - ok(testForError(() => ss.forgetClosedWindow(test_state._closedWindows.length + 1)), - "Invalid window for forgetClosedWindow throws"); - - // Remove third window, then first window - ss.forgetClosedWindow(2); - ss.forgetClosedWindow(null); - - closedWindows = JSON.parse(ss.getClosedWindowData()); - is(closedWindows.length, remember_count, - "The correct amount of windows were removed"); - is(countByTitle(closedWindows, FORGET), 0, - "All windows specifically forgotten were indeed removed"); - is(countByTitle(closedWindows, REMEMBER), remember_count, - "... and windows not specifically forgetten weren't."); - - // clean up - gPrefService.clearUserPref("browser.sessionstore.max_windows_undo"); - BrowserTestUtils.closeWindow(newWin).then(finish); - }); -} diff --git a/browser/components/sessionstore/test/browser_495495.js b/browser/components/sessionstore/test/browser_495495.js deleted file mode 100644 index 658f81c20..000000000 --- a/browser/components/sessionstore/test/browser_495495.js +++ /dev/null @@ -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/. */ - -function test() { - /** Test for Bug 495495 **/ - - waitForExplicitFinish(); - - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no,toolbar=yes"); - promiseWindowLoaded(newWin).then(() => { - let state1 = ss.getWindowState(newWin); - BrowserTestUtils.closeWindow(newWin).then(() => { - - newWin = openDialog(location, "_blank", - "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar=no,location,personal,directories,dialog=no"); - promiseWindowLoaded(newWin).then(() => { - let state2 = ss.getWindowState(newWin); - - function testState(state, expected, callback) { - let win = openDialog(location, "_blank", "chrome,all,dialog=no"); - promiseWindowLoaded(win).then(() => { - - is(win.gURLBar.readOnly, false, - "URL bar should not be read-only before setting the state"); - is(win.gURLBar.getAttribute("enablehistory"), "true", - "URL bar autocomplete should be enabled before setting the state"); - ss.setWindowState(win, state, true); - is(win.gURLBar.readOnly, expected.readOnly, - "URL bar read-only state should be restored correctly"); - is(win.gURLBar.getAttribute("enablehistory"), expected.enablehistory, - "URL bar autocomplete state should be restored correctly"); - - BrowserTestUtils.closeWindow(win).then(callback); - }); - } - - BrowserTestUtils.closeWindow(newWin).then(() => { - testState(state1, {readOnly: false, enablehistory: "true"}, function() { - testState(state2, {readOnly: true, enablehistory: "false"}, finish); - }); - }); - }); - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_500328.js b/browser/components/sessionstore/test/browser_500328.js deleted file mode 100644 index 44650ef8b..000000000 --- a/browser/components/sessionstore/test/browser_500328.js +++ /dev/null @@ -1,120 +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/. */ - -let checkState = Task.async(function*(browser) { - // Go back and then forward, and make sure that the state objects received - // from the popState event are as we expect them to be. - // - // We also add a node to the document's body when after going back and make - // sure it's still there after we go forward -- this is to test that the two - // history entries correspond to the same document. - - let deferred = {}; - deferred.promise = new Promise(resolve => deferred.resolve = resolve); - - let popStateCount = 0; - - browser.addEventListener("popstate", function(aEvent) { - if (popStateCount == 0) { - popStateCount++; - - ok(aEvent.state, "Event should have a state property."); - - ContentTask.spawn(browser, null, function() { - is(content.testState, "foo", - "testState after going back"); - is(JSON.stringify(content.history.state), JSON.stringify({obj1:1}), - "first popstate object."); - - // Add a node with id "new-elem" to the document. - let doc = content.document; - ok(!doc.getElementById("new-elem"), - "doc shouldn't contain new-elem before we add it."); - let elem = doc.createElement("div"); - elem.id = "new-elem"; - doc.body.appendChild(elem); - }).then(() => { - browser.goForward(); - }); - } else if (popStateCount == 1) { - popStateCount++; - // When content fires a PopStateEvent and we observe it from a chrome event - // listener (as we do here, and, thankfully, nowhere else in the tree), the - // state object will be a cross-compartment wrapper to an object that was - // deserialized in the content scope. And in this case, since RegExps are - // not currently Xrayable (see bug 1014991), trying to pull |obj3| (a RegExp) - // off of an Xrayed Object won't work. So we need to waive. - ContentTask.spawn(browser, aEvent.state, function(state) { - Assert.equal(Cu.waiveXrays(state).obj3.toString(), - "/^a$/", "second popstate object."); - - // Make sure that the new-elem node is present in the document. If it's - // not, then this history entry has a different doc identifier than the - // previous entry, which is bad. - let doc = content.document; - let newElem = doc.getElementById("new-elem"); - ok(newElem, "doc should contain new-elem."); - newElem.parentNode.removeChild(newElem); - ok(!doc.getElementById("new-elem"), "new-elem should be removed."); - }).then(() => { - browser.removeEventListener("popstate", arguments.callee, true); - deferred.resolve(); - }); - } - }); - - // Set some state in the page's window. When we go back(), the page should - // be retrieved from bfcache, and this state should still be there. - yield ContentTask.spawn(browser, null, function() { - content.testState = "foo"; - }); - - // Now go back. This should trigger the popstate event handler above. - browser.goBack(); - - yield deferred.promise; -}); - -add_task(function* test() { - // Tests session restore functionality of history.pushState and - // history.replaceState(). (Bug 500328) - - // We open a new blank window, let it load, and then load in - // http://example.com. We need to load the blank window first, otherwise the - // docshell gets confused and doesn't have a current history entry. - let state; - yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) { - BrowserTestUtils.loadURI(browser, "http://example.com"); - yield BrowserTestUtils.browserLoaded(browser); - - // After these push/replaceState calls, the window should have three - // history entries: - // testURL (state object: null) <-- oldest - // testURL (state object: {obj1:1}) - // testURL?page2 (state object: {obj3:/^a$/}) <-- newest - function contentTest() { - let history = content.window.history; - history.pushState({obj1:1}, "title-obj1"); - history.pushState({obj2:2}, "title-obj2", "?page2"); - history.replaceState({obj3:/^a$/}, "title-obj3"); - } - yield ContentTask.spawn(browser, null, contentTest); - yield TabStateFlusher.flush(browser); - - state = ss.getTabState(gBrowser.getTabForBrowser(browser)); - }); - - // Restore the state into a new tab. Things don't work well when we - // restore into the old tab, but that's not a real use case anyway. - yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) { - let tab2 = gBrowser.getTabForBrowser(browser); - - let tabRestoredPromise = promiseTabRestored(tab2); - ss.setTabState(tab2, state, true); - - // Run checkState() once the tab finishes loading its restored state. - yield tabRestoredPromise; - yield checkState(browser); - }); -}); diff --git a/browser/components/sessionstore/test/browser_506482.js b/browser/components/sessionstore/test/browser_506482.js deleted file mode 100644 index 6e5bd83bd..000000000 --- a/browser/components/sessionstore/test/browser_506482.js +++ /dev/null @@ -1,73 +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/. */ - -function test() { - /** Test for Bug 506482 **/ - - // test setup - waitForExplicitFinish(); - - // read the sessionstore.js mtime (picked from browser_248970_a.js) - let profilePath = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("ProfD", Ci.nsIFile); - function getSessionstoreFile() { - let sessionStoreJS = profilePath.clone(); - sessionStoreJS.append("sessionstore.js"); - return sessionStoreJS; - } - function getSessionstorejsModificationTime() { - let file = getSessionstoreFile(); - if (file.exists()) - return file.lastModifiedTime; - else - return -1; - } - - // delete existing sessionstore.js, to make sure we're not reading - // the mtime of an old one initially. - let sessionStoreJS = getSessionstoreFile(); - if (sessionStoreJS.exists()) - sessionStoreJS.remove(false); - - // test content URL - const TEST_URL = "data:text/html;charset=utf-8," - + "<body style='width: 100000px; height: 100000px;'><p>top</p></body>" - - // preferences that we use - const PREF_INTERVAL = "browser.sessionstore.interval"; - - // make sure sessionstore.js is saved ASAP on all events - gPrefService.setIntPref(PREF_INTERVAL, 0); - - // get the initial sessionstore.js mtime (-1 if it doesn't exist yet) - let mtime0 = getSessionstorejsModificationTime(); - - // create and select a first tab - let tab = gBrowser.addTab(TEST_URL); - promiseBrowserLoaded(tab.linkedBrowser).then(() => { - // step1: the above has triggered some saveStateDelayed(), sleep until - // it's done, and get the initial sessionstore.js mtime - setTimeout(function step1(e) { - let mtime1 = getSessionstorejsModificationTime(); - isnot(mtime1, mtime0, "initial sessionstore.js update"); - - // step2: test sessionstore.js is not updated on tab selection - // or content scrolling - gBrowser.selectedTab = tab; - tab.linkedBrowser.contentWindow.scrollTo(1100, 1200); - setTimeout(function step2(e) { - let mtime2 = getSessionstorejsModificationTime(); - is(mtime2, mtime1, - "tab selection and scrolling: sessionstore.js not updated"); - - // ok, done, cleanup and finish - if (gPrefService.prefHasUserValue(PREF_INTERVAL)) - gPrefService.clearUserPref(PREF_INTERVAL); - gBrowser.removeTab(tab); - finish(); - }, 3500); // end of sleep after tab selection and scrolling - }, 3500); // end of sleep after initial saveStateDelayed() - }); -} diff --git a/browser/components/sessionstore/test/browser_514751.js b/browser/components/sessionstore/test/browser_514751.js deleted file mode 100644 index ff80245c4..000000000 --- a/browser/components/sessionstore/test/browser_514751.js +++ /dev/null @@ -1,38 +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/. */ - -function test() { - /** Test for Bug 514751 (Wallpaper) **/ - - waitForExplicitFinish(); - - let state = { - windows: [{ - tabs: [{ - entries: [ - { url: "about:mozilla", title: "Mozilla" }, - {} - ] - }] - }] - }; - - var theWin = openDialog(location, "", "chrome,all,dialog=no"); - theWin.addEventListener("load", function () { - theWin.removeEventListener("load", arguments.callee, false); - - executeSoon(function () { - var gotError = false; - try { - ss.setWindowState(theWin, JSON.stringify(state), true); - } catch (e) { - if (/NS_ERROR_MALFORMED_URI/.test(e)) - gotError = true; - } - ok(!gotError, "Didn't get a malformed URI error."); - BrowserTestUtils.closeWindow(theWin).then(finish); - }); - }, false); -} - diff --git a/browser/components/sessionstore/test/browser_522375.js b/browser/components/sessionstore/test/browser_522375.js deleted file mode 100644 index 50b74d6cd..000000000 --- a/browser/components/sessionstore/test/browser_522375.js +++ /dev/null @@ -1,21 +0,0 @@ -function test() { - var startup_info = Components.classes["@mozilla.org/toolkit/app-startup;1"].getService(Components.interfaces.nsIAppStartup).getStartupInfo(); - // No .process info on mac - - // Check if we encountered a telemetry error for the the process creation - // timestamp and turn the first test into a known failure. - var telemetry = Cc["@mozilla.org/base/telemetry;1"].getService(Ci.nsITelemetry); - var snapshot = telemetry.getHistogramById("STARTUP_MEASUREMENT_ERRORS") - .snapshot(); - - if (snapshot.counts[0] == 0) - ok(startup_info.process <= startup_info.main, "process created before main is run " + uneval(startup_info)); - else - todo(false, "An error occurred while recording the process creation timestamp, skipping this test"); - - // on linux firstPaint can happen after everything is loaded (especially with remote X) - if (startup_info.firstPaint) - ok(startup_info.main <= startup_info.firstPaint, "main ran before first paint " + uneval(startup_info)); - - ok(startup_info.main < startup_info.sessionRestored, "Session restored after main " + uneval(startup_info)); -} diff --git a/browser/components/sessionstore/test/browser_522545.js b/browser/components/sessionstore/test/browser_522545.js deleted file mode 100644 index f4d373166..000000000 --- a/browser/components/sessionstore/test/browser_522545.js +++ /dev/null @@ -1,269 +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/. */ - -function test() { - /** Test for Bug 522545 **/ - - waitForExplicitFinish(); - requestLongerTimeout(4); - - // This tests the following use case: - // User opens a new tab which gets focus. The user types something into the - // address bar, then crashes or quits. - function test_newTabFocused() { - let state = { - windows: [{ - tabs: [ - { entries: [{ url: "about:mozilla" }] }, - { entries: [], userTypedValue: "example.com", userTypedClear: 0 } - ], - selected: 2 - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.selectedBrowser; - is(browser.currentURI.spec, "about:blank", - "No history entries still sets currentURI to about:blank"); - is(browser.userTypedValue, "example.com", - "userTypedValue was correctly restored"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "We still know that no load is ongoing"); - is(gURLBar.value, "example.com", - "Address bar's value correctly restored"); - // Change tabs to make sure address bar value gets updated - gBrowser.selectedTab = gBrowser.tabContainer.getItemAtIndex(0); - is(gURLBar.value, "about:mozilla", - "Address bar's value correctly updated"); - runNextTest(); - }); - } - - // This tests the following use case: - // User opens a new tab which gets focus. The user types something into the - // address bar, switches back to the first tab, then crashes or quits. - function test_newTabNotFocused() { - let state = { - windows: [{ - tabs: [ - { entries: [{ url: "about:mozilla" }] }, - { entries: [], userTypedValue: "example.org", userTypedClear: 0 } - ], - selected: 1 - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.getBrowserAtIndex(1); - is(browser.currentURI.spec, "about:blank", - "No history entries still sets currentURI to about:blank"); - is(browser.userTypedValue, "example.org", - "userTypedValue was correctly restored"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "We still know that no load is ongoing"); - is(gURLBar.value, "about:mozilla", - "Address bar's value correctly restored"); - // Change tabs to make sure address bar value gets updated - gBrowser.selectedTab = gBrowser.tabContainer.getItemAtIndex(1); - is(gURLBar.value, "example.org", - "Address bar's value correctly updated"); - runNextTest(); - }); - } - - // This tests the following use case: - // User is in a tab with session history, then types something in the - // address bar, then crashes or quits. - function test_existingSHEnd_noClear() { - let state = { - windows: [{ - tabs: [{ - entries: [{ url: "about:mozilla" }, { url: "about:config" }], - index: 2, - userTypedValue: "example.com", - userTypedClear: 0 - }] - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.selectedBrowser; - is(browser.currentURI.spec, "about:config", - "browser.currentURI set to current entry in SH"); - is(browser.userTypedValue, "example.com", - "userTypedValue was correctly restored"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "We still know that no load is ongoing"); - is(gURLBar.value, "example.com", - "Address bar's value correctly restored to userTypedValue"); - runNextTest(); - }); - } - - // This tests the following use case: - // User is in a tab with session history, presses back at some point, then - // types something in the address bar, then crashes or quits. - function test_existingSHMiddle_noClear() { - let state = { - windows: [{ - tabs: [{ - entries: [{ url: "about:mozilla" }, { url: "about:config" }], - index: 1, - userTypedValue: "example.org", - userTypedClear: 0 - }] - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.selectedBrowser; - is(browser.currentURI.spec, "about:mozilla", - "browser.currentURI set to current entry in SH"); - is(browser.userTypedValue, "example.org", - "userTypedValue was correctly restored"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "We still know that no load is ongoing"); - is(gURLBar.value, "example.org", - "Address bar's value correctly restored to userTypedValue"); - runNextTest(); - }); - } - - // This test simulates lots of tabs opening at once and then quitting/crashing. - function test_getBrowserState_lotsOfTabsOpening() { - gBrowser.stop(); - - let uris = []; - for (let i = 0; i < 25; i++) - uris.push("http://example.com/" + i); - - // We're waiting for the first location change, which should indicate - // one of the tabs has loaded and the others haven't. So one should - // be in a non-userTypedValue case, while others should still have - // userTypedValue and userTypedClear set. - gBrowser.addTabsProgressListener({ - onLocationChange: function (aBrowser) { - if (uris.indexOf(aBrowser.currentURI.spec) > -1) { - gBrowser.removeTabsProgressListener(this); - firstLocationChange(); - } - } - }); - - function firstLocationChange() { - let state = JSON.parse(ss.getBrowserState()); - let hasUTV = state.windows[0].tabs.some(function(aTab) { - return aTab.userTypedValue && aTab.userTypedClear && !aTab.entries.length; - }); - - ok(hasUTV, "At least one tab has a userTypedValue with userTypedClear with no loaded URL"); - - BrowserTestUtils.waitForMessage(gBrowser.selectedBrowser.messageManager, "SessionStore:update").then(firstLoad); - } - - function firstLoad() { - let state = JSON.parse(ss.getTabState(gBrowser.selectedTab)); - let hasSH = !("userTypedValue" in state) && state.entries[0].url; - ok(hasSH, "The selected tab has its entry in SH"); - - runNextTest(); - } - - gBrowser.loadTabs(uris); - } - - // This simulates setting a userTypedValue and ensures that just typing in the - // URL bar doesn't set userTypedClear as well. - function test_getBrowserState_userTypedValue() { - let state = { - windows: [{ - tabs: [{ entries: [] }] - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.selectedBrowser; - // Make sure this tab isn't loading and state is clear before we test. - is(browser.userTypedValue, null, "userTypedValue is empty to start"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "Initially, no load should be ongoing"); - - let inputText = "example.org"; - gURLBar.focus(); - gURLBar.value = inputText.slice(0, -1); - EventUtils.synthesizeKey(inputText.slice(-1) , {}); - - executeSoon(function () { - is(browser.userTypedValue, "example.org", - "userTypedValue was set when changing URLBar value"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "No load started since changing URLBar value"); - - // Now make sure ss gets these values too - let newState = JSON.parse(ss.getBrowserState()); - is(newState.windows[0].tabs[0].userTypedValue, "example.org", - "sessionstore got correct userTypedValue"); - is(newState.windows[0].tabs[0].userTypedClear, 0, - "sessionstore got correct userTypedClear"); - runNextTest(); - }); - }); - } - - // test_getBrowserState_lotsOfTabsOpening tested userTypedClear in a few cases, - // but not necessarily any that had legitimate URIs in the state of loading - // (eg, "http://example.com"), so this test will cover that case. - function test_userTypedClearLoadURI() { - let state = { - windows: [{ - tabs: [ - { entries: [], userTypedValue: "http://example.com", userTypedClear: 2 } - ] - }] - }; - - waitForBrowserState(state, function() { - let browser = gBrowser.selectedBrowser; - is(browser.currentURI.spec, "http://example.com/", - "userTypedClear=2 caused userTypedValue to be loaded"); - is(browser.userTypedValue, null, - "userTypedValue was null after loading a URI"); - ok(!browser.didStartLoadSinceLastUserTyping(), - "We should have reset the load state when the tab loaded"); - is(gURLBar.textValue, gURLBar.trimValue("http://example.com/"), - "Address bar's value set after loading URI"); - runNextTest(); - }); - } - - - let tests = [test_newTabFocused, test_newTabNotFocused, - test_existingSHEnd_noClear, test_existingSHMiddle_noClear, - test_getBrowserState_lotsOfTabsOpening, - test_getBrowserState_userTypedValue, test_userTypedClearLoadURI]; - let originalState = JSON.parse(ss.getBrowserState()); - let state = { - windows: [{ - tabs: [{ entries: [{ url: "about:blank" }] }] - }] - }; - function runNextTest() { - if (tests.length) { - waitForBrowserState(state, function() { - gBrowser.selectedBrowser.userTypedValue = null; - URLBarSetURI(); - (tests.shift())(); - }); - } else { - waitForBrowserState(originalState, function() { - gBrowser.selectedBrowser.userTypedValue = null; - URLBarSetURI(); - finish(); - }); - } - } - - // Run the tests! - runNextTest(); -} diff --git a/browser/components/sessionstore/test/browser_524745.js b/browser/components/sessionstore/test/browser_524745.js deleted file mode 100644 index de53f6c92..000000000 --- a/browser/components/sessionstore/test/browser_524745.js +++ /dev/null @@ -1,42 +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/. */ - -function test() { - /** Test for Bug 524745 **/ - - let uniqKey = "bug524745"; - let uniqVal = Date.now().toString(); - - waitForExplicitFinish(); - - whenNewWindowLoaded({ private: false }, function (window_B) { - waitForFocus(function() { - // Add identifying information to window_B - ss.setWindowValue(window_B, uniqKey, uniqVal); - let state = JSON.parse(ss.getBrowserState()); - let selectedWindow = state.windows[state.selectedWindow - 1]; - is(selectedWindow.extData && selectedWindow.extData[uniqKey], uniqVal, - "selectedWindow is window_B"); - - // Now minimize window_B. The selected window shouldn't have the secret data - window_B.minimize(); - waitForFocus(function() { - state = JSON.parse(ss.getBrowserState()); - selectedWindow = state.windows[state.selectedWindow - 1]; - ok(!selectedWindow.extData || !selectedWindow.extData[uniqKey], - "selectedWindow is not window_B after minimizing it"); - - // Now minimize the last open window (assumes no other tests left windows open) - window.minimize(); - state = JSON.parse(ss.getBrowserState()); - is(state.selectedWindow, 0, - "selectedWindow should be 0 when all windows are minimized"); - - // Cleanup - window.restore(); - BrowserTestUtils.closeWindow(window_B).then(finish); - }); - }, window_B); - }); -} diff --git a/browser/components/sessionstore/test/browser_526613.js b/browser/components/sessionstore/test/browser_526613.js deleted file mode 100644 index 7e7fe8059..000000000 --- a/browser/components/sessionstore/test/browser_526613.js +++ /dev/null @@ -1,72 +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/. */ - -function test() { - /** Test for Bug 526613 **/ - - // test setup - waitForExplicitFinish(); - - function browserWindowsCount(expected) { - let count = 0; - let e = Services.wm.getEnumerator("navigator:browser"); - while (e.hasMoreElements()) { - if (!e.getNext().closed) - ++count; - } - is(count, expected, - "number of open browser windows according to nsIWindowMediator"); - let state = ss.getBrowserState(); - info(state); - is(JSON.parse(state).windows.length, expected, - "number of open browser windows according to getBrowserState"); - } - - browserWindowsCount(1); - - // backup old state - let oldState = ss.getBrowserState(); - // create a new state for testing - let testState = { - windows: [ - { tabs: [{ entries: [{ url: "http://example.com/" }] }], selected: 1 }, - { tabs: [{ entries: [{ url: "about:mozilla" }] }], selected: 1 }, - ], - // make sure the first window is focused, otherwise when restoring the - // old state, the first window is closed and the test harness gets unloaded - selectedWindow: 1 - }; - - let pass = 1; - function observer(aSubject, aTopic, aData) { - is(aTopic, "sessionstore-browser-state-restored", - "The sessionstore-browser-state-restored notification was observed"); - - if (pass++ == 1) { - browserWindowsCount(2); - - // let the first window be focused (see above) - function pollMostRecentWindow() { - if (Services.wm.getMostRecentWindow("navigator:browser") == window) { - ss.setBrowserState(oldState); - } else { - info("waiting for the current window to become active"); - setTimeout(pollMostRecentWindow, 0); - window.focus(); //XXX Why is this needed? - } - } - pollMostRecentWindow(); - } - else { - browserWindowsCount(1); - ok(!window.closed, "Restoring the old state should have left this window open"); - Services.obs.removeObserver(observer, "sessionstore-browser-state-restored"); - finish(); - } - } - Services.obs.addObserver(observer, "sessionstore-browser-state-restored", false); - - // set browser to test state - ss.setBrowserState(JSON.stringify(testState)); -} diff --git a/browser/components/sessionstore/test/browser_528776.js b/browser/components/sessionstore/test/browser_528776.js deleted file mode 100644 index d799c9740..000000000 --- a/browser/components/sessionstore/test/browser_528776.js +++ /dev/null @@ -1,21 +0,0 @@ -function browserWindowsCount(expected) { - var count = 0; - var e = Services.wm.getEnumerator("navigator:browser"); - while (e.hasMoreElements()) { - if (!e.getNext().closed) - ++count; - } - is(count, expected, - "number of open browser windows according to nsIWindowMediator"); - is(JSON.parse(ss.getBrowserState()).windows.length, expected, - "number of open browser windows according to getBrowserState"); -} - -add_task(function() { - browserWindowsCount(1); - - let win = yield BrowserTestUtils.openNewBrowserWindow(); - browserWindowsCount(2); - yield BrowserTestUtils.closeWindow(win); - browserWindowsCount(1); -}); diff --git a/browser/components/sessionstore/test/browser_579868.js b/browser/components/sessionstore/test/browser_579868.js deleted file mode 100644 index d6c6245d0..000000000 --- a/browser/components/sessionstore/test/browser_579868.js +++ /dev/null @@ -1,30 +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/. */ - -function test() { - waitForExplicitFinish(); - - let tab1 = gBrowser.addTab("about:rights"); - let tab2 = gBrowser.addTab("about:mozilla"); - - promiseBrowserLoaded(tab1.linkedBrowser).then(() => { - // Tell the session storer that the tab is pinned - let newTabState = '{"entries":[{"url":"about:rights"}],"pinned":true,"userTypedValue":"Hello World!"}'; - ss.setTabState(tab1, newTabState); - - // Undo pinning - gBrowser.unpinTab(tab1); - - // Close and restore tab - gBrowser.removeTab(tab1); - let savedState = JSON.parse(ss.getClosedTabData(window))[0].state; - isnot(savedState.pinned, true, "Pinned should not be true"); - tab1 = ss.undoCloseTab(window, 0); - - isnot(tab1.pinned, true, "Should not be pinned"); - gBrowser.removeTab(tab1); - gBrowser.removeTab(tab2); - finish(); - }); -} diff --git a/browser/components/sessionstore/test/browser_579879.js b/browser/components/sessionstore/test/browser_579879.js deleted file mode 100644 index 6886be038..000000000 --- a/browser/components/sessionstore/test/browser_579879.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; - -add_task(function* () { - let tab1 = gBrowser.addTab("data:text/plain;charset=utf-8,foo"); - gBrowser.pinTab(tab1); - - yield promiseBrowserLoaded(tab1.linkedBrowser); - let tab2 = gBrowser.addTab(); - gBrowser.pinTab(tab2); - - is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 is at the first position"); - yield promiseRemoveTab(tab1); - - tab1 = undoCloseTab(); - ok(tab1.pinned, "pinned tab 1 has been restored as a pinned tab"); - is(Array.indexOf(gBrowser.tabs, tab1), 0, "pinned tab 1 has been restored to the first position"); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -}); diff --git a/browser/components/sessionstore/test/browser_580512.js b/browser/components/sessionstore/test/browser_580512.js deleted file mode 100644 index ef048cd37..000000000 --- a/browser/components/sessionstore/test/browser_580512.js +++ /dev/null @@ -1,81 +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 URIS_PINNED = ["about:license", "about:about"]; -const URIS_NORMAL_A = ["about:mozilla"]; -const URIS_NORMAL_B = ["about:buildconfig"]; - -function test() { - waitForExplicitFinish(); - - isnot(Services.prefs.getIntPref("browser.startup.page"), 3, - "pref to save session must not be set for this test"); - ok(!Services.prefs.getBoolPref("browser.sessionstore.resume_session_once"), - "pref to save session once must not be set for this test"); - - document.documentElement.setAttribute("windowtype", "navigator:browsertestdummy"); - - openWinWithCb(closeFirstWin, URIS_PINNED.concat(URIS_NORMAL_A)); -} - -function closeFirstWin(win) { - win.gBrowser.pinTab(win.gBrowser.tabs[0]); - win.gBrowser.pinTab(win.gBrowser.tabs[1]); - - let winClosed = BrowserTestUtils.windowClosed(win); - // We need to call BrowserTryToCloseWindow in order to trigger - // the machinery that chooses whether or not to save the session - // for the last window. - win.BrowserTryToCloseWindow(); - ok(win.closed, "window closed"); - - winClosed.then(() => { - openWinWithCb(checkSecondWin, URIS_NORMAL_B, URIS_PINNED.concat(URIS_NORMAL_B)); - }); -} - -function checkSecondWin(win) { - is(win.gBrowser.browsers[0].currentURI.spec, URIS_PINNED[0], "first pinned tab restored"); - is(win.gBrowser.browsers[1].currentURI.spec, URIS_PINNED[1], "second pinned tab restored"); - ok(win.gBrowser.tabs[0].pinned, "first pinned tab is still pinned"); - ok(win.gBrowser.tabs[1].pinned, "second pinned tab is still pinned"); - - BrowserTestUtils.closeWindow(win).then(() => { - // cleanup - document.documentElement.setAttribute("windowtype", "navigator:browser"); - finish(); - }); -} - -function openWinWithCb(cb, argURIs, expectedURIs) { - if (!expectedURIs) - expectedURIs = argURIs; - - var win = openDialog(getBrowserURL(), "_blank", - "chrome,all,dialog=no", argURIs.join("|")); - - win.addEventListener("load", function () { - win.removeEventListener("load", arguments.callee, false); - info("the window loaded"); - - var expectedLoads = expectedURIs.length; - - win.gBrowser.addTabsProgressListener({ - onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { - if (aRequest && - aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && - aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && - expectedURIs.indexOf(aRequest.QueryInterface(Ci.nsIChannel).originalURI.spec) > -1 && - --expectedLoads <= 0) { - win.gBrowser.removeTabsProgressListener(this); - info("all tabs loaded"); - is(win.gBrowser.tabs.length, expectedURIs.length, "didn't load any unexpected tabs"); - executeSoon(function () { - cb(win); - }); - } - } - }); - }, false); -} diff --git a/browser/components/sessionstore/test/browser_581937.js b/browser/components/sessionstore/test/browser_581937.js deleted file mode 100644 index 74ddaa9d2..000000000 --- a/browser/components/sessionstore/test/browser_581937.js +++ /dev/null @@ -1,19 +0,0 @@ -// Tests that an about:blank tab with no history will not be saved into -// session store and thus, it will not show up in Recently Closed Tabs. - -"use strict"; - -add_task(function* () { - let tab = gBrowser.addTab("about:blank"); - yield promiseBrowserLoaded(tab.linkedBrowser); - - is(tab.linkedBrowser.currentURI.spec, "about:blank", - "we will be removing an about:blank tab"); - - let r = `rand-${Math.random()}`; - ss.setTabValue(tab, "foobar", r); - - yield promiseRemoveTab(tab); - let closedTabData = ss.getClosedTabData(window); - ok(!closedTabData.includes(r), "tab not stored in _closedTabs"); -}); diff --git a/browser/components/sessionstore/test/browser_586068-apptabs.js b/browser/components/sessionstore/test/browser_586068-apptabs.js deleted file mode 100644 index f8727c04f..000000000 --- a/browser/components/sessionstore/test/browser_586068-apptabs.js +++ /dev/null @@ -1,58 +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/. */ - -requestLongerTimeout(2); - -const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } }, - ], selected: 5 }] }; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - loadCount++; - - // We'll make sure that the loads we get come from pinned tabs or the - // the selected tab. - - // get the tab - let tab; - for (let i = 0; i < window.gBrowser.tabs.length; i++) { - if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser) - tab = window.gBrowser.tabs[i]; - } - - ok(tab.pinned || tab.selected, - "load came from pinned or selected tab"); - - // We should get 4 loads: 3 app tabs + 1 normal selected tab - if (loadCount < 4) - return; - - gProgressListener.unsetCallback(); - resolve(); - }); - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js b/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js deleted file mode 100644 index b58aa649b..000000000 --- a/browser/components/sessionstore/test/browser_586068-apptabs_ondemand.js +++ /dev/null @@ -1,53 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; -const PREF_RESTORE_PINNED_TABS_ON_DEMAND = "browser.sessionstore.restore_pinned_tabs_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true); - Services.prefs.setBoolPref(PREF_RESTORE_PINNED_TABS_ON_DEMAND, true); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - Services.prefs.clearUserPref(PREF_RESTORE_PINNED_TABS_ON_DEMAND); - }); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() }, pinned: true }, - { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } }, - ], selected: 5 }] }; - - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - // get the tab - let tab; - for (let i = 0; i < window.gBrowser.tabs.length; i++) { - if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser) - tab = window.gBrowser.tabs[i]; - } - - // Check that the load only comes from the selected tab. - ok(tab.selected, "load came from selected tab"); - is(aNeedRestore, 6, "six tabs left to restore"); - is(aRestoring, 1, "one tab is restoring"); - is(aRestored, 0, "no tabs have been restored, yet"); - - gProgressListener.unsetCallback(); - resolve(); - }); - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js b/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js deleted file mode 100644 index de8f1aba0..000000000 --- a/browser/components/sessionstore/test/browser_586068-browser_state_interrupted.js +++ /dev/null @@ -1,113 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -requestLongerTimeout(2); - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - // The first state will be loaded using setBrowserState, followed by the 2nd - // state also being loaded using setBrowserState, interrupting the first restore. - let state1 = { windows: [ - { - tabs: [ - { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } } - ], - selected: 1 - }, - { - tabs: [ - { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } }, - ], - selected: 3 - } - ] }; - let state2 = { windows: [ - { - tabs: [ - { entries: [{ url: "http://example.org#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#6" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#7" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#8" }], extData: { "uniq": r() } } - ], - selected: 3 - }, - { - tabs: [ - { entries: [{ url: "http://example.com#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#6" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#7" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#8" }], extData: { "uniq": r() } }, - ], - selected: 1 - } - ] }; - - // interruptedAfter will be set after the selected tab from each window have loaded. - let interruptedAfter = 0; - let loadedWindow1 = false; - let loadedWindow2 = false; - let numTabs = state2.windows[0].tabs.length + state2.windows[1].tabs.length; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - loadCount++; - - if (aBrowser.currentURI.spec == state1.windows[0].tabs[2].entries[0].url) - loadedWindow1 = true; - if (aBrowser.currentURI.spec == state1.windows[1].tabs[0].entries[0].url) - loadedWindow2 = true; - - if (!interruptedAfter && loadedWindow1 && loadedWindow2) { - interruptedAfter = loadCount; - ss.setBrowserState(JSON.stringify(state2)); - return; - } - - if (loadCount < numTabs + interruptedAfter) - return; - - // We don't actually care about load order in this test, just that they all - // do load. - is(loadCount, numTabs + interruptedAfter, "all tabs were restored"); - is(aNeedRestore, 0, "there are no tabs left needing restore"); - - // Remove the progress listener. - gProgressListener.unsetCallback(); - resolve(); - }); - }); - - // We also want to catch the extra windows (there should be 2), so we need to observe domwindowopened - Services.ww.registerNotification(function observer(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - let win = aSubject.QueryInterface(Ci.nsIDOMWindow); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad); - Services.ww.unregisterNotification(observer); - win.gBrowser.addTabsProgressListener(gProgressListener); - }); - } - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state1)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseAllButPrimaryWindowClosed(); - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-cascade.js b/browser/components/sessionstore/test/browser_586068-cascade.js deleted file mode 100644 index 041aea85c..000000000 --- a/browser/components/sessionstore/test/browser_586068-cascade.js +++ /dev/null @@ -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/. */ - -const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com" }], extData: { "uniq": r() } } - ] }] }; - - let expectedCounts = [ - [3, 3, 0], - [2, 3, 1], - [1, 3, 2], - [0, 3, 3], - [0, 2, 4], - [0, 1, 5] - ]; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - loadCount++; - let expected = expectedCounts[loadCount - 1]; - - is(aNeedRestore, expected[0], "load " + loadCount + " - # tabs that need to be restored"); - is(aRestoring, expected[1], "load " + loadCount + " - # tabs that are restoring"); - is(aRestored, expected[2], "load " + loadCount + " - # tabs that has been restored"); - - if (loadCount == state.windows[0].tabs.length) { - gProgressListener.unsetCallback(); - resolve(); - } - }); - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-multi_window.js b/browser/components/sessionstore/test/browser_586068-multi_window.js deleted file mode 100644 index 03337568e..000000000 --- a/browser/components/sessionstore/test/browser_586068-multi_window.js +++ /dev/null @@ -1,70 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - // The first window will be put into the already open window and the second - // window will be opened with _openWindowWithState, which is the source of the problem. - let state = { windows: [ - { - tabs: [ - { entries: [{ url: "http://example.org#0" }], extData: { "uniq": r() } } - ], - selected: 1 - }, - { - tabs: [ - { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#6" }], extData: { "uniq": r() } } - ], - selected: 4 - } - ] }; - let numTabs = state.windows[0].tabs.length + state.windows[1].tabs.length; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - if (++loadCount == numTabs) { - // We don't actually care about load order in this test, just that they all - // do load. - is(loadCount, numTabs, "all tabs were restored"); - is(aNeedRestore, 0, "there are no tabs left needing restore"); - - gProgressListener.unsetCallback(); - resolve(); - } - }); - }); - - // We also want to catch the 2nd window, so we need to observe domwindowopened - Services.ww.registerNotification(function observer(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - let win = aSubject.QueryInterface(Ci.nsIDOMWindow); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad); - Services.ww.unregisterNotification(observer); - win.gBrowser.addTabsProgressListener(gProgressListener); - }); - } - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseAllButPrimaryWindowClosed(); - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-reload.js b/browser/components/sessionstore/test/browser_586068-reload.js deleted file mode 100644 index 630c91f2d..000000000 --- a/browser/components/sessionstore/test/browser_586068-reload.js +++ /dev/null @@ -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/. */ - -const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org/#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#4" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#5" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#6" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#7" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#8" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org/#9" }], extData: { "uniq": r() } }, - ], selected: 1 }] }; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gBrowser.tabContainer.addEventListener("SSTabRestored", function onRestored(event) { - let tab = event.target; - let browser = tab.linkedBrowser; - let tabData = state.windows[0].tabs[loadCount++]; - - // double check that this tab was the right one - is(browser.currentURI.spec, tabData.entries[0].url, - "load " + loadCount + " - browser loaded correct url"); - is(ss.getTabValue(tab, "uniq"), tabData.extData.uniq, - "load " + loadCount + " - correct tab was restored"); - - if (loadCount == state.windows[0].tabs.length) { - gBrowser.tabContainer.removeEventListener("SSTabRestored", onRestored); - resolve(); - } else { - // reload the next tab - gBrowser.browsers[loadCount].reload(); - } - }); - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-select.js b/browser/components/sessionstore/test/browser_586068-select.js deleted file mode 100644 index 433e1754c..000000000 --- a/browser/components/sessionstore/test/browser_586068-select.js +++ /dev/null @@ -1,69 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, true); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org" }], extData: { "uniq": r() } } - ], selected: 1 }] }; - - let expectedCounts = [ - [5, 1, 0], - [4, 1, 1], - [3, 1, 2], - [2, 1, 3], - [1, 1, 4], - [0, 1, 5] - ]; - let tabOrder = [0, 5, 1, 4, 3, 2]; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - loadCount++; - let expected = expectedCounts[loadCount - 1]; - - is(aNeedRestore, expected[0], "load " + loadCount + " - # tabs that need to be restored"); - is(aRestoring, expected[1], "load " + loadCount + " - # tabs that are restoring"); - is(aRestored, expected[2], "load " + loadCount + " - # tabs that has been restored"); - - if (loadCount < state.windows[0].tabs.length) { - // double check that this tab was the right one - let expectedData = state.windows[0].tabs[tabOrder[loadCount - 1]].extData.uniq; - let tab; - for (let i = 0; i < window.gBrowser.tabs.length; i++) { - if (!tab && window.gBrowser.tabs[i].linkedBrowser == aBrowser) - tab = window.gBrowser.tabs[i]; - } - - is(ss.getTabValue(tab, "uniq"), expectedData, - "load " + loadCount + " - correct tab was restored"); - - // select the next tab - window.gBrowser.selectTabAtIndex(tabOrder[loadCount]); - } else { - gProgressListener.unsetCallback(); - resolve(); - } - }); - }); - - let backupState = ss.getBrowserState(); - ss.setBrowserState(JSON.stringify(state)); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-window_state.js b/browser/components/sessionstore/test/browser_586068-window_state.js deleted file mode 100644 index 6097a70db..000000000 --- a/browser/components/sessionstore/test/browser_586068-window_state.js +++ /dev/null @@ -1,59 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - // We'll use 2 states so that we can make sure calling setWindowState doesn't - // wipe out currently restoring data. - let state1 = { windows: [{ tabs: [ - { entries: [{ url: "http://example.com#1" }] }, - { entries: [{ url: "http://example.com#2" }] }, - { entries: [{ url: "http://example.com#3" }] }, - { entries: [{ url: "http://example.com#4" }] }, - { entries: [{ url: "http://example.com#5" }] }, - ] }] }; - let state2 = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org#1" }] }, - { entries: [{ url: "http://example.org#2" }] }, - { entries: [{ url: "http://example.org#3" }] }, - { entries: [{ url: "http://example.org#4" }] }, - { entries: [{ url: "http://example.org#5" }] } - ] }] }; - let numTabs = state1.windows[0].tabs.length + state2.windows[0].tabs.length; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - // When loadCount == 2, we'll also restore state2 into the window - if (++loadCount == 2) { - ss.setWindowState(window, JSON.stringify(state2), false); - } - - if (loadCount < numTabs) { - return; - } - - // We don't actually care about load order in this test, just that they all - // do load. - is(loadCount, numTabs, "test_setWindowStateNoOverwrite: all tabs were restored"); - is(aNeedRestore, 0, "there are no tabs left needing restore"); - - gProgressListener.unsetCallback(); - resolve(); - }); - }); - - let backupState = ss.getBrowserState(); - ss.setWindowState(window, JSON.stringify(state1), true); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586068-window_state_override.js b/browser/components/sessionstore/test/browser_586068-window_state_override.js deleted file mode 100644 index 731e03307..000000000 --- a/browser/components/sessionstore/test/browser_586068-window_state_override.js +++ /dev/null @@ -1,59 +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 PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false); - registerCleanupFunction(function () { - Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND); - }); - - // We'll use 2 states so that we can make sure calling setWindowState doesn't - // wipe out currently restoring data. - let state1 = { windows: [{ tabs: [ - { entries: [{ url: "http://example.com#1" }] }, - { entries: [{ url: "http://example.com#2" }] }, - { entries: [{ url: "http://example.com#3" }] }, - { entries: [{ url: "http://example.com#4" }] }, - { entries: [{ url: "http://example.com#5" }] }, - ] }] }; - let state2 = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org#1" }] }, - { entries: [{ url: "http://example.org#2" }] }, - { entries: [{ url: "http://example.org#3" }] }, - { entries: [{ url: "http://example.org#4" }] }, - { entries: [{ url: "http://example.org#5" }] } - ] }] }; - let numTabs = 2 + state2.windows[0].tabs.length; - - let loadCount = 0; - let promiseRestoringTabs = new Promise(resolve => { - gProgressListener.setCallback(function (aBrowser, aNeedRestore, aRestoring, aRestored) { - // When loadCount == 2, we'll also restore state2 into the window - if (++loadCount == 2) { - executeSoon(() => ss.setWindowState(window, JSON.stringify(state2), true)); - } - - if (loadCount < numTabs) { - return; - } - - // We don't actually care about load order in this test, just that they all - // do load. - is(loadCount, numTabs, "all tabs were restored"); - is(aNeedRestore, 0, "there are no tabs left needing restore"); - - gProgressListener.unsetCallback(); - resolve(); - }); - }); - - let backupState = ss.getBrowserState(); - ss.setWindowState(window, JSON.stringify(state1), true); - yield promiseRestoringTabs; - - // Cleanup. - yield promiseBrowserState(backupState); -}); diff --git a/browser/components/sessionstore/test/browser_586147.js b/browser/components/sessionstore/test/browser_586147.js deleted file mode 100644 index fbfec53c7..000000000 --- a/browser/components/sessionstore/test/browser_586147.js +++ /dev/null @@ -1,52 +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/. */ - -function observeOneRestore(callback) { - let topic = "sessionstore-browser-state-restored"; - Services.obs.addObserver(function onRestore() { - Services.obs.removeObserver(onRestore, topic); - callback(); - }, topic, false); -}; - -function test() { - waitForExplicitFinish(); - - // There should be one tab when we start the test - let [origTab] = gBrowser.visibleTabs; - let hiddenTab = gBrowser.addTab(); - - is(gBrowser.visibleTabs.length, 2, "should have 2 tabs before hiding"); - gBrowser.showOnlyTheseTabs([origTab]); - is(gBrowser.visibleTabs.length, 1, "only 1 after hiding"); - ok(hiddenTab.hidden, "sanity check that it's hidden"); - - let extraTab = gBrowser.addTab(); - let state = ss.getBrowserState(); - let stateObj = JSON.parse(state); - let tabs = stateObj.windows[0].tabs; - is(tabs.length, 3, "just checking that browser state is correct"); - ok(!tabs[0].hidden, "first tab is visible"); - ok(tabs[1].hidden, "second is hidden"); - ok(!tabs[2].hidden, "third is visible"); - - // Make the third tab hidden and then restore the modified state object - tabs[2].hidden = true; - - observeOneRestore(function() { - let testWindow = Services.wm.getEnumerator("navigator:browser").getNext(); - is(testWindow.gBrowser.visibleTabs.length, 1, "only restored 1 visible tab"); - let tabs = testWindow.gBrowser.tabs; - ok(!tabs[0].hidden, "first is still visible"); - ok(tabs[1].hidden, "second tab is still hidden"); - ok(tabs[2].hidden, "third tab is now hidden"); - - // Restore the original state and clean up now that we're done - gBrowser.removeTab(hiddenTab); - gBrowser.removeTab(extraTab); - - finish(); - }); - ss.setBrowserState(JSON.stringify(stateObj)); -} diff --git a/browser/components/sessionstore/test/browser_588426.js b/browser/components/sessionstore/test/browser_588426.js deleted file mode 100644 index d2462f2bd..000000000 --- a/browser/components/sessionstore/test/browser_588426.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - let state = { windows: [{ tabs: [ - {entries: [{url: "about:mozilla"}], hidden: true}, - {entries: [{url: "about:rights"}], hidden: true} - ] }] }; - - waitForExplicitFinish(); - - newWindowWithState(state, function (win) { - registerCleanupFunction(() => BrowserTestUtils.closeWindow(win)); - - is(win.gBrowser.tabs.length, 2, "two tabs were restored"); - is(win.gBrowser.visibleTabs.length, 1, "one tab is visible"); - - let tab = win.gBrowser.visibleTabs[0]; - is(tab.linkedBrowser.currentURI.spec, "about:mozilla", "visible tab is about:mozilla"); - - finish(); - }); -} - -function newWindowWithState(state, callback) { - let opts = "chrome,all,dialog=no,height=800,width=800"; - let win = window.openDialog(getBrowserURL(), "_blank", opts); - - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - - executeSoon(function () { - win.addEventListener("SSWindowStateReady", function onReady() { - win.removeEventListener("SSWindowStateReady", onReady, false); - promiseTabRestored(win.gBrowser.tabs[0]).then(() => callback(win)); - }, false); - - ss.setWindowState(win, JSON.stringify(state), true); - }); - }, false); -} diff --git a/browser/components/sessionstore/test/browser_589246.js b/browser/components/sessionstore/test/browser_589246.js deleted file mode 100644 index d1f539073..000000000 --- a/browser/components/sessionstore/test/browser_589246.js +++ /dev/null @@ -1,242 +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/. */ - -// Mirrors WINDOW_ATTRIBUTES IN nsSessionStore.js -const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"]; - -var stateBackup = ss.getBrowserState(); - -var originalWarnOnClose = gPrefService.getBoolPref("browser.tabs.warnOnClose"); -var originalStartupPage = gPrefService.getIntPref("browser.startup.page"); -var originalWindowType = document.documentElement.getAttribute("windowtype"); - -var gotLastWindowClosedTopic = false; -var shouldPinTab = false; -var shouldOpenTabs = false; -var shouldCloseTab = false; -var testNum = 0; -var afterTestCallback; - -// Set state so we know the closed windows content -var testState = { - windows: [ - { tabs: [{ entries: [{ url: "http://example.org" }] }] } - ], - _closedWindows: [] -}; - -// We'll push a set of conditions and callbacks into this array -// Ideally we would also test win/linux under a complete set of conditions, but -// the tests for osx mirror the other set of conditions possible on win/linux. -var tests = []; - -// the third & fourth test share a condition check, keep it DRY -function checkOSX34Generator(num) { - return function(aPreviousState, aCurState) { - // In here, we should have restored the pinned tab, so only the unpinned tab - // should be in aCurState. So let's shape our expectations. - let expectedState = JSON.parse(aPreviousState); - expectedState[0].tabs.shift(); - // size attributes are stripped out in _prepDataForDeferredRestore in nsSessionStore. - // This isn't the best approach, but neither is comparing JSON strings - WINDOW_ATTRIBUTES.forEach(attr => delete expectedState[0][attr]); - - is(aCurState, JSON.stringify(expectedState), - "test #" + num + ": closedWindowState is as expected"); - }; -} -function checkNoWindowsGenerator(num) { - return function(aPreviousState, aCurState) { - is(aCurState, "[]", "test #" + num + ": there should be no closedWindowsLeft"); - }; -} - -// The first test has 0 pinned tabs and 1 unpinned tab -tests.push({ - pinned: false, - extra: false, - close: false, - checkWinLin: checkNoWindowsGenerator(1), - checkOSX: function(aPreviousState, aCurState) { - is(aCurState, aPreviousState, "test #1: closed window state is unchanged"); - } -}); - -// The second test has 1 pinned tab and 0 unpinned tabs. -tests.push({ - pinned: true, - extra: false, - close: false, - checkWinLin: checkNoWindowsGenerator(2), - checkOSX: checkNoWindowsGenerator(2) -}); - -// The third test has 1 pinned tab and 2 unpinned tabs. -tests.push({ - pinned: true, - extra: true, - close: false, - checkWinLin: checkNoWindowsGenerator(3), - checkOSX: checkOSX34Generator(3) -}); - -// The fourth test has 1 pinned tab, 2 unpinned tabs, and closes one unpinned tab. -tests.push({ - pinned: true, - extra: true, - close: "one", - checkWinLin: checkNoWindowsGenerator(4), - checkOSX: checkOSX34Generator(4) -}); - -// The fifth test has 1 pinned tab, 2 unpinned tabs, and closes both unpinned tabs. -tests.push({ - pinned: true, - extra: true, - close: "both", - checkWinLin: checkNoWindowsGenerator(5), - checkOSX: checkNoWindowsGenerator(5) -}); - - -function test() { - /** Test for Bug 589246 - Closed window state getting corrupted when closing - and reopening last browser window without exiting browser **/ - waitForExplicitFinish(); - // windows opening & closing, so extending the timeout - requestLongerTimeout(2); - - // We don't want the quit dialog pref - gPrefService.setBoolPref("browser.tabs.warnOnClose", false); - // Ensure that we would restore the session (important for Windows) - gPrefService.setIntPref("browser.startup.page", 3); - - runNextTestOrFinish(); -} - -function runNextTestOrFinish() { - if (tests.length) { - setupForTest(tests.shift()) - } - else { - // some state is cleaned up at the end of each test, but not all - ["browser.tabs.warnOnClose", "browser.startup.page"].forEach(function(p) { - if (gPrefService.prefHasUserValue(p)) - gPrefService.clearUserPref(p); - }); - - ss.setBrowserState(stateBackup); - executeSoon(finish); - } -} - -function setupForTest(aConditions) { - // reset some checks - gotLastWindowClosedTopic = false; - shouldPinTab = aConditions.pinned; - shouldOpenTabs = aConditions.extra; - shouldCloseTab = aConditions.close; - testNum++; - - // set our test callback - afterTestCallback = /Mac/.test(navigator.platform) ? aConditions.checkOSX - : aConditions.checkWinLin; - - // Add observers - Services.obs.addObserver(onLastWindowClosed, "browser-lastwindow-close-granted", false); - - // Set the state - Services.obs.addObserver(onStateRestored, "sessionstore-browser-state-restored", false); - ss.setBrowserState(JSON.stringify(testState)); -} - -function onStateRestored(aSubject, aTopic, aData) { - info("test #" + testNum + ": onStateRestored"); - Services.obs.removeObserver(onStateRestored, "sessionstore-browser-state-restored"); - - // change this window's windowtype so that closing a new window will trigger - // browser-lastwindow-close-granted. - document.documentElement.setAttribute("windowtype", "navigator:testrunner"); - - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no", "http://example.com"); - newWin.addEventListener("load", function(aEvent) { - newWin.removeEventListener("load", arguments.callee, false); - - promiseBrowserLoaded(newWin.gBrowser.selectedBrowser).then(() => { - // pin this tab - if (shouldPinTab) - newWin.gBrowser.pinTab(newWin.gBrowser.selectedTab); - - newWin.addEventListener("unload", function () { - newWin.removeEventListener("unload", arguments.callee, false); - onWindowUnloaded(); - }, false); - // Open a new tab as well. On Windows/Linux this will be restored when the - // new window is opened below (in onWindowUnloaded). On OS X we'll just - // restore the pinned tabs, leaving the unpinned tab in the closedWindowsData. - if (shouldOpenTabs) { - let newTab = newWin.gBrowser.addTab("about:config"); - let newTab2 = newWin.gBrowser.addTab("about:buildconfig"); - - newTab.linkedBrowser.addEventListener("load", function() { - newTab.linkedBrowser.removeEventListener("load", arguments.callee, true); - - if (shouldCloseTab == "one") { - newWin.gBrowser.removeTab(newTab2); - } - else if (shouldCloseTab == "both") { - newWin.gBrowser.removeTab(newTab); - newWin.gBrowser.removeTab(newTab2); - } - newWin.BrowserTryToCloseWindow(); - }, true); - } - else { - newWin.BrowserTryToCloseWindow(); - } - }); - }, false); -} - -// This will be called before the window is actually closed -function onLastWindowClosed(aSubject, aTopic, aData) { - info("test #" + testNum + ": onLastWindowClosed"); - Services.obs.removeObserver(onLastWindowClosed, "browser-lastwindow-close-granted"); - gotLastWindowClosedTopic = true; -} - -// This is the unload event listener on the new window (from onStateRestored). -// Unload is fired after the window is closed, so sessionstore has already -// updated _closedWindows (which is important). We'll open a new window here -// which should actually trigger the bug. -function onWindowUnloaded() { - info("test #" + testNum + ": onWindowClosed"); - ok(gotLastWindowClosedTopic, "test #" + testNum + ": browser-lastwindow-close-granted was notified prior"); - - let previousClosedWindowData = ss.getClosedWindowData(); - - // Now we want to open a new window - let newWin = openDialog(location, "_blank", "chrome,all,dialog=no", "about:mozilla"); - newWin.addEventListener("load", function(aEvent) { - newWin.removeEventListener("load", arguments.callee, false); - - newWin.gBrowser.selectedBrowser.addEventListener("load", function () { - newWin.gBrowser.selectedBrowser.removeEventListener("load", arguments.callee, true); - - // Good enough for checking the state - afterTestCallback(previousClosedWindowData, ss.getClosedWindowData()); - afterTestCleanup(newWin); - }, true); - - }, false); -} - -function afterTestCleanup(aNewWin) { - executeSoon(function() { - BrowserTestUtils.closeWindow(aNewWin).then(() => { - document.documentElement.setAttribute("windowtype", originalWindowType); - runNextTestOrFinish(); - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_590268.js b/browser/components/sessionstore/test/browser_590268.js deleted file mode 100644 index 2b0c2f32d..000000000 --- a/browser/components/sessionstore/test/browser_590268.js +++ /dev/null @@ -1,137 +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 NUM_TABS = 12; - -var stateBackup = ss.getBrowserState(); - -function test() { - /** Test for Bug 590268 - Provide access to sessionstore tab data sooner **/ - waitForExplicitFinish(); - requestLongerTimeout(2); - - let startedTest = false; - - // wasLoaded will be used to keep track of tabs that have already had SSTabRestoring - // fired for them. - let wasLoaded = { }; - let restoringTabsCount = 0; - let restoredTabsCount = 0; - let uniq2 = { }; - let uniq2Count = 0; - let state = { windows: [{ tabs: [] }] }; - // We're going to put a bunch of tabs into this state - for (let i = 0; i < NUM_TABS; i++) { - let uniq = r(); - let tabData = { - entries: [{ url: "http://example.com/#" + i }], - extData: { "uniq": uniq, "baz": "qux" } - }; - state.windows[0].tabs.push(tabData); - wasLoaded[uniq] = false; - } - - - function onSSTabRestoring(aEvent) { - restoringTabsCount++; - let uniq = ss.getTabValue(aEvent.originalTarget, "uniq"); - wasLoaded[uniq] = true; - - is(ss.getTabValue(aEvent.originalTarget, "foo"), "", - "There is no value for 'foo'"); - - // On the first SSTabRestoring we're going to run the the real test. - // We'll keep this listener around so we can keep marking tabs as restored. - if (restoringTabsCount == 1) - onFirstSSTabRestoring(); - else if (restoringTabsCount == NUM_TABS) - onLastSSTabRestoring(); - } - - function onSSTabRestored(aEvent) { - if (++restoredTabsCount < NUM_TABS) - return; - cleanup(); - } - - function onTabOpen(aEvent) { - // To test bug 614708, we'll just set a value on the tab here. This value - // would previously cause us to not recognize the values in extData until - // much later. So testing "uniq" failed. - ss.setTabValue(aEvent.originalTarget, "foo", "bar"); - } - - // This does the actual testing. SSTabRestoring should be firing on tabs from - // left to right, so we're going to start with the rightmost tab. - function onFirstSSTabRestoring() { - info("onFirstSSTabRestoring..."); - for (let i = gBrowser.tabs.length - 1; i >= 0; i--) { - let tab = gBrowser.tabs[i]; - let actualUniq = ss.getTabValue(tab, "uniq"); - let expectedUniq = state.windows[0].tabs[i].extData["uniq"]; - - if (wasLoaded[actualUniq]) { - info("tab " + i + ": already restored"); - continue; - } - is(actualUniq, expectedUniq, "tab " + i + ": extData was correct"); - - // Now we're going to set a piece of data back on the tab so it can be read - // to test setting a value "early". - uniq2[actualUniq] = r(); - ss.setTabValue(tab, "uniq2", uniq2[actualUniq]); - - // Delete the value we have for "baz". This tests that deleteTabValue - // will delete "early access" values (c.f. bug 617175). If this doesn't throw - // then the test is successful. - try { - ss.deleteTabValue(tab, "baz"); - } - catch (e) { - ok(false, "no error calling deleteTabValue - " + e); - } - - // This will be used in the final comparison to make sure we checked the - // same number as we set. - uniq2Count++; - } - } - - function onLastSSTabRestoring() { - let checked = 0; - for (let i = 0; i < gBrowser.tabs.length; i++) { - let tab = gBrowser.tabs[i]; - let uniq = ss.getTabValue(tab, "uniq"); - - // Look to see if we set a uniq2 value for this uniq value - if (uniq in uniq2) { - is(ss.getTabValue(tab, "uniq2"), uniq2[uniq], "tab " + i + " has correct uniq2 value"); - checked++; - } - } - ok(uniq2Count > 0, "at least 1 tab properly checked 'early access'"); - is(checked, uniq2Count, "checked the same number of uniq2 as we set"); - } - - function cleanup() { - // remove the event listener and clean up before finishing - gBrowser.tabContainer.removeEventListener("SSTabRestoring", onSSTabRestoring, false); - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true); - gBrowser.tabContainer.removeEventListener("TabOpen", onTabOpen, false); - // Put this in an executeSoon because we still haven't called restoreNextTab - // in sessionstore for the last tab (we'll call it after this). We end up - // trying to restore the tab (since we then add a closed tab to the array). - executeSoon(function() { - ss.setBrowserState(stateBackup); - executeSoon(finish); - }); - } - - // Add the event listeners - gBrowser.tabContainer.addEventListener("SSTabRestoring", onSSTabRestoring, false); - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true); - gBrowser.tabContainer.addEventListener("TabOpen", onTabOpen, false); - // Restore state - ss.setBrowserState(JSON.stringify(state)); -} diff --git a/browser/components/sessionstore/test/browser_590563.js b/browser/components/sessionstore/test/browser_590563.js deleted file mode 100644 index 5d1d8f866..000000000 --- a/browser/components/sessionstore/test/browser_590563.js +++ /dev/null @@ -1,74 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - let sessionData = { - windows: [{ - tabs: [ - { entries: [{ url: "about:mozilla" }], hidden: true }, - { entries: [{ url: "about:blank" }], hidden: false } - ] - }] - }; - let url = "about:sessionrestore"; - let formdata = {id: {sessionData}, url}; - let state = { windows: [{ tabs: [{ entries: [{url}], formdata }] }] }; - - waitForExplicitFinish(); - - newWindowWithState(state, function (win) { - registerCleanupFunction(() => BrowserTestUtils.closeWindow(win)); - - is(gBrowser.tabs.length, 1, "The total number of tabs should be 1"); - is(gBrowser.visibleTabs.length, 1, "The total number of visible tabs should be 1"); - - executeSoon(function () { - waitForFocus(function () { - middleClickTest(win); - finish(); - }, win); - }); - }); -} - -function middleClickTest(win) { - let browser = win.gBrowser.selectedBrowser; - let tree = browser.contentDocument.getElementById("tabList"); - is(tree.view.rowCount, 3, "There should be three items"); - - // click on the first tab item - var rect = tree.treeBoxObject.getCoordsForCellItem(1, tree.columns[1], "text"); - EventUtils.synthesizeMouse(tree.body, rect.x, rect.y, { button: 1 }, - browser.contentWindow); - // click on the second tab item - rect = tree.treeBoxObject.getCoordsForCellItem(2, tree.columns[1], "text"); - EventUtils.synthesizeMouse(tree.body, rect.x, rect.y, { button: 1 }, - browser.contentWindow); - - is(win.gBrowser.tabs.length, 3, - "The total number of tabs should be 3 after restoring 2 tabs by middle click."); - is(win.gBrowser.visibleTabs.length, 3, - "The total number of visible tabs should be 3 after restoring 2 tabs by middle click"); -} - -function newWindowWithState(state, callback) { - let opts = "chrome,all,dialog=no,height=800,width=800"; - let win = window.openDialog(getBrowserURL(), "_blank", opts); - - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - - let tab = win.gBrowser.selectedTab; - - // The form data will be restored before SSTabRestored, so we want to listen - // for that on the currently selected tab (it will be reused) - tab.addEventListener("SSTabRestored", function onRestored() { - tab.removeEventListener("SSTabRestored", onRestored, true); - callback(win); - }, true); - - executeSoon(function () { - ss.setWindowState(win, JSON.stringify(state), true); - }); - }, false); -} diff --git a/browser/components/sessionstore/test/browser_595601-restore_hidden.js b/browser/components/sessionstore/test/browser_595601-restore_hidden.js deleted file mode 100644 index 4c2b2d24a..000000000 --- a/browser/components/sessionstore/test/browser_595601-restore_hidden.js +++ /dev/null @@ -1,112 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var state = {windows:[{tabs:[ - {entries:[{url:"http://example.com#1"}]}, - {entries:[{url:"http://example.com#2"}]}, - {entries:[{url:"http://example.com#3"}]}, - {entries:[{url:"http://example.com#4"}]}, - {entries:[{url:"http://example.com#5"}], hidden: true}, - {entries:[{url:"http://example.com#6"}], hidden: true}, - {entries:[{url:"http://example.com#7"}], hidden: true}, - {entries:[{url:"http://example.com#8"}], hidden: true} -]}]}; - -function test() { - waitForExplicitFinish(); - requestLongerTimeout(2); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.restore_hidden_tabs"); - }); - - // First stage: restoreHiddenTabs = true - // Second stage: restoreHiddenTabs = false - test_loadTabs(true, function () { - test_loadTabs(false, finish); - }); -} - -function test_loadTabs(restoreHiddenTabs, callback) { - Services.prefs.setBoolPref("browser.sessionstore.restore_hidden_tabs", restoreHiddenTabs); - - let expectedTabs = restoreHiddenTabs ? 8 : 4; - let firstProgress = true; - - newWindowWithState(state, function (win, needsRestore, isRestoring) { - if (firstProgress) { - firstProgress = false; - is(isRestoring, 3, "restoring 3 tabs concurrently"); - } else { - ok(isRestoring < 4, "restoring max. 3 tabs concurrently"); - } - - // We're explicity checking for (isRestoring == 1) here because the test - // progress listener is called before the session store one. So when we're - // called with one tab left to restore we know that the last tab has - // finished restoring and will soon be handled by the SS listener. - let tabsNeedingRestore = win.gBrowser.tabs.length - needsRestore; - if (isRestoring == 1 && tabsNeedingRestore == expectedTabs) { - is(win.gBrowser.visibleTabs.length, 4, "only 4 visible tabs"); - - TabsProgressListener.uninit(); - executeSoon(callback); - } - }); -} - -var TabsProgressListener = { - init: function (win) { - this.window = win; - Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false); - }, - - uninit: function () { - Services.obs.removeObserver(this, "sessionstore-debug-tab-restored"); - - delete this.window; - delete this.callback; - }, - - setCallback: function (callback) { - this.callback = callback; - }, - - observe: function (browser) { - TabsProgressListener.onRestored(browser); - }, - - onRestored: function (browser) { - if (this.callback && browser.__SS_restoreState == TAB_STATE_RESTORING) - this.callback.apply(null, [this.window].concat(this.countTabs())); - }, - - countTabs: function () { - let needsRestore = 0, isRestoring = 0; - - for (let i = 0; i < this.window.gBrowser.tabs.length; i++) { - let browser = this.window.gBrowser.tabs[i].linkedBrowser; - if (browser.__SS_restoreState == TAB_STATE_RESTORING) - isRestoring++; - else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) - needsRestore++; - } - - return [needsRestore, isRestoring]; - } -} - -// ---------- -function newWindowWithState(state, callback) { - let opts = "chrome,all,dialog=no,height=800,width=800"; - let win = window.openDialog(getBrowserURL(), "_blank", opts); - - registerCleanupFunction(() => BrowserTestUtils.closeWindow(win)); - - whenWindowLoaded(win, function onWindowLoaded(aWin) { - TabsProgressListener.init(aWin); - TabsProgressListener.setCallback(callback); - - ss.setWindowState(aWin, JSON.stringify(state), true); - }); -} diff --git a/browser/components/sessionstore/test/browser_597071.js b/browser/components/sessionstore/test/browser_597071.js deleted file mode 100644 index f8ddaaf54..000000000 --- a/browser/components/sessionstore/test/browser_597071.js +++ /dev/null @@ -1,36 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Bug 597071 - Closed windows should only be resurrected when there is a single - * popup window - */ -add_task(function test_close_last_nonpopup_window() { - // Purge the list of closed windows. - forgetClosedWindows(); - - let oldState = ss.getWindowState(window); - - let popupState = {windows: [ - {tabs: [{entries: []}], isPopup: true, hidden: "toolbar"} - ]}; - - // Set this window to be a popup. - ss.setWindowState(window, JSON.stringify(popupState), true); - - // Open a new window with a tab. - let win = yield BrowserTestUtils.openNewBrowserWindow({private: false}); - let tab = win.gBrowser.addTab("http://example.com/"); - yield BrowserTestUtils.browserLoaded(tab.linkedBrowser); - - // Make sure sessionstore sees this window. - let state = JSON.parse(ss.getBrowserState()); - is(state.windows.length, 2, "sessionstore knows about this window"); - - // Closed the window and check the closed window count. - yield BrowserTestUtils.closeWindow(win); - is(ss.getClosedWindowCount(), 1, "correct closed window count"); - - // Cleanup. - ss.setWindowState(window, oldState, true); -}); diff --git a/browser/components/sessionstore/test/browser_599909.js b/browser/components/sessionstore/test/browser_599909.js deleted file mode 100644 index 1d2c411fe..000000000 --- a/browser/components/sessionstore/test/browser_599909.js +++ /dev/null @@ -1,120 +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 stateBackup = ss.getBrowserState(); - -function cleanup() { - // Reset the pref - try { - Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); - } catch (e) {} - ss.setBrowserState(stateBackup); - executeSoon(finish); -} - -function test() { - /** Bug 599909 - to-be-reloaded tabs don't show up in switch-to-tab **/ - waitForExplicitFinish(); - - // Set the pref to true so we know exactly how many tabs should be restoring at - // any given time. This guarantees that a finishing load won't start another. - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org/#1" }] }, - { entries: [{ url: "http://example.org/#2" }] }, - { entries: [{ url: "http://example.org/#3" }] }, - { entries: [{ url: "http://example.org/#4" }] } - ], selected: 1 }] }; - - let tabsForEnsure = {}; - state.windows[0].tabs.forEach(function(tab) { - tabsForEnsure[tab.entries[0].url] = 1; - }); - - let tabsRestoring = 0; - let tabsRestored = 0; - - function handleEvent(aEvent) { - if (aEvent.type == "SSTabRestoring") - tabsRestoring++; - else - tabsRestored++; - - if (tabsRestoring < state.windows[0].tabs.length || - tabsRestored < 1) - return; - - gBrowser.tabContainer.removeEventListener("SSTabRestoring", handleEvent, true); - gBrowser.tabContainer.removeEventListener("SSTabRestored", handleEvent, true); - executeSoon(function() { - checkAutocompleteResults(tabsForEnsure, cleanup); - }); - } - - // currentURI is set before SSTabRestoring is fired, so we can sucessfully check - // after that has fired for all tabs. Since 1 tab will be restored though, we - // also need to wait for 1 SSTabRestored since currentURI will be set, unset, then set. - gBrowser.tabContainer.addEventListener("SSTabRestoring", handleEvent, true); - gBrowser.tabContainer.addEventListener("SSTabRestored", handleEvent, true); - ss.setBrowserState(JSON.stringify(state)); -} - -// The following was taken from browser/base/content/test/general/browser_tabMatchesInAwesomebar.js -// so that we could do the same sort of checking. -var gController = Cc["@mozilla.org/autocomplete/controller;1"]. - getService(Ci.nsIAutoCompleteController); - -function checkAutocompleteResults(aExpected, aCallback) { - gController.input = { - timeout: 10, - textValue: "", - searches: ["unifiedcomplete"], - searchParam: "enable-actions", - popupOpen: false, - minResultsForPopup: 0, - invalidate: function() {}, - disableAutoComplete: false, - completeDefaultIndex: false, - get popup() { return this; }, - onSearchBegin: function() {}, - onSearchComplete: function () - { - info("Found " + gController.matchCount + " matches."); - // Check to see the expected uris and titles match up (in any order) - for (let i = 0; i < gController.matchCount; i++) { - if (gController.getStyleAt(i).includes("heuristic")) { - info("Skip heuristic match"); - continue; - } - let action = gURLBar.popup.input._parseActionUrl(gController.getValueAt(i)); - let uri = action.params.url; - - info("Search for '" + uri + "' in open tabs."); - ok(uri in aExpected, "Registered open page found in autocomplete."); - // Remove the found entry from expected results. - delete aExpected[uri]; - } - - // Make sure there is no reported open page that is not open. - for (let entry in aExpected) { - ok(false, "'" + entry + "' not found in autocomplete."); - } - - executeSoon(aCallback); - }, - setSelectedIndex: function() {}, - get searchCount() { return this.searches.length; }, - getSearchAt: function(aIndex) { - return this.searches[aIndex]; - }, - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsIAutoCompleteInput, - Ci.nsIAutoCompletePopup, - ]) - }; - - info("Searching open pages."); - gController.startSearch(Services.prefs.getCharPref("browser.urlbar.restrict.openpage")); -} diff --git a/browser/components/sessionstore/test/browser_600545.js b/browser/components/sessionstore/test/browser_600545.js deleted file mode 100644 index 6852357c2..000000000 --- a/browser/components/sessionstore/test/browser_600545.js +++ /dev/null @@ -1,89 +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/. */ - -requestLongerTimeout(2); - -var stateBackup = JSON.parse(ss.getBrowserState()); - -function test() { - /** Test for Bug 600545 **/ - waitForExplicitFinish(); - testBug600545(); -} - -function testBug600545() { - // Set the pref to false to cause non-app tabs to be stripped out on a save - Services.prefs.setBoolPref("browser.sessionstore.resume_from_crash", false); - Services.prefs.setIntPref("browser.sessionstore.interval", 2000); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.resume_from_crash"); - Services.prefs.clearUserPref("browser.sessionstore.interval"); - }); - - // This tests the following use case: When multiple windows are open - // and browser.sessionstore.resume_from_crash preference is false, - // tab session data for non-active window is stripped for non-pinned - // tabs. This occurs after "sessionstore-state-write-complete" - // fires which will only fire in this case if there is at least one - // pinned tab. - let state = { windows: [ - { - tabs: [ - { entries: [{ url: "http://example.org#0" }], pinned:true }, - { entries: [{ url: "http://example.com#1" }] }, - { entries: [{ url: "http://example.com#2" }] }, - ], - selected: 2 - }, - { - tabs: [ - { entries: [{ url: "http://example.com#3" }] }, - { entries: [{ url: "http://example.com#4" }] }, - { entries: [{ url: "http://example.com#5" }] }, - { entries: [{ url: "http://example.com#6" }] } - ], - selected: 3 - } - ] }; - - waitForBrowserState(state, function() { - // Need to wait for SessionStore's saveState function to be called - // so that non-pinned tabs will be stripped from non-active window - waitForSaveState(function () { - let expectedNumberOfTabs = getStateTabCount(state); - let retrievedState = JSON.parse(ss.getBrowserState()); - let actualNumberOfTabs = getStateTabCount(retrievedState); - - is(actualNumberOfTabs, expectedNumberOfTabs, - "Number of tabs in retreived session data, matches number of tabs set."); - - done(); - }); - }); -} - -function done() { - // Enumerate windows and close everything but our primary window. We can't - // use waitForFocus() because apparently it's buggy. See bug 599253. - let windowsEnum = Services.wm.getEnumerator("navigator:browser"); - let closeWinPromises = []; - while (windowsEnum.hasMoreElements()) { - let currentWindow = windowsEnum.getNext(); - if (currentWindow != window) - closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow)); - } - - Promise.all(closeWinPromises).then(() => { - waitForBrowserState(stateBackup, finish); - }); -} - -// Count up the number of tabs in the state data -function getStateTabCount(aState) { - let tabCount = 0; - for (let i in aState.windows) - tabCount += aState.windows[i].tabs.length; - return tabCount; -} diff --git a/browser/components/sessionstore/test/browser_601955.js b/browser/components/sessionstore/test/browser_601955.js deleted file mode 100644 index 797d5d7cc..000000000 --- a/browser/components/sessionstore/test/browser_601955.js +++ /dev/null @@ -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/. */ - -// This tests that pinning/unpinning a tab, on its own, eventually triggers a -// session store. - -function test() { - waitForExplicitFinish(); - // We speed up the interval between session saves to ensure that the test - // runs quickly. - Services.prefs.setIntPref("browser.sessionstore.interval", 2000); - - // Loading a tab causes a save state and this is meant to catch that event. - waitForSaveState(testBug601955_1); - - // Assumption: Only one window is open and it has one tab open. - gBrowser.addTab("about:mozilla"); -} - -function testBug601955_1() { - // Because pinned tabs are at the front of |gBrowser.tabs|, pinning tabs - // re-arranges the |tabs| array. - ok(!gBrowser.tabs[0].pinned, "first tab should not be pinned yet"); - ok(!gBrowser.tabs[1].pinned, "second tab should not be pinned yet"); - - waitForSaveState(testBug601955_2); - gBrowser.pinTab(gBrowser.tabs[0]); -} - -function testBug601955_2() { - let state = JSON.parse(ss.getBrowserState()); - ok(state.windows[0].tabs[0].pinned, "first tab should be pinned by now"); - ok(!state.windows[0].tabs[1].pinned, "second tab should still not be pinned"); - - waitForSaveState(testBug601955_3); - gBrowser.unpinTab(window.gBrowser.tabs[0]); -} - -function testBug601955_3() { - let state = JSON.parse(ss.getBrowserState()); - ok(!state.windows[0].tabs[0].pinned, "first tab should not be pinned"); - ok(!state.windows[0].tabs[1].pinned, "second tab should not be pinned"); - - done(); -} - -function done() { - gBrowser.removeTab(window.gBrowser.tabs[1]); - - Services.prefs.clearUserPref("browser.sessionstore.interval"); - - executeSoon(finish); -} diff --git a/browser/components/sessionstore/test/browser_607016.js b/browser/components/sessionstore/test/browser_607016.js deleted file mode 100644 index ed4b03b9c..000000000 --- a/browser/components/sessionstore/test/browser_607016.js +++ /dev/null @@ -1,98 +0,0 @@ -"use strict"; - -var stateBackup = ss.getBrowserState(); - -add_task(function* () { - /** Bug 607016 - If a tab is never restored, attributes (eg. hidden) aren't updated correctly **/ - ignoreAllUncaughtExceptions(); - - // Set the pref to true so we know exactly how many tabs should be restoring at - // any given time. This guarantees that a finishing load won't start another. - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - let state = { windows: [{ tabs: [ - { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } }, // overwriting - { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } }, // hiding - { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } }, // adding - { entries: [{ url: "http://example.org#5" }], extData: { "uniq": r() } }, // deleting - { entries: [{ url: "http://example.org#6" }] } // creating - ], selected: 1 }] }; - - function* progressCallback() { - let curState = JSON.parse(ss.getBrowserState()); - for (let i = 0; i < curState.windows[0].tabs.length; i++) { - let tabState = state.windows[0].tabs[i]; - let tabCurState = curState.windows[0].tabs[i]; - if (tabState.extData) { - is(tabCurState.extData["uniq"], tabState.extData["uniq"], - "sanity check that tab has correct extData"); - } - else { - // We aren't expecting there to be any data on extData, but panorama - // may be setting something, so we need to make sure that if we do have - // data, we just don't have anything for "uniq". - ok(!("extData" in tabCurState) || !("uniq" in tabCurState.extData), - "sanity check that tab doesn't have extData or extData doesn't have 'uniq'"); - } - } - - // Now we'll set a new unique value on 1 of the tabs - let newUniq = r(); - ss.setTabValue(gBrowser.tabs[1], "uniq", newUniq); - let tabState = JSON.parse(ss.getTabState(gBrowser.tabs[1])); - is(tabState.extData.uniq, newUniq, - "(overwriting) new data is stored in extData"); - - // hide the next tab before closing it - gBrowser.hideTab(gBrowser.tabs[2]); - tabState = JSON.parse(ss.getTabState(gBrowser.tabs[2])); - ok(tabState.hidden, "(hiding) tab data has hidden == true"); - - // set data that's not in a conflicting key - let stillUniq = r(); - ss.setTabValue(gBrowser.tabs[3], "stillUniq", stillUniq); - tabState = JSON.parse(ss.getTabState(gBrowser.tabs[3])); - is(tabState.extData.stillUniq, stillUniq, - "(adding) new data is stored in extData"); - - // remove the uniq value and make sure it's not there in the closed data - ss.deleteTabValue(gBrowser.tabs[4], "uniq"); - tabState = JSON.parse(ss.getTabState(gBrowser.tabs[4])); - // Since Panorama might have put data in, first check if there is extData. - // If there is explicitly check that "uniq" isn't in it. Otherwise, we're ok - if ("extData" in tabState) { - ok(!("uniq" in tabState.extData), - "(deleting) uniq not in existing extData"); - } - else { - ok(true, "(deleting) no data is stored in extData"); - } - - // set unique data on the tab that never had any set, make sure that's saved - let newUniq2 = r(); - ss.setTabValue(gBrowser.tabs[5], "uniq", newUniq2); - tabState = JSON.parse(ss.getTabState(gBrowser.tabs[5])); - is(tabState.extData.uniq, newUniq2, - "(creating) new data is stored in extData where there was none"); - - while (gBrowser.tabs.length > 1) { - yield promiseRemoveTab(gBrowser.tabs[1]); - } - } - - // Set the test state. - ss.setBrowserState(JSON.stringify(state)); - - // Wait until the selected tab is restored and all others are pending. - yield Promise.all(Array.map(gBrowser.tabs, tab => { - return (tab == gBrowser.selectedTab) ? - promiseTabRestored(tab) : promiseTabRestoring(tab) - })); - - // Kick off the actual tests. - yield progressCallback(); - - // Cleanup. - yield promiseBrowserState(stateBackup); -}); diff --git a/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js b/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js deleted file mode 100644 index 0b6b8faa6..000000000 --- a/browser/components/sessionstore/test/browser_615394-SSWindowState_events.js +++ /dev/null @@ -1,361 +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 stateBackup = JSON.parse(ss.getBrowserState()); -const testState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:blank" }] }, - { entries: [{ url: "about:rights" }] } - ] - }] -}; -const lameMultiWindowState = { windows: [ - { - tabs: [ - { entries: [{ url: "http://example.org#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.org#4" }], extData: { "uniq": r() } } - ], - selected: 1 - }, - { - tabs: [ - { entries: [{ url: "http://example.com#1" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#2" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#3" }], extData: { "uniq": r() } }, - { entries: [{ url: "http://example.com#4" }], extData: { "uniq": r() } }, - ], - selected: 3 - } - ] }; - - -function getOuterWindowID(aWindow) { - return aWindow.QueryInterface(Ci.nsIInterfaceRequestor). - getInterface(Ci.nsIDOMWindowUtils).outerWindowID; -} - -function test() { - /** Test for Bug 615394 - Session Restore should notify when it is beginning and ending a restore **/ - waitForExplicitFinish(); - // Preemptively extend the timeout to prevent [orange] - requestLongerTimeout(4); - runNextTest(); -} - - -var tests = [ - test_setTabState, - test_duplicateTab, - test_undoCloseTab, - test_setWindowState, - test_setBrowserState, - test_undoCloseWindow -]; -function runNextTest() { - // set an empty state & run the next test, or finish - if (tests.length) { - // Enumerate windows and close everything but our primary window. We can't - // use waitForFocus() because apparently it's buggy. See bug 599253. - var windowsEnum = Services.wm.getEnumerator("navigator:browser"); - let closeWinPromises = []; - while (windowsEnum.hasMoreElements()) { - var currentWindow = windowsEnum.getNext(); - if (currentWindow != window) { - closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow)); - } - } - - Promise.all(closeWinPromises).then(() => { - let currentTest = tests.shift(); - info("prepping for " + currentTest.name); - waitForBrowserState(testState, currentTest); - }); - } - else { - waitForBrowserState(stateBackup, finish); - } -} - -/** ACTUAL TESTS **/ - -function test_setTabState() { - let tab = gBrowser.tabs[1]; - let newTabState = JSON.stringify({ entries: [{ url: "http://example.org" }], extData: { foo: "bar" } }); - let busyEventCount = 0; - let readyEventCount = 0; - - function onSSWindowStateBusy(aEvent) { - busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - readyEventCount++; - is(ss.getTabValue(tab, "foo"), "bar"); - ss.setTabValue(tab, "baz", "qux"); - } - - function onSSTabRestored(aEvent) { - is(busyEventCount, 1); - is(readyEventCount, 1); - is(ss.getTabValue(tab, "baz"), "qux"); - is(tab.linkedBrowser.currentURI.spec, "http://example.org/"); - - window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - - runNextTest(); - } - - window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - ss.setTabState(tab, newTabState); -} - - -function test_duplicateTab() { - let tab = gBrowser.tabs[1]; - let busyEventCount = 0; - let readyEventCount = 0; - let newTab; - - // We'll look to make sure this value is on the duplicated tab - ss.setTabValue(tab, "foo", "bar"); - - function onSSWindowStateBusy(aEvent) { - busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - newTab = gBrowser.tabs[2]; - readyEventCount++; - is(ss.getTabValue(newTab, "foo"), "bar"); - ss.setTabValue(newTab, "baz", "qux"); - } - - function onSSTabRestored(aEvent) { - is(busyEventCount, 1); - is(readyEventCount, 1); - is(ss.getTabValue(newTab, "baz"), "qux"); - is(newTab.linkedBrowser.currentURI.spec, "about:rights"); - - window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - - runNextTest(); - } - - window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - - newTab = ss.duplicateTab(window, tab); -} - - -function test_undoCloseTab() { - let tab = gBrowser.tabs[1], - busyEventCount = 0, - readyEventCount = 0, - reopenedTab; - - ss.setTabValue(tab, "foo", "bar"); - - function onSSWindowStateBusy(aEvent) { - busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - reopenedTab = gBrowser.tabs[1]; - readyEventCount++; - is(ss.getTabValue(reopenedTab, "foo"), "bar"); - ss.setTabValue(reopenedTab, "baz", "qux"); - } - - function onSSTabRestored(aEvent) { - is(busyEventCount, 1); - is(readyEventCount, 1); - is(ss.getTabValue(reopenedTab, "baz"), "qux"); - is(reopenedTab.linkedBrowser.currentURI.spec, "about:rights"); - - window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - - runNextTest(); - } - - window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - - gBrowser.removeTab(tab); - reopenedTab = ss.undoCloseTab(window, 0); -} - - -function test_setWindowState() { - let testState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:mozilla" }], extData: { "foo": "bar" } }, - { entries: [{ url: "http://example.org" }], extData: { "baz": "qux" } } - ] - }] - }; - - let busyEventCount = 0, - readyEventCount = 0, - tabRestoredCount = 0; - - function onSSWindowStateBusy(aEvent) { - busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - readyEventCount++; - is(ss.getTabValue(gBrowser.tabs[0], "foo"), "bar"); - is(ss.getTabValue(gBrowser.tabs[1], "baz"), "qux"); - } - - function onSSTabRestored(aEvent) { - if (++tabRestoredCount < 2) - return; - - is(busyEventCount, 1); - is(readyEventCount, 1); - is(gBrowser.tabs[0].linkedBrowser.currentURI.spec, "about:mozilla"); - is(gBrowser.tabs[1].linkedBrowser.currentURI.spec, "http://example.org/"); - - window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - - runNextTest(); - } - - window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - - ss.setWindowState(window, JSON.stringify(testState), true); -} - - -function test_setBrowserState() { - // We'll track events per window so we are sure that they are each happening once - // pre window. - let windowEvents = {}; - windowEvents[getOuterWindowID(window)] = { busyEventCount: 0, readyEventCount: 0 }; - - // waitForBrowserState does it's own observing for windows, but doesn't attach - // the listeners we want here, so do it ourselves. - let newWindow; - function windowObserver(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow); - newWindow.addEventListener("load", function() { - newWindow.removeEventListener("load", arguments.callee, false); - - Services.ww.unregisterNotification(windowObserver); - - windowEvents[getOuterWindowID(newWindow)] = { busyEventCount: 0, readyEventCount: 0 }; - - newWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - newWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - }, false); - } - } - - function onSSWindowStateBusy(aEvent) { - windowEvents[getOuterWindowID(aEvent.originalTarget)].busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - windowEvents[getOuterWindowID(aEvent.originalTarget)].readyEventCount++; - } - - window.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - Services.ww.registerNotification(windowObserver); - - waitForBrowserState(lameMultiWindowState, function() { - let checkedWindows = 0; - for (let id of Object.keys(windowEvents)) { - let winEvents = windowEvents[id]; - is(winEvents.busyEventCount, 1, - "[test_setBrowserState] window" + id + " busy event count correct"); - is(winEvents.readyEventCount, 1, - "[test_setBrowserState] window" + id + " ready event count correct"); - checkedWindows++; - } - is(checkedWindows, 2, - "[test_setBrowserState] checked 2 windows"); - window.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - window.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - newWindow.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - newWindow.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - runNextTest(); - }); -} - - -function test_undoCloseWindow() { - let newWindow, reopenedWindow; - - function firstWindowObserver(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow); - Services.ww.unregisterNotification(firstWindowObserver); - } - } - Services.ww.registerNotification(firstWindowObserver); - - waitForBrowserState(lameMultiWindowState, function() { - // Close the window which isn't window - BrowserTestUtils.closeWindow(newWindow).then(() => { - // Now give it time to close - reopenedWindow = ss.undoCloseWindow(0); - reopenedWindow.addEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - reopenedWindow.addEventListener("SSWindowStateReady", onSSWindowStateReady, false); - - reopenedWindow.addEventListener("load", function() { - reopenedWindow.removeEventListener("load", arguments.callee, false); - - reopenedWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - }, false); - }); - }); - - let busyEventCount = 0, - readyEventCount = 0, - tabRestoredCount = 0; - // These will listen to the reopened closed window... - function onSSWindowStateBusy(aEvent) { - busyEventCount++; - } - - function onSSWindowStateReady(aEvent) { - readyEventCount++; - } - - function onSSTabRestored(aEvent) { - if (++tabRestoredCount < 4) - return; - - is(busyEventCount, 1); - is(readyEventCount, 1); - - reopenedWindow.removeEventListener("SSWindowStateBusy", onSSWindowStateBusy, false); - reopenedWindow.removeEventListener("SSWindowStateReady", onSSWindowStateReady, false); - reopenedWindow.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - - BrowserTestUtils.closeWindow(reopenedWindow).then(runNextTest); - } -} diff --git a/browser/components/sessionstore/test/browser_618151.js b/browser/components/sessionstore/test/browser_618151.js deleted file mode 100644 index bdc268e6c..000000000 --- a/browser/components/sessionstore/test/browser_618151.js +++ /dev/null @@ -1,65 +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 stateBackup = ss.getBrowserState(); -const testState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:blank" }] }, - { entries: [{ url: "about:mozilla" }] } - ] - }] -}; - - -function test() { - /** Test for Bug 618151 - Overwriting state can lead to unrestored tabs **/ - waitForExplicitFinish(); - runNextTest(); -} - -// Just a subset of tests from bug 615394 that causes a timeout. -var tests = [test_setup, test_hang]; -function runNextTest() { - // set an empty state & run the next test, or finish - if (tests.length) { - // Enumerate windows and close everything but our primary window. We can't - // use waitForFocus() because apparently it's buggy. See bug 599253. - var windowsEnum = Services.wm.getEnumerator("navigator:browser"); - let closeWinPromises = []; - while (windowsEnum.hasMoreElements()) { - var currentWindow = windowsEnum.getNext(); - if (currentWindow != window) { - closeWinPromises.push(BrowserTestUtils.closeWindow(currentWindow)); - } - } - - Promise.all(closeWinPromises).then(() => { - let currentTest = tests.shift(); - info("running " + currentTest.name); - waitForBrowserState(testState, currentTest); - }); - } - else { - ss.setBrowserState(stateBackup); - executeSoon(finish); - } -} - -function test_setup() { - function onSSTabRestored(aEvent) { - gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, false); - runNextTest(); - } - - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, false); - ss.setTabState(gBrowser.tabs[1], JSON.stringify({ - entries: [{ url: "http://example.org" }], - extData: { foo: "bar" } })); -} - -function test_hang() { - ok(true, "test didn't time out"); - runNextTest(); -} diff --git a/browser/components/sessionstore/test/browser_623779.js b/browser/components/sessionstore/test/browser_623779.js deleted file mode 100644 index 267bccb2d..000000000 --- a/browser/components/sessionstore/test/browser_623779.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; - -add_task(function* () { - gBrowser.pinTab(gBrowser.selectedTab); - - let newTab = gBrowser.duplicateTab(gBrowser.selectedTab); - yield promiseTabRestored(newTab); - - ok(!newTab.pinned, "duplicating a pinned tab creates unpinned tab"); - yield promiseRemoveTab(newTab); - - gBrowser.unpinTab(gBrowser.selectedTab); -}); diff --git a/browser/components/sessionstore/test/browser_624727.js b/browser/components/sessionstore/test/browser_624727.js deleted file mode 100644 index 85d6ff042..000000000 --- a/browser/components/sessionstore/test/browser_624727.js +++ /dev/null @@ -1,35 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var TEST_STATE = { windows: [{ tabs: [{ url: "about:blank" }] }] }; - -add_task(function* () { - function assertNumberOfTabs(num, msg) { - is(gBrowser.tabs.length, num, msg); - } - - function assertNumberOfPinnedTabs(num, msg) { - is(gBrowser._numPinnedTabs, num, msg); - } - - // check prerequisites - assertNumberOfTabs(1, "we start off with one tab"); - assertNumberOfPinnedTabs(0, "no pinned tabs so far"); - - // setup - gBrowser.addTab("about:blank"); - assertNumberOfTabs(2, "there are two tabs, now"); - - let [tab1, tab2] = gBrowser.tabs; - let linkedBrowser = tab1.linkedBrowser; - gBrowser.pinTab(tab1); - gBrowser.pinTab(tab2); - assertNumberOfPinnedTabs(2, "both tabs are now pinned"); - - // run the test - yield promiseBrowserState(TEST_STATE); - - assertNumberOfTabs(1, "one tab left after setBrowserState()"); - assertNumberOfPinnedTabs(0, "there are no pinned tabs"); - is(gBrowser.tabs[0].linkedBrowser, linkedBrowser, "first tab's browser got re-used"); -}); diff --git a/browser/components/sessionstore/test/browser_625016.js b/browser/components/sessionstore/test/browser_625016.js deleted file mode 100644 index b551fcbb3..000000000 --- a/browser/components/sessionstore/test/browser_625016.js +++ /dev/null @@ -1,82 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -add_task(function* setup() { - /** Test for Bug 625016 - Restore windows closed in succession to quit (non-OSX only) **/ - - // We'll test this by opening a new window, waiting for the save - // event, then closing that window. We'll observe the - // "sessionstore-state-write-complete" notification and check that - // the state contains no _closedWindows. We'll then add a new tab - // and make sure that the state following that was reset and the - // closed window is now in _closedWindows. - - requestLongerTimeout(2); - - yield forceSaveState(); - - // We'll clear all closed windows to make sure our state is clean - // forgetClosedWindow doesn't trigger a delayed save - forgetClosedWindows(); - is(ss.getClosedWindowCount(), 0, "starting with no closed windows"); -}); - -add_task(function* new_window() { - let newWin; - try { - newWin = yield promiseNewWindowLoaded(); - let tab = newWin.gBrowser.addTab("http://example.com/browser_625016.js?" + Math.random()); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // Double check that we have no closed windows - is(ss.getClosedWindowCount(), 0, "no closed windows on first save"); - - yield BrowserTestUtils.closeWindow(newWin); - newWin = null; - - let state = JSON.parse((yield promiseRecoveryFileContents())); - is(state.windows.length, 2, - "observe1: 2 windows in data written to disk"); - is(state._closedWindows.length, 0, - "observe1: no closed windows in data written to disk"); - - // The API still treats the closed window as closed, so ensure that window is there - is(ss.getClosedWindowCount(), 1, - "observe1: 1 closed window according to API"); - } finally { - if (newWin) { - yield BrowserTestUtils.closeWindow(newWin); - } - yield forceSaveState(); - } -}); - -// We'll open a tab, which should trigger another state save which would wipe -// the _shouldRestore attribute from the closed window -add_task(function* new_tab() { - let newTab; - try { - newTab = gBrowser.addTab("about:mozilla"); - - let state = JSON.parse((yield promiseRecoveryFileContents())); - is(state.windows.length, 1, - "observe2: 1 window in data being written to disk"); - is(state._closedWindows.length, 1, - "observe2: 1 closed window in data being written to disk"); - - // The API still treats the closed window as closed, so ensure that window is there - is(ss.getClosedWindowCount(), 1, - "observe2: 1 closed window according to API"); - } finally { - gBrowser.removeTab(newTab); - } -}); - - -add_task(function* done() { - // The API still represents the closed window as closed, so we can clear it - // with the API, but just to make sure... -// is(ss.getClosedWindowCount(), 1, "1 closed window according to API"); - forgetClosedWindows(); - Services.prefs.clearUserPref("browser.sessionstore.interval"); -}); diff --git a/browser/components/sessionstore/test/browser_628270.js b/browser/components/sessionstore/test/browser_628270.js deleted file mode 100644 index f552cbfda..000000000 --- a/browser/components/sessionstore/test/browser_628270.js +++ /dev/null @@ -1,52 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - let assertNumberOfTabs = function (num, msg) { - is(gBrowser.tabs.length, num, msg); - } - - let assertNumberOfVisibleTabs = function (num, msg) { - is(gBrowser.visibleTabs.length, num, msg); - } - - let assertNumberOfPinnedTabs = function (num, msg) { - is(gBrowser._numPinnedTabs, num, msg); - } - - waitForExplicitFinish(); - - // check prerequisites - assertNumberOfTabs(1, "we start off with one tab"); - - // setup - let tab = gBrowser.addTab("about:mozilla"); - - whenTabIsLoaded(tab, function () { - // hide the newly created tab - assertNumberOfVisibleTabs(2, "there are two visible tabs"); - gBrowser.showOnlyTheseTabs([gBrowser.tabs[0]]); - assertNumberOfVisibleTabs(1, "there is one visible tab"); - ok(tab.hidden, "newly created tab is now hidden"); - - // close and restore hidden tab - promiseRemoveTab(tab).then(() => { - tab = ss.undoCloseTab(window, 0); - - // check that everything was restored correctly, clean up and finish - whenTabIsLoaded(tab, function () { - is(tab.linkedBrowser.currentURI.spec, "about:mozilla", "restored tab has correct url"); - - gBrowser.removeTab(tab); - finish(); - }); - }); - }); -} - -function whenTabIsLoaded(tab, callback) { - tab.linkedBrowser.addEventListener("load", function onLoad() { - tab.linkedBrowser.removeEventListener("load", onLoad, true); - callback(); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_635418.js b/browser/components/sessionstore/test/browser_635418.js deleted file mode 100644 index 3b21c5b0f..000000000 --- a/browser/components/sessionstore/test/browser_635418.js +++ /dev/null @@ -1,55 +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 tests that hiding/showing a tab, on its own, eventually triggers a -// session store. - -function test() { - waitForExplicitFinish(); - - // We speed up the interval between session saves to ensure that the test - // runs quickly. - Services.prefs.setIntPref("browser.sessionstore.interval", 2000); - - // Loading a tab causes a save state and this is meant to catch that event. - waitForSaveState(testBug635418_1); - - // Assumption: Only one window is open and it has one tab open. - gBrowser.addTab("about:mozilla"); -} - -function testBug635418_1() { - ok(!gBrowser.tabs[0].hidden, "first tab should not be hidden"); - ok(!gBrowser.tabs[1].hidden, "second tab should not be hidden"); - - waitForSaveState(testBug635418_2); - - // We can't hide the selected tab, so hide the new one - gBrowser.hideTab(gBrowser.tabs[1]); -} - -function testBug635418_2() { - let state = JSON.parse(ss.getBrowserState()); - ok(!state.windows[0].tabs[0].hidden, "first tab should still not be hidden"); - ok(state.windows[0].tabs[1].hidden, "second tab should be hidden by now"); - - waitForSaveState(testBug635418_3); - gBrowser.showTab(gBrowser.tabs[1]); -} - -function testBug635418_3() { - let state = JSON.parse(ss.getBrowserState()); - ok(!state.windows[0].tabs[0].hidden, "first tab should still still not be hidden"); - ok(!state.windows[0].tabs[1].hidden, "second tab should not be hidden again"); - - done(); -} - -function done() { - gBrowser.removeTab(window.gBrowser.tabs[1]); - - Services.prefs.clearUserPref("browser.sessionstore.interval"); - - executeSoon(finish); -} diff --git a/browser/components/sessionstore/test/browser_636279.js b/browser/components/sessionstore/test/browser_636279.js deleted file mode 100644 index 250995606..000000000 --- a/browser/components/sessionstore/test/browser_636279.js +++ /dev/null @@ -1,101 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var stateBackup = ss.getBrowserState(); - -var statePinned = {windows:[{tabs:[ - {entries:[{url:"http://example.com#1"}], pinned: true} -]}]}; - -var state = {windows:[{tabs:[ - {entries:[{url:"http://example.com#1"}]}, - {entries:[{url:"http://example.com#2"}]}, - {entries:[{url:"http://example.com#3"}]}, - {entries:[{url:"http://example.com#4"}]}, -]}]}; - -function test() { - waitForExplicitFinish(); - - registerCleanupFunction(function () { - TabsProgressListener.uninit(); - ss.setBrowserState(stateBackup); - }); - - - TabsProgressListener.init(); - - window.addEventListener("SSWindowStateReady", function onReady() { - window.removeEventListener("SSWindowStateReady", onReady, false); - - let firstProgress = true; - - TabsProgressListener.setCallback(function (needsRestore, isRestoring) { - if (firstProgress) { - firstProgress = false; - is(isRestoring, 3, "restoring 3 tabs concurrently"); - } else { - ok(isRestoring <= 3, "restoring max. 2 tabs concurrently"); - } - - if (0 == needsRestore) { - TabsProgressListener.unsetCallback(); - waitForFocus(finish); - } - }); - - ss.setBrowserState(JSON.stringify(state)); - }, false); - - ss.setBrowserState(JSON.stringify(statePinned)); -} - -function countTabs() { - let needsRestore = 0, isRestoring = 0; - let windowsEnum = Services.wm.getEnumerator("navigator:browser"); - - while (windowsEnum.hasMoreElements()) { - let window = windowsEnum.getNext(); - if (window.closed) - continue; - - for (let i = 0; i < window.gBrowser.tabs.length; i++) { - let browser = window.gBrowser.tabs[i].linkedBrowser; - if (browser.__SS_restoreState == TAB_STATE_RESTORING) - isRestoring++; - else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) - needsRestore++; - } - } - - return [needsRestore, isRestoring]; -} - -var TabsProgressListener = { - init: function () { - Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false); - }, - - uninit: function () { - Services.obs.removeObserver(this, "sessionstore-debug-tab-restored"); - this.unsetCallback(); - }, - - setCallback: function (callback) { - this.callback = callback; - }, - - unsetCallback: function () { - delete this.callback; - }, - - observe: function (browser, topic, data) { - TabsProgressListener.onRestored(browser); - }, - - onRestored: function (browser) { - if (this.callback && browser.__SS_restoreState == TAB_STATE_RESTORING) { - this.callback.apply(null, countTabs()); - } - } -} diff --git a/browser/components/sessionstore/test/browser_637020.js b/browser/components/sessionstore/test/browser_637020.js deleted file mode 100644 index 1c1f357d7..000000000 --- a/browser/components/sessionstore/test/browser_637020.js +++ /dev/null @@ -1,66 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const TEST_URL = "http://mochi.test:8888/browser/browser/components/" + - "sessionstore/test/browser_637020_slow.sjs"; - -const TEST_STATE = { - windows: [{ - tabs: [ - { entries: [{ url: "about:mozilla" }] }, - { entries: [{ url: "about:robots" }] } - ] - }, { - tabs: [ - { entries: [{ url: TEST_URL }] }, - { entries: [{ url: TEST_URL }] } - ] - }] -}; - -/** - * This test ensures that windows that have just been restored will be marked - * as dirty, otherwise _getCurrentState() might ignore them when collecting - * state for the first time and we'd just save them as empty objects. - * - * The dirty state acts as a cache to not collect data from all windows all the - * time, so at the beginning, each window must be dirty so that we collect - * their state at least once. - */ - -add_task(function* test() { - // Wait until the new window has been opened. - let promiseWindow = new Promise(resolve => { - Services.obs.addObserver(function onOpened(subject) { - Services.obs.removeObserver(onOpened, "domwindowopened"); - resolve(subject); - }, "domwindowopened", false); - }); - - // Set the new browser state that will - // restore a window with two slowly loading tabs. - let backupState = SessionStore.getBrowserState(); - SessionStore.setBrowserState(JSON.stringify(TEST_STATE)); - let win = yield promiseWindow; - - // The window has now been opened. Check the state that is returned, - // this should come from the cache while the window isn't restored, yet. - info("the window has been opened"); - checkWindows(); - - // The history has now been restored and the tabs are loading. The data must - // now come from the window, if it's correctly been marked as dirty before. - yield new Promise(resolve => whenDelayedStartupFinished(win, resolve)); - info("the delayed startup has finished"); - checkWindows(); - - // Cleanup. - yield BrowserTestUtils.closeWindow(win); - yield promiseBrowserState(backupState); -}); - -function checkWindows() { - let state = JSON.parse(SessionStore.getBrowserState()); - is(state.windows[0].tabs.length, 2, "first window has two tabs"); - is(state.windows[1].tabs.length, 2, "second window has two tabs"); -} diff --git a/browser/components/sessionstore/test/browser_637020_slow.sjs b/browser/components/sessionstore/test/browser_637020_slow.sjs deleted file mode 100644 index 41da3c2ad..000000000 --- a/browser/components/sessionstore/test/browser_637020_slow.sjs +++ /dev/null @@ -1,21 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Cc = Components.classes; -const Ci = Components.interfaces; - -const DELAY_MS = "2000"; - -let timer; - -function handleRequest(req, resp) { - resp.processAsync(); - resp.setHeader("Cache-Control", "no-cache", false); - resp.setHeader("Content-Type", "text/html;charset=utf-8", false); - - timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - timer.init(() => { - resp.write("hi"); - resp.finish(); - }, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT); -} diff --git a/browser/components/sessionstore/test/browser_644409-scratchpads.js b/browser/components/sessionstore/test/browser_644409-scratchpads.js deleted file mode 100644 index 56826801a..000000000 --- a/browser/components/sessionstore/test/browser_644409-scratchpads.js +++ /dev/null @@ -1,68 +0,0 @@ - /* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const testState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:blank" }] }, - ] - }], - scratchpads: [ - { text: "text1", executionContext: 1 }, - { text: "", executionContext: 2, filename: "test.js" } - ] -}; - -// only finish() when correct number of windows opened -var restored = []; -function addState(state) { - restored.push(state); - - if (restored.length == testState.scratchpads.length) { - ok(statesMatch(restored, testState.scratchpads), - "Two scratchpad windows restored"); - - Services.ww.unregisterNotification(windowObserver); - finish(); - } -} - -function test() { - waitForExplicitFinish(); - - Services.ww.registerNotification(windowObserver); - - ss.setBrowserState(JSON.stringify(testState)); -} - -function windowObserver(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - let win = aSubject.QueryInterface(Ci.nsIDOMWindow); - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - - if (win.Scratchpad) { - win.Scratchpad.addObserver({ - onReady: function() { - win.Scratchpad.removeObserver(this); - - let state = win.Scratchpad.getState(); - BrowserTestUtils.closeWindow(win).then(() => { - addState(state); - }); - }, - }); - } - }, false); - } -} - -function statesMatch(restored, states) { - return states.every(function(state) { - return restored.some(function(restoredState) { - return state.filename == restoredState.filename && - state.text == restoredState.text && - state.executionContext == restoredState.executionContext; - }) - }); -} diff --git a/browser/components/sessionstore/test/browser_645428.js b/browser/components/sessionstore/test/browser_645428.js deleted file mode 100644 index 124a7aea9..000000000 --- a/browser/components/sessionstore/test/browser_645428.js +++ /dev/null @@ -1,22 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const NOTIFICATION = "sessionstore-browser-state-restored"; - -function test() { - waitForExplicitFinish(); - - function observe(subject, topic, data) { - if (NOTIFICATION == topic) { - finish(); - ok(true, "TOPIC received"); - } - } - - Services.obs.addObserver(observe, NOTIFICATION, false); - registerCleanupFunction(function () { - Services.obs.removeObserver(observe, NOTIFICATION); - }); - - ss.setBrowserState(JSON.stringify({ windows: [] })); -} diff --git a/browser/components/sessionstore/test/browser_659591.js b/browser/components/sessionstore/test/browser_659591.js deleted file mode 100644 index 60b1dcd2e..000000000 --- a/browser/components/sessionstore/test/browser_659591.js +++ /dev/null @@ -1,33 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - waitForExplicitFinish(); - - let eventReceived = false; - - registerCleanupFunction(function () { - ok(eventReceived, "SSWindowClosing event received"); - }); - - newWindow(function (win) { - win.addEventListener("SSWindowClosing", function onWindowClosing() { - win.removeEventListener("SSWindowClosing", onWindowClosing, false); - eventReceived = true; - }, false); - - BrowserTestUtils.closeWindow(win).then(() => { - waitForFocus(finish); - }); - }); -} - -function newWindow(callback) { - let opts = "chrome,all,dialog=no,height=800,width=800"; - let win = window.openDialog(getBrowserURL(), "_blank", opts); - - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad, false); - executeSoon(() => callback(win)); - }, false); -} diff --git a/browser/components/sessionstore/test/browser_662743.js b/browser/components/sessionstore/test/browser_662743.js deleted file mode 100644 index 212180213..000000000 --- a/browser/components/sessionstore/test/browser_662743.js +++ /dev/null @@ -1,110 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -// This tests that session restore component does restore the right <select> option. -// Session store should not rely only on previous user's selectedIndex, it should -// check its value as well. - -function test() { - /** Tests selected options **/ - requestLongerTimeout(2); - waitForExplicitFinish(); - - let testTabCount = 0; - let formData = [ - // default case - { }, - - // new format - // index doesn't match value (testing an option in between (two)) - { id:{ "select_id": {"selectedIndex":0,"value":"val2"} } }, - // index doesn't match value (testing an invalid value) - { id:{ "select_id": {"selectedIndex":4,"value":"val8"} } }, - // index doesn't match value (testing an invalid index) - { id:{ "select_id": {"selectedIndex":8,"value":"val5"} } }, - // index and value match position zero - { id:{ "select_id": {"selectedIndex":0,"value":"val0"} }, xpath: {} }, - // index doesn't match value (testing the last option (seven)) - { id:{},"xpath":{ "/xhtml:html/xhtml:body/xhtml:select[@name='select_name']": {"selectedIndex":1,"value":"val7"} } }, - // index and value match the default option "selectedIndex":3,"value":"val3" - { xpath: { "/xhtml:html/xhtml:body/xhtml:select[@name='select_name']" : {"selectedIndex":3,"value":"val3"} } }, - // index matches default option however it doesn't match value - { id:{ "select_id": {"selectedIndex":3,"value":"val4"} } }, - ]; - - let expectedValues = [ - null, // default value - "val2", - null, // default value (invalid value) - "val5", // value is still valid (even it has an invalid index) - "val0", - "val7", - null, - "val4", - ]; - let callback = function() { - testTabCount--; - if (testTabCount == 0) { - finish(); - } - }; - - for (let i = 0; i < formData.length; i++) { - testTabCount++; - testTabRestoreData(formData[i], expectedValues[i], callback); - } -} - -function testTabRestoreData(aFormData, aExpectedValue, aCallback) { - let testURL = - getRootDirectory(gTestPath) + "browser_662743_sample.html"; - let tab = gBrowser.addTab(testURL); - - aFormData.url = testURL; - let tabState = { entries: [{ url: testURL, }], formdata: aFormData }; - - promiseBrowserLoaded(tab.linkedBrowser).then(() => { - promiseTabState(tab, tabState).then(() => { - // Flush to make sure we have the latest form data. - return TabStateFlusher.flush(tab.linkedBrowser); - }).then(() => { - let doc = tab.linkedBrowser.contentDocument; - let select = doc.getElementById("select_id"); - let value = select.options[select.selectedIndex].value; - let restoredTabState = JSON.parse(ss.getTabState(tab)); - - // If aExpectedValue=null we don't expect any form data to be collected. - if (!aExpectedValue) { - ok(!restoredTabState.hasOwnProperty("formdata"), "no formdata collected"); - gBrowser.removeTab(tab); - aCallback(); - return; - } - - // test select options values - is(value, aExpectedValue, - "Select Option by selectedIndex &/or value has been restored correctly"); - - let restoredFormData = restoredTabState.formdata; - let selectIdFormData = restoredFormData.id.select_id; - value = restoredFormData.id.select_id.value; - - // test format - ok("id" in restoredFormData || "xpath" in restoredFormData, - "FormData format is valid"); - // test format - ok("selectedIndex" in selectIdFormData && "value" in selectIdFormData, - "select format is valid"); - // test set collection values - is(value, aExpectedValue, - "Collection has been saved correctly"); - - // clean up - gBrowser.removeTab(tab); - - aCallback(); - }); - }); -} diff --git a/browser/components/sessionstore/test/browser_662743_sample.html b/browser/components/sessionstore/test/browser_662743_sample.html deleted file mode 100644 index de48fa0c9..000000000 --- a/browser/components/sessionstore/test/browser_662743_sample.html +++ /dev/null @@ -1,15 +0,0 @@ -<!DOCTYPE html> -<title>Test 662743</title> - -<!-- Select events --> -<h3>Select options</h3> -<select id="select_id" name="select_name"> - <option value="val0">Zero</option> - <option value="val1">One</option> - <option value="val2">Two</option> - <option value="val3" selected="selected">Three</option> - <option value="val4">Four</option> - <option value="val5">Five</option> - <option value="val6">Six</option> - <option value="val7">Seven</option> -</select>
\ No newline at end of file diff --git a/browser/components/sessionstore/test/browser_662812.js b/browser/components/sessionstore/test/browser_662812.js deleted file mode 100644 index 1bbaf67dc..000000000 --- a/browser/components/sessionstore/test/browser_662812.js +++ /dev/null @@ -1,36 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - waitForExplicitFinish(); - - window.addEventListener("SSWindowStateBusy", function onBusy() { - window.removeEventListener("SSWindowStateBusy", onBusy, false); - - let state = JSON.parse(ss.getWindowState(window)); - ok(state.windows[0].busy, "window is busy"); - - window.addEventListener("SSWindowStateReady", function onReady() { - window.removeEventListener("SSWindowStateReady", onReady, false); - - let state = JSON.parse(ss.getWindowState(window)); - ok(!state.windows[0].busy, "window is not busy"); - - executeSoon(() => { - gBrowser.removeTab(gBrowser.tabs[1]); - finish(); - }); - }, false); - }, false); - - // create a new tab - let tab = gBrowser.addTab("about:mozilla"); - let browser = tab.linkedBrowser; - - // close and restore it - browser.addEventListener("load", function onLoad() { - browser.removeEventListener("load", onLoad, true); - gBrowser.removeTab(tab); - ss.undoCloseTab(window, 0); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_665702-state_session.js b/browser/components/sessionstore/test/browser_665702-state_session.js deleted file mode 100644 index 524b4969f..000000000 --- a/browser/components/sessionstore/test/browser_665702-state_session.js +++ /dev/null @@ -1,24 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function compareArray(a, b) { - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} - -function test() { - let currentState = JSON.parse(ss.getBrowserState()); - ok(currentState.session, "session data returned by getBrowserState"); - - let keys = Object.keys(currentState.session); - let expectedKeys = ["lastUpdate", "startTime", "recentCrashes"]; - ok(compareArray(keys.sort(), expectedKeys.sort()), - "session object from getBrowserState has correct keys"); -} diff --git a/browser/components/sessionstore/test/browser_682507.js b/browser/components/sessionstore/test/browser_682507.js deleted file mode 100644 index 52b95341b..000000000 --- a/browser/components/sessionstore/test/browser_682507.js +++ /dev/null @@ -1,16 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function test() { - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - gBrowser.addTab("about:mozilla"); - - ss.setTabState(gBrowser.tabs[1], ss.getTabState(gBrowser.tabs[1])); - ok(gBrowser.tabs[1].hasAttribute("pending"), "second tab should have 'pending' attribute"); - - gBrowser.selectedTab = gBrowser.tabs[1]; - ok(!gBrowser.tabs[1].hasAttribute("pending"), "second tab should have not 'pending' attribute"); - - gBrowser.removeTab(gBrowser.tabs[1]); - Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); -} diff --git a/browser/components/sessionstore/test/browser_687710.js b/browser/components/sessionstore/test/browser_687710.js deleted file mode 100644 index 372ecf7ae..000000000 --- a/browser/components/sessionstore/test/browser_687710.js +++ /dev/null @@ -1,44 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// Test that sessionrestore handles cycles in the shentry graph properly. -// -// These cycles shouldn't be there in the first place, but they cause hangs -// when they mysteriously appear (bug 687710). Docshell code assumes this -// graph is a tree and tires to walk to the root. But if there's a cycle, -// there is no root, and we loop forever. - -var stateBackup = ss.getBrowserState(); - -var state = {windows:[{tabs:[{entries:[ - { - docIdentifier: 1, - url: "http://example.com", - children: [ - { - docIdentifier: 2, - url: "http://example.com" - } - ] - }, - { - docIdentifier: 2, - url: "http://example.com", - children: [ - { - docIdentifier: 1, - url: "http://example.com" - } - ] - } -]}]}]} - -function test() { - registerCleanupFunction(function () { - ss.setBrowserState(stateBackup); - }); - - /* This test fails by hanging. */ - ss.setBrowserState(JSON.stringify(state)); - ok(true, "Didn't hang!"); -} diff --git a/browser/components/sessionstore/test/browser_687710_2.js b/browser/components/sessionstore/test/browser_687710_2.js deleted file mode 100644 index c22e73750..000000000 --- a/browser/components/sessionstore/test/browser_687710_2.js +++ /dev/null @@ -1,64 +0,0 @@ -/* eslint-env mozilla/frame-script */ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// Test that the fix for bug 687710 isn't too aggressive -- shentries which are -// cousins should be able to share bfcache entries. - -var stateBackup = ss.getBrowserState(); - -var state = {entries:[ - { - docIdentifier: 1, - url: "http://example.com?1", - children: [{ docIdentifier: 10, - url: "http://example.com?10" }] - }, - { - docIdentifier: 1, - url: "http://example.com?1#a", - children: [{ docIdentifier: 10, - url: "http://example.com?10#aa" }] - } -]}; - -add_task(function* test() { - let tab = gBrowser.addTab("about:blank"); - yield promiseTabState(tab, state); - yield ContentTask.spawn(tab.linkedBrowser, null, function() { - function compareEntries(i, j, history) { - let e1 = history.getEntryAtIndex(i, false) - .QueryInterface(Ci.nsISHEntry) - .QueryInterface(Ci.nsISHContainer); - - let e2 = history.getEntryAtIndex(j, false) - .QueryInterface(Ci.nsISHEntry) - .QueryInterface(Ci.nsISHContainer); - - ok(e1.sharesDocumentWith(e2), - `${i} should share doc with ${j}`); - is(e1.childCount, e2.childCount, - `Child count mismatch (${i}, ${j})`); - - for (let c = 0; c < e1.childCount; c++) { - let c1 = e1.GetChildAt(c); - let c2 = e2.GetChildAt(c); - - ok(c1.sharesDocumentWith(c2), - `Cousins should share documents. (${i}, ${j}, ${c})`); - } - } - - let history = docShell.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsISHistory); - - is(history.count, 2, "history.count"); - for (let i = 0; i < history.count; i++) { - for (let j = 0; j < history.count; j++) { - compareEntries(i, j, history); - } - } - }); - - ss.setBrowserState(stateBackup); -}); diff --git a/browser/components/sessionstore/test/browser_694378.js b/browser/components/sessionstore/test/browser_694378.js deleted file mode 100644 index 8578428d8..000000000 --- a/browser/components/sessionstore/test/browser_694378.js +++ /dev/null @@ -1,33 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// Test Summary: -// 1. call ss.setWindowState with a broken state -// 1a. ensure that it doesn't throw. - -function test() { - waitForExplicitFinish(); - - let brokenState = { - windows: [ - { tabs: [{ entries: [{ url: "about:mozilla" }] }] } - ], - selectedWindow: 2 - }; - let brokenStateString = JSON.stringify(brokenState); - - let gotError = false; - try { - ss.setWindowState(window, brokenStateString, true); - } - catch (ex) { - gotError = true; - info(ex); - } - - ok(!gotError, "ss.setWindowState did not throw an error"); - - // Make sure that we reset the state. Use a full state just in case things get crazy. - let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]}; - waitForBrowserState(blankState, finish); -} diff --git a/browser/components/sessionstore/test/browser_701377.js b/browser/components/sessionstore/test/browser_701377.js deleted file mode 100644 index 1bf2625ef..000000000 --- a/browser/components/sessionstore/test/browser_701377.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var state = {windows:[{tabs:[ - {entries:[{url:"http://example.com#1"}]}, - {entries:[{url:"http://example.com#2"}], hidden: true} -]}]}; - -function test() { - waitForExplicitFinish(); - - newWindowWithState(state, function (aWindow) { - let tab = aWindow.gBrowser.tabs[1]; - ok(tab.hidden, "the second tab is hidden"); - - let tabShown = false; - let tabShowCallback = () => tabShown = true; - tab.addEventListener("TabShow", tabShowCallback, false); - - let tabState = ss.getTabState(tab); - ss.setTabState(tab, tabState); - - tab.removeEventListener("TabShow", tabShowCallback, false); - ok(tab.hidden && !tabShown, "tab remains hidden"); - - finish(); - }); -} - -// ---------- -function newWindowWithState(aState, aCallback) { - let opts = "chrome,all,dialog=no,height=800,width=800"; - let win = window.openDialog(getBrowserURL(), "_blank", opts); - - registerCleanupFunction(() => BrowserTestUtils.closeWindow(win)); - - whenWindowLoaded(win, function onWindowLoaded(aWin) { - ss.setWindowState(aWin, JSON.stringify(aState), true); - executeSoon(() => aCallback(aWin)); - }); -} diff --git a/browser/components/sessionstore/test/browser_705597.js b/browser/components/sessionstore/test/browser_705597.js deleted file mode 100644 index efadcfe88..000000000 --- a/browser/components/sessionstore/test/browser_705597.js +++ /dev/null @@ -1,58 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var tabState = { - entries: [{url: "about:robots", children: [{url: "about:mozilla"}]}] -}; - -function test() { - waitForExplicitFinish(); - requestLongerTimeout(2); - - Services.prefs.setIntPref("browser.sessionstore.interval", 4000); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.interval"); - }); - - let tab = gBrowser.addTab("about:blank"); - - let browser = tab.linkedBrowser; - - promiseTabState(tab, tabState).then(() => { - let sessionHistory = browser.sessionHistory; - let entry = sessionHistory.getEntryAtIndex(0, false); - entry.QueryInterface(Ci.nsISHContainer); - - whenChildCount(entry, 1, function () { - whenChildCount(entry, 2, function () { - promiseBrowserLoaded(browser).then(() => { - return TabStateFlusher.flush(browser); - }).then(() => { - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "tab has one history entry"); - ok(!entries[0].children, "history entry has no subframes"); - - // Make sure that we reset the state. - let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]}; - waitForBrowserState(blankState, finish); - }); - - // reload the browser to deprecate the subframes - browser.reload(); - }); - - // create a dynamic subframe - let doc = browser.contentDocument; - let iframe = doc.createElement("iframe"); - doc.body.appendChild(iframe); - iframe.setAttribute("src", "about:mozilla"); - }); - }); -} - -function whenChildCount(aEntry, aChildCount, aCallback) { - if (aEntry.childCount == aChildCount) - aCallback(); - else - setTimeout(() => whenChildCount(aEntry, aChildCount, aCallback), 100); -} diff --git a/browser/components/sessionstore/test/browser_707862.js b/browser/components/sessionstore/test/browser_707862.js deleted file mode 100644 index e12c44af4..000000000 --- a/browser/components/sessionstore/test/browser_707862.js +++ /dev/null @@ -1,61 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var tabState = { - entries: [{url: "about:robots", children: [{url: "about:mozilla"}]}] -}; - -function test() { - waitForExplicitFinish(); - requestLongerTimeout(2); - - Services.prefs.setIntPref("browser.sessionstore.interval", 4000); - registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.interval"); - }); - - let tab = gBrowser.addTab("about:blank"); - - let browser = tab.linkedBrowser; - - promiseTabState(tab, tabState).then(() => { - let sessionHistory = browser.sessionHistory; - let entry = sessionHistory.getEntryAtIndex(0, false); - entry.QueryInterface(Ci.nsISHContainer); - - whenChildCount(entry, 1, function () { - whenChildCount(entry, 2, function () { - promiseBrowserLoaded(browser).then(() => { - let sessionHistory = browser.sessionHistory; - let entry = sessionHistory.getEntryAtIndex(0, false); - - whenChildCount(entry, 0, function () { - // Make sure that we reset the state. - let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank" }] }]}]}; - waitForBrowserState(blankState, finish); - }); - }); - - // reload the browser to deprecate the subframes - browser.reload(); - }); - - // create a dynamic subframe - let doc = browser.contentDocument; - let iframe = doc.createElement("iframe"); - doc.body.appendChild(iframe); - iframe.setAttribute("src", "about:mozilla"); - }); - }); - - // This test relies on the test timing out in order to indicate failure so - // let's add a dummy pass. - ok(true, "Each test requires at least one pass, fail or todo so here is a pass."); -} - -function whenChildCount(aEntry, aChildCount, aCallback) { - if (aEntry.childCount == aChildCount) - aCallback(); - else - setTimeout(() => whenChildCount(aEntry, aChildCount, aCallback), 100); -} diff --git a/browser/components/sessionstore/test/browser_739531.js b/browser/components/sessionstore/test/browser_739531.js deleted file mode 100644 index e5927caf6..000000000 --- a/browser/components/sessionstore/test/browser_739531.js +++ /dev/null @@ -1,47 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// This test ensures that attempts made to save/restore ("duplicate") pages -// using designmode AND make changes to document structure (remove body) -// don't result in uncaught errors and a broken browser state. - -function test() { - waitForExplicitFinish(); - - let testURL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_739531_sample.html"; - - let loadCount = 0; - let tab = gBrowser.addTab(testURL); - tab.linkedBrowser.addEventListener("load", function onLoad(aEvent) { - // make sure both the page and the frame are loaded - if (++loadCount < 2) - return; - tab.linkedBrowser.removeEventListener("load", onLoad, true); - - // executeSoon to allow the JS to execute on the page - executeSoon(function() { - - let tab2; - let caughtError = false; - try { - tab2 = ss.duplicateTab(window, tab); - } - catch (e) { - caughtError = true; - info(e); - } - - is(gBrowser.tabs.length, 3, "there should be 3 tabs") - - ok(!caughtError, "duplicateTab didn't throw"); - - // if the test fails, we don't want to try to close a tab that doesn't exist - if (tab2) - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); - - finish(); - }); - }, true); -} diff --git a/browser/components/sessionstore/test/browser_739531_sample.html b/browser/components/sessionstore/test/browser_739531_sample.html deleted file mode 100644 index ad317ab0c..000000000 --- a/browser/components/sessionstore/test/browser_739531_sample.html +++ /dev/null @@ -1,25 +0,0 @@ -<!-- originally a crash test for bug 713417 - https://bug713417.bugzilla.mozilla.org/attachment.cgi?id=584240 --> -<!DOCTYPE html> -<html> -<head> -<meta charset="utf-8"> -<script> - -function boom() -{ - var w = document.getElementById("f").contentWindow; - var d = w.document; - d.designMode = 'on'; - var r = d.documentElement; - d.removeChild(r); - document.adoptNode(r); -} - -</script> -</head> -<body onload="boom();"> -<iframe src="data:text/html;charset=utf-8,1" id="f"></iframe> -</body> -</html> - diff --git a/browser/components/sessionstore/test/browser_739805.js b/browser/components/sessionstore/test/browser_739805.js deleted file mode 100644 index f00871661..000000000 --- a/browser/components/sessionstore/test/browser_739805.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -var url = "data:text/html;charset=utf-8,<input%20id='foo'>"; -var tabState = { - entries: [{ url }], formdata: { id: { "foo": "bar" }, url } -}; - -function test() { - waitForExplicitFinish(); - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - registerCleanupFunction(function () { - if (gBrowser.tabs.length > 1) - gBrowser.removeTab(gBrowser.tabs[1]); - Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); - }); - - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - - promiseBrowserLoaded(browser).then(() => { - isnot(gBrowser.selectedTab, tab, "newly created tab is not selected"); - - ss.setTabState(tab, JSON.stringify(tabState)); - is(browser.__SS_restoreState, TAB_STATE_NEEDS_RESTORE, "tab needs restoring"); - - let {formdata} = JSON.parse(ss.getTabState(tab)); - is(formdata && formdata.id["foo"], "bar", "tab state's formdata is valid"); - - promiseTabRestored(tab).then(() => { - ContentTask.spawn(browser, null, function() { - let input = content.document.getElementById("foo"); - is(input.value, "bar", "formdata has been restored correctly"); - }).then(() => { finish(); }); - }); - - // Restore the tab by selecting it. - gBrowser.selectedTab = tab; - }); -} diff --git a/browser/components/sessionstore/test/browser_819510_perwindowpb.js b/browser/components/sessionstore/test/browser_819510_perwindowpb.js deleted file mode 100644 index 21f916f0d..000000000 --- a/browser/components/sessionstore/test/browser_819510_perwindowpb.js +++ /dev/null @@ -1,120 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// Test opening default mochitest-normal-private-normal-private windows -// (saving the state with last window being private) - -requestLongerTimeout(2); - -add_task(function* test_1() { - let win = yield promiseNewWindowLoaded(); - win.gBrowser.addTab("http://www.example.com/1"); - - win = yield promiseNewWindowLoaded({private: true}); - win.gBrowser.addTab("http://www.example.com/2"); - - win = yield promiseNewWindowLoaded(); - win.gBrowser.addTab("http://www.example.com/3"); - - win = yield promiseNewWindowLoaded({private: true}); - win.gBrowser.addTab("http://www.example.com/4"); - - let curState = JSON.parse(ss.getBrowserState()); - is(curState.windows.length, 5, "Browser has opened 5 windows"); - is(curState.windows[2].isPrivate, true, "Window is private"); - is(curState.windows[4].isPrivate, true, "Last window is private"); - is(curState.selectedWindow, 5, "Last window opened is the one selected"); - - let state = JSON.parse(yield promiseRecoveryFileContents()); - - is(state.windows.length, 3, - "sessionstore state: 3 windows in data being written to disk"); - is(state.selectedWindow, 3, - "Selected window is updated to match one of the saved windows"); - ok(state.windows.every(win => !win.isPrivate), - "Saved windows are not private"); - is(state._closedWindows.length, 0, - "sessionstore state: no closed windows in data being written to disk"); - - // Cleanup. - yield promiseAllButPrimaryWindowClosed(); - forgetClosedWindows(); -}); - -// Test opening default mochitest window + 2 private windows -add_task(function* test_2() { - let win = yield promiseNewWindowLoaded({private: true}); - win.gBrowser.addTab("http://www.example.com/1"); - - win = yield promiseNewWindowLoaded({private: true}); - win.gBrowser.addTab("http://www.example.com/2"); - - let curState = JSON.parse(ss.getBrowserState()); - is(curState.windows.length, 3, "Browser has opened 3 windows"); - is(curState.windows[1].isPrivate, true, "Window 1 is private"); - is(curState.windows[2].isPrivate, true, "Window 2 is private"); - is(curState.selectedWindow, 3, "Last window opened is the one selected"); - - let state = JSON.parse(yield promiseRecoveryFileContents()); - - is(state.windows.length, 1, - "sessionstore state: 1 windows in data being written to disk"); - is(state.selectedWindow, 1, - "Selected window is updated to match one of the saved windows"); - is(state._closedWindows.length, 0, - "sessionstore state: no closed windows in data being written to disk"); - - // Cleanup. - yield promiseAllButPrimaryWindowClosed(); - forgetClosedWindows(); -}); - -// Test opening default-normal-private-normal windows and closing a normal window -add_task(function* test_3() { - let normalWindow = yield promiseNewWindowLoaded(); - yield promiseTabLoad(normalWindow, "http://www.example.com/"); - - let win = yield promiseNewWindowLoaded({private: true}); - yield promiseTabLoad(win, "http://www.example.com/"); - - win = yield promiseNewWindowLoaded(); - yield promiseTabLoad(win, "http://www.example.com/"); - - let curState = JSON.parse(ss.getBrowserState()); - is(curState.windows.length, 4, "Browser has opened 4 windows"); - is(curState.windows[2].isPrivate, true, "Window 2 is private"); - is(curState.selectedWindow, 4, "Last window opened is the one selected"); - - yield BrowserTestUtils.closeWindow(normalWindow); - - // Pin and unpin a tab before checking the written state so that - // the list of restoring windows gets cleared. Otherwise the - // window we just closed would be marked as not closed. - let tab = win.gBrowser.tabs[0]; - win.gBrowser.pinTab(tab); - win.gBrowser.unpinTab(tab); - - let state = JSON.parse(yield promiseRecoveryFileContents()); - - is(state.windows.length, 2, - "sessionstore state: 2 windows in data being written to disk"); - is(state.selectedWindow, 2, - "Selected window is updated to match one of the saved windows"); - ok(state.windows.every(win => !win.isPrivate), - "Saved windows are not private"); - is(state._closedWindows.length, 1, - "sessionstore state: 1 closed window in data being written to disk"); - ok(state._closedWindows.every(win => !win.isPrivate), - "Closed windows are not private"); - - // Cleanup. - yield promiseAllButPrimaryWindowClosed(); - forgetClosedWindows(); -}); - -function* promiseTabLoad(win, url) { - let browser = win.gBrowser.selectedBrowser; - browser.loadURI(url); - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); -} diff --git a/browser/components/sessionstore/test/browser_911547.js b/browser/components/sessionstore/test/browser_911547.js deleted file mode 100644 index 58b2e9ef1..000000000 --- a/browser/components/sessionstore/test/browser_911547.js +++ /dev/null @@ -1,63 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// This tests that session restore component does restore the right content -// security policy with the document. -// The policy being tested disallows inline scripts - -add_task(function* test() { - // create a tab that has a CSP - let testURL = "http://mochi.test:8888/browser/browser/components/sessionstore/test/browser_911547_sample.html"; - let tab = gBrowser.selectedTab = gBrowser.addTab(testURL); - gBrowser.selectedTab = tab; - - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // this is a baseline to ensure CSP is active - // attempt to inject and run a script via inline (pre-restore, allowed) - yield injectInlineScript(browser, `document.getElementById("test_id").value = "fail";`); - - let loadedPromise = promiseBrowserLoaded(browser); - yield ContentTask.spawn(browser, null, function() { - is(content.document.getElementById("test_id").value, "ok", - "CSP should block the inline script that modifies test_id"); - - // attempt to click a link to a data: URI (will inherit the CSP of the - // origin document) and navigate to the data URI in the link. - content.document.getElementById("test_data_link").click(); - }); - - yield loadedPromise; - - yield ContentTask.spawn(browser, null, function() { - is(content.document.getElementById("test_id2").value, "ok", - "CSP should block the script loaded by the clicked data URI"); - }); - - // close the tab - yield promiseRemoveTab(tab); - - // open new tab and recover the state - tab = ss.undoCloseTab(window, 0); - yield promiseTabRestored(tab); - browser = tab.linkedBrowser; - - yield ContentTask.spawn(browser, null, function() { - is(content.document.getElementById("test_id2").value, "ok", - "CSP should block the script loaded by the clicked data URI after restore"); - }); - - // clean up - gBrowser.removeTab(tab); -}); - -// injects an inline script element (with a text body) -function injectInlineScript(browser, scriptText) { - return ContentTask.spawn(browser, scriptText, function(text) { - let scriptElt = content.document.createElement("script"); - scriptElt.type = "text/javascript"; - scriptElt.text = text; - content.document.body.appendChild(scriptElt); - }); -} diff --git a/browser/components/sessionstore/test/browser_911547_sample.html b/browser/components/sessionstore/test/browser_911547_sample.html deleted file mode 100644 index ccc201159..000000000 --- a/browser/components/sessionstore/test/browser_911547_sample.html +++ /dev/null @@ -1,19 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <meta charset="utf-8"> - <title>Test 911547</title> - </head> -<body> - - <!-- - this element gets modified by an injected script; - that script should be blocked by CSP. - Inline scripts can modify it, but not data uris. - --> - <input type="text" id="test_id" value="ok"> - - <a id="test_data_link" href="data:text/html;charset=utf-8,<input type='text' id='test_id2' value='ok'/> <script>document.getElementById('test_id2').value = 'fail';</script>">Test Link</a> - -</body> -</html> diff --git a/browser/components/sessionstore/test/browser_911547_sample.html^headers^ b/browser/components/sessionstore/test/browser_911547_sample.html^headers^ deleted file mode 100644 index 4623dec30..000000000 --- a/browser/components/sessionstore/test/browser_911547_sample.html^headers^ +++ /dev/null @@ -1 +0,0 @@ -Content-Security-Policy: script-src 'self' diff --git a/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js b/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js deleted file mode 100644 index 3050bd4c1..000000000 --- a/browser/components/sessionstore/test/browser_aboutPrivateBrowsing.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; - -// Tests that an about:privatebrowsing tab with no history will not -// be saved into session store and thus, it will not show up in -// Recently Closed Tabs. - -add_task(function* () { - let tab = gBrowser.addTab("about:privatebrowsing"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - is(gBrowser.browsers[1].currentURI.spec, "about:privatebrowsing", - "we will be removing an about:privatebrowsing tab"); - - let r = `rand-${Math.random()}`; - ss.setTabValue(tab, "foobar", r); - - yield promiseRemoveTab(tab); - let closedTabData = ss.getClosedTabData(window); - ok(!closedTabData.includes(r), "tab not stored in _closedTabs"); -}); diff --git a/browser/components/sessionstore/test/browser_aboutSessionRestore.js b/browser/components/sessionstore/test/browser_aboutSessionRestore.js deleted file mode 100644 index 8ab91e4df..000000000 --- a/browser/components/sessionstore/test/browser_aboutSessionRestore.js +++ /dev/null @@ -1,55 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const CRASH_URL = "about:mozilla"; -const CRASH_FAVICON = "chrome://branding/content/icon32.png"; -const CRASH_SHENTRY = {url: CRASH_URL}; -const CRASH_TAB = {entries: [CRASH_SHENTRY], image: CRASH_FAVICON}; -const CRASH_STATE = {windows: [{tabs: [CRASH_TAB]}]}; - -const TAB_URL = "about:sessionrestore"; -const TAB_FORMDATA = {url: TAB_URL, id: {sessionData: CRASH_STATE}}; -const TAB_SHENTRY = {url: TAB_URL}; -const TAB_STATE = {entries: [TAB_SHENTRY], formdata: TAB_FORMDATA}; - -const FRAME_SCRIPT = "data:," + - "content.document.getElementById('errorTryAgain').click()"; - -add_task(function* () { - // Prepare a blank tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Fake a post-crash tab. - ss.setTabState(tab, JSON.stringify(TAB_STATE)); - yield promiseTabRestored(tab); - - ok(gBrowser.tabs.length > 1, "we have more than one tab"); - - let view = browser.contentDocument.getElementById("tabList").view; - ok(view.isContainer(0), "first entry is the window"); - is(view.getCellProperties(1, { id: "title" }), "icon", - "second entry is the tab and has a favicon"); - - browser.messageManager.loadFrameScript(FRAME_SCRIPT, true); - - // Wait until the new window was restored. - let win = yield waitForNewWindow(); - yield BrowserTestUtils.closeWindow(win); - - let [{tabs: [{entries: [{url}]}]}] = JSON.parse(ss.getClosedWindowData()); - is(url, CRASH_URL, "session was restored correctly"); - ss.forgetClosedWindow(0); -}); - -function waitForNewWindow() { - return new Promise(resolve => { - Services.obs.addObserver(function observe(win, topic) { - Services.obs.removeObserver(observe, topic); - resolve(win); - }, "browser-delayed-startup-finished", false); - }); -} diff --git a/browser/components/sessionstore/test/browser_async_duplicate_tab.js b/browser/components/sessionstore/test/browser_async_duplicate_tab.js deleted file mode 100644 index 8696a284f..000000000 --- a/browser/components/sessionstore/test/browser_async_duplicate_tab.js +++ /dev/null @@ -1,78 +0,0 @@ -"use strict"; - -const URL = "data:text/html;charset=utf-8,<a href=%23>clickme</a>"; - -add_task(function* test_duplicate() { - // Create new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // Click the link to navigate, this will add second shistory entry. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("hashchange", function onHashChange() { - removeEventListener("hashchange", onHashChange); - resolve(); - }); - - // Click the link. - content.document.querySelector("a").click(); - }); - }); - - // Duplicate the tab. - let tab2 = ss.duplicateTab(window, tab); - - // Wait until the tab has fully restored. - yield promiseTabRestored(tab2); - yield TabStateFlusher.flush(tab2.linkedBrowser); - - // There should be two history entries now. - let {entries} = JSON.parse(ss.getTabState(tab2)); - is(entries.length, 2, "there are two shistory entries"); - - // Cleanup. - yield promiseRemoveTab(tab2); - yield promiseRemoveTab(tab); -}); - -add_task(function* test_duplicate_remove() { - // Create new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // Click the link to navigate, this will add second shistory entry. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("hashchange", function onHashChange() { - removeEventListener("hashchange", onHashChange); - resolve(); - }); - - // Click the link. - content.document.querySelector("a").click(); - }); - }); - - // Duplicate the tab. - let tab2 = ss.duplicateTab(window, tab); - - // Before the duplication finished, remove the tab. - yield Promise.all([promiseRemoveTab(tab), promiseTabRestored(tab2)]); - yield TabStateFlusher.flush(tab2.linkedBrowser); - - // There should be two history entries now. - let {entries} = JSON.parse(ss.getTabState(tab2)); - is(entries.length, 2, "there are two shistory entries"); - - // Cleanup. - yield promiseRemoveTab(tab2); -}); diff --git a/browser/components/sessionstore/test/browser_async_flushes.js b/browser/components/sessionstore/test/browser_async_flushes.js deleted file mode 100644 index a4cbbfbc7..000000000 --- a/browser/components/sessionstore/test/browser_async_flushes.js +++ /dev/null @@ -1,113 +0,0 @@ -"use strict"; - -const URL = "data:text/html;charset=utf-8,<a href=%23>clickme</a>"; - -add_task(function* test_flush() { - // Create new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // There should be one history entry. - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is a single history entry"); - - // Click the link to navigate, this will add second shistory entry. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("hashchange", function onHashChange() { - removeEventListener("hashchange", onHashChange); - resolve(); - }); - - // Click the link. - content.document.querySelector("a").click(); - }); - }); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // There should be two history entries now. - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there are two shistory entries"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -add_task(function* test_crash() { - // Create new tab. - let tab = gBrowser.addTab(URL); - gBrowser.selectedTab = tab; - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // There should be one history entry. - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is a single history entry"); - - // Click the link to navigate. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("hashchange", function onHashChange() { - removeEventListener("hashchange", onHashChange); - resolve(); - }); - - // Click the link. - content.document.querySelector("a").click(); - }); - }); - - // Crash the browser and flush. Both messages are async and will be sent to - // the content process. The "crash" message makes it first so that we don't - // get a chance to process the flush. The TabStateFlusher however should be - // notified so that the flush still completes. - let promise1 = BrowserTestUtils.crashBrowser(browser); - let promise2 = TabStateFlusher.flush(browser); - yield Promise.all([promise1, promise2]); - - // The pending update should be lost. - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 1, "still only one history entry"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -add_task(function* test_remove() { - // Create new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to empty any queued update messages. - yield TabStateFlusher.flush(browser); - - // There should be one history entry. - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is a single history entry"); - - // Click the link to navigate. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("hashchange", function onHashChange() { - removeEventListener("hashchange", onHashChange); - resolve(); - }); - - // Click the link. - content.document.querySelector("a").click(); - }); - }); - - // Request a flush and remove the tab. The flush should still complete. - yield Promise.all([TabStateFlusher.flush(browser), promiseRemoveTab(tab)]); -}) diff --git a/browser/components/sessionstore/test/browser_async_remove_tab.js b/browser/components/sessionstore/test/browser_async_remove_tab.js deleted file mode 100644 index 20f3463d0..000000000 --- a/browser/components/sessionstore/test/browser_async_remove_tab.js +++ /dev/null @@ -1,242 +0,0 @@ -"use strict"; - -function* createTabWithRandomValue(url) { - let tab = gBrowser.addTab(url); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Set a random value. - let r = `rand-${Math.random()}`; - ss.setTabValue(tab, "foobar", r); - - // Flush to ensure there are no scheduled messages. - yield TabStateFlusher.flush(browser); - - return {tab, r}; -} - -function isValueInClosedData(rval) { - return ss.getClosedTabData(window).includes(rval); -} - -function restoreClosedTabWithValue(rval) { - let closedTabData = JSON.parse(ss.getClosedTabData(window)); - let index = closedTabData.findIndex(function (data) { - return (data.state.extData && data.state.extData.foobar) == rval; - }); - - if (index == -1) { - throw new Error("no closed tab found for given rval"); - } - - return ss.undoCloseTab(window, index); -} - -function promiseNewLocationAndHistoryEntryReplaced(browser, snippet) { - return ContentTask.spawn(browser, snippet, function* (snippet) { - let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation); - let shistory = webNavigation.sessionHistory; - - // Evaluate the snippet that the changes the location. - eval(snippet); - - return new Promise(resolve => { - let listener = { - OnHistoryReplaceEntry() { - shistory.removeSHistoryListener(this); - resolve(); - }, - - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsISHistoryListener, - Ci.nsISupportsWeakReference - ]) - }; - - shistory.addSHistoryListener(listener); - - /* Keep the weak shistory listener alive. */ - addEventListener("unload", function () { - try { - shistory.removeSHistoryListener(listener); - } catch (e) { /* Will most likely fail. */ } - }); - }); - }); -} - -function promiseHistoryEntryReplacedNonRemote(browser) { - let {listeners} = promiseHistoryEntryReplacedNonRemote; - - return new Promise(resolve => { - let shistory = browser.webNavigation.sessionHistory; - - let listener = { - OnHistoryReplaceEntry() { - shistory.removeSHistoryListener(this); - resolve(); - }, - - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsISHistoryListener, - Ci.nsISupportsWeakReference - ]) - }; - - shistory.addSHistoryListener(listener); - listeners.set(browser, listener); - }); -} -promiseHistoryEntryReplacedNonRemote.listeners = new WeakMap(); - -add_task(function* dont_save_empty_tabs() { - let {tab, r} = yield createTabWithRandomValue("about:blank"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // No tab state worth saving. - ok(!isValueInClosedData(r), "closed tab not saved"); - yield promise; - - // Still no tab state worth saving. - ok(!isValueInClosedData(r), "closed tab not saved"); -}); - -add_task(function* save_worthy_tabs_remote() { - let {tab, r} = yield createTabWithRandomValue("https://example.com/"); - ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // Tab state deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); - yield promise; - - // Tab state still deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); -}); - -add_task(function* save_worthy_tabs_nonremote() { - let {tab, r} = yield createTabWithRandomValue("about:robots"); - ok(!tab.linkedBrowser.isRemoteBrowser, "browser is not remote"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // Tab state deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); - yield promise; - - // Tab state still deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); -}); - -add_task(function* save_worthy_tabs_remote_final() { - let {tab, r} = yield createTabWithRandomValue("about:blank"); - let browser = tab.linkedBrowser; - ok(browser.isRemoteBrowser, "browser is remote"); - - // Replace about:blank with a new remote page. - let snippet = 'webNavigation.loadURI("https://example.com/", null, null, null, null)'; - yield promiseNewLocationAndHistoryEntryReplaced(browser, snippet); - - // Remotness shouldn't have changed. - ok(browser.isRemoteBrowser, "browser is still remote"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // No tab state worth saving (that we know about yet). - ok(!isValueInClosedData(r), "closed tab not saved"); - yield promise; - - // Turns out there is a tab state worth saving. - ok(isValueInClosedData(r), "closed tab saved"); -}); - -add_task(function* save_worthy_tabs_nonremote_final() { - let {tab, r} = yield createTabWithRandomValue("about:blank"); - let browser = tab.linkedBrowser; - ok(browser.isRemoteBrowser, "browser is remote"); - - // Replace about:blank with a non-remote entry. - yield BrowserTestUtils.loadURI(browser, "about:robots"); - ok(!browser.isRemoteBrowser, "browser is not remote anymore"); - - // Wait until the new entry replaces about:blank. - yield promiseHistoryEntryReplacedNonRemote(browser); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // No tab state worth saving (that we know about yet). - ok(!isValueInClosedData(r), "closed tab not saved"); - yield promise; - - // Turns out there is a tab state worth saving. - ok(isValueInClosedData(r), "closed tab saved"); -}); - -add_task(function* dont_save_empty_tabs_final() { - let {tab, r} = yield createTabWithRandomValue("https://example.com/"); - let browser = tab.linkedBrowser; - - // Replace the current page with an about:blank entry. - let snippet = 'content.location.replace("about:blank")'; - yield promiseNewLocationAndHistoryEntryReplaced(browser, snippet); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // Tab state deemed worth saving (yet). - ok(isValueInClosedData(r), "closed tab saved"); - yield promise; - - // Turns out we don't want to save the tab state. - ok(!isValueInClosedData(r), "closed tab not saved"); -}); - -add_task(function* undo_worthy_tabs() { - let {tab, r} = yield createTabWithRandomValue("https://example.com/"); - ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // Tab state deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); - - // Restore the closed tab before receiving its final message. - tab = restoreClosedTabWithValue(r); - - // Wait for the final update message. - yield promise; - - // Check we didn't add the tab back to the closed list. - ok(!isValueInClosedData(r), "tab no longer closed"); - - // Cleanup. - yield promiseRemoveTab(tab); -}); - -add_task(function* forget_worthy_tabs_remote() { - let {tab, r} = yield createTabWithRandomValue("https://example.com/"); - ok(tab.linkedBrowser.isRemoteBrowser, "browser is remote"); - - // Remove the tab before the update arrives. - let promise = promiseRemoveTab(tab); - - // Tab state deemed worth saving. - ok(isValueInClosedData(r), "closed tab saved"); - - // Forget the closed tab. - ss.forgetClosedTab(window, 0); - - // Wait for the final update message. - yield promise; - - // Check we didn't add the tab back to the closed list. - ok(!isValueInClosedData(r), "we forgot about the tab"); -}); diff --git a/browser/components/sessionstore/test/browser_async_window_flushing.js b/browser/components/sessionstore/test/browser_async_window_flushing.js deleted file mode 100644 index 418c055c2..000000000 --- a/browser/components/sessionstore/test/browser_async_window_flushing.js +++ /dev/null @@ -1,178 +0,0 @@ -"use strict"; - -const PAGE = "http://example.com/"; - -/** - * Tests that if we initially discard a window as not interesting - * to save in the closed windows array, that we revisit that decision - * after a window flush has completed. - */ -add_task(function* test_add_interesting_window() { - // We want to suppress all non-final updates from the browser tabs - // so as to eliminate any racy-ness with this test. - yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]); - - // Depending on previous tests, we might already have some closed - // windows stored. We'll use its length to determine whether or not - // the window was added or not. - let initialClosedWindows = ss.getClosedWindowCount(); - - // Make sure we can actually store another closed window - yield pushPrefs(["browser.sessionstore.max_windows_undo", - initialClosedWindows + 1]); - - // Create a new browser window. Since the default window will start - // at about:blank, SessionStore should find this tab (and therefore the - // whole window) uninteresting, and should not initially put it into - // the closed windows array. - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - - let browser = newWin.gBrowser.selectedBrowser; - - // Send a message that will cause the content to change its location - // to someplace more interesting. We've disabled auto updates from - // the browser, so the parent won't know about this - yield ContentTask.spawn(browser, PAGE, function*(PAGE) { - content.location = PAGE; - }); - - yield promiseContentMessage(browser, "ss-test:OnHistoryReplaceEntry"); - - // Clear out the userTypedValue so that the new window looks like - // it's really not worth restoring. - browser.userTypedValue = null; - - // Once the domWindowClosed Promise resolves, the window should - // have closed, and SessionStore's onClose handler should have just - // run. - let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin); - - // Once this windowClosed Promise resolves, we should have finished - // the flush and revisited our decision to put this window into - // the closed windows array. - let windowClosed = BrowserTestUtils.windowClosed(newWin); - - // Ok, let's close the window. - newWin.close(); - - yield domWindowClosed; - // OnClose has just finished running. - let currentClosedWindows = ss.getClosedWindowCount(); - is(currentClosedWindows, initialClosedWindows, - "We should not have added the window to the closed windows array"); - - yield windowClosed; - // The window flush has finished - currentClosedWindows = ss.getClosedWindowCount(); - is(currentClosedWindows, - initialClosedWindows + 1, - "We should have added the window to the closed windows array"); -}); - -/** - * Tests that if we initially store a closed window as interesting - * to save in the closed windows array, that we revisit that decision - * after a window flush has completed, and stop storing a window that - * we've deemed no longer interesting. - */ -add_task(function* test_remove_uninteresting_window() { - // We want to suppress all non-final updates from the browser tabs - // so as to eliminate any racy-ness with this test. - yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]); - - // Depending on previous tests, we might already have some closed - // windows stored. We'll use its length to determine whether or not - // the window was added or not. - let initialClosedWindows = ss.getClosedWindowCount(); - - // Make sure we can actually store another closed window - yield pushPrefs(["browser.sessionstore.max_windows_undo", - initialClosedWindows + 1]); - - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - - // Now browse the initial tab of that window to an interesting - // site. - let tab = newWin.gBrowser.selectedTab; - let browser = tab.linkedBrowser; - browser.loadURI(PAGE); - - yield BrowserTestUtils.browserLoaded(browser, false, PAGE); - yield TabStateFlusher.flush(browser); - - // Send a message that will cause the content to purge its - // history entries and make itself seem uninteresting. - yield ContentTask.spawn(browser, null, function*() { - // Epic hackery to make this browser seem suddenly boring. - Components.utils.import("resource://gre/modules/BrowserUtils.jsm"); - docShell.setCurrentURI(BrowserUtils.makeURI("about:blank")); - - let {sessionHistory} = docShell.QueryInterface(Ci.nsIWebNavigation); - sessionHistory.PurgeHistory(sessionHistory.count); - }); - - // Once the domWindowClosed Promise resolves, the window should - // have closed, and SessionStore's onClose handler should have just - // run. - let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin); - - // Once this windowClosed Promise resolves, we should have finished - // the flush and revisited our decision to put this window into - // the closed windows array. - let windowClosed = BrowserTestUtils.windowClosed(newWin); - - // Ok, let's close the window. - newWin.close(); - - yield domWindowClosed; - // OnClose has just finished running. - let currentClosedWindows = ss.getClosedWindowCount(); - is(currentClosedWindows, initialClosedWindows + 1, - "We should have added the window to the closed windows array"); - - yield windowClosed; - // The window flush has finished - currentClosedWindows = ss.getClosedWindowCount(); - is(currentClosedWindows, - initialClosedWindows, - "We should have removed the window from the closed windows array"); -}); - -/** - * Tests that when we close a window, it is immediately removed from the - * _windows array. - */ -add_task(function* test_synchronously_remove_window_state() { - // Depending on previous tests, we might already have some closed - // windows stored. We'll use its length to determine whether or not - // the window was added or not. - let state = JSON.parse(ss.getBrowserState()); - ok(state, "Make sure we can get the state"); - let initialWindows = state.windows.length; - - // Open a new window and send the first tab somewhere - // interesting. - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - let browser = newWin.gBrowser.selectedBrowser; - browser.loadURI(PAGE); - yield BrowserTestUtils.browserLoaded(browser, false, PAGE); - yield TabStateFlusher.flush(browser); - - state = JSON.parse(ss.getBrowserState()); - is(state.windows.length, initialWindows + 1, - "The new window to be in the state"); - - // Now close the window, and make sure that the window was removed - // from the windows list from the SessionState. We're specifically - // testing the case where the window is _not_ removed in between - // the close-initiated flush request and the flush response. - let windowClosed = BrowserTestUtils.windowClosed(newWin); - newWin.close(); - - state = JSON.parse(ss.getBrowserState()); - is(state.windows.length, initialWindows, - "The new window should have been removed from the state"); - - // Wait for our window to go away - yield windowClosed; -}); diff --git a/browser/components/sessionstore/test/browser_attributes.js b/browser/components/sessionstore/test/browser_attributes.js deleted file mode 100644 index 40c7b4e02..000000000 --- a/browser/components/sessionstore/test/browser_attributes.js +++ /dev/null @@ -1,73 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * This test makes sure that we correctly preserve tab attributes when storing - * and restoring tabs. It also ensures that we skip special attributes like - * 'image', 'muted' and 'pending' that need to be handled differently or internally. - */ - -const PREF = "browser.sessionstore.restore_on_demand"; - -add_task(function* test() { - Services.prefs.setBoolPref(PREF, true) - registerCleanupFunction(() => Services.prefs.clearUserPref(PREF)); - - // Add a new tab with a nice icon. - let tab = gBrowser.addTab("about:robots"); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // Check that the tab has 'image' and 'iconLoadingPrincipal' attributes. - ok(tab.hasAttribute("image"), "tab.image exists"); - ok(tab.hasAttribute("iconLoadingPrincipal"), "tab.iconLoadingPrincipal exists"); - - tab.toggleMuteAudio(); - // Check that the tab has a 'muted' attribute. - ok(tab.hasAttribute("muted"), "tab.muted exists"); - - // Make sure we do not persist 'image' or 'muted' attributes. - ss.persistTabAttribute("image"); - ss.persistTabAttribute("muted"); - ss.persistTabAttribute("iconLoadingPrincipal"); - let {attributes} = JSON.parse(ss.getTabState(tab)); - ok(!("image" in attributes), "'image' attribute not saved"); - ok(!("iconLoadingPrincipal" in attributes), "'iconLoadingPrincipal' attribute not saved"); - ok(!("muted" in attributes), "'muted' attribute not saved"); - ok(!("custom" in attributes), "'custom' attribute not saved"); - - // Test persisting a custom attribute. - tab.setAttribute("custom", "foobar"); - ss.persistTabAttribute("custom"); - - ({attributes} = JSON.parse(ss.getTabState(tab))); - is(attributes.custom, "foobar", "'custom' attribute is correct"); - - // Make sure we're backwards compatible and restore old 'image' attributes. - let state = { - entries: [{url: "about:mozilla"}], - attributes: {custom: "foobaz"}, - image: gBrowser.getIcon(tab) - }; - - // Prepare a pending tab waiting to be restored. - let promise = promiseTabRestoring(tab); - ss.setTabState(tab, JSON.stringify(state)); - yield promise; - - ok(tab.hasAttribute("pending"), "tab is pending"); - is(gBrowser.getIcon(tab), state.image, "tab has correct icon"); - ok(!state.attributes.image, "'image' attribute not saved"); - - // Let the pending tab load. - gBrowser.selectedTab = tab; - yield promiseTabRestored(tab); - - // Ensure no 'image' or 'pending' attributes are stored. - ({attributes} = JSON.parse(ss.getTabState(tab))); - ok(!("image" in attributes), "'image' attribute not saved"); - ok(!("pending" in attributes), "'pending' attribute not saved"); - is(attributes.custom, "foobaz", "'custom' attribute is correct"); - - // Clean up. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_background_tab_crash.js b/browser/components/sessionstore/test/browser_background_tab_crash.js deleted file mode 100644 index e804b177e..000000000 --- a/browser/components/sessionstore/test/browser_background_tab_crash.js +++ /dev/null @@ -1,221 +0,0 @@ -"use strict"; - -/** - * These tests the behaviour of the browser when background tabs crash, - * while the foreground tab remains. - * - * The current behavioural rule is this: if only background tabs crash, - * then only the first tab shown of that group should show the tab crash - * page, and subsequent ones should restore on demand. - */ - -/** - * Makes the current browser tab non-remote, and then sets up two remote - * background tabs, ensuring that both belong to the same content process. - * Callers should pass in a testing function that will execute (and possibly - * yield Promises) taking the created background tabs as arguments. Once - * the testing function completes, this function will take care of closing - * the opened tabs. - * - * @param testFn (function) - * A Promise-generating function that will be called once the tabs - * are opened and ready. - * @return Promise - * Resolves once the testing function completes and the opened tabs - * have been completely closed. - */ -function* setupBackgroundTabs(testFn) { - const REMOTE_PAGE = "http://www.example.com"; - const NON_REMOTE_PAGE = "about:robots"; - - // Browse the initial tab to a non-remote page, which we'll have in the - // foreground. - let initialTab = gBrowser.selectedTab; - let initialBrowser = initialTab.linkedBrowser; - initialBrowser.loadURI(NON_REMOTE_PAGE); - yield BrowserTestUtils.browserLoaded(initialBrowser); - - // Open some tabs that should be running in the content process. - let tab1 = - yield BrowserTestUtils.openNewForegroundTab(gBrowser, REMOTE_PAGE); - let remoteBrowser1 = tab1.linkedBrowser; - yield TabStateFlusher.flush(remoteBrowser1); - - let tab2 = - yield BrowserTestUtils.openNewForegroundTab(gBrowser, REMOTE_PAGE); - let remoteBrowser2 = tab2.linkedBrowser; - yield TabStateFlusher.flush(remoteBrowser2); - - // Quick sanity check - the two browsers should be remote and share the - // same childID, or else this test is not going to work. - Assert.ok(remoteBrowser1.isRemoteBrowser, - "Browser should be remote in order to crash."); - Assert.ok(remoteBrowser2.isRemoteBrowser, - "Browser should be remote in order to crash."); - Assert.equal(remoteBrowser1.frameLoader.childID, - remoteBrowser2.frameLoader.childID, - "Both remote browsers should share the same content process."); - - // Now switch back to the non-remote browser... - yield BrowserTestUtils.switchTab(gBrowser, initialTab); - - yield testFn([tab1, tab2]); - - yield BrowserTestUtils.removeTab(tab1); - yield BrowserTestUtils.removeTab(tab2); -} - -/** - * Takes some set of background tabs that are assumed to all belong to - * the same content process, and crashes them. - * - * @param tabs (Array(<xul:tab>)) - * The tabs to crash. - * @return Promise - * Resolves once the tabs have crashed and entered the pending - * background state. - */ -function* crashBackgroundTabs(tabs) { - Assert.ok(tabs.length > 0, "Need to crash at least one tab."); - for (let tab of tabs) { - Assert.ok(tab.linkedBrowser.isRemoteBrowser, "tab is remote"); - } - - let remotenessChangePromises = tabs.map((t) => { - return BrowserTestUtils.waitForEvent(t, "TabRemotenessChange"); - }); - - let tabsRevived = tabs.map((t) => { - return promiseTabRestoring(t); - }); - - yield BrowserTestUtils.crashBrowser(tabs[0].linkedBrowser, false); - yield Promise.all(remotenessChangePromises); - yield Promise.all(tabsRevived); - - // Both background tabs should now be in the pending restore - // state. - for (let tab of tabs) { - Assert.ok(!tab.linkedBrowser.isRemoteBrowser, "tab is not remote"); - Assert.ok(!tab.linkedBrowser.hasAttribute("crashed"), "tab is not crashed"); - Assert.ok(tab.linkedBrowser.hasAttribute("pending"), "tab is pending"); - } -} - -add_task(function* setup() { - // We'll simplify by making sure we only ever one content process for this - // test. - yield SpecialPowers.pushPrefEnv({ set: [[ "dom.ipc.processCount", 1 ]] }); - - // On debug builds, crashing tabs results in much thinking, which - // slows down the test and results in intermittent test timeouts, - // so we'll pump up the expected timeout for this test. - requestLongerTimeout(5); -}); - -/** - * Tests that if a content process crashes taking down only - * background tabs, then the first of those tabs that the user - * selects will show the tab crash page, but the rest will restore - * on demand. - */ -add_task(function* test_background_crash_simple() { - yield setupBackgroundTabs(function*([tab1, tab2]) { - // Let's crash one of those background tabs now... - yield crashBackgroundTabs([tab1, tab2]); - - // Selecting the first tab should now send it to the tab crashed page. - let tabCrashedPagePromise = - BrowserTestUtils.waitForContentEvent(tab1.linkedBrowser, - "AboutTabCrashedReady", - false, null, true); - yield BrowserTestUtils.switchTab(gBrowser, tab1); - yield tabCrashedPagePromise; - - // Selecting the second tab should restore it. - let tabRestored = promiseTabRestored(tab2); - yield BrowserTestUtils.switchTab(gBrowser, tab2); - yield tabRestored; - }); -}); - -/** - * Tests that if a content process crashes taking down only - * background tabs, and the user is configured to send backlogged - * crash reports automatically, that the tab crashed page is not - * shown. - */ -add_task(function* test_background_crash_autosubmit_backlogged() { - yield SpecialPowers.pushPrefEnv({ - set: [["browser.crashReports.unsubmittedCheck.autoSubmit2", true]], - }); - - yield setupBackgroundTabs(function*([tab1, tab2]) { - // Let's crash one of those background tabs now... - yield crashBackgroundTabs([tab1, tab2]); - - // Selecting the first tab should restore it. - let tabRestored = promiseTabRestored(tab1); - yield BrowserTestUtils.switchTab(gBrowser, tab1); - yield tabRestored; - - // Selecting the second tab should restore it. - tabRestored = promiseTabRestored(tab2); - yield BrowserTestUtils.switchTab(gBrowser, tab2); - yield tabRestored; - }); - - yield SpecialPowers.popPrefEnv(); -}); - -/** - * Tests that if there are two background tab crashes in a row, that - * the two sets of background crashes don't interfere with one another. - * - * Specifically, if we start with two background tabs (1, 2) which crash, - * and we visit 1, 1 should go to the tab crashed page. If we then have - * two new background tabs (3, 4) crash, visiting 2 should still restore. - * Visiting 4 should show us the tab crashed page, and then visiting 3 - * should restore. - */ -add_task(function* test_background_crash_multiple() { - let initialTab = gBrowser.selectedTab; - - yield setupBackgroundTabs(function*([tab1, tab2]) { - // Let's crash one of those background tabs now... - yield crashBackgroundTabs([tab1, tab2]); - - // Selecting the first tab should now send it to the tab crashed page. - let tabCrashedPagePromise = - BrowserTestUtils.waitForContentEvent(tab1.linkedBrowser, - "AboutTabCrashedReady", - false, null, true); - yield BrowserTestUtils.switchTab(gBrowser, tab1); - yield tabCrashedPagePromise; - - // Now switch back to the original non-remote tab... - yield BrowserTestUtils.switchTab(gBrowser, initialTab); - - yield setupBackgroundTabs(function*([tab3, tab4]) { - yield crashBackgroundTabs([tab3, tab4]); - - // Selecting the second tab should restore it. - let tabRestored = promiseTabRestored(tab2); - yield BrowserTestUtils.switchTab(gBrowser, tab2); - yield tabRestored; - - // Selecting the fourth tab should now send it to the tab crashed page. - let tabCrashedPagePromise = - BrowserTestUtils.waitForContentEvent(tab4.linkedBrowser, - "AboutTabCrashedReady", - false, null, true); - yield BrowserTestUtils.switchTab(gBrowser, tab4); - yield tabCrashedPagePromise; - - // Selecting the third tab should restore it. - tabRestored = promiseTabRestored(tab3); - yield BrowserTestUtils.switchTab(gBrowser, tab3); - yield tabRestored; - }); - }); -}); diff --git a/browser/components/sessionstore/test/browser_backup_recovery.js b/browser/components/sessionstore/test/browser_backup_recovery.js deleted file mode 100644 index 81f678856..000000000 --- a/browser/components/sessionstore/test/browser_backup_recovery.js +++ /dev/null @@ -1,206 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// This tests are for a sessionstore.js atomic backup. -// Each test will wait for a write to the Session Store -// before executing. - -var OS = Cu.import("resource://gre/modules/osfile.jsm", {}).OS; -var {File, Constants, Path} = OS; - -const PREF_SS_INTERVAL = "browser.sessionstore.interval"; -const Paths = SessionFile.Paths; - -// A text decoder. -var gDecoder = new TextDecoder(); -// Global variables that contain sessionstore.js and sessionstore.bak data for -// comparison between tests. -var gSSData; -var gSSBakData; - -function promiseRead(path) { - return File.read(path, {encoding: "utf-8"}); -} - -add_task(function* init() { - // Make sure that we are not racing with SessionSaver's time based - // saves. - Services.prefs.setIntPref(PREF_SS_INTERVAL, 10000000); - registerCleanupFunction(() => Services.prefs.clearUserPref(PREF_SS_INTERVAL)); -}); - -add_task(function* test_creation() { - // Create dummy sessionstore backups - let OLD_BACKUP = Path.join(Constants.Path.profileDir, "sessionstore.bak"); - let OLD_UPGRADE_BACKUP = Path.join(Constants.Path.profileDir, "sessionstore.bak-0000000"); - - yield File.writeAtomic(OLD_BACKUP, "sessionstore.bak"); - yield File.writeAtomic(OLD_UPGRADE_BACKUP, "sessionstore upgrade backup"); - - yield SessionFile.wipe(); - yield SessionFile.read(); // Reinitializes SessionFile - - // Ensure none of the sessionstore files and backups exists - for (let k of Paths.loadOrder) { - ok(!(yield File.exists(Paths[k])), "After wipe " + k + " sessionstore file doesn't exist"); - } - ok(!(yield File.exists(OLD_BACKUP)), "After wipe, old backup doesn't exist"); - ok(!(yield File.exists(OLD_UPGRADE_BACKUP)), "After wipe, old upgrade backup doesn't exist"); - - // Open a new tab, save session, ensure that the correct files exist. - let URL_BASE = "http://example.com/?atomic_backup_test_creation=" + Math.random(); - let URL = URL_BASE + "?first_write"; - let tab = gBrowser.addTab(URL); - - info("Testing situation after a single write"); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - yield SessionSaver.run(); - - ok((yield File.exists(Paths.recovery)), "After write, recovery sessionstore file exists again"); - ok(!(yield File.exists(Paths.recoveryBackup)), "After write, recoveryBackup sessionstore doesn't exist"); - ok((yield promiseRead(Paths.recovery)).indexOf(URL) != -1, "Recovery sessionstore file contains the required tab"); - ok(!(yield File.exists(Paths.clean)), "After first write, clean shutdown sessionstore doesn't exist, since we haven't shutdown yet"); - - // Open a second tab, save session, ensure that the correct files exist. - info("Testing situation after a second write"); - let URL2 = URL_BASE + "?second_write"; - tab.linkedBrowser.loadURI(URL2); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - yield SessionSaver.run(); - - ok((yield File.exists(Paths.recovery)), "After second write, recovery sessionstore file still exists"); - ok((yield promiseRead(Paths.recovery)).indexOf(URL2) != -1, "Recovery sessionstore file contains the latest url"); - ok((yield File.exists(Paths.recoveryBackup)), "After write, recoveryBackup sessionstore now exists"); - let backup = yield promiseRead(Paths.recoveryBackup); - ok(backup.indexOf(URL2) == -1, "Recovery backup doesn't contain the latest url"); - ok(backup.indexOf(URL) != -1, "Recovery backup contains the original url"); - ok(!(yield File.exists(Paths.clean)), "After first write, clean shutdown sessinstore doesn't exist, since we haven't shutdown yet"); - - info("Reinitialize, ensure that we haven't leaked sensitive files"); - yield SessionFile.read(); // Reinitializes SessionFile - yield SessionSaver.run(); - ok(!(yield File.exists(Paths.clean)), "After second write, clean shutdown sessonstore doesn't exist, since we haven't shutdown yet"); - ok(!(yield File.exists(Paths.upgradeBackup)), "After second write, clean shutdwn sessionstore doesn't exist, since we haven't shutdown yet"); - ok(!(yield File.exists(Paths.nextUpgradeBackup)), "After second write, clean sutdown sessionstore doesn't exist, since we haven't shutdown yet"); - - gBrowser.removeTab(tab); - yield SessionFile.wipe(); -}); - -var promiseSource = Task.async(function*(name) { - let URL = "http://example.com/?atomic_backup_test_recovery=" + Math.random() + "&name=" + name; - let tab = gBrowser.addTab(URL); - - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - yield SessionSaver.run(); - gBrowser.removeTab(tab); - - let SOURCE = yield promiseRead(Paths.recovery); - yield SessionFile.wipe(); - return SOURCE; -}); - -add_task(function* test_recovery() { - // Remove all files. - yield SessionFile.wipe(); - info("Attempting to recover from the recovery file"); - - // Create Paths.recovery, ensure that we can recover from it. - let SOURCE = yield promiseSource("Paths.recovery"); - yield File.makeDir(Paths.backups); - yield File.writeAtomic(Paths.recovery, SOURCE); - is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file"); - yield SessionFile.wipe(); - - info("Corrupting recovery file, attempting to recover from recovery backup"); - SOURCE = yield promiseSource("Paths.recoveryBackup"); - yield File.makeDir(Paths.backups); - yield File.writeAtomic(Paths.recoveryBackup, SOURCE); - yield File.writeAtomic(Paths.recovery, "<Invalid JSON>"); - is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file"); - yield SessionFile.wipe(); -}); - -add_task(function* test_recovery_inaccessible() { - // Can't do chmod() on non-UNIX platforms, we need that for this test. - if (AppConstants.platform != "macosx" && AppConstants.platform != "linux") { - return; - } - - info("Making recovery file inaccessible, attempting to recover from recovery backup"); - let SOURCE_RECOVERY = yield promiseSource("Paths.recovery"); - let SOURCE = yield promiseSource("Paths.recoveryBackup"); - yield File.makeDir(Paths.backups); - yield File.writeAtomic(Paths.recoveryBackup, SOURCE); - - // Write a valid recovery file but make it inaccessible. - yield File.writeAtomic(Paths.recovery, SOURCE_RECOVERY); - yield File.setPermissions(Paths.recovery, { unixMode: 0 }); - - is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the recovery file"); - yield File.setPermissions(Paths.recovery, { unixMode: 0o644 }); -}); - -add_task(function* test_clean() { - yield SessionFile.wipe(); - let SOURCE = yield promiseSource("Paths.clean"); - yield File.writeAtomic(Paths.clean, SOURCE); - yield SessionFile.read(); - yield SessionSaver.run(); - is((yield promiseRead(Paths.cleanBackup)), SOURCE, "After first read/write, clean shutdown file has been moved to cleanBackup"); -}); - - -/** - * Tests loading of sessionstore when format version is known. - */ -add_task(function* test_version() { - info("Preparing sessionstore"); - let SOURCE = yield promiseSource("Paths.clean"); - - // Check there's a format version number - is(JSON.parse(SOURCE).version[0], "sessionrestore", "Found sessionstore format version"); - - // Create Paths.clean file - yield File.makeDir(Paths.backups); - yield File.writeAtomic(Paths.clean, SOURCE); - - info("Attempting to recover from the clean file"); - // Ensure that we can recover from Paths.recovery - is((yield SessionFile.read()).source, SOURCE, "Recovered the correct source from the clean file"); -}); - -/** - * Tests fallback to previous backups if format version is unknown. - */ -add_task(function* test_version_fallback() { - info("Preparing data, making sure that it has a version number"); - let SOURCE = yield promiseSource("Paths.clean"); - let BACKUP_SOURCE = yield promiseSource("Paths.cleanBackup"); - - is(JSON.parse(SOURCE).version[0], "sessionrestore", "Found sessionstore format version"); - is(JSON.parse(BACKUP_SOURCE).version[0], "sessionrestore", "Found backup sessionstore format version"); - - yield File.makeDir(Paths.backups); - - info("Modifying format version number to something incorrect, to make sure that we disregard the file."); - let parsedSource = JSON.parse(SOURCE); - parsedSource.version[0] = "bookmarks"; - yield File.writeAtomic(Paths.clean, JSON.stringify(parsedSource)); - yield File.writeAtomic(Paths.cleanBackup, BACKUP_SOURCE); - is((yield SessionFile.read()).source, BACKUP_SOURCE, "Recovered the correct source from the backup recovery file"); - - info("Modifying format version number to a future version, to make sure that we disregard the file."); - parsedSource = JSON.parse(SOURCE); - parsedSource.version[1] = Number.MAX_SAFE_INTEGER; - yield File.writeAtomic(Paths.clean, JSON.stringify(parsedSource)); - yield File.writeAtomic(Paths.cleanBackup, BACKUP_SOURCE); - is((yield SessionFile.read()).source, BACKUP_SOURCE, "Recovered the correct source from the backup recovery file"); -}); - -add_task(function* cleanup() { - yield SessionFile.wipe(); -}); diff --git a/browser/components/sessionstore/test/browser_broadcast.js b/browser/components/sessionstore/test/browser_broadcast.js deleted file mode 100644 index 95984d6d0..000000000 --- a/browser/components/sessionstore/test/browser_broadcast.js +++ /dev/null @@ -1,131 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const INITIAL_VALUE = "browser_broadcast.js-initial-value-" + Date.now(); - -/** - * This test ensures we won't lose tab data queued in the content script when - * closing a tab. - */ -add_task(function flush_on_tabclose() { - let tab = yield createTabWithStorageData(["http://example.com"]); - let browser = tab.linkedBrowser; - - yield modifySessionStorage(browser, {test: "on-tab-close"}); - yield promiseRemoveTab(tab); - - let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://example.com"].test, "on-tab-close", - "sessionStorage data has been flushed on TabClose"); -}); - -/** - * This test ensures we won't lose tab data queued in the content script when - * duplicating a tab. - */ -add_task(function flush_on_duplicate() { - let tab = yield createTabWithStorageData(["http://example.com"]); - let browser = tab.linkedBrowser; - - yield modifySessionStorage(browser, {test: "on-duplicate"}); - let tab2 = ss.duplicateTab(window, tab); - yield promiseTabRestored(tab2); - - yield promiseRemoveTab(tab2); - let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://example.com"].test, "on-duplicate", - "sessionStorage data has been flushed when duplicating tabs"); - - gBrowser.removeTab(tab); -}); - -/** - * This test ensures we won't lose tab data queued in the content script when - * a window is closed. - */ -add_task(function flush_on_windowclose() { - let win = yield promiseNewWindow(); - let tab = yield createTabWithStorageData(["http://example.com"], win); - let browser = tab.linkedBrowser; - - yield modifySessionStorage(browser, {test: "on-window-close"}); - yield BrowserTestUtils.closeWindow(win); - - let [{tabs: [_, {storage}]}] = JSON.parse(ss.getClosedWindowData()); - is(storage["http://example.com"].test, "on-window-close", - "sessionStorage data has been flushed when closing a window"); -}); - -/** - * This test ensures that stale tab data is ignored when reusing a tab - * (via e.g. setTabState) and does not overwrite the new data. - */ -add_task(function flush_on_settabstate() { - let tab = yield createTabWithStorageData(["http://example.com"]); - let browser = tab.linkedBrowser; - - // Flush to make sure our tab state is up-to-date. - yield TabStateFlusher.flush(browser); - - let state = ss.getTabState(tab); - yield modifySessionStorage(browser, {test: "on-set-tab-state"}); - - // Flush all data contained in the content script but send it using - // asynchronous messages. - TabStateFlusher.flush(browser); - - yield promiseTabState(tab, state); - - let {storage} = JSON.parse(ss.getTabState(tab)); - is(storage["http://example.com"].test, INITIAL_VALUE, - "sessionStorage data has not been overwritten"); - - gBrowser.removeTab(tab); -}); - -/** - * This test ensures that we won't lose tab data that has been sent - * asynchronously just before closing a tab. Flushing must re-send all data - * that hasn't been received by chrome, yet. - */ -add_task(function flush_on_tabclose_racy() { - let tab = yield createTabWithStorageData(["http://example.com"]); - let browser = tab.linkedBrowser; - - // Flush to make sure we start with an empty queue. - yield TabStateFlusher.flush(browser); - - yield modifySessionStorage(browser, {test: "on-tab-close-racy"}); - - // Flush all data contained in the content script but send it using - // asynchronous messages. - TabStateFlusher.flush(browser); - yield promiseRemoveTab(tab); - - let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://example.com"].test, "on-tab-close-racy", - "sessionStorage data has been merged correctly to prevent data loss"); -}); - -function promiseNewWindow() { - let deferred = Promise.defer(); - whenNewWindowLoaded({private: false}, deferred.resolve); - return deferred.promise; -} - -function createTabWithStorageData(urls, win = window) { - return Task.spawn(function task() { - let tab = win.gBrowser.addTab(); - let browser = tab.linkedBrowser; - - for (let url of urls) { - browser.loadURI(url); - yield promiseBrowserLoaded(browser); - yield modifySessionStorage(browser, {test: INITIAL_VALUE}); - } - - throw new Task.Result(tab); - }); -} diff --git a/browser/components/sessionstore/test/browser_capabilities.js b/browser/components/sessionstore/test/browser_capabilities.js deleted file mode 100644 index 456e41882..000000000 --- a/browser/components/sessionstore/test/browser_capabilities.js +++ /dev/null @@ -1,76 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * These tests ensures that disabling features by flipping nsIDocShell.allow* - * properties are (re)stored as disabled. Disallowed features must be - * re-enabled when the tab is re-used by another tab restoration. - */ -add_task(function docshell_capabilities() { - let tab = yield createTab(); - let browser = tab.linkedBrowser; - let docShell = browser.docShell; - - // Get the list of capabilities for docShells. - let flags = Object.keys(docShell).filter(k => k.startsWith("allow")); - - // Check that everything is allowed by default for new tabs. - let state = JSON.parse(ss.getTabState(tab)); - ok(!("disallow" in state), "everything allowed by default"); - ok(flags.every(f => docShell[f]), "all flags set to true"); - - // Flip a couple of allow* flags. - docShell.allowImages = false; - docShell.allowMetaRedirects = false; - - // Now reload the document to ensure that these capabilities - // are taken into account. - browser.reload(); - yield promiseBrowserLoaded(browser); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - - // Check that we correctly save disallowed features. - let disallowedState = JSON.parse(ss.getTabState(tab)); - let disallow = new Set(disallowedState.disallow.split(",")); - ok(disallow.has("Images"), "images not allowed"); - ok(disallow.has("MetaRedirects"), "meta redirects not allowed"); - is(disallow.size, 2, "two capabilities disallowed"); - - // Reuse the tab to restore a new, clean state into it. - yield promiseTabState(tab, {entries: [{url: "about:robots"}]}); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - - // After restoring disallowed features must be available again. - state = JSON.parse(ss.getTabState(tab)); - ok(!("disallow" in state), "everything allowed again"); - ok(flags.every(f => docShell[f]), "all flags set to true"); - - // Restore the state with disallowed features. - yield promiseTabState(tab, disallowedState); - - // Check that docShell flags are set. - ok(!docShell.allowImages, "images not allowed"); - ok(!docShell.allowMetaRedirects, "meta redirects not allowed"); - - // Check that we correctly restored features as disabled. - state = JSON.parse(ss.getTabState(tab)); - disallow = new Set(state.disallow.split(",")); - ok(disallow.has("Images"), "images not allowed anymore"); - ok(disallow.has("MetaRedirects"), "meta redirects not allowed anymore"); - is(disallow.size, 2, "two capabilities disallowed"); - - // Clean up after ourselves. - gBrowser.removeTab(tab); -}); - -function createTab() { - let tab = gBrowser.addTab("about:mozilla"); - let browser = tab.linkedBrowser; - return promiseBrowserLoaded(browser).then(() => tab); -} diff --git a/browser/components/sessionstore/test/browser_cleaner.js b/browser/components/sessionstore/test/browser_cleaner.js deleted file mode 100644 index 921d7d3e4..000000000 --- a/browser/components/sessionstore/test/browser_cleaner.js +++ /dev/null @@ -1,157 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - - -/* - * This test ensures that Session Restore eventually forgets about - * tabs and windows that have been closed a long time ago. - */ - -"use strict"; - -Cu.import("resource://gre/modules/Services.jsm", this); -Cu.import("resource://gre/modules/osfile.jsm", this); -Cu.import("resource://gre/modules/Task.jsm", this); - -const LONG_TIME_AGO = 1; - -const URL_TAB1 = "http://example.com/browser_cleaner.js?newtab1=" + Math.random(); -const URL_TAB2 = "http://example.com/browser_cleaner.js?newtab2=" + Math.random(); -const URL_NEWWIN = "http://example.com/browser_cleaner.js?newwin=" + Math.random(); - -function isRecent(stamp) { - is(typeof stamp, "number", "This is a timestamp"); - return Date.now() - stamp <= 60000; -} - -function promiseCleanup () { - info("Cleaning up browser"); - - return promiseBrowserState(getClosedState()); -}; - -function getClosedState() { - return Cu.cloneInto(CLOSED_STATE, {}); -} - -var CLOSED_STATE; - -add_task(function* init() { - forgetClosedWindows(); - while (ss.getClosedTabCount(window) > 0) { - ss.forgetClosedTab(window, 0); - } -}); - -add_task(function* test_open_and_close() { - let newTab1 = gBrowser.addTab(URL_TAB1); - yield promiseBrowserLoaded(newTab1.linkedBrowser); - - let newTab2 = gBrowser.addTab(URL_TAB2); - yield promiseBrowserLoaded(newTab2.linkedBrowser); - - let newWin = yield promiseNewWindowLoaded(); - let tab = newWin.gBrowser.addTab(URL_NEWWIN); - - yield promiseBrowserLoaded(tab.linkedBrowser); - - yield TabStateFlusher.flushWindow(window); - yield TabStateFlusher.flushWindow(newWin); - - info("1. Making sure that before closing, we don't have closedAt"); - // For the moment, no "closedAt" - let state = JSON.parse(ss.getBrowserState()); - is(state.windows[0].closedAt || false, false, "1. Main window doesn't have closedAt"); - is(state.windows[1].closedAt || false, false, "1. Second window doesn't have closedAt"); - is(state.windows[0].tabs[0].closedAt || false, false, "1. First tab doesn't have closedAt"); - is(state.windows[0].tabs[1].closedAt || false, false, "1. Second tab doesn't have closedAt"); - - info("2. Making sure that after closing, we have closedAt"); - - // Now close stuff, this should add closeAt - yield BrowserTestUtils.closeWindow(newWin); - yield promiseRemoveTab(newTab1); - yield promiseRemoveTab(newTab2); - - state = CLOSED_STATE = JSON.parse(ss.getBrowserState()); - - is(state.windows[0].closedAt || false, false, "2. Main window doesn't have closedAt"); - ok(isRecent(state._closedWindows[0].closedAt), "2. Second window was closed recently"); - ok(isRecent(state.windows[0]._closedTabs[0].closedAt), "2. First tab was closed recently"); - ok(isRecent(state.windows[0]._closedTabs[1].closedAt), "2. Second tab was closed recently"); -}); - - -add_task(function* test_restore() { - info("3. Making sure that after restoring, we don't have closedAt"); - yield promiseBrowserState(CLOSED_STATE); - - let newWin = ss.undoCloseWindow(0); - yield promiseDelayedStartupFinished(newWin); - - let newTab2 = ss.undoCloseTab(window, 0); - yield promiseTabRestored(newTab2); - - let newTab1 = ss.undoCloseTab(window, 0); - yield promiseTabRestored(newTab1); - - let state = JSON.parse(ss.getBrowserState()); - - is(state.windows[0].closedAt || false, false, "3. Main window doesn't have closedAt"); - is(state.windows[1].closedAt || false, false, "3. Second window doesn't have closedAt"); - is(state.windows[0].tabs[0].closedAt || false, false, "3. First tab doesn't have closedAt"); - is(state.windows[0].tabs[1].closedAt || false, false, "3. Second tab doesn't have closedAt"); - - yield BrowserTestUtils.closeWindow(newWin); - gBrowser.removeTab(newTab1); - gBrowser.removeTab(newTab2); -}); - - -add_task(function* test_old_data() { - info("4. Removing closedAt from the sessionstore, making sure that it is added upon idle-daily"); - - let state = getClosedState(); - delete state._closedWindows[0].closedAt; - delete state.windows[0]._closedTabs[0].closedAt; - delete state.windows[0]._closedTabs[1].closedAt; - yield promiseBrowserState(state); - - info("Sending idle-daily"); - Services.obs.notifyObservers(null, "idle-daily", ""); - info("Sent idle-daily"); - - state = JSON.parse(ss.getBrowserState()); - is(state.windows[0].closedAt || false, false, "4. Main window doesn't have closedAt"); - ok(isRecent(state._closedWindows[0].closedAt), "4. Second window was closed recently"); - ok(isRecent(state.windows[0]._closedTabs[0].closedAt), "4. First tab was closed recently"); - ok(isRecent(state.windows[0]._closedTabs[1].closedAt), "4. Second tab was closed recently"); - yield promiseCleanup(); -}); - - -add_task(function* test_cleanup() { - - info("5. Altering closedAt to an old date, making sure that stuff gets collected, eventually"); - yield promiseCleanup(); - - let state = getClosedState(); - state._closedWindows[0].closedAt = LONG_TIME_AGO; - state.windows[0]._closedTabs[0].closedAt = LONG_TIME_AGO; - state.windows[0]._closedTabs[1].closedAt = Date.now(); - let url = state.windows[0]._closedTabs[1].state.entries[0].url; - - yield promiseBrowserState(state); - - info("Sending idle-daily"); - Services.obs.notifyObservers(null, "idle-daily", ""); - info("Sent idle-daily"); - - state = JSON.parse(ss.getBrowserState()); - is(state._closedWindows[0], undefined, "5. Second window was forgotten"); - - is(state.windows[0]._closedTabs.length, 1, "5. Only one closed tab left"); - is(state.windows[0]._closedTabs[0].state.entries[0].url, url, "5. The second tab is still here"); - yield promiseCleanup(); -}); - diff --git a/browser/components/sessionstore/test/browser_cookies.js b/browser/components/sessionstore/test/browser_cookies.js deleted file mode 100644 index cc5b41e4b..000000000 --- a/browser/components/sessionstore/test/browser_cookies.js +++ /dev/null @@ -1,173 +0,0 @@ -"use strict"; - -const PATH = "/browser/browser/components/sessionstore/test/"; - -/** - * Remove all cookies to start off a clean slate. - */ -add_task(function* test_setup() { - requestLongerTimeout(2); - Services.cookies.removeAll(); -}); - -/** - * Test multiple scenarios with different Set-Cookie header domain= params. - */ -add_task(function* test_run() { - // Set-Cookie: foobar=random() - // The domain of the cookie should be the request domain (www.example.com). - // We should collect data only for the request domain, no parent or subdomains. - yield testCookieCollection({ - host: "http://www.example.com", - cookieHost: "www.example.com", - cookieURIs: ["http://www.example.com" + PATH], - noCookieURIs: ["http://example.com/" + PATH] - }); - - // Set-Cookie: foobar=random() - // The domain of the cookie should be the request domain (example.com). - // We should collect data only for the request domain, no parent or subdomains. - yield testCookieCollection({ - host: "http://example.com", - cookieHost: "example.com", - cookieURIs: ["http://example.com" + PATH], - noCookieURIs: ["http://www.example.com/" + PATH] - }); - - // Set-Cookie: foobar=random(); Domain=example.com - // The domain of the cookie should be the given one (.example.com). - // We should collect data for the given domain and its subdomains. - yield testCookieCollection({ - host: "http://example.com", - domain: "example.com", - cookieHost: ".example.com", - cookieURIs: ["http://example.com" + PATH, "http://www.example.com/" + PATH], - noCookieURIs: ["about:robots"] - }); - - // Set-Cookie: foobar=random(); Domain=.example.com - // The domain of the cookie should be the given one (.example.com). - // We should collect data for the given domain and its subdomains. - yield testCookieCollection({ - host: "http://example.com", - domain: ".example.com", - cookieHost: ".example.com", - cookieURIs: ["http://example.com" + PATH, "http://www.example.com/" + PATH], - noCookieURIs: ["about:robots"] - }); - - // Set-Cookie: foobar=random(); Domain=www.example.com - // The domain of the cookie should be the given one (.www.example.com). - // We should collect data for the given domain and its subdomains. - yield testCookieCollection({ - host: "http://www.example.com", - domain: "www.example.com", - cookieHost: ".www.example.com", - cookieURIs: ["http://www.example.com/" + PATH], - noCookieURIs: ["http://example.com"] - }); - - // Set-Cookie: foobar=random(); Domain=.www.example.com - // The domain of the cookie should be the given one (.www.example.com). - // We should collect data for the given domain and its subdomains. - yield testCookieCollection({ - host: "http://www.example.com", - domain: ".www.example.com", - cookieHost: ".www.example.com", - cookieURIs: ["http://www.example.com/" + PATH], - noCookieURIs: ["http://example.com"] - }); -}); - -/** - * Generic test function to check sessionstore's cookie collection module with - * different cookie domains given in the Set-Cookie header. See above for some - * usage examples. - */ -var testCookieCollection = Task.async(function (params) { - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - - let urlParams = new URLSearchParams(); - let value = Math.random(); - urlParams.append("value", value); - - if (params.domain) { - urlParams.append("domain", params.domain); - } - - // Construct request URI. - let uri = `${params.host}${PATH}browser_cookies.sjs?${urlParams}`; - - // Wait for the browser to load and the cookie to be set. - // These two events can probably happen in no particular order, - // so let's wait for them in parallel. - yield Promise.all([ - waitForNewCookie(), - replaceCurrentURI(browser, uri) - ]); - - // Check all URIs for which the cookie should be collected. - for (let uri of params.cookieURIs || []) { - yield replaceCurrentURI(browser, uri); - - // Check the cookie. - let cookie = getCookie(); - is(cookie.host, params.cookieHost, "cookie host is correct"); - is(cookie.path, PATH, "cookie path is correct"); - is(cookie.name, "foobar", "cookie name is correct"); - is(cookie.value, value, "cookie value is correct"); - } - - // Check all URIs for which the cookie should NOT be collected. - for (let uri of params.noCookieURIs || []) { - yield replaceCurrentURI(browser, uri); - - // Cookie should be ignored. - ok(!getCookie(), "no cookie collected"); - } - - // Clean up. - gBrowser.removeTab(tab); - Services.cookies.removeAll(); -}); - -/** - * Replace the current URI of the given browser by loading a new URI. The - * browser's session history will be completely replaced. This function ensures - * that the parent process has the lastest shistory data before resolving. - */ -var replaceCurrentURI = Task.async(function* (browser, uri) { - // Replace the tab's current URI with the parent domain. - let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY; - browser.loadURIWithFlags(uri, flags); - yield promiseBrowserLoaded(browser); - - // Ensure the tab's session history is up-to-date. - yield TabStateFlusher.flush(browser); -}); - -/** - * Waits for a new "*example.com" cookie to be added. - */ -function waitForNewCookie() { - return new Promise(resolve => { - Services.obs.addObserver(function observer(subj, topic, data) { - let cookie = subj.QueryInterface(Ci.nsICookie2); - if (data == "added" && cookie.host.endsWith("example.com")) { - Services.obs.removeObserver(observer, topic); - resolve(); - } - }, "cookie-changed", false); - }); -} - -/** - * Retrieves the first cookie in the first window from the current sessionstore - * state. - */ -function getCookie() { - let state = JSON.parse(ss.getWindowState(window)); - let cookies = state.windows[0].cookies || []; - return cookies[0] || null; -} diff --git a/browser/components/sessionstore/test/browser_cookies.sjs b/browser/components/sessionstore/test/browser_cookies.sjs deleted file mode 100644 index bffbd66d9..000000000 --- a/browser/components/sessionstore/test/browser_cookies.sjs +++ /dev/null @@ -1,21 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -Components.utils.importGlobalProperties(["URLSearchParams"]); - -function handleRequest(req, resp) { - resp.setStatusLine(req.httpVersion, 200); - - let params = new URLSearchParams(req.queryString); - let value = params.get("value"); - - let domain = ""; - if (params.has("domain")) { - domain = `; Domain=${params.get("domain")}`; - } - - resp.setHeader("Set-Cookie", `foobar=${value}${domain}`); - resp.write("<meta charset=utf-8>hi"); -} diff --git a/browser/components/sessionstore/test/browser_crashedTabs.js b/browser/components/sessionstore/test/browser_crashedTabs.js deleted file mode 100644 index 5841d536a..000000000 --- a/browser/components/sessionstore/test/browser_crashedTabs.js +++ /dev/null @@ -1,462 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -requestLongerTimeout(10); - -const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page."; -const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page."; - -// Turn off tab animations for testing and use a single content process -// for these tests since we want to test tabs within the crashing process here. -add_task(function* test_initialize() { - yield SpecialPowers.pushPrefEnv({ - set: [ - [ "dom.ipc.processCount", 1 ], - [ "browser.tabs.animate", false] - ] }); -}); - -// Allow tabs to restore on demand so we can test pending states -Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); - -function clickButton(browser, id) { - info("Clicking " + id); - - let frame_script = (id) => { - let button = content.document.getElementById(id); - button.click(); - }; - - let mm = browser.messageManager; - mm.loadFrameScript("data:,(" + frame_script.toString() + ")('" + id + "');", false); -} - -/** - * Checks the documentURI of the root document of a remote browser - * to see if it equals URI. Returns a Promise that resolves if - * there is a match, and rejects with an error message if they - * do not match. - * - * @param browser - * The remote <xul:browser> to check the root document URI in. - * @param URI - * A string to match the root document URI against. - * @return Promise - */ -function promiseContentDocumentURIEquals(browser, URI) { - return new Promise((resolve, reject) => { - let frame_script = () => { - sendAsyncMessage("test:documenturi", { - uri: content.document.documentURI, - }); - }; - - let mm = browser.messageManager; - mm.addMessageListener("test:documenturi", function onMessage(message) { - mm.removeMessageListener("test:documenturi", onMessage); - let contentURI = message.data.uri; - if (contentURI == URI) { - resolve(); - } else { - reject(`Content has URI ${contentURI} which does not match ${URI}`); - } - }); - - mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", false); - }); -} - -/** - * Checks the window.history.length of the root window of a remote - * browser to see if it equals length. Returns a Promise that resolves - * if there is a match, and rejects with an error message if they - * do not match. - * - * @param browser - * The remote <xul:browser> to check the root window.history.length - * @param length - * The expected history length - * @return Promise - */ -function promiseHistoryLength(browser, length) { - return new Promise((resolve, reject) => { - let frame_script = () => { - sendAsyncMessage("test:historylength", { - length: content.history.length, - }); - }; - - let mm = browser.messageManager; - mm.addMessageListener("test:historylength", function onMessage(message) { - mm.removeMessageListener("test:historylength", onMessage); - let contentLength = message.data.length; - if (contentLength == length) { - resolve(); - } else { - reject(`Content has window.history.length ${contentLength} which does ` + - `not equal expected ${length}`); - } - }); - - mm.loadFrameScript("data:,(" + frame_script.toString() + ")();", false); - }); -} - -/** - * Returns a Promise that resolves when a browser has fired the - * AboutTabCrashedReady event. - * - * @param browser - * The remote <xul:browser> that will fire the event. - * @return Promise - */ -function promiseTabCrashedReady(browser) { - return new Promise((resolve) => { - browser.addEventListener("AboutTabCrashedReady", function ready(e) { - browser.removeEventListener("AboutTabCrashedReady", ready, false, true); - resolve(); - }, false, true); - }); -} - -/** - * Checks that if a tab crashes, that information about the tab crashed - * page does not get added to the tab history. - */ -add_task(function test_crash_page_not_in_history() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - // Check the tab state and make sure the tab crashed page isn't - // mentioned. - let {entries} = JSON.parse(ss.getTabState(newTab)); - is(entries.length, 1, "Should have a single history entry"); - is(entries[0].url, PAGE_1, - "Single entry should be the page we visited before crashing"); - - gBrowser.removeTab(newTab); -}); - -/** - * Checks that if a tab crashes, that when we browse away from that page - * to a non-blacklisted site (so the browser becomes remote again), that - * we record history for that new visit. - */ -add_task(function test_revived_history_from_remote() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - // Browse to a new site that will cause the browser to - // become remote again. - browser.loadURI(PAGE_2); - yield promiseTabRestored(newTab); - ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore."); - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield TabStateFlusher.flush(browser); - - // Check the tab state and make sure the tab crashed page isn't - // mentioned. - let {entries} = JSON.parse(ss.getTabState(newTab)); - is(entries.length, 2, "Should have two history entries"); - is(entries[0].url, PAGE_1, - "First entry should be the page we visited before crashing"); - is(entries[1].url, PAGE_2, - "Second entry should be the page we visited after crashing"); - - gBrowser.removeTab(newTab); -}); - -/** - * Checks that if a tab crashes, that when we browse away from that page - * to a blacklisted site (so the browser stays non-remote), that - * we record history for that new visit. - */ -add_task(function test_revived_history_from_non_remote() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - // Browse to a new site that will not cause the browser to - // become remote again. - browser.loadURI("about:mozilla"); - yield promiseBrowserLoaded(browser); - ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore."); - ok(!browser.isRemoteBrowser, "Should not be a remote browser"); - yield TabStateFlusher.flush(browser); - - // Check the tab state and make sure the tab crashed page isn't - // mentioned. - let {entries} = JSON.parse(ss.getTabState(newTab)); - is(entries.length, 2, "Should have two history entries"); - is(entries[0].url, PAGE_1, - "First entry should be the page we visited before crashing"); - is(entries[1].url, "about:mozilla", - "Second entry should be the page we visited after crashing"); - - gBrowser.removeTab(newTab); -}); - -/** - * Checks that we can revive a crashed tab back to the page that - * it was on when it crashed. - */ -add_task(function test_revive_tab_from_session_store() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - let newTab2 = gBrowser.addTab(); - let browser2 = newTab2.linkedBrowser; - ok(browser2.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser2); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_2); - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - // Background tabs should not be crashed, but should be in the "to be restored" - // state. - ok(!newTab2.hasAttribute("crashed"), "Second tab should not be crashed."); - ok(newTab2.hasAttribute("pending"), "Second tab should be pending."); - - // Use SessionStore to revive the first tab - clickButton(browser, "restoreTab"); - yield promiseTabRestored(newTab); - ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore."); - ok(newTab2.hasAttribute("pending"), "Second tab should still be pending."); - - // We can't just check browser.currentURI.spec, because from - // the outside, a crashed tab has the same URI as the page - // it crashed on (much like an about:neterror page). Instead, - // we have to use the documentURI on the content. - yield promiseContentDocumentURIEquals(browser, PAGE_2); - - // We should also have two entries in the browser history. - yield promiseHistoryLength(browser, 2); - - gBrowser.removeTab(newTab); - gBrowser.removeTab(newTab2); -}); - -/** - * Checks that we can revive multiple crashed tabs back to the pages - * that they were on when they crashed. - */ -add_task(function test_revive_all_tabs_from_session_store() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - // In order to see a second about:tabcrashed page, we'll need - // a second window, since only selected tabs will show - // about:tabcrashed. - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - let newTab2 = win2.gBrowser.addTab(PAGE_1); - win2.gBrowser.selectedTab = newTab2; - let browser2 = newTab2.linkedBrowser; - ok(browser2.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser2); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_2); - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - yield TabStateFlusher.flush(browser2); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - // Both tabs should now be crashed. - is(newTab.getAttribute("crashed"), "true", "First tab should be crashed"); - is(newTab2.getAttribute("crashed"), "true", "Second window tab should be crashed"); - - // Use SessionStore to revive all the tabs - clickButton(browser, "restoreAll"); - yield promiseTabRestored(newTab); - ok(!newTab.hasAttribute("crashed"), "Tab shouldn't be marked as crashed anymore."); - ok(!newTab.hasAttribute("pending"), "Tab shouldn't be pending."); - ok(!newTab2.hasAttribute("crashed"), "Second tab shouldn't be marked as crashed anymore."); - ok(!newTab2.hasAttribute("pending"), "Second tab shouldn't be pending."); - - // We can't just check browser.currentURI.spec, because from - // the outside, a crashed tab has the same URI as the page - // it crashed on (much like an about:neterror page). Instead, - // we have to use the documentURI on the content. - yield promiseContentDocumentURIEquals(browser, PAGE_2); - yield promiseContentDocumentURIEquals(browser2, PAGE_1); - - // We should also have two entries in the browser history. - yield promiseHistoryLength(browser, 2); - - yield BrowserTestUtils.closeWindow(win2); - gBrowser.removeTab(newTab); -}); - -/** - * Checks that about:tabcrashed can close the current tab - */ -add_task(function test_close_tab_after_crash() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - let promise = promiseEvent(gBrowser.tabContainer, "TabClose"); - - // Click the close tab button - clickButton(browser, "closeTab"); - yield promise; - - is(gBrowser.tabs.length, 1, "Should have closed the tab"); -}); - - -/** - * Checks that "restore all" button is only shown if more than one tab - * is showing about:tabcrashed - */ -add_task(function* test_hide_restore_all_button() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - let doc = browser.contentDocument; - let restoreAllButton = doc.getElementById("restoreAll"); - let restoreOneButton = doc.getElementById("restoreTab"); - - let restoreAllStyles = window.getComputedStyle(restoreAllButton); - is(restoreAllStyles.display, "none", "Restore All button should be hidden"); - ok(restoreOneButton.classList.contains("primary"), "Restore Tab button should have the primary class"); - - let newTab2 = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - - browser.loadURI(PAGE_2); - yield promiseBrowserLoaded(browser); - - // Load up a second window so we can get another tab to show - // about:tabcrashed - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - let newTab3 = win2.gBrowser.addTab(PAGE_2); - win2.gBrowser.selectedTab = newTab3; - let otherWinBrowser = newTab3.linkedBrowser; - yield promiseBrowserLoaded(otherWinBrowser); - // We'll need to make sure the second tab's browser has finished - // sending its AboutTabCrashedReady event before we know for - // sure whether or not we're showing the right Restore buttons. - let otherBrowserReady = promiseTabCrashedReady(otherWinBrowser); - - // Crash the first tab. - yield BrowserTestUtils.crashBrowser(browser); - yield otherBrowserReady; - - doc = browser.contentDocument; - restoreAllButton = doc.getElementById("restoreAll"); - restoreOneButton = doc.getElementById("restoreTab"); - - restoreAllStyles = window.getComputedStyle(restoreAllButton); - isnot(restoreAllStyles.display, "none", "Restore All button should not be hidden"); - ok(!(restoreOneButton.classList.contains("primary")), "Restore Tab button should not have the primary class"); - - yield BrowserTestUtils.closeWindow(win2); - gBrowser.removeTab(newTab); - gBrowser.removeTab(newTab2); -}); - -add_task(function* test_aboutcrashedtabzoom() { - let newTab = gBrowser.addTab(); - gBrowser.selectedTab = newTab; - let browser = newTab.linkedBrowser; - ok(browser.isRemoteBrowser, "Should be a remote browser"); - yield promiseBrowserLoaded(browser); - - browser.loadURI(PAGE_1); - yield promiseBrowserLoaded(browser); - - FullZoom.enlarge(); - let zoomLevel = ZoomManager.getZoomForBrowser(browser); - ok(zoomLevel !== 1, "should have enlarged"); - - yield TabStateFlusher.flush(browser); - - // Crash the tab - yield BrowserTestUtils.crashBrowser(browser); - - ok(ZoomManager.getZoomForBrowser(browser) === 1, "zoom should have reset on crash"); - - clickButton(browser, "restoreTab"); - yield promiseTabRestored(newTab); - - ok(ZoomManager.getZoomForBrowser(browser) === zoomLevel, "zoom should have gone back to enlarged"); - FullZoom.reset(); - - gBrowser.removeTab(newTab); -}); diff --git a/browser/components/sessionstore/test/browser_dying_cache.js b/browser/components/sessionstore/test/browser_dying_cache.js deleted file mode 100644 index c573aa5d4..000000000 --- a/browser/components/sessionstore/test/browser_dying_cache.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; - -/** - * This test ensures that after closing a window we keep its state data around - * as long as something keeps a reference to it. It should only be possible to - * read data after closing - writing should fail. - */ - -add_task(function* test() { - // Open a new window. - let win = yield promiseNewWindowLoaded(); - - // Load some URL in the current tab. - let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY; - win.gBrowser.selectedBrowser.loadURIWithFlags("about:robots", flags); - yield promiseBrowserLoaded(win.gBrowser.selectedBrowser); - - // Open a second tab and close the first one. - let tab = win.gBrowser.addTab("about:mozilla"); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - yield promiseRemoveTab(win.gBrowser.tabs[0]); - - // Make sure our window is still tracked by sessionstore - // and the window state is as expected. - ok("__SSi" in win, "window is being tracked by sessionstore"); - ss.setWindowValue(win, "foo", "bar"); - checkWindowState(win); - - let state = ss.getWindowState(win); - let closedTabData = ss.getClosedTabData(win); - - // Close our window. - yield BrowserTestUtils.closeWindow(win); - - // SessionStore should no longer track our window - // but it should still report the same state. - ok(!("__SSi" in win), "sessionstore does no longer track our window"); - checkWindowState(win); - - // Make sure we're not allowed to modify state data. - Assert.throws(() => ss.setWindowState(win, {}), - "we're not allowed to modify state data anymore"); - Assert.throws(() => ss.setWindowValue(win, "foo", "baz"), - "we're not allowed to modify state data anymore"); -}); - -function checkWindowState(window) { - let {windows: [{tabs}]} = JSON.parse(ss.getWindowState(window)); - is(tabs.length, 1, "the window has a single tab"); - is(tabs[0].entries[0].url, "about:mozilla", "the tab is about:mozilla"); - - is(ss.getClosedTabCount(window), 1, "the window has one closed tab"); - let [{state: {entries: [{url}]}}] = JSON.parse(ss.getClosedTabData(window)); - is(url, "about:robots", "the closed tab is about:robots"); - - is(ss.getWindowValue(window, "foo"), "bar", "correct extData value"); -} - -function shouldThrow(f) { - try { - f(); - } catch (e) { - return true; - } -} diff --git a/browser/components/sessionstore/test/browser_dynamic_frames.js b/browser/components/sessionstore/test/browser_dynamic_frames.js deleted file mode 100644 index e4355fee3..000000000 --- a/browser/components/sessionstore/test/browser_dynamic_frames.js +++ /dev/null @@ -1,87 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * Ensure that static frames of framesets are serialized but dynamically - * inserted iframes are ignored. - */ -add_task(function () { - // This URL has the following frames: - // + data:text/html,A (static) - // + data:text/html,B (static) - // + data:text/html,C (dynamic iframe) - const URL = "data:text/html;charset=utf-8," + - "<frameset cols=50%25,50%25><frame src='data:text/html,A'>" + - "<frame src='data:text/html,B'></frameset>" + - "<script>var i=document.createElement('iframe');" + - "i.setAttribute('src', 'data:text/html,C');" + - "document.body.appendChild(i);</script>"; - - // Add a new tab with two "static" and one "dynamic" frame. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - - // Check URLs. - ok(entries[0].url.startsWith("data:text/html"), "correct root url"); - is(entries[0].children[0].url, "data:text/html,A", "correct url for 1st frame"); - is(entries[0].children[1].url, "data:text/html,B", "correct url for 2nd frame"); - - // Check the number of children. - is(entries.length, 1, "there is one root entry ..."); - is(entries[0].children.length, 2, "... with two child entries"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that iframes created by the network parser are serialized but - * dynamically inserted iframes are ignored. Navigating a subframe should - * create a second root entry that doesn't contain any dynamic children either. - */ -add_task(function () { - // This URL has the following frames: - // + data:text/html,A (static) - // + data:text/html,C (dynamic iframe) - const URL = "data:text/html;charset=utf-8," + - "<iframe name=t src='data:text/html,A'></iframe>" + - "<a id=lnk href='data:text/html,B' target=t>clickme</a>" + - "<script>var i=document.createElement('iframe');" + - "i.setAttribute('src', 'data:text/html,C');" + - "document.body.appendChild(i);</script>"; - - // Add a new tab with one "static" and one "dynamic" frame. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - - // Check URLs. - ok(entries[0].url.startsWith("data:text/html"), "correct root url"); - ok(!entries[0].children, "no children collected"); - - // Navigate the subframe. - browser.messageManager.sendAsyncMessage("ss-test:click", {id: "lnk"}); - yield promiseBrowserLoaded(browser, false /* don't ignore subframes */); - - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - - // Check URLs. - ok(entries[0].url.startsWith("data:text/html"), "correct 1st root url"); - ok(entries[1].url.startsWith("data:text/html"), "correct 2nd root url"); - ok(!entries.children, "no children collected"); - ok(!entries[0].children, "no children collected"); - ok(!entries[1].children, "no children collected"); - - // Cleanup. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_forget_async_closings.js b/browser/components/sessionstore/test/browser_forget_async_closings.js deleted file mode 100644 index c130ec5ad..000000000 --- a/browser/components/sessionstore/test/browser_forget_async_closings.js +++ /dev/null @@ -1,144 +0,0 @@ -"use strict"; - -const PAGE = "http://example.com/"; - -/** - * Creates a tab in the current window worth storing in the - * closedTabs array, and then closes it. Runs a synchronous - * forgetFn passed in that should cause us to forget the tab, - * and then ensures that after the tab has sent its final - * update message that we didn't accidentally store it in - * the closedTabs array. - * - * @param forgetFn (function) - * A synchronous function that should cause the tab - * to be forgotten. - * @returns Promise - */ -let forgetTabHelper = Task.async(function*(forgetFn) { - // We want to suppress all non-final updates from the browser tabs - // so as to eliminate any racy-ness with this test. - yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]); - - // Forget any previous closed tabs from other tests that may have - // run in the same session. - Services.obs.notifyObservers(null, "browser:purge-session-history", 0); - - is(ss.getClosedTabCount(window), 0, - "We should have 0 closed tabs being stored."); - - // Create a tab worth remembering. - let tab = gBrowser.addTab(PAGE); - let browser = tab.linkedBrowser; - yield BrowserTestUtils.browserLoaded(browser, false, PAGE); - yield TabStateFlusher.flush(browser); - - // Now close the tab, and immediately choose to forget it. - let promise = BrowserTestUtils.removeTab(tab); - - // At this point, the tab will have closed, but the final update - // to SessionStore hasn't come up yet. Now do the operation that - // should cause us to forget the tab. - forgetFn(); - - is(ss.getClosedTabCount(window), 0, "Should have forgotten the closed tab"); - - // Now wait for the final update to come up. - yield promise; - - is(ss.getClosedTabCount(window), 0, - "Should not have stored the forgotten closed tab"); -}); - -/** - * Creates a new window worth storing in the closeWIndows array, - * and then closes it. Runs a synchronous forgetFn passed in that - * should cause us to forget the window, and then ensures that after - * the window has sent its final update message that we didn't - * accidentally store it in the closedWindows array. - * - * @param forgetFn (function) - * A synchronous function that should cause the window - * to be forgotten. - * @returns Promise - */ -let forgetWinHelper = Task.async(function*(forgetFn) { - // We want to suppress all non-final updates from the browser tabs - // so as to eliminate any racy-ness with this test. - yield pushPrefs(["browser.sessionstore.debug.no_auto_updates", true]); - - // Forget any previous closed windows from other tests that may have - // run in the same session. - Services.obs.notifyObservers(null, "browser:purge-session-history", 0); - - is(ss.getClosedWindowCount(), 0, "We should have 0 closed windows being stored."); - - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - - // Create a tab worth remembering. - let tab = newWin.gBrowser.selectedTab; - let browser = tab.linkedBrowser; - browser.loadURI(PAGE); - yield BrowserTestUtils.browserLoaded(browser, false, PAGE); - yield TabStateFlusher.flush(browser); - - // Now close the window and immediately choose to forget it. - let windowClosed = BrowserTestUtils.windowClosed(newWin); - let domWindowClosed = BrowserTestUtils.domWindowClosed(newWin); - - newWin.close(); - yield domWindowClosed; - - // At this point, the window will have closed and the onClose handler - // has run, but the final update to SessionStore hasn't come up yet. - // Now do the oepration that should cause us to forget the window. - forgetFn(); - - is(ss.getClosedWindowCount(), 0, "Should have forgotten the closed window"); - - // Now wait for the final update to come up. - yield windowClosed; - - is(ss.getClosedWindowCount(), 0, "Should not have stored the closed window"); -}); - -/** - * Tests that if we choose to forget a tab while waiting for its - * final flush to complete, we don't accidentally store it. - */ -add_task(function* test_forget_closed_tab() { - yield forgetTabHelper(() => { - ss.forgetClosedTab(window, 0); - }); -}); - -/** - * Tests that if we choose to forget a tab while waiting for its - * final flush to complete, we don't accidentally store it. - */ -add_task(function* test_forget_closed_window() { - yield forgetWinHelper(() => { - ss.forgetClosedWindow(0); - }); -}); - -/** - * Tests that if we choose to purge history while waiting for a - * final flush of a tab to complete, we don't accidentally store it. - */ -add_task(function* test_forget_purged_tab() { - yield forgetTabHelper(() => { - Services.obs.notifyObservers(null, "browser:purge-session-history", 0); - }); -}); - -/** - * Tests that if we choose to purge history while waiting for a - * final flush of a window to complete, we don't accidentally - * store it. - */ -add_task(function* test_forget_purged_window() { - yield forgetWinHelper(() => { - Services.obs.notifyObservers(null, "browser:purge-session-history", 0); - }); -}); diff --git a/browser/components/sessionstore/test/browser_form_restore_events.js b/browser/components/sessionstore/test/browser_form_restore_events.js deleted file mode 100644 index 3fc2e0fd4..000000000 --- a/browser/components/sessionstore/test/browser_form_restore_events.js +++ /dev/null @@ -1,63 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_form_restore_events_sample.html"; - -/** - * Originally a test for Bug 476161, but then expanded to include all input - * types in bug 640136. - */ -add_task(function () { - // Load a page with some form elements. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // text fields - yield setInputValue(browser, {id: "modify01", value: Math.random()}); - yield setInputValue(browser, {id: "modify02", value: Date.now()}); - - // textareas - yield setInputValue(browser, {id: "modify03", value: Math.random()}); - yield setInputValue(browser, {id: "modify04", value: Date.now()}); - - // file - let file = Services.dirsvc.get("TmpD", Ci.nsIFile); - yield setInputValue(browser, {id: "modify05", value: file.path}); - - // select - yield setSelectedIndex(browser, {id: "modify06", index: 1}); - yield setMultipleSelected(browser, {id: "modify07", indices: [0,1,2]}); - - // checkbox - yield setInputChecked(browser, {id: "modify08", checked: true}); - yield setInputChecked(browser, {id: "modify09", checked: false}); - - // radio - yield setInputChecked(browser, {id: "modify10", checked: true}); - yield setInputChecked(browser, {id: "modify11", checked: true}); - - // Duplicate the tab and check that restoring form data yields the expected - // input and change events for modified form fields. - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - let inputFired = yield getTextContent(browser2, {id: "inputFired"}); - inputFired = inputFired.trim().split().sort().join(" "); - - let changeFired = yield getTextContent(browser2, {id: "changeFired"}); - changeFired = changeFired.trim().split().sort().join(" "); - - is(inputFired, "modify01 modify02 modify03 modify04 modify05", - "input events were only dispatched for modified input, textarea fields"); - - is(changeFired, "modify06 modify07 modify08 modify09 modify11", - "change events were only dispatched for modified select, checkbox, radio fields"); - - // Cleanup. - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_form_restore_events_sample.html b/browser/components/sessionstore/test/browser_form_restore_events_sample.html deleted file mode 100644 index 1d46d4040..000000000 --- a/browser/components/sessionstore/test/browser_form_restore_events_sample.html +++ /dev/null @@ -1,99 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>Test for form restore events (originally bug 476161)</title> - -<script> - -document.addEventListener("input", function(aEvent) { - var inputEl = aEvent.originalTarget; - var changedEl = document.getElementById("inputFired"); - changedEl.textContent += " " + inputEl.id; -}, false); - -document.addEventListener("change", function(aEvent) { - var inputEl = aEvent.originalTarget; - var changedEl = document.getElementById("changeFired"); - changedEl.textContent += " " + inputEl.id; -}, false); - -</script> - -<!-- input events --> -<h3>Text fields with changed text</h3> -<input type="text" id="modify1"> -<input type="text" id="modify2" value="preset value"> -<input type="text" id="modify01"> -<input type="text" id="modify02" value="preset value"> - -<h3>Text fields with unchanged text</h3> -<input type="text" id="unchanged1"> -<input type="text" id="unchanged2" value="preset value"> -<input type="text" id="unchanged01"> -<input type="text" id="unchanged02" value="preset value"> - -<h3>Textarea with changed text</h3> -<textarea id="modify03"></textarea> -<textarea id="modify04">preset value</textarea> - -<h3>Textarea with unchanged text</h3> -<textarea id="unchanged03"></textarea> -<textarea id="unchanged04">preset value</textarea> - -<h3>file field with changed value</h3> -<input type="file" id="modify05"> - -<h3>file field with unchanged value</h3> -<input type="file" id="unchanged05"> - -<!-- change events --> - -<h3>Select menu with changed selection</h3> -<select id="modify06"> - <option value="one">one</option> - <option value="two">two</option> - <option value="three">three</option> -</select> - -<h3>Select menu with unchanged selection (change event still fires)</h3> -<select id="unchanged06"> - <option value="one">one</option> - <option value="two" selected>two</option> - <option value="three">three</option> -</select> - -<h3>Multiple Select menu with changed selection</h3> -<select id="modify07" multiple> - <option value="one">one</option> - <option value="two" selected>two</option> - <option value="three">three</option> -</select> - -<h3>Select menu with unchanged selection</h3> -<select id="unchanged07" multiple> - <option value="one">one</option> - <option value="two" selected>two</option> - <option value="three" selected>three</option> -</select> - -<h3>checkbox with changed value</h3> -<input type="checkbox" id="modify08"> -<input type="checkbox" id="modify09" checked> - -<h3>checkbox with unchanged value</h3> -<input type="checkbox" id="unchanged08"> -<input type="checkbox" id="unchanged09" checked> - -<h3>radio with changed value</h3> -<input type="radio" id="modify10" name="group">Radio 1</input> -<input type="radio" id="modify11" name="group">Radio 2</input> -<input type="radio" id="modify12" name="group" checked>Radio 3</input> - -<h3>radio with unchanged value</h3> -<input type="radio" id="unchanged10" name="group2">Radio 4</input> -<input type="radio" id="unchanged11" name="group2">Radio 5</input> -<input type="radio" id="unchanged12" name="group2" checked>Radio 6</input> - -<h3>Changed field IDs</h3> -<div id="changed"></div> -<div id="inputFired"></div> -<div id="changeFired"></div> diff --git a/browser/components/sessionstore/test/browser_formdata.js b/browser/components/sessionstore/test/browser_formdata.js deleted file mode 100644 index ce1272888..000000000 --- a/browser/components/sessionstore/test/browser_formdata.js +++ /dev/null @@ -1,194 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -requestLongerTimeout(2); - -/** - * This test ensures that form data collection respects the privacy level as - * set by the user. - */ -add_task(function test_formdata() { - const URL = "http://mochi.test:8888/browser/browser/components/" + - "sessionstore/test/browser_formdata_sample.html"; - - const OUTER_VALUE = "browser_formdata_" + Math.random(); - const INNER_VALUE = "browser_formdata_" + Math.random(); - - // Creates a tab, loads a page with some form fields, - // modifies their values and closes the tab. - function createAndRemoveTab() { - return Task.spawn(function () { - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Modify form data. - yield setInputValue(browser, {id: "txt", value: OUTER_VALUE}); - yield setInputValue(browser, {id: "txt", value: INNER_VALUE, frame: 0}); - - // Remove the tab. - yield promiseRemoveTab(tab); - }); - } - - yield createAndRemoveTab(); - let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window)); - is(formdata.id.txt, OUTER_VALUE, "outer value is correct"); - is(formdata.children[0].id.txt, INNER_VALUE, "inner value is correct"); - - // Disable saving data for encrypted sites. - Services.prefs.setIntPref("browser.sessionstore.privacy_level", 1); - - yield createAndRemoveTab(); - [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window)); - is(formdata.id.txt, OUTER_VALUE, "outer value is correct"); - ok(!formdata.children, "inner value was *not* stored"); - - // Disable saving data for any site. - Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2); - - yield createAndRemoveTab(); - [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window)); - ok(!formdata, "form data has *not* been stored"); - - // Restore the default privacy level. - Services.prefs.clearUserPref("browser.sessionstore.privacy_level"); -}); - -/** - * This test ensures that a malicious website can't trick us into restoring - * form data into a wrong website and that we always check the stored URL - * before doing so. - */ -add_task(function test_url_check() { - const URL = "data:text/html;charset=utf-8,<input%20id=input>"; - const VALUE = "value-" + Math.random(); - - // Create a tab with an iframe containing an input field. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Restore a tab state with a given form data url. - function restoreStateWithURL(url) { - let state = {entries: [{url: URL}], formdata: {id: {input: VALUE}}}; - - if (url) { - state.formdata.url = url; - } - - return promiseTabState(tab, state).then(() => getInputValue(browser, "input")); - } - - // Check that the form value is restored with the correct URL. - is((yield restoreStateWithURL(URL)), VALUE, "form data restored"); - - // Check that the form value is *not* restored with the wrong URL. - is((yield restoreStateWithURL(URL + "?")), "", "form data not restored"); - is((yield restoreStateWithURL()), "", "form data not restored"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * This test ensures that collecting form data works as expected when having - * nested frame sets. - */ -add_task(function test_nested() { - const URL = "data:text/html;charset=utf-8," + - "<iframe src='data:text/html;charset=utf-8," + - "<input autofocus=true>'/>"; - - const FORM_DATA = { - children: [{ - xpath: {"/xhtml:html/xhtml:body/xhtml:input": "M"}, - url: "data:text/html;charset=utf-8,<input%20autofocus=true>" - }] - }; - - // Create a tab with an iframe containing an input field. - let tab = gBrowser.selectedTab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Modify the input field's value. - yield sendMessage(browser, "ss-test:sendKeyEvent", {key: "m", frame: 0}); - - // Remove the tab and check that we stored form data correctly. - yield promiseRemoveTab(tab); - let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window)); - is(JSON.stringify(formdata), JSON.stringify(FORM_DATA), - "formdata for iframe stored correctly"); - - // Restore the closed tab. - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that the input field has the right value. - yield TabStateFlusher.flush(browser); - ({formdata} = JSON.parse(ss.getTabState(tab))); - is(JSON.stringify(formdata), JSON.stringify(FORM_DATA), - "formdata for iframe restored correctly"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * This test ensures that collecting form data for documents with - * designMode=on works as expected. - */ -add_task(function test_design_mode() { - const URL = "data:text/html;charset=utf-8,<h1>mozilla</h1>" + - "<script>document.designMode='on'</script>"; - - // Load a tab with an editable document. - let tab = gBrowser.selectedTab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Modify the document content. - yield sendMessage(browser, "ss-test:sendKeyEvent", {key: "m"}); - - // Close and restore the tab. - yield promiseRemoveTab(tab); - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that the innerHTML value was restored. - let html = yield getInnerHTML(browser); - let expected = "<h1>Mmozilla</h1><script>document.designMode='on'</script>"; - is(html, expected, "editable document has been restored correctly"); - - // Close and restore the tab. - yield promiseRemoveTab(tab); - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that the innerHTML value was restored. - html = yield getInnerHTML(browser); - expected = "<h1>Mmozilla</h1><script>document.designMode='on'</script>"; - is(html, expected, "editable document has been restored correctly"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -function getInputValue(browser, id) { - return sendMessage(browser, "ss-test:getInputValue", {id: id}); -} - -function setInputValue(browser, data) { - return sendMessage(browser, "ss-test:setInputValue", data); -} - -function getInnerHTML(browser) { - return sendMessage(browser, "ss-test:getInnerHTML", {selector: "body"}); -} diff --git a/browser/components/sessionstore/test/browser_formdata_cc.js b/browser/components/sessionstore/test/browser_formdata_cc.js deleted file mode 100644 index 6e27ca970..000000000 --- a/browser/components/sessionstore/test/browser_formdata_cc.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; - -const URL = "http://mochi.test:8888/browser/browser/components/" + - "sessionstore/test/browser_formdata_sample.html"; - -requestLongerTimeout(3); - -/** - * This test ensures that credit card numbers in form data will not be - * collected, while numbers that don't look like credit card numbers will - * still be collected. - */ -add_task(function* () { - const validCCNumbers = [ - // 15 digits - "930771457288760", "474915027480942", - "924894781317325", "714816113937185", - "790466087343106", "474320195408363", - "219211148122351", "633038472250799", - "354236732906484", "095347810189325", - // 16 digits - "3091269135815020", "5471839082338112", - "0580828863575793", "5015290610002932", - "9465714503078607", "4302068493801686", - "2721398408985465", "6160334316984331", - "8643619970075142", "0218246069710785" - ]; - - const invalidCCNumbers = [ - // 15 digits - "526931005800649", "724952425140686", - "379761391174135", "030551436468583", - "947377014076746", "254848023655752", - "226871580283345", "708025346034339", - "917585839076788", "918632588027666", - // 16 digits - "9946177098017064", "4081194386488872", - "3095975979578034", "3662215692222536", - "6723210018630429", "4411962856225025", - "8276996369036686", "4449796938248871", - "3350852696538147", "5011802870046957" - ]; - - // Creates a tab, loads a page with a form field, sets the value of the - // field, and then removes the tab to trigger data collection. - function* createAndRemoveTab(formValue) { - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Set form value. - yield setInputValue(browser, formValue); - - // Remove the tab. - yield promiseRemoveTab(tab); - } - - // Test that valid CC numbers are not collected. - for (let number of validCCNumbers) { - yield createAndRemoveTab(number); - let [{state}] = JSON.parse(ss.getClosedTabData(window)); - ok(!("formdata" in state), "valid CC numbers are not collected"); - } - - // Test that non-CC numbers are still collected. - for (let number of invalidCCNumbers) { - yield createAndRemoveTab(number); - let [{state: {formdata}}] = JSON.parse(ss.getClosedTabData(window)); - is(formdata.id.txt, number, - "numbers that are not valid CC numbers are still collected"); - } -}); - -function setInputValue(browser, formValue) { - return ContentTask.spawn(browser, formValue, function* (formValue) { - content.document.getElementById("txt").setUserInput(formValue); - }); -} diff --git a/browser/components/sessionstore/test/browser_formdata_format.js b/browser/components/sessionstore/test/browser_formdata_format.js deleted file mode 100644 index 6a1b5975d..000000000 --- a/browser/components/sessionstore/test/browser_formdata_format.js +++ /dev/null @@ -1,113 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -function test() { - /** Tests formdata format **/ - waitForExplicitFinish(); - - let formData = [ - { }, - // old format - { "#input1" : "value0" }, - { "#input1" : "value1", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value2" }, - { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value3" }, - // new format - { id: { "input1" : "value4" } }, - { id: { "input1" : "value5" }, xpath: {} }, - { id: { "input1" : "value6" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value7" } }, - { id: {}, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value8" } }, - { xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value9" } }, - // combinations - { "#input1" : "value10", id: { "input1" : "value11" } }, - { "#input1" : "value12", id: { "input1" : "value13" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value14" } }, - { "#input1" : "value15", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value16" } }, - { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value17", id: { "input1" : "value18" } }, - { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value19", id: { "input1" : "value20" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value21" } }, - { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value22", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value23" } }, - { "#input1" : "value24", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value25", id: { "input1" : "value26" } }, - { "#input1" : "value27", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value28", id: { "input1" : "value29" }, xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value30" } }, - { "#input1" : "value31", "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value32", xpath: { "/xhtml:html/xhtml:body/xhtml:input[@name='input2']" : "value33" } } - ] - let expectedValues = [ - [ "" , "" ], - // old format - [ "value0", "" ], - [ "value1", "value2" ], - [ "", "value3" ], - // new format - [ "value4", "" ], - [ "value5", "" ], - [ "value6", "value7" ], - [ "", "value8" ], - [ "", "value9" ], - // combinations - [ "value11", "" ], - [ "value13", "value14" ], - [ "", "value16" ], - [ "value18", "" ], - [ "value20", "value21" ], - [ "", "value23" ], - [ "value26", "" ], - [ "value29", "value30" ], - [ "", "value33" ] - ]; - let testTabCount = 0; - let callback = function() { - testTabCount--; - if (testTabCount == 0) { - finish(); - } - }; - - for (let i = 0; i < formData.length; i++) { - testTabCount++; - testTabRestoreData(formData[i], expectedValues[i], callback); - } -} - -function testTabRestoreData(aFormData, aExpectedValue, aCallback) { - let URL = ROOT + "browser_formdata_format_sample.html"; - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - - aFormData.url = URL; - let tabState = { entries: [{ url: URL }], formdata: aFormData }; - - Task.spawn(function () { - yield promiseBrowserLoaded(tab.linkedBrowser); - yield promiseTabState(tab, tabState); - - yield TabStateFlusher.flush(tab.linkedBrowser); - let restoredTabState = JSON.parse(ss.getTabState(tab)); - let restoredFormData = restoredTabState.formdata; - - if (restoredFormData) { - let doc = tab.linkedBrowser.contentDocument; - let input1 = doc.getElementById("input1"); - let input2 = doc.querySelector("input[name=input2]"); - - // test format - ok("id" in restoredFormData || "xpath" in restoredFormData, - "FormData format is valid: " + restoredFormData); - // validate that there are no old keys - for (let key of Object.keys(restoredFormData)) { - if (["id", "xpath", "url"].indexOf(key) === -1) { - ok(false, "FormData format is invalid."); - } - } - // test id - is(input1.value, aExpectedValue[0], - "FormData by 'id' has been restored correctly"); - // test xpath - is(input2.value, aExpectedValue[1], - "FormData by 'xpath' has been restored correctly"); - } - - // clean up - gBrowser.removeTab(tab); - - // This test might time out if the task fails. - }).then(aCallback); -} diff --git a/browser/components/sessionstore/test/browser_formdata_format_sample.html b/browser/components/sessionstore/test/browser_formdata_format_sample.html deleted file mode 100644 index f991e3657..000000000 --- a/browser/components/sessionstore/test/browser_formdata_format_sample.html +++ /dev/null @@ -1,7 +0,0 @@ -<!DOCTYPE html> -<title>Test formdata format</title> - -<!-- input events --> -<h3>Input fields</h3> -<input type="text" id="input1"> -<input type="text" name="input2">
\ No newline at end of file diff --git a/browser/components/sessionstore/test/browser_formdata_sample.html b/browser/components/sessionstore/test/browser_formdata_sample.html deleted file mode 100644 index 6cbb54fb5..000000000 --- a/browser/components/sessionstore/test/browser_formdata_sample.html +++ /dev/null @@ -1,20 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_formdata_sample.html</title> - </head> - <body> - <input id="txt" /> - - <script type="text/javascript;version=1.8"> - let isOuter = window == window.top; - - if (isOuter) { - let iframe = document.createElement("iframe"); - iframe.setAttribute("src", "https://example.com" + location.pathname); - document.body.appendChild(iframe); - } - </script> - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_formdata_xpath.js b/browser/components/sessionstore/test/browser_formdata_xpath.js deleted file mode 100644 index d69feb546..000000000 --- a/browser/components/sessionstore/test/browser_formdata_xpath.js +++ /dev/null @@ -1,151 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = ROOT + "browser_formdata_xpath_sample.html"; - -/** - * Bug 346337 - Generic form data restoration tests. - */ -add_task(function setup() { - // make sure we don't save form data at all (except for tab duplication) - Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2); - - registerCleanupFunction(() => { - Services.prefs.clearUserPref("browser.sessionstore.privacy_level"); - }); -}); - -const FILE1 = createFilePath("346337_test1.file"); -const FILE2 = createFilePath("346337_test2.file"); - -const FIELDS = { - "//input[@name='input']": Date.now().toString(), - "//input[@name='spaced 1']": Math.random().toString(), - "//input[3]": "three", - "//input[@type='checkbox']": true, - "//input[@name='uncheck']": false, - "//input[@type='radio'][1]": false, - "//input[@type='radio'][2]": true, - "//input[@type='radio'][3]": false, - "//select": 2, - "//select[@multiple]": [1, 3], - "//textarea[1]": "", - "//textarea[2]": "Some text... " + Math.random(), - "//textarea[3]": "Some more text\n" + new Date(), - "//input[@type='file'][1]": [FILE1], - "//input[@type='file'][2]": [FILE1, FILE2] -}; - -add_task(function test_form_data_restoration() { - // Load page with some input fields. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Fill in some values. - for (let xpath of Object.keys(FIELDS)) { - yield setFormValue(browser, xpath); - } - - // Duplicate the tab. - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - // Check that all form values have been duplicated. - for (let xpath of Object.keys(FIELDS)) { - let expected = JSON.stringify(FIELDS[xpath]); - let actual = JSON.stringify(yield getFormValue(browser2, xpath)); - is(actual, expected, "The value for \"" + xpath + "\" was correctly restored"); - } - - // Remove all tabs. - yield promiseRemoveTab(tab2); - yield promiseRemoveTab(tab); - - // Restore one of the tabs again. - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that none of the form values have been restored due to the privacy - // level settings. - for (let xpath of Object.keys(FIELDS)) { - let expected = FIELDS[xpath]; - if (expected) { - let actual = yield getFormValue(browser, xpath, expected); - isnot(actual, expected, "The value for \"" + xpath + "\" was correctly discarded"); - } - } - - // Cleanup. - yield promiseRemoveTab(tab); -}); - -function createFilePath(leaf) { - let file = Services.dirsvc.get("TmpD", Ci.nsIFile); - file.append(leaf); - return file.path; -} - -function isArrayOfNumbers(value) { - return Array.isArray(value) && value.every(n => typeof(n) === "number"); -} - -function isArrayOfStrings(value) { - return Array.isArray(value) && value.every(n => typeof(n) === "string"); -} - -function getFormValue(browser, xpath) { - let value = FIELDS[xpath]; - - if (typeof value == "string") { - return getInputValue(browser, {xpath: xpath}); - } - - if (typeof value == "boolean") { - return getInputChecked(browser, {xpath: xpath}); - } - - if (typeof value == "number") { - return getSelectedIndex(browser, {xpath: xpath}); - } - - if (isArrayOfNumbers(value)) { - return getMultipleSelected(browser, {xpath: xpath}); - } - - if (isArrayOfStrings(value)) { - return getFileNameArray(browser, {xpath: xpath}); - } - - throw new Error("unknown input type"); -} - -function setFormValue(browser, xpath) { - let value = FIELDS[xpath]; - - if (typeof value == "string") { - return setInputValue(browser, {xpath: xpath, value: value}); - } - - if (typeof value == "boolean") { - return setInputChecked(browser, {xpath: xpath, checked: value}); - } - - if (typeof value == "number") { - return setSelectedIndex(browser, {xpath: xpath, index: value}); - } - - if (isArrayOfNumbers(value)) { - return setMultipleSelected(browser, {xpath: xpath, indices: value}); - } - - if (isArrayOfStrings(value)) { - return setFileNameArray(browser, {xpath: xpath, names: value}); - } - - throw new Error("unknown input type"); -} diff --git a/browser/components/sessionstore/test/browser_formdata_xpath_sample.html b/browser/components/sessionstore/test/browser_formdata_xpath_sample.html deleted file mode 100644 index 682162d6a..000000000 --- a/browser/components/sessionstore/test/browser_formdata_xpath_sample.html +++ /dev/null @@ -1,37 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> -<title>Test for bug 346337</title> - -<h3>Text Fields</h3> -<input type="text" name="input"> -<input type="text" name="spaced 1"> -<input> - -<h3>Checkboxes and Radio buttons</h3> -<input type="checkbox" name="check"> Check 1 -<input type="checkbox" name="uncheck" checked> Check 2 -<p> -<input type="radio" name="group" value="1"> Radio 1 -<input type="radio" name="group" value="some"> Radio 2 -<input type="radio" name="group" checked> Radio 3 - -<h3>Selects</h3> -<select name="any"> - <option value="1"> Select 1 - <option value="some"> Select 2 - <option>Select 3 -</select> -<select multiple="multiple"> - <option value=1> Multi-select 1 - <option value=2> Multi-select 2 - <option value=3> Multi-select 3 - <option value=4> Multi-select 4 -</select> - -<h3>Text Areas</h3> -<textarea name="testarea"></textarea> -<textarea name="sized one" rows="5" cols="25"></textarea> -<textarea></textarea> - -<h3>File Selector</h3> -<input type="file"> -<input type="file" multiple> diff --git a/browser/components/sessionstore/test/browser_frame_history.js b/browser/components/sessionstore/test/browser_frame_history.js deleted file mode 100644 index e0d152f77..000000000 --- a/browser/components/sessionstore/test/browser_frame_history.js +++ /dev/null @@ -1,170 +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/. */ - -/** - Ensure that frameset history works properly when restoring a tab, - provided that the frameset is static. - */ - -// Loading a toplevel frameset -add_task(function() { - let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index.html"; - let tab = gBrowser.addTab(testURL); - gBrowser.selectedTab = tab; - - info("Opening a page with three frames, 4 loads should take place"); - yield waitForLoadsInBrowser(tab.linkedBrowser, 4); - - let browser_b = tab.linkedBrowser.contentDocument.getElementsByTagName("frame")[1]; - let document_b = browser_b.contentDocument; - let links = document_b.getElementsByTagName("a"); - - // We're going to click on the first link, so listen for another load event - info("Clicking on link 1, 1 load should take place"); - let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow); - yield promise; - - info("Clicking on link 2, 1 load should take place"); - promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow); - yield promise; - - info("Close then un-close page, 4 loads should take place"); - yield promiseRemoveTab(tab); - let newTab = ss.undoCloseTab(window, 0); - yield waitForLoadsInBrowser(newTab.linkedBrowser, 4); - - info("Go back in time, 1 load should take place"); - gBrowser.goBack(); - yield waitForLoadsInBrowser(newTab.linkedBrowser, 1); - - let expectedURLEnds = ["a.html", "b.html", "c1.html"]; - let frames = newTab.linkedBrowser.contentDocument.getElementsByTagName("frame"); - for (let i = 0; i < frames.length; i++) { - is(frames[i].contentDocument.location, - getRootDirectory(gTestPath) + "browser_frame_history_" + expectedURLEnds[i], - "frame " + i + " has the right url"); - } - gBrowser.removeTab(newTab); -}); - -// Loading the frameset inside an iframe -add_task(function() { - let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index2.html"; - let tab = gBrowser.addTab(testURL); - gBrowser.selectedTab = tab; - - info("iframe: Opening a page with an iframe containing three frames, 5 loads should take place"); - yield waitForLoadsInBrowser(tab.linkedBrowser, 5); - - let browser_b = tab.linkedBrowser.contentDocument. - getElementById("iframe").contentDocument. - getElementsByTagName("frame")[1]; - let document_b = browser_b.contentDocument; - let links = document_b.getElementsByTagName("a"); - - // We're going to click on the first link, so listen for another load event - info("iframe: Clicking on link 1, 1 load should take place"); - let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow); - yield promise; - - info("iframe: Clicking on link 2, 1 load should take place"); - promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow); - yield promise; - - info("iframe: Close then un-close page, 5 loads should take place"); - yield promiseRemoveTab(tab); - let newTab = ss.undoCloseTab(window, 0); - yield waitForLoadsInBrowser(newTab.linkedBrowser, 5); - - info("iframe: Go back in time, 1 load should take place"); - gBrowser.goBack(); - yield waitForLoadsInBrowser(newTab.linkedBrowser, 1); - - let expectedURLEnds = ["a.html", "b.html", "c1.html"]; - let frames = newTab.linkedBrowser.contentDocument. - getElementById("iframe").contentDocument. - getElementsByTagName("frame"); - for (let i = 0; i < frames.length; i++) { - is(frames[i].contentDocument.location, - getRootDirectory(gTestPath) + "browser_frame_history_" + expectedURLEnds[i], - "frame " + i + " has the right url"); - } - gBrowser.removeTab(newTab); -}); - -// Now, test that we don't record history if the iframe is added dynamically -add_task(function() { - // Start with an empty history - let blankState = JSON.stringify({ - windows: [{ - tabs: [{ entries: [{ url: "about:blank" }] }], - _closedTabs: [] - }], - _closedWindows: [] - }); - ss.setBrowserState(blankState); - - let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index_blank.html"; - let tab = gBrowser.addTab(testURL); - gBrowser.selectedTab = tab; - yield waitForLoadsInBrowser(tab.linkedBrowser, 1); - - info("dynamic: Opening a page with an iframe containing three frames, 4 dynamic loads should take place"); - let doc = tab.linkedBrowser.contentDocument; - let iframe = doc.createElement("iframe"); - iframe.id = "iframe"; - iframe.src="browser_frame_history_index.html"; - doc.body.appendChild(iframe); - yield waitForLoadsInBrowser(tab.linkedBrowser, 4); - - let browser_b = tab.linkedBrowser.contentDocument. - getElementById("iframe").contentDocument. - getElementsByTagName("frame")[1]; - let document_b = browser_b.contentDocument; - let links = document_b.getElementsByTagName("a"); - - // We're going to click on the first link, so listen for another load event - info("dynamic: Clicking on link 1, 1 load should take place"); - let promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[0], browser_b.contentWindow); - yield promise; - - info("dynamic: Clicking on link 2, 1 load should take place"); - promise = waitForLoadsInBrowser(tab.linkedBrowser, 1); - EventUtils.sendMouseEvent({type:"click"}, links[1], browser_b.contentWindow); - yield promise; - - info("Check in the state that we have not stored this history"); - let state = ss.getBrowserState(); - info(JSON.stringify(JSON.parse(state), null, "\t")); - is(state.indexOf("c1.html"), -1, "History entry was not stored in the session state");; - gBrowser.removeTab(tab); -}); - -// helper functions -function waitForLoadsInBrowser(aBrowser, aLoadCount) { - let deferred = Promise.defer(); - let loadCount = 0; - aBrowser.addEventListener("load", function(aEvent) { - if (++loadCount < aLoadCount) { - info("Got " + loadCount + " loads, waiting until we have " + aLoadCount); - return; - } - - aBrowser.removeEventListener("load", arguments.callee, true); - deferred.resolve(); - }, true); - return deferred.promise; -} - -function timeout(delay, task) { - let deferred = Promise.defer(); - setTimeout(() => deferred.resolve(true), delay); - task.then(() => deferred.resolve(false), deferred.reject); - return deferred.promise; -} diff --git a/browser/components/sessionstore/test/browser_frame_history_a.html b/browser/components/sessionstore/test/browser_frame_history_a.html deleted file mode 100755 index 8e7b35d7a..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_a.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - I'm A! - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_frame_history_b.html b/browser/components/sessionstore/test/browser_frame_history_b.html deleted file mode 100755 index 38b43da21..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_b.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> - <body> - I'm B!<br/> - <a target="c" href="browser_frame_history_c1.html">click me first</a><br/> - <a target="c" href="browser_frame_history_c2.html">then click me</a><br/> - Close this tab.<br/> - Restore this tab.<br/> - Click back.<br/> - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_frame_history_c.html b/browser/components/sessionstore/test/browser_frame_history_c.html deleted file mode 100755 index 0efd7d902..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_c.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - I'm C! - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_frame_history_c1.html b/browser/components/sessionstore/test/browser_frame_history_c1.html deleted file mode 100755 index b55c1d45a..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_c1.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - I'm C1! - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_frame_history_c2.html b/browser/components/sessionstore/test/browser_frame_history_c2.html deleted file mode 100755 index aec504141..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_c2.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - I'm C2! - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_frame_history_index.html b/browser/components/sessionstore/test/browser_frame_history_index.html deleted file mode 100644 index 76eeb4c4d..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_index.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> - <frameset cols="20%,80%"> - <frameset rows="30%,70%"> - <frame src="browser_frame_history_a.html"/> - <frame src="browser_frame_history_b.html"/> - </frameset> - <frame src="browser_frame_history_c.html" name="c"/> - </frameset> -</html> - diff --git a/browser/components/sessionstore/test/browser_frame_history_index2.html b/browser/components/sessionstore/test/browser_frame_history_index2.html deleted file mode 100644 index e4dfb4083..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_index2.html +++ /dev/null @@ -1,4 +0,0 @@ -<html> - <iframe src="browser_frame_history_index.html" id="iframe" /> -</html> - diff --git a/browser/components/sessionstore/test/browser_frame_history_index_blank.html b/browser/components/sessionstore/test/browser_frame_history_index_blank.html deleted file mode 100644 index 30fd1f58c..000000000 --- a/browser/components/sessionstore/test/browser_frame_history_index_blank.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> - <body> - </body> -</html> - diff --git a/browser/components/sessionstore/test/browser_frametree.js b/browser/components/sessionstore/test/browser_frametree.js deleted file mode 100644 index a342f8c66..000000000 --- a/browser/components/sessionstore/test/browser_frametree.js +++ /dev/null @@ -1,131 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = HTTPROOT + "browser_frametree_sample.html"; -const URL_FRAMESET = HTTPROOT + "browser_frametree_sample_frameset.html"; - -/** - * This ensures that loading a page normally, aborting a page load, reloading - * a page, navigating using the bfcache, and ignoring frames that were - * created dynamically work as expect. We expect the frame tree to be reset - * when a page starts loading and we also expect a valid frame tree to exist - * when it has stopped loading. - */ -add_task(function test_frametree() { - const FRAME_TREE_SINGLE = { href: URL }; - const FRAME_TREE_FRAMESET = { - href: URL_FRAMESET, - children: [{href: URL}, {href: URL}, {href: URL}] - }; - - // Create a tab with a single frame. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseNewFrameTree(browser); - yield checkFrameTree(browser, FRAME_TREE_SINGLE, - "loading a page resets and creates the frame tree correctly"); - - // Load the frameset and create two frames dynamically, the first on - // DOMContentLoaded and the second on load. - yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL}); - browser.loadURI(URL_FRAMESET); - yield promiseNewFrameTree(browser); - yield checkFrameTree(browser, FRAME_TREE_FRAMESET, - "dynamic frames created on or after the load event are ignored"); - - // Go back to the previous single-frame page. There will be no load event as - // the page is still in the bfcache. We thus make sure this type of navigation - // resets the frame tree. - browser.goBack(); - yield promiseNewFrameTree(browser); - yield checkFrameTree(browser, FRAME_TREE_SINGLE, - "loading from bfache resets and creates the frame tree correctly"); - - // Load the frameset again but abort the load early. - // The frame tree should still be reset and created. - browser.loadURI(URL_FRAMESET); - executeSoon(() => browser.stop()); - yield promiseNewFrameTree(browser); - - // Load the frameset and check the tree again. - yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL}); - browser.loadURI(URL_FRAMESET); - yield promiseNewFrameTree(browser); - yield checkFrameTree(browser, FRAME_TREE_FRAMESET, - "reloading a page resets and creates the frame tree correctly"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * This test ensures that we ignore frames that were created dynamically at or - * after the load event. SessionStore can't handle these and will not restore - * or collect any data for them. - */ -add_task(function test_frametree_dynamic() { - // The frame tree as expected. The first two frames are static - // and the third one was created on DOMContentLoaded. - const FRAME_TREE = { - href: URL_FRAMESET, - children: [{href: URL}, {href: URL}, {href: URL}] - }; - const FRAME_TREE_REMOVED = { - href: URL_FRAMESET, - children: [{href: URL}, {href: URL}] - }; - - // Add an empty tab for a start. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Create dynamic frames on "DOMContentLoaded" and on "load". - yield sendMessage(browser, "ss-test:createDynamicFrames", {id: "frames", url: URL}); - browser.loadURI(URL_FRAMESET); - yield promiseNewFrameTree(browser); - - // Check that the frame tree does not contain the frame created on "load". - // The two static frames and the one created on DOMContentLoaded must be in - // the tree. - yield checkFrameTree(browser, FRAME_TREE, - "frame tree contains first four frames"); - - // Remove the last frame in the frameset. - yield sendMessage(browser, "ss-test:removeLastFrame", {id: "frames"}); - // Check that the frame tree didn't change. - yield checkFrameTree(browser, FRAME_TREE, - "frame tree contains first four frames"); - - // Remove the last frame in the frameset. - yield sendMessage(browser, "ss-test:removeLastFrame", {id: "frames"}); - // Check that the frame tree excludes the removed frame. - yield checkFrameTree(browser, FRAME_TREE_REMOVED, - "frame tree contains first three frames"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Checks whether the current frame hierarchy of a given |browser| matches the - * |expected| frame hierarchy. - */ -function checkFrameTree(browser, expected, msg) { - return sendMessage(browser, "ss-test:mapFrameTree").then(tree => { - is(JSON.stringify(tree), JSON.stringify(expected), msg); - }); -} - -/** - * Returns a promise that will be resolved when the given |browser| has loaded - * and we received messages saying that its frame tree has been reset and - * recollected. - */ -function promiseNewFrameTree(browser) { - let reset = promiseContentMessage(browser, "ss-test:onFrameTreeCollected"); - let collect = promiseContentMessage(browser, "ss-test:onFrameTreeCollected"); - return Promise.all([reset, collect]); -} diff --git a/browser/components/sessionstore/test/browser_frametree_sample.html b/browser/components/sessionstore/test/browser_frametree_sample.html deleted file mode 100644 index dda129448..000000000 --- a/browser/components/sessionstore/test/browser_frametree_sample.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_frametree_sample.html</title> - </head> - <body style='width: 100000px; height: 100000px;'>top</body> -</html> diff --git a/browser/components/sessionstore/test/browser_frametree_sample_frameset.html b/browser/components/sessionstore/test/browser_frametree_sample_frameset.html deleted file mode 100644 index e1cd08735..000000000 --- a/browser/components/sessionstore/test/browser_frametree_sample_frameset.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN"> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_frametree_sample_frameset.html</title> - </head> - <frameset id="frames" rows="50%, 50%"> - <frame src="browser_frametree_sample.html"> - <frame src="browser_frametree_sample.html"> - </frameset> -</html> diff --git a/browser/components/sessionstore/test/browser_global_store.js b/browser/components/sessionstore/test/browser_global_store.js deleted file mode 100644 index 792154830..000000000 --- a/browser/components/sessionstore/test/browser_global_store.js +++ /dev/null @@ -1,45 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -// Tests the API for saving global session data. -add_task(function* () { - const key1 = "Unique name 1: " + Date.now(); - const key2 = "Unique name 2: " + Date.now(); - const value1 = "Unique value 1: " + Math.random(); - const value2 = "Unique value 2: " + Math.random(); - - let global = {}; - global[key1] = value1; - - const testState = { - windows: [ - { - tabs: [ - { entries: [{ url: "about:blank" }] }, - ] - } - ], - global: global - }; - - function testRestoredState() { - is(ss.getGlobalValue(key1), value1, "restored state has global value"); - } - - function testGlobalStore() { - is(ss.getGlobalValue(key2), "", "global value initially not set"); - - ss.setGlobalValue(key2, value1); - is(ss.getGlobalValue(key2), value1, "retreived value matches stored"); - - ss.setGlobalValue(key2, value2); - is(ss.getGlobalValue(key2), value2, "previously stored value was overwritten"); - - ss.deleteGlobalValue(key2); - is(ss.getGlobalValue(key2), "", "global value was deleted"); - } - - yield promiseBrowserState(testState); - testRestoredState(); - testGlobalStore(); -}); diff --git a/browser/components/sessionstore/test/browser_history_persist.js b/browser/components/sessionstore/test/browser_history_persist.js deleted file mode 100644 index 6b9e62abc..000000000 --- a/browser/components/sessionstore/test/browser_history_persist.js +++ /dev/null @@ -1,93 +0,0 @@ -/* eslint-env mozilla/frame-script */ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * Ensure that history entries that should not be persisted are restored in the - * same state. - */ -add_task(function check_history_not_persisted() { - // Create an about:blank tab - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Retrieve the tab state. - yield TabStateFlusher.flush(browser); - let state = JSON.parse(ss.getTabState(tab)); - ok(!state.entries[0].persist, "Should have collected the persistence state"); - yield promiseRemoveTab(tab); - browser = null; - - // Open a new tab to restore into. - tab = gBrowser.addTab("about:blank"); - browser = tab.linkedBrowser; - yield promiseTabState(tab, state); - - yield ContentTask.spawn(browser, null, function() { - let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsISHistory); - - is(sessionHistory.count, 1, "Should be a single history entry"); - is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL"); - }); - - // Load a new URL into the tab, it should replace the about:blank history entry - browser.loadURI("about:robots"); - yield promiseBrowserLoaded(browser); - yield ContentTask.spawn(browser, null, function() { - let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsISHistory); - is(sessionHistory.count, 1, "Should be a single history entry"); - is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:robots", "Should be the right URL"); - }); - - // Cleanup. - yield promiseRemoveTab(tab); -}); - -/** - * Check that entries default to being persisted when the attribute doesn't - * exist - */ -add_task(function check_history_default_persisted() { - // Create an about:blank tab - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Retrieve the tab state. - yield TabStateFlusher.flush(browser); - let state = JSON.parse(ss.getTabState(tab)); - delete state.entries[0].persist; - yield promiseRemoveTab(tab); - browser = null; - - // Open a new tab to restore into. - tab = gBrowser.addTab("about:blank"); - browser = tab.linkedBrowser; - yield promiseTabState(tab, state); - yield ContentTask.spawn(browser, null, function() { - let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsISHistory); - - is(sessionHistory.count, 1, "Should be a single history entry"); - is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL"); - }); - - // Load a new URL into the tab, it should replace the about:blank history entry - browser.loadURI("about:robots"); - yield promiseBrowserLoaded(browser); - yield ContentTask.spawn(browser, null, function() { - let sessionHistory = docShell.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsISHistory); - is(sessionHistory.count, 2, "Should be two history entries"); - is(sessionHistory.getEntryAtIndex(0, false).URI.spec, "about:blank", "Should be the right URL"); - is(sessionHistory.getEntryAtIndex(1, false).URI.spec, "about:robots", "Should be the right URL"); - }); - - // Cleanup. - yield promiseRemoveTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_label_and_icon.js b/browser/components/sessionstore/test/browser_label_and_icon.js deleted file mode 100644 index db68eb042..000000000 --- a/browser/components/sessionstore/test/browser_label_and_icon.js +++ /dev/null @@ -1,53 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const {classes: Cc, interfaces: Ci} = Components; - -/** - * Make sure that tabs are restored on demand as otherwise the tab will start - * loading immediately and we can't check its icon and label. - */ -add_task(function setup() { - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - registerCleanupFunction(() => { - Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); - }); -}); - -/** - * Ensure that a pending tab has label and icon correctly set. - */ -add_task(function test_label_and_icon() { - // Create a new tab. - let tab = gBrowser.addTab("about:robots"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Retrieve the tab state. - yield TabStateFlusher.flush(browser); - let state = ss.getTabState(tab); - yield promiseRemoveTab(tab); - browser = null; - - // Open a new tab to restore into. - tab = gBrowser.addTab("about:blank"); - ss.setTabState(tab, state); - yield promiseTabRestoring(tab); - - // Check that label and icon are set for the restoring tab. - ok(gBrowser.getIcon(tab).startsWith("data:image/png;"), "icon is set"); - is(tab.label, "Gort! Klaatu barada nikto!", "label is set"); - - let serhelper = Cc["@mozilla.org/network/serialization-helper;1"] - .getService(Ci.nsISerializationHelper); - let serializedPrincipal = tab.getAttribute("iconLoadingPrincipal"); - let iconLoadingPrincipal = serhelper.deserializeObject(serializedPrincipal) - .QueryInterface(Ci.nsIPrincipal); - is(iconLoadingPrincipal.origin, "about:robots", "correct loadingPrincipal used"); - - // Cleanup. - yield promiseRemoveTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_merge_closed_tabs.js b/browser/components/sessionstore/test/browser_merge_closed_tabs.js deleted file mode 100644 index b26e86f22..000000000 --- a/browser/components/sessionstore/test/browser_merge_closed_tabs.js +++ /dev/null @@ -1,71 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * This test ensures that closed tabs are merged when restoring - * a window state without overwriting tabs. - */ -add_task(function () { - const initialState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:blank" }] } - ], - _closedTabs: [ - { state: { entries: [{ ID: 1000, url: "about:blank" }]} }, - { state: { entries: [{ ID: 1001, url: "about:blank" }]} } - ] - }] - } - - const restoreState = { - windows: [{ - tabs: [ - { entries: [{ url: "about:robots" }] } - ], - _closedTabs: [ - { state: { entries: [{ ID: 1002, url: "about:robots" }]} }, - { state: { entries: [{ ID: 1003, url: "about:robots" }]} }, - { state: { entries: [{ ID: 1004, url: "about:robots" }]} } - ] - }] - } - - const maxTabsUndo = 4; - gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", maxTabsUndo); - - // Open a new window and restore it to an initial state. - let win = yield promiseNewWindowLoaded({private: false}); - SessionStore.setWindowState(win, JSON.stringify(initialState), true); - is(SessionStore.getClosedTabCount(win), 2, "2 closed tabs after restoring initial state"); - - // Restore the new state but do not overwrite existing tabs (this should - // cause the closed tabs to be merged). - SessionStore.setWindowState(win, JSON.stringify(restoreState), false); - - // Verify the windows closed tab data is correct. - let iClosed = initialState.windows[0]._closedTabs; - let rClosed = restoreState.windows[0]._closedTabs; - let cData = JSON.parse(SessionStore.getClosedTabData(win)); - - is(cData.length, Math.min(iClosed.length + rClosed.length, maxTabsUndo), - "Number of closed tabs is correct"); - - // When the closed tabs are merged the restored tabs are considered to be - // closed more recently. - for (let i = 0; i < cData.length; i++) { - if (i < rClosed.length) { - is(cData[i].state.entries[0].ID, rClosed[i].state.entries[0].ID, - "Closed tab entry matches"); - } else { - is(cData[i].state.entries[0].ID, iClosed[i - rClosed.length].state.entries[0].ID, - "Closed tab entry matches"); - } - } - - // Clean up. - gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo"); - yield BrowserTestUtils.closeWindow(win); -}); - - diff --git a/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js b/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js deleted file mode 100644 index fc958b293..000000000 --- a/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; - -const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page."; -const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page."; - -add_task(function*() { - // Load an empty, non-remote tab at about:blank... - let tab = gBrowser.addTab("about:blank", { - forceNotRemote: true, - }); - gBrowser.selectedTab = tab; - let browser = gBrowser.selectedBrowser; - ok(!browser.isRemoteBrowser, "Ensure browser is not remote"); - // Load a remote page, and then another remote page immediately - // after. - browser.loadURI(PAGE_1); - browser.stop(); - browser.loadURI(PAGE_2); - yield BrowserTestUtils.browserLoaded(browser); - - ok(browser.isRemoteBrowser, "Should have switched remoteness"); - yield TabStateFlusher.flush(browser); - let state = JSON.parse(ss.getTabState(tab)); - let entries = state.entries; - is(entries.length, 1, "There should only be one entry"); - is(entries[0].url, PAGE_2, "Should have PAGE_2 as the sole history entry"); - is(browser.currentURI.spec, PAGE_2, "Should have PAGE_2 as the browser currentURI"); - - yield ContentTask.spawn(browser, PAGE_2, function*(PAGE_2) { - docShell.QueryInterface(Ci.nsIWebNavigation); - Assert.equal(docShell.currentURI.spec, PAGE_2, - "Content should have PAGE_2 as the browser currentURI"); - }); - - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_newtab_userTypedValue.js b/browser/components/sessionstore/test/browser_newtab_userTypedValue.js deleted file mode 100644 index 66dc93380..000000000 --- a/browser/components/sessionstore/test/browser_newtab_userTypedValue.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -requestLongerTimeout(4); - -/** - * Test that when restoring an 'initial page' with session restore, it - * produces an empty URL bar, rather than leaving its URL explicitly - * there as a 'user typed value'. - */ -add_task(function* () { - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:logo"); - let tabOpenedAndSwitchedTo = BrowserTestUtils.switchTab(win.gBrowser, () => {}); - - // This opens about:newtab: - win.BrowserOpenTab(); - let tab = yield tabOpenedAndSwitchedTo; - is(win.gURLBar.value, "", "URL bar should be empty"); - is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null"); - let state = JSON.parse(SessionStore.getTabState(tab)); - ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state"); - tab = null; - - yield BrowserTestUtils.closeWindow(win); - - ok(SessionStore.getClosedWindowCount(), "Should have a closed window"); - - win = SessionStore.undoCloseWindow(0); - yield TestUtils.topicObserved("sessionstore-single-window-restored", - subject => subject == win); - // Don't wait for load here because it's about:newtab and we may have swapped in - // a preloaded browser. - yield TabStateFlusher.flush(win.gBrowser.selectedBrowser); - - is(win.gURLBar.value, "", "URL bar should be empty"); - tab = win.gBrowser.selectedTab; - is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null"); - state = JSON.parse(SessionStore.getTabState(tab)); - ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state"); - - yield BrowserTestUtils.removeTab(tab); - - for (let url of gInitialPages) { - if (url == BROWSER_NEW_TAB_URL) { - continue; // We tested about:newtab using BrowserOpenTab() above. - } - info("Testing " + url + " - " + new Date()); - yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, url); - yield BrowserTestUtils.closeWindow(win); - - ok(SessionStore.getClosedWindowCount(), "Should have a closed window"); - - win = SessionStore.undoCloseWindow(0); - yield TestUtils.topicObserved("sessionstore-single-window-restored", - subject => subject == win); - yield BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser); - yield TabStateFlusher.flush(win.gBrowser.selectedBrowser); - - is(win.gURLBar.value, "", "URL bar should be empty"); - tab = win.gBrowser.selectedTab; - is(tab.linkedBrowser.userTypedValue, null, "userTypedValue should be null"); - state = JSON.parse(SessionStore.getTabState(tab)); - ok(!state.userTypedValue, "userTypedValue should be undefined on the tab's state"); - - info("Removing tab - " + new Date()); - yield BrowserTestUtils.removeTab(tab); - info("Finished removing tab - " + new Date()); - } - info("Removing window - " + new Date()); - yield BrowserTestUtils.closeWindow(win); - info("Finished removing window - " + new Date()); -}); diff --git a/browser/components/sessionstore/test/browser_pageStyle.js b/browser/components/sessionstore/test/browser_pageStyle.js deleted file mode 100644 index 7abee5d9d..000000000 --- a/browser/components/sessionstore/test/browser_pageStyle.js +++ /dev/null @@ -1,89 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const URL = getRootDirectory(gTestPath) + "browser_pageStyle_sample.html"; -const URL_NESTED = getRootDirectory(gTestPath) + "browser_pageStyle_sample_nested.html"; - -/** - * This test ensures that page style information is correctly persisted. - */ -add_task(function page_style() { - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - let sheets = yield getStyleSheets(browser); - - // Enable all style sheets one by one. - for (let [title, disabled] of sheets) { - yield enableStyleSheetsForSet(browser, title); - - let tab2 = gBrowser.duplicateTab(tab); - yield promiseTabRestored(tab2); - - let sheets = yield getStyleSheets(tab2.linkedBrowser); - let enabled = sheets.filter(([title, disabled]) => !disabled); - - if (title.startsWith("fail_")) { - ok(!enabled.length, "didn't restore " + title); - } else { - is(enabled.length, 1, "restored one style sheet"); - is(enabled[0][0], title, "restored correct sheet"); - } - - gBrowser.removeTab(tab2); - } - - // Disable all styles and verify that this is correctly persisted. - yield setAuthorStyleDisabled(browser, true); - - let tab2 = gBrowser.duplicateTab(tab); - yield promiseTabRestored(tab2); - - let authorStyleDisabled = yield getAuthorStyleDisabled(tab2.linkedBrowser); - ok(authorStyleDisabled, "disabled all stylesheets"); - - // Clean up. - gBrowser.removeTab(tab); - gBrowser.removeTab(tab2); -}); - -/** - * This test ensures that page style notification from nested documents are - * received and the page style is persisted correctly. - */ -add_task(function nested_page_style() { - let tab = gBrowser.addTab(URL_NESTED); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - yield enableSubDocumentStyleSheetsForSet(browser, "alternate"); - yield promiseRemoveTab(tab); - - let [{state: {pageStyle}}] = JSON.parse(ss.getClosedTabData(window)); - let expected = JSON.stringify({children: [{pageStyle: "alternate"}]}); - is(JSON.stringify(pageStyle), expected, "correct pageStyle persisted"); -}); - -function getStyleSheets(browser) { - return sendMessage(browser, "ss-test:getStyleSheets"); -} - -function enableStyleSheetsForSet(browser, name) { - return sendMessage(browser, "ss-test:enableStyleSheetsForSet", name); -} - -function enableSubDocumentStyleSheetsForSet(browser, name) { - return sendMessage(browser, "ss-test:enableSubDocumentStyleSheetsForSet", { - id: "iframe", set: name - }); -} - -function getAuthorStyleDisabled(browser) { - return sendMessage(browser, "ss-test:getAuthorStyleDisabled"); -} - -function setAuthorStyleDisabled(browser, val) { - return sendMessage(browser, "ss-test:setAuthorStyleDisabled", val) -} diff --git a/browser/components/sessionstore/test/browser_pageStyle_sample.html b/browser/components/sessionstore/test/browser_pageStyle_sample.html deleted file mode 100644 index 810054049..000000000 --- a/browser/components/sessionstore/test/browser_pageStyle_sample.html +++ /dev/null @@ -1,16 +0,0 @@ -<html> -<head> - <meta charset="utf-8"> - <title>pageStyle sample</title> - - <link href="404.css" title="default" rel="stylesheet"> - <link href="404.css" title="alternate" rel="alternate stylesheet"> - <link href="404.css" title="altERnate" rel=" styLEsheet altERnate "> - <link href="404.css" title="media_empty" rel="alternate stylesheet" media=""> - <link href="404.css" title="media_all" rel="alternate stylesheet" media="all"> - <link href="404.css" title="media_ALL" rel="alternate stylesheet" media=" ALL "> - <link href="404.css" title="media_screen" rel="alternate stylesheet" media="screen"> - <link href="404.css" title="media_print_screen" rel="alternate stylesheet" media="print,screen"> -</head> -<body></body> -</html> diff --git a/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html b/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html deleted file mode 100644 index 157609fa6..000000000 --- a/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html +++ /dev/null @@ -1,9 +0,0 @@ -<html> -<head> - <meta charset="utf-8"> - <title>pageStyle sample (nested)</title> -</head> -<body> - <iframe id="iframe" src="browser_pageStyle_sample.html"/> -</body> -</html> diff --git a/browser/components/sessionstore/test/browser_page_title.js b/browser/components/sessionstore/test/browser_page_title.js deleted file mode 100644 index 9bbb1ca76..000000000 --- a/browser/components/sessionstore/test/browser_page_title.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -const URL = "data:text/html,<title>initial title</title>"; - -add_task(function* () { - // Create a new tab. - let tab = gBrowser.addTab(URL); - yield promiseBrowserLoaded(tab.linkedBrowser); - - // Remove the tab. - yield promiseRemoveTab(tab); - - // Check the title. - let [{state: {entries}}] = JSON.parse(ss.getClosedTabData(window)); - is(entries[0].title, "initial title", "correct title"); -}); - -add_task(function* () { - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to ensure we collected the initial title. - yield TabStateFlusher.flush(browser); - - // Set a new title. - yield ContentTask.spawn(browser, null, function* () { - return new Promise(resolve => { - addEventListener("DOMTitleChanged", function onTitleChanged() { - removeEventListener("DOMTitleChanged", onTitleChanged); - resolve(); - }); - - content.document.title = "new title"; - }); - }); - - // Remove the tab. - yield promiseRemoveTab(tab); - - // Check the title. - let [{state: {entries}}] = JSON.parse(ss.getClosedTabData(window)); - is(entries[0].title, "new title", "correct title"); -}); diff --git a/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js b/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js deleted file mode 100644 index 1deb461c8..000000000 --- a/browser/components/sessionstore/test/browser_parentProcessRestoreHash.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; - -const SELFCHROMEURL = - "chrome://mochitests/content/browser/browser/" + - "components/sessionstore/test/browser_parentProcessRestoreHash.js"; - -const Cm = Components.manager; - -const TESTCLASSID = "78742c04-3630-448c-9be3-6c5070f062de"; - -const TESTURL = "about:testpageforsessionrestore#foo"; - - -let TestAboutPage = { - QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]), - getURIFlags: function(aURI) { - // No CAN_ or MUST_LOAD_IN_CHILD means this loads in the parent: - return Ci.nsIAboutModule.ALLOW_SCRIPT | - Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT | - Ci.nsIAboutModule.HIDE_FROM_ABOUTABOUT; - }, - - newChannel: function(aURI, aLoadInfo) { - // about: page inception! - let newURI = Services.io.newURI(SELFCHROMEURL, null, null); - let channel = Services.io.newChannelFromURIWithLoadInfo(newURI, - aLoadInfo); - channel.originalURI = aURI; - return channel; - }, - - createInstance: function(outer, iid) { - if (outer != null) { - throw Cr.NS_ERROR_NO_AGGREGATION; - } - return this.QueryInterface(iid); - }, - - register: function() { - Cm.QueryInterface(Ci.nsIComponentRegistrar).registerFactory( - Components.ID(TESTCLASSID), "Only here for a test", - "@mozilla.org/network/protocol/about;1?what=testpageforsessionrestore", this); - }, - - unregister: function() { - Cm.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactory( - Components.ID(TESTCLASSID), this); - } -}; - - -/** - * Test that switching from a remote to a parent process browser - * correctly clears the userTypedValue - */ -add_task(function* () { - TestAboutPage.register(); - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com/", true, true); - ok(tab.linkedBrowser.isRemoteBrowser, "Browser should be remote"); - - let resolveLocationChangePromise; - let locationChangePromise = new Promise(r => resolveLocationChangePromise = r); - let wpl = { - onStateChange(wpl, request, state, status) { - let location = request.QueryInterface(Ci.nsIChannel).originalURI; - // Ignore about:blank loads. - let docStop = Ci.nsIWebProgressListener.STATE_STOP | - Ci.nsIWebProgressListener.STATE_IS_NETWORK; - if (location.spec == "about:blank" || (state & docStop == docStop)) { - return; - } - is(location.spec, TESTURL, "Got the expected URL"); - resolveLocationChangePromise(); - }, - }; - gBrowser.addProgressListener(wpl); - - gURLBar.value = TESTURL; - gURLBar.select(); - EventUtils.sendKey("return"); - - yield locationChangePromise; - - ok(!tab.linkedBrowser.isRemoteBrowser, "Browser should no longer be remote"); - - is(gURLBar.textValue, TESTURL, "URL bar visible value should be correct."); - is(gURLBar.value, TESTURL, "URL bar value should be correct."); - is(gURLBar.getAttribute("pageproxystate"), "valid", "URL bar is in valid page proxy state"); - - ok(!tab.linkedBrowser.userTypedValue, "No userTypedValue should be on the browser."); - - yield BrowserTestUtils.removeTab(tab); - gBrowser.removeProgressListener(wpl); - TestAboutPage.unregister(); -}); diff --git a/browser/components/sessionstore/test/browser_pending_tabs.js b/browser/components/sessionstore/test/browser_pending_tabs.js deleted file mode 100644 index e734e55c9..000000000 --- a/browser/components/sessionstore/test/browser_pending_tabs.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; - -const TAB_STATE = { - entries: [{ url: "about:mozilla" }, { url: "about:robots" }], - index: 1, -}; - -add_task(function* () { - // Create a background tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // The tab shouldn't be restored right away. - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - // Prepare the tab state. - let promise = promiseTabRestoring(tab); - ss.setTabState(tab, JSON.stringify(TAB_STATE)); - ok(tab.hasAttribute("pending"), "tab is pending"); - yield promise; - - // Flush to ensure the parent has all data. - yield TabStateFlusher.flush(browser); - - // Check that the shistory index is the one we restored. - let tabState = TabState.collect(tab); - is(tabState.index, TAB_STATE.index, "correct shistory index"); - - // Check we don't collect userTypedValue when we shouldn't. - ok(!tabState.userTypedValue, "tab didn't have a userTypedValue"); - - // Cleanup. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_privatetabs.js b/browser/components/sessionstore/test/browser_privatetabs.js deleted file mode 100644 index cc02e56cf..000000000 --- a/browser/components/sessionstore/test/browser_privatetabs.js +++ /dev/null @@ -1,133 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -add_task(function cleanup() { - info("Forgetting closed tabs"); - while (ss.getClosedTabCount(window)) { - ss.forgetClosedTab(window, 0); - } -}); - -add_task(function() { - let URL_PUBLIC = "http://example.com/public/" + Math.random(); - let URL_PRIVATE = "http://example.com/private/" + Math.random(); - let tab1, tab2; - try { - // Setup a public tab and a private tab - info("Setting up public tab"); - tab1 = gBrowser.addTab(URL_PUBLIC); - yield promiseBrowserLoaded(tab1.linkedBrowser); - - info("Setting up private tab"); - tab2 = gBrowser.addTab(); - yield promiseBrowserLoaded(tab2.linkedBrowser); - yield setUsePrivateBrowsing(tab2.linkedBrowser, true); - tab2.linkedBrowser.loadURI(URL_PRIVATE); - yield promiseBrowserLoaded(tab2.linkedBrowser); - - info("Flush to make sure chrome received all data."); - yield TabStateFlusher.flush(tab1.linkedBrowser); - yield TabStateFlusher.flush(tab2.linkedBrowser); - - info("Checking out state"); - let state = yield promiseRecoveryFileContents(); - - info("State: " + state); - // Ensure that sessionstore.js only knows about the public tab - ok(state.indexOf(URL_PUBLIC) != -1, "State contains public tab"); - ok(state.indexOf(URL_PRIVATE) == -1, "State does not contain private tab"); - - // Ensure that we can close and undo close the public tab but not the private tab - gBrowser.removeTab(tab2); - tab2 = null; - - gBrowser.removeTab(tab1); - tab1 = null; - - tab1 = ss.undoCloseTab(window, 0); - ok(true, "Public tab supports undo close"); - - is(ss.getClosedTabCount(window), 0, "Private tab does not support undo close"); - - } finally { - if (tab1) { - gBrowser.removeTab(tab1); - } - if (tab2) { - gBrowser.removeTab(tab2); - } - } -}); - -add_task(function () { - const FRAME_SCRIPT = "data:," + - "docShell.QueryInterface%28Components.interfaces.nsILoadContext%29.usePrivateBrowsing%3Dtrue"; - - // Clear the list of closed windows. - forgetClosedWindows(); - - // Create a new window to attach our frame script to. - let win = yield promiseNewWindowLoaded(); - let mm = win.getGroupMessageManager("browsers"); - mm.loadFrameScript(FRAME_SCRIPT, true); - - // Create a new tab in the new window that will load the frame script. - let tab = win.gBrowser.addTab("about:mozilla"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Check that we consider the tab as private. - let state = JSON.parse(ss.getTabState(tab)); - ok(state.isPrivate, "tab considered private"); - - // Ensure we don't allow restoring closed private tabs in non-private windows. - win.gBrowser.removeTab(tab); - is(ss.getClosedTabCount(win), 0, "no tabs to restore"); - - // Create a new tab in the new window that will load the frame script. - tab = win.gBrowser.addTab("about:mozilla"); - browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Check that we consider the tab as private. - state = JSON.parse(ss.getTabState(tab)); - ok(state.isPrivate, "tab considered private"); - - // Check that all private tabs are removed when the non-private - // window is closed and we don't save windows without any tabs. - yield BrowserTestUtils.closeWindow(win); - is(ss.getClosedWindowCount(), 0, "no windows to restore"); -}); - -add_task(function () { - // Clear the list of closed windows. - forgetClosedWindows(); - - // Create a new window to attach our frame script to. - let win = yield promiseNewWindowLoaded({private: true}); - - // Create a new tab in the new window that will load the frame script. - let tab = win.gBrowser.addTab("about:mozilla"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - yield TabStateFlusher.flush(browser); - - // Check that we consider the tab as private. - let state = JSON.parse(ss.getTabState(tab)); - ok(state.isPrivate, "tab considered private"); - - // Ensure that closed tabs in a private windows can be restored. - win.gBrowser.removeTab(tab); - is(ss.getClosedTabCount(win), 1, "there is a single tab to restore"); - - // Ensure that closed private windows can never be restored. - yield BrowserTestUtils.closeWindow(win); - is(ss.getClosedWindowCount(), 0, "no windows to restore"); -}); - -function setUsePrivateBrowsing(browser, val) { - return sendMessage(browser, "ss-test:setUsePrivateBrowsing", val); -} - diff --git a/browser/components/sessionstore/test/browser_purge_shistory.js b/browser/components/sessionstore/test/browser_purge_shistory.js deleted file mode 100644 index 28c6f6f24..000000000 --- a/browser/components/sessionstore/test/browser_purge_shistory.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; - -/** - * This test checks that pending tabs are treated like fully loaded tabs when - * purging session history. Just like for fully loaded tabs we want to remove - * every but the current shistory entry. - */ - -const TAB_STATE = { - entries: [{url: "about:mozilla"}, {url: "about:robots"}], - index: 1, -}; - -function checkTabContents(browser) { - return ContentTask.spawn(browser, null, function* () { - let Ci = Components.interfaces; - let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation); - let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal); - Assert.ok(history && history.count == 1 && content.document.documentURI == "about:mozilla", - "expected tab contents found"); - }); -} - -add_task(function* () { - // Create a new tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - yield promiseTabState(tab, TAB_STATE); - - // Create another new tab. - let tab2 = gBrowser.addTab("about:blank"); - let browser2 = tab2.linkedBrowser; - yield promiseBrowserLoaded(browser2); - - // The tab shouldn't be restored right away. - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - // Prepare the tab state. - let promise = promiseTabRestoring(tab2); - ss.setTabState(tab2, JSON.stringify(TAB_STATE)); - ok(tab2.hasAttribute("pending"), "tab is pending"); - yield promise; - - // Purge session history. - Services.obs.notifyObservers(null, "browser:purge-session-history", ""); - yield checkTabContents(browser); - ok(tab2.hasAttribute("pending"), "tab is still pending"); - - // Kick off tab restoration. - gBrowser.selectedTab = tab2; - yield promiseTabRestored(tab2); - yield checkTabContents(browser2); - ok(!tab2.hasAttribute("pending"), "tab is not pending anymore"); - - // Cleanup. - gBrowser.removeTab(tab2); - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js b/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js deleted file mode 100644 index 7dbee03fd..000000000 --- a/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js +++ /dev/null @@ -1,342 +0,0 @@ -"use strict"; - -/** - * This set of tests checks that the remoteness is properly - * set for each browser in a window when that window has - * session state loaded into it. - */ - -/** - * Takes a SessionStore window state object for a single - * window, sets the selected tab for it, and then returns - * the object to be passed to SessionStore.setWindowState. - * - * @param state (object) - * The state to prepare to be sent to a window. This is - * state should just be for a single window. - * @param selected (int) - * The 1-based index of the selected tab. Note that - * If this is 0, then the selected tab will not change - * from what's already selected in the window that we're - * sending state to. - * @returns (object) - * The JSON encoded string to call - * SessionStore.setWindowState with. - */ -function prepareState(state, selected) { - // We'll create a copy so that we don't accidentally - // modify the caller's selected property. - let copy = {}; - Object.assign(copy, state); - copy.selected = selected; - - return { - windows: [ copy ], - }; -} - -const SIMPLE_STATE = { - tabs: [ - { entries: [{ url: "http://example.com/", title: "title" }] }, - { entries: [{ url: "http://example.com/", title: "title" }] }, - { entries: [{ url: "http://example.com/", title: "title" }] }, - ], - title: "", - _closedTabs: [], -}; - -const PINNED_STATE = { - tabs: [ - { entries: [{ url: "http://example.com/", title: "title" }], pinned: true }, - { entries: [{ url: "http://example.com/", title: "title" }], pinned: true }, - { entries: [{ url: "http://example.com/", title: "title" }] }, - ], - title: "", - _closedTabs: [], -}; - -/** - * This is where most of the action is happening. This function takes - * an Array of "test scenario" Objects and runs them. For each scenario, a - * window is opened, put into some state, and then a new state is - * loaded into that window. We then check to make sure that the - * right things have happened in that window wrt remoteness flips. - * - * The schema for a testing scenario Object is as follows: - * - * initialRemoteness: - * an Array that represents the starting window. Each bool - * in the Array represents the window tabs in order. A "true" - * indicates that that tab should be remote. "false" if the tab - * should be non-remote. - * - * initialSelectedTab: - * The 1-based index of the tab that we want to select for the - * restored window. This is 1-based to avoid confusion with the - * selectedTab property described down below, though you probably - * want to set this to be greater than 0, since the initial window - * needs to have a defined initial selected tab. Because of this, - * the test will throw if initialSelectedTab is 0. - * - * stateToRestore: - * A JS Object for the state to send down to the window. - * - * selectedTab: - * The 1-based index of the tab that we want to select for the - * restored window. Leave this at 0 if you don't want to change - * the selection from the initial window state. - * - * expectedFlips: - * an Array that represents the window that we end up with after - * restoring state. Each bool in the Array represents the window tabs, - * in order. A "true" indicates that the tab should have flipped - * its remoteness once. "false" indicates that the tab should never - * have flipped remoteness. Note that any tab that flips its remoteness - * more than once will cause a test failure. - * - * expectedRemoteness: - * an Array that represents the window that we end up with after - * restoring state. Each bool in the Array represents the window - * tabs in order. A "true" indicates that the tab be remote, and - * a "false" indicates that the tab should be "non-remote". We - * need this Array in order to test pinned tabs which will also - * be loaded by default, and therefore should end up remote. - * - */ -function* runScenarios(scenarios) { - for (let scenario of scenarios) { - // Let's make sure our scenario is sane first. - Assert.equal(scenario.expectedFlips.length, - scenario.expectedRemoteness.length, - "All expected flips and remoteness needs to be supplied"); - Assert.ok(scenario.initialSelectedTab > 0, - "You must define an initially selected tab"); - - // First, we need to create the initial conditions, so we - // open a new window to put into our starting state... - let win = yield BrowserTestUtils.openNewBrowserWindow(); - let tabbrowser = win.gBrowser; - Assert.ok(tabbrowser.selectedBrowser.isRemoteBrowser, - "The initial browser should be remote."); - // Now put the window into the expected initial state. - for (let i = 0; i < scenario.initialRemoteness.length; ++i) { - let tab; - if (i > 0) { - // The window starts with one tab, so we need to create - // any of the additional ones required by this test. - info("Opening a new tab"); - tab = yield BrowserTestUtils.openNewForegroundTab(tabbrowser) - } else { - info("Using the selected tab"); - tab = tabbrowser.selectedTab; - } - let browser = tab.linkedBrowser; - let remotenessState = scenario.initialRemoteness[i]; - tabbrowser.updateBrowserRemoteness(browser, remotenessState); - } - - // And select the requested tab. - let tabToSelect = tabbrowser.tabs[scenario.initialSelectedTab - 1]; - if (tabbrowser.selectedTab != tabToSelect) { - yield BrowserTestUtils.switchTab(tabbrowser, tabToSelect); - } - - // Hook up an event listener to make sure that the right - // tabs flip remoteness, and only once. - let flipListener = { - seenBeforeTabs: new Set(), - seenAfterTabs: new Set(), - handleEvent(e) { - let index = Array.from(tabbrowser.tabs).indexOf(e.target); - switch (e.type) { - case "BeforeTabRemotenessChange": - info(`Saw tab at index ${index} before remoteness flip`); - if (this.seenBeforeTabs.has(e.target)) { - Assert.ok(false, "Saw tab before remoteness flip more than once"); - } - this.seenBeforeTabs.add(e.target); - break; - case "TabRemotenessChange": - info(`Saw tab at index ${index} after remoteness flip`); - if (this.seenAfterTabs.has(e.target)) { - Assert.ok(false, "Saw tab after remoteness flip more than once"); - } - this.seenAfterTabs.add(e.target); - break; - } - }, - }; - - win.addEventListener("BeforeTabRemotenessChange", flipListener); - win.addEventListener("TabRemotenessChange", flipListener); - - // Okay, time to test! - let state = prepareState(scenario.stateToRestore, - scenario.selectedTab); - - SessionStore.setWindowState(win, state, true); - - win.removeEventListener("BeforeTabRemotenessChange", flipListener); - win.removeEventListener("TabRemotenessChange", flipListener); - - // Because we know that scenario.expectedFlips and - // scenario.expectedRemoteness have the same length, we - // can check that we satisfied both with the same loop. - for (let i = 0; i < scenario.expectedFlips.length; ++i) { - let expectedToFlip = scenario.expectedFlips[i]; - let expectedRemoteness = scenario.expectedRemoteness[i]; - let tab = tabbrowser.tabs[i]; - if (expectedToFlip) { - Assert.ok(flipListener.seenBeforeTabs.has(tab), - `We should have seen tab at index ${i} before remoteness flip`); - Assert.ok(flipListener.seenAfterTabs.has(tab), - `We should have seen tab at index ${i} after remoteness flip`); - } else { - Assert.ok(!flipListener.seenBeforeTabs.has(tab), - `We should not have seen tab at index ${i} before remoteness flip`); - Assert.ok(!flipListener.seenAfterTabs.has(tab), - `We should not have seen tab at index ${i} after remoteness flip`); - } - - Assert.equal(tab.linkedBrowser.isRemoteBrowser, expectedRemoteness, - "Should have gotten the expected remoteness " + - `for the tab at index ${i}`); - } - - yield BrowserTestUtils.closeWindow(win); - } -} - -/** - * Tests that if we restore state to browser windows with - * a variety of initial remoteness states, that we only flip - * the remoteness on the necessary tabs. For this particular - * set of tests, we assume that tabs are restoring on demand. - */ -add_task(function*() { - // This test opens and closes windows, which might bog down - // a debug build long enough to time out the test, so we - // extend the tolerance on timeouts. - requestLongerTimeout(5); - - yield SpecialPowers.pushPrefEnv({ - "set": [["browser.sessionstore.restore_on_demand", true]], - }); - - const TEST_SCENARIOS = [ - // Only one tab in the new window, and it's remote. This - // is the common case, since this is how restoration occurs - // when the restored window is being opened. - { - initialRemoteness: [true], - initialSelectedTab: 1, - stateToRestore: SIMPLE_STATE, - selectedTab: 3, - // The initial tab is remote and should go into - // the background state. The second and third tabs - // are new and should be initialized non-remote. - expectedFlips: [true, false, true], - // Only the selected tab should be remote. - expectedRemoteness: [false, false, true], - }, - - // A single remote tab, and this is the one that's going - // to be selected once state is restored. - { - initialRemoteness: [true], - initialSelectedTab: 1, - stateToRestore: SIMPLE_STATE, - selectedTab: 1, - // The initial tab is remote and selected, so it should - // not flip remoteness. The other two new tabs should - // be non-remote by default. - expectedFlips: [false, false, false], - // Only the selected tab should be remote. - expectedRemoteness: [true, false, false], - }, - - // A single remote tab which starts selected. We set the - // selectedTab to 0 which is equivalent to "don't change - // the tab selection in the window". - { - initialRemoteness: [true], - initialSelectedTab: 1, - stateToRestore: SIMPLE_STATE, - selectedTab: 0, - // The initial tab is remote and selected, so it should - // not flip remoteness. The other two new tabs should - // be non-remote by default. - expectedFlips: [false, false, false], - // Only the selected tab should be remote. - expectedRemoteness: [true, false, false], - }, - - // An initially remote tab, but we're going to load - // some pinned tabs now, and the pinned tabs should load - // right away. - { - initialRemoteness: [true], - initialSelectedTab: 1, - stateToRestore: PINNED_STATE, - selectedTab: 3, - // The initial tab is pinned and will load right away, - // so it should stay remote. The second tab is new - // and pinned, so it should start remote and not flip. - // The third tab is not pinned, but it is selected, - // so it will start non-remote, and then flip remoteness. - expectedFlips: [false, false, true], - // Both pinned tabs and the selected tabs should all - // end up being remote. - expectedRemoteness: [true, true, true], - }, - - // A single non-remote tab. - { - initialRemoteness: [false], - initialSelectedTab: 1, - stateToRestore: SIMPLE_STATE, - selectedTab: 2, - // The initial tab is non-remote and should stay - // that way. The second and third tabs are new and - // should be initialized non-remote. - expectedFlips: [false, true, false], - // Only the selected tab should be remote. - expectedRemoteness: [false, true, false], - }, - - // A mixture of remote and non-remote tabs. - { - initialRemoteness: [true, false, true], - initialSelectedTab: 1, - stateToRestore: SIMPLE_STATE, - selectedTab: 3, - // The initial tab is remote and should flip to non-remote - // as it is put into the background. The second tab should - // stay non-remote, and the third one should stay remote. - expectedFlips: [true, false, false], - // Only the selected tab should be remote. - expectedRemoteness: [false, false, true], - }, - - // An initially non-remote tab, but we're going to load - // some pinned tabs now, and the pinned tabs should load - // right away. - { - initialRemoteness: [false], - initialSelectedTab: 1, - stateToRestore: PINNED_STATE, - selectedTab: 3, - // The initial tab is pinned and will load right away, - // so it should flip remoteness. The second tab is new - // and pinned, so it should start remote and not flip. - // The third tab is not pinned, but it is selected, - // so it will start non-remote, and then flip remoteness. - expectedFlips: [true, false, true], - // Both pinned tabs and the selected tabs should all - // end up being remote. - expectedRemoteness: [true, true, true], - }, - ]; - - yield* runScenarios(TEST_SCENARIOS); -}); diff --git a/browser/components/sessionstore/test/browser_replace_load.js b/browser/components/sessionstore/test/browser_replace_load.js deleted file mode 100644 index 5464a0874..000000000 --- a/browser/components/sessionstore/test/browser_replace_load.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; - -const STATE = { - entries: [{url: "about:robots"}, {url: "about:mozilla"}], - selected: 2 -}; - -/** - * Bug 1100223. Calling browser.loadURI() while a tab is loading causes - * sessionstore to override the desired target URL. This test ensures that - * calling loadURI() on a pending tab causes the tab to no longer be marked - * as pending and correctly finish the instructed load while keeping the - * restored history around. - */ -add_task(function* () { - yield testSwitchToTab("about:mozilla#fooobar", {ignoreFragment: "whenComparingAndReplace"}); - yield testSwitchToTab("about:mozilla?foo=bar", {replaceQueryString: true}); -}); - -var testSwitchToTab = Task.async(function* (url, options) { - // Create a background tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // The tab shouldn't be restored right away. - Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", true); - - // Prepare the tab state. - let promise = promiseTabRestoring(tab); - ss.setTabState(tab, JSON.stringify(STATE)); - ok(tab.hasAttribute("pending"), "tab is pending"); - yield promise; - - // Switch-to-tab with a similar URI. - switchToTabHavingURI(url, false, options); - - // Tab should now restore - yield promiseTabRestored(tab); - is(browser.currentURI.spec, url, "correct URL loaded"); - - // Check that we didn't lose any history entries. - yield ContentTask.spawn(browser, null, function* () { - let Ci = Components.interfaces; - let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation); - let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal); - Assert.equal(history && history.count, 3, "three history entries"); - }); - - // Cleanup. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js b/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js deleted file mode 100644 index 5767c6c0f..000000000 --- a/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Bug 1267910 - The regression test case for session cookies. - */ - -"use strict"; - -const TEST_HOST = "www.example.com"; -const COOKIE = -{ - name: "test1", - value: "yes1", - path: "/browser/browser/components/sessionstore/test/" -}; -const SESSION_DATA = ` -{ - "version": ["sessionrestore", 1], - "windows": [{ - "tabs": [{ - "entries": [], - "lastAccessed": 1463893009797, - "hidden": false, - "attributes": {}, - "image": null - }, { - "entries": [{ - "url": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html", - \"charset": "UTF-8", - "ID": 0, - "docshellID": 2, - "originalURI": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html", - \"docIdentifier": 0, - "persist": true - }], - "lastAccessed": 1463893009321, - "hidden": false, - "attributes": {}, - "userContextId": 0, - "index": 1, - "image": "http://www.example.com/favicon.ico" - }], - "selected": 1, - "_closedTabs": [], - "busy": false, - "width": 1024, - "height": 768, - "screenX": 4, - "screenY": 23, - "sizemode": "normal", - "cookies": [{ - "host": "www.example.com", - "value": "yes1", - "path": "/browser/browser/components/sessionstore/test/", - "name": "test1" - }] - }], - "selectedWindow": 1, - "_closedWindows": [], - "session": { - "lastUpdate": 1463893009801, - "startTime": 1463893007134, - "recentCrashes": 0 - }, - "global": {} -}`; -const SESSION_DATA_OA = ` -{ - "version": ["sessionrestore", 1], - "windows": [{ - "tabs": [{ - "entries": [], - "lastAccessed": 1463893009797, - "hidden": false, - "attributes": {}, - "image": null - }, { - "entries": [{ - "url": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html", - \"charset": "UTF-8", - "ID": 0, - "docshellID": 2, - "originalURI": "http://www.example.com/browser/browser/components/sessionstore/test/browser_1267910_page.html", - \"docIdentifier": 0, - "persist": true - }], - "lastAccessed": 1463893009321, - "hidden": false, - "attributes": {}, - "userContextId": 0, - "index": 1, - "image": "http://www.example.com/favicon.ico" - }], - "selected": 1, - "_closedTabs": [], - "busy": false, - "width": 1024, - "height": 768, - "screenX": 4, - "screenY": 23, - "sizemode": "normal", - "cookies": [{ - "host": "www.example.com", - "value": "yes1", - "path": "/browser/browser/components/sessionstore/test/", - "name": "test1", - "originAttributes": { - "addonId": "", - "appId": 0, - "inIsolatedMozBrowser": false, - "userContextId": 0 - } - }] - }], - "selectedWindow": 1, - "_closedWindows": [], - "session": { - "lastUpdate": 1463893009801, - "startTime": 1463893007134, - "recentCrashes": 0 - }, - "global": {} -}`; - -add_task(function* run_test() { - // Wait until initialization is complete. - yield SessionStore.promiseInitialized; - - // Clear cookies. - Services.cookies.removeAll(); - - // Open a new window. - let win = yield promiseNewWindowLoaded(); - - // Restore window with session cookies that have no originAttributes. - ss.setWindowState(win, SESSION_DATA, true); - - let enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {}); - let cookie; - let cookieCount = 0; - while (enumerator.hasMoreElements()) { - cookie = enumerator.getNext().QueryInterface(Ci.nsICookie); - cookieCount++; - } - - // Check that the cookie is restored successfully. - is(cookieCount, 1, "expected one cookie"); - is(cookie.name, COOKIE.name, "cookie name successfully restored"); - is(cookie.value, COOKIE.value, "cookie value successfully restored"); - is(cookie.path, COOKIE.path, "cookie path successfully restored"); - - // Clear cookies. - Services.cookies.removeAll(); - - // Restore window with session cookies that have originAttributes within. - ss.setWindowState(win, SESSION_DATA_OA, true); - - enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {}); - cookieCount = 0; - while (enumerator.hasMoreElements()) { - cookie = enumerator.getNext().QueryInterface(Ci.nsICookie); - cookieCount++; - } - - // Check that the cookie is restored successfully. - is(cookieCount, 1, "expected one cookie"); - is(cookie.name, COOKIE.name, "cookie name successfully restored"); - is(cookie.value, COOKIE.value, "cookie value successfully restored"); - is(cookie.path, COOKIE.path, "cookie path successfully restored"); - - // Close our window. - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/sessionstore/test/browser_restore_redirect.js b/browser/components/sessionstore/test/browser_restore_redirect.js deleted file mode 100644 index bea6e9f47..000000000 --- a/browser/components/sessionstore/test/browser_restore_redirect.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; - -const BASE = "http://example.com/browser/browser/components/sessionstore/test/"; -const TARGET = BASE + "restore_redirect_target.html"; - -/** - * Ensure that a http redirect leaves a working tab. - */ -add_task(function check_http_redirect() { - let state = { - entries: [{ url: BASE + "restore_redirect_http.html" }] - }; - - // Open a new tab to restore into. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseTabState(tab, state); - - info("Restored tab"); - - yield TabStateFlusher.flush(browser); - let data = TabState.collect(tab); - is(data.entries.length, 1, "Should be one entry in session history"); - is(data.entries[0].url, TARGET, "Should be the right session history entry"); - - ok(!("__SS_data" in browser), "Temporary restore data should have been cleared"); - - // Cleanup. - yield promiseRemoveTab(tab); -}); - -/** - * Ensure that a js redirect leaves a working tab. - */ -add_task(function check_js_redirect() { - let state = { - entries: [{ url: BASE + "restore_redirect_js.html" }] - }; - - let loadPromise = new Promise(resolve => { - function listener(msg) { - if (msg.data.url.endsWith("restore_redirect_target.html")) { - window.messageManager.removeMessageListener("ss-test:loadEvent", listener); - resolve(); - } - } - - window.messageManager.addMessageListener("ss-test:loadEvent", listener); - }); - - // Open a new tab to restore into. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseTabState(tab, state); - - info("Restored tab"); - - yield loadPromise; - - yield TabStateFlusher.flush(browser); - let data = TabState.collect(tab); - is(data.entries.length, 1, "Should be one entry in session history"); - is(data.entries[0].url, TARGET, "Should be the right session history entry"); - - ok(!("__SS_data" in browser), "Temporary restore data should have been cleared"); - - // Cleanup. - yield promiseRemoveTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js b/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js deleted file mode 100644 index e29cd5e49..000000000 --- a/browser/components/sessionstore/test/browser_revive_crashed_bg_tabs.js +++ /dev/null @@ -1,56 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that even if the user has set their tabs to restore - * immediately on session start, that background tabs after a - * content process crash restore on demand. - */ - -"use strict"; - -const PAGE_1 = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page."; -const PAGE_2 = "data:text/html,<html><body>Another%20regular,%20everyday,%20normal%20page."; - -add_task(function* setup() { - yield pushPrefs(["dom.ipc.processCount", 1], - ["browser.tabs.animate", false], - ["browser.sessionstore.restore_on_demand", false]); -}); - -add_task(function* test_revive_bg_tabs_on_demand() { - let newTab1 = gBrowser.addTab(PAGE_1); - let browser1 = newTab1.linkedBrowser; - gBrowser.selectedTab = newTab1; - - let newTab2 = gBrowser.addTab(PAGE_2); - let browser2 = newTab2.linkedBrowser; - - yield BrowserTestUtils.browserLoaded(browser1); - yield BrowserTestUtils.browserLoaded(browser2); - - yield TabStateFlusher.flush(browser2); - - // Now crash the selected tab - let windowReady = BrowserTestUtils.waitForEvent(window, "SSWindowStateReady"); - yield BrowserTestUtils.crashBrowser(browser1); - - ok(newTab1.hasAttribute("crashed"), "Selected tab should be crashed"); - ok(!newTab2.hasAttribute("crashed"), "Background tab should not be crashed"); - - // Wait until we've had a chance to restore all tabs immediately - yield windowReady; - - // But we should not have restored the background tab - ok(newTab2.hasAttribute("pending"), "Background tab should be pending"); - - // Now select newTab2 to make sure it restores. - let newTab2Restored = promiseTabRestored(newTab2); - gBrowser.selectedTab = newTab2; - yield newTab2Restored; - - ok(browser2.isRemoteBrowser, "Restored browser should be remote"); - - yield BrowserTestUtils.removeTab(newTab1); - yield BrowserTestUtils.removeTab(newTab2); -}); diff --git a/browser/components/sessionstore/test/browser_scrollPositions.js b/browser/components/sessionstore/test/browser_scrollPositions.js deleted file mode 100644 index 865520772..000000000 --- a/browser/components/sessionstore/test/browser_scrollPositions.js +++ /dev/null @@ -1,153 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const BASE = "http://example.com/browser/browser/components/sessionstore/test/" -const URL = BASE + "browser_scrollPositions_sample.html"; -const URL_FRAMESET = BASE + "browser_scrollPositions_sample_frameset.html"; - -// Randomized set of scroll positions we will use in this test. -const SCROLL_X = Math.round(100 * (1 + Math.random())); -const SCROLL_Y = Math.round(200 * (1 + Math.random())); -const SCROLL_STR = SCROLL_X + "," + SCROLL_Y; - -const SCROLL2_X = Math.round(300 * (1 + Math.random())); -const SCROLL2_Y = Math.round(400 * (1 + Math.random())); -const SCROLL2_STR = SCROLL2_X + "," + SCROLL2_Y; - -requestLongerTimeout(2); - -/** - * This test ensures that we properly serialize and restore scroll positions - * for an average page without any frames. - */ -add_task(function test_scroll() { - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Scroll down a little. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y}); - yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is fine"); - - // Duplicate and check that the scroll position is restored. - let tab2 = ss.duplicateTab(window, tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - let scroll = yield sendMessage(browser2, "ss-test:getScrollPosition"); - is(JSON.stringify(scroll), JSON.stringify({x: SCROLL_X, y: SCROLL_Y}), - "scroll position has been duplicated correctly"); - - // Check that reloading retains the scroll positions. - browser2.reload(); - yield promiseBrowserLoaded(browser2); - yield checkScroll(tab2, {scroll: SCROLL_STR}, "reloading retains scroll positions"); - - // Check that a force-reload resets scroll positions. - browser2.reloadWithFlags(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE); - yield promiseBrowserLoaded(browser2); - yield checkScroll(tab2, null, "force-reload resets scroll positions"); - - // Scroll back to the top and check that the position has been reset. We - // expect the scroll position to be "null" here because there is no data to - // be stored if the frame is in its default scroll position. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0}); - yield checkScroll(tab, null, "no scroll stored"); - - // Cleanup. - yield promiseRemoveTab(tab); - yield promiseRemoveTab(tab2); -}); - -/** - * This tests ensures that we properly serialize and restore scroll positions - * for multiple frames of pages with framesets. - */ -add_task(function test_scroll_nested() { - let tab = gBrowser.addTab(URL_FRAMESET); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Scroll the first child frame down a little. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y, frame: 0}); - yield checkScroll(tab, {children: [{scroll: SCROLL_STR}]}, "scroll is fine"); - - // Scroll the second child frame down a little. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL2_X, y: SCROLL2_Y, frame: 1}); - yield checkScroll(tab, {children: [{scroll: SCROLL_STR}, {scroll: SCROLL2_STR}]}, "scroll is fine"); - - // Duplicate and check that the scroll position is restored. - let tab2 = ss.duplicateTab(window, tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - let scroll = yield sendMessage(browser2, "ss-test:getScrollPosition", {frame: 0}); - is(JSON.stringify(scroll), JSON.stringify({x: SCROLL_X, y: SCROLL_Y}), - "scroll position #1 has been duplicated correctly"); - - scroll = yield sendMessage(browser2, "ss-test:getScrollPosition", {frame: 1}); - is(JSON.stringify(scroll), JSON.stringify({x: SCROLL2_X, y: SCROLL2_Y}), - "scroll position #2 has been duplicated correctly"); - - // Check that resetting one frame's scroll position removes it from the - // serialized value. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0, frame: 0}); - yield checkScroll(tab, {children: [null, {scroll: SCROLL2_STR}]}, "scroll is fine"); - - // Check the resetting all frames' scroll positions nulls the stored value. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: 0, frame: 1}); - yield checkScroll(tab, null, "no scroll stored"); - - // Cleanup. - yield promiseRemoveTab(tab); - yield promiseRemoveTab(tab2); -}); - -/** - * Test that scroll positions persist after restoring background tabs in - * a restored window (bug 1228518). - */ -add_task(function test_scroll_background_tabs() { - pushPrefs(["browser.sessionstore.restore_on_demand", true]); - - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - let tab = newWin.gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield BrowserTestUtils.browserLoaded(browser); - - // Scroll down a little. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: SCROLL_X, y: SCROLL_Y}); - yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is fine"); - - // Close the window - yield BrowserTestUtils.closeWindow(newWin); - - // Now restore the window - newWin = ss.undoCloseWindow(0); - - // Make sure to wait for the window to be restored. - yield BrowserTestUtils.waitForEvent(newWin, "SSWindowStateReady"); - - is(newWin.gBrowser.tabs.length, 2, "There should be two tabs"); - - // The second tab should be the one we loaded URL at still - tab = newWin.gBrowser.tabs[1]; - yield promiseTabRestoring(tab); - - ok(tab.hasAttribute("pending"), "Tab should be pending"); - browser = tab.linkedBrowser; - - // Ensure there are no pending queued messages in the child. - yield TabStateFlusher.flush(browser); - - // Now check to see if the background tab remembers where it - // should be scrolled to. - newWin.gBrowser.selectedTab = tab; - yield promiseTabRestored(tab); - - yield checkScroll(tab, {scroll: SCROLL_STR}, "scroll is still fine"); - - yield BrowserTestUtils.closeWindow(newWin); -}); diff --git a/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js b/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js deleted file mode 100644 index 735a87634..000000000 --- a/browser/components/sessionstore/test/browser_scrollPositionsReaderMode.js +++ /dev/null @@ -1,67 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const BASE = "http://example.com/browser/browser/components/sessionstore/test/" -const READER_MODE_URL = "about:reader?url=" + - encodeURIComponent(BASE + "browser_scrollPositions_readerModeArticle.html"); - -// Randomized set of scroll positions we will use in this test. -const SCROLL_READER_MODE_Y = Math.round(400 * (1 + Math.random())); -const SCROLL_READER_MODE_STR = "0," + SCROLL_READER_MODE_Y; - -requestLongerTimeout(2); - -/** - * Test that scroll positions of about reader page after restoring background - * tabs in a restored window (bug 1153393). - */ -add_task(function test_scroll_background_about_reader_tabs() { - pushPrefs(["browser.sessionstore.restore_on_demand", true]); - - let newWin = yield BrowserTestUtils.openNewBrowserWindow(); - let tab = newWin.gBrowser.addTab(READER_MODE_URL); - let browser = tab.linkedBrowser; - yield Promise.all([ - BrowserTestUtils.browserLoaded(browser), - BrowserTestUtils.waitForContentEvent(browser, "AboutReaderContentReady") - ]); - - // Scroll down a little. - yield sendMessage(browser, "ss-test:setScrollPosition", {x: 0, y: SCROLL_READER_MODE_Y}); - yield checkScroll(tab, {scroll: SCROLL_READER_MODE_STR}, "scroll is fine"); - - // Close the window - yield BrowserTestUtils.closeWindow(newWin); - - // Now restore the window - newWin = ss.undoCloseWindow(0); - - // Make sure to wait for the window to be restored. - yield BrowserTestUtils.waitForEvent(newWin, "SSWindowStateReady"); - - is(newWin.gBrowser.tabs.length, 2, "There should be two tabs"); - - // The second tab should be the one we loaded URL at still - tab = newWin.gBrowser.tabs[1]; - yield promiseTabRestoring(tab); - - ok(tab.hasAttribute("pending"), "Tab should be pending"); - browser = tab.linkedBrowser; - - // Ensure there are no pending queued messages in the child. - yield TabStateFlusher.flush(browser); - - // Now check to see if the background tab remembers where it - // should be scrolled to. - newWin.gBrowser.selectedTab = tab; - yield Promise.all([ - promiseTabRestored(tab), - BrowserTestUtils.waitForContentEvent(tab.linkedBrowser, "AboutReaderContentReady") - ]); - - yield checkScroll(tab, {scroll: SCROLL_READER_MODE_STR}, "scroll is still fine"); - - yield BrowserTestUtils.closeWindow(newWin); -}); diff --git a/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html b/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html deleted file mode 100644 index 55452e043..000000000 --- a/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html +++ /dev/null @@ -1,26 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<title>Article title</title> -<meta name="description" content="This is the article description." /> -</head> -<body> -<header>Site header</header> -<div> -<h1>Article title</h1> -<h2 class="author">by Jane Doe</h2> -<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -<p>Vivamus fermentum semper porta. Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio. Maecenas convallis ullamcorper ultricies. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi. Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis. Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci. Fusce eget orci a orci congue vestibulum. Ut dolor diam, elementum et vestibulum eu, porttitor vel elit. Curabitur venenatis pulvinar tellus gravida ornare. Sed et erat faucibus nunc euismod ultricies ut id justo. Nullam cursus suscipit nisi, et ultrices justo sodales nec. Fusce venenatis facilisis lectus ac semper. Aliquam at massa ipsum. Quisque bibendum purus convallis nulla ultrices ultricies. Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi. Fusce vel volutpat elit. Nam sagittis nisi dui.</p> -</div> -</body> -</html> diff --git a/browser/components/sessionstore/test/browser_scrollPositions_sample.html b/browser/components/sessionstore/test/browser_scrollPositions_sample.html deleted file mode 100644 index 0182783db..000000000 --- a/browser/components/sessionstore/test/browser_scrollPositions_sample.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_scrollPositions_sample.html</title> - </head> - <body style='width: 100000px; height: 100000px;'>top</body> -</html> diff --git a/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html b/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html deleted file mode 100644 index c7e363fa1..000000000 --- a/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN"> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_scrollPositions_sample_frameset.html</title> - </head> - <frameset id="frames" rows="50%, 50%"> - <frame src="browser_scrollPositions_sample.html"> - <frame src="browser_scrollPositions_sample.html"> - </frameset> -</html> diff --git a/browser/components/sessionstore/test/browser_send_async_message_oom.js b/browser/components/sessionstore/test/browser_send_async_message_oom.js deleted file mode 100644 index 6afd771db..000000000 --- a/browser/components/sessionstore/test/browser_send_async_message_oom.js +++ /dev/null @@ -1,75 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -const {Services} = Cu.import("resource://gre/modules/Services.jsm", {}); - -const HISTOGRAM_NAME = "FX_SESSION_RESTORE_SEND_UPDATE_CAUSED_OOM"; - -/** - * Test that an OOM in sendAsyncMessage in a framescript will be reported - * to Telemetry. - */ - -add_task(function* init() { - Services.telemetry.canRecordExtended = true; -}); - -function frameScript() { - // Make send[A]syncMessage("SessionStore:update", ...) simulate OOM. - // Other operations are unaffected. - let mm = docShell.sameTypeRootTreeItem. - QueryInterface(Ci.nsIDocShell). - QueryInterface(Ci.nsIInterfaceRequestor). - getInterface(Ci.nsIContentFrameMessageManager); - - let wrap = function(original) { - return function(name, ...args) { - if (name != "SessionStore:update") { - return original(name, ...args); - } - throw new Components.Exception("Simulated OOM", Cr.NS_ERROR_OUT_OF_MEMORY); - } - } - - mm.sendAsyncMessage = wrap(mm.sendAsyncMessage); - mm.sendSyncMessage = wrap(mm.sendSyncMessage); -} - -add_task(function*() { - // Capture original state. - let snapshot = Services.telemetry.getHistogramById(HISTOGRAM_NAME).snapshot(); - - // Open a browser, configure it to cause OOM. - let newTab = gBrowser.addTab("about:robots"); - let browser = newTab.linkedBrowser; - yield ContentTask.spawn(browser, null, frameScript); - - - let promiseReported = new Promise(resolve => { - browser.messageManager.addMessageListener("SessionStore:error", resolve); - }); - - // Attempt to flush. This should fail. - let promiseFlushed = TabStateFlusher.flush(browser); - promiseFlushed.then((success) => { - if (success) { - throw new Error("Flush should have failed") - } - }); - - // The frame script should report an error. - yield promiseReported; - - // Give us some time to handle that error. - yield new Promise(resolve => setTimeout(resolve, 10)); - - // By now, Telemetry should have been updated. - let snapshot2 = Services.telemetry.getHistogramById(HISTOGRAM_NAME).snapshot(); - gBrowser.removeTab(newTab); - - Assert.ok(snapshot2.sum > snapshot.sum); -}); - -add_task(function* cleanup() { - Services.telemetry.canRecordExtended = false; -}); diff --git a/browser/components/sessionstore/test/browser_sessionHistory.js b/browser/components/sessionstore/test/browser_sessionHistory.js deleted file mode 100644 index f4523e06a..000000000 --- a/browser/components/sessionstore/test/browser_sessionHistory.js +++ /dev/null @@ -1,240 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -requestLongerTimeout(2); - -/** - * Ensure that starting a load invalidates shistory. - */ -add_task(function test_load_start() { - // Create a new tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Load a new URI. - yield BrowserTestUtils.loadURI(browser, "about:mozilla"); - - // Remove the tab before it has finished loading. - yield promiseContentMessage(browser, "ss-test:OnHistoryReplaceEntry"); - yield promiseRemoveTab(tab); - - // Undo close the tab. - tab = ss.undoCloseTab(window, 0); - browser = tab.linkedBrowser; - yield promiseTabRestored(tab); - - // Check that the correct URL was restored. - is(browser.currentURI.spec, "about:mozilla", "url is correct"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that anchor navigation invalidates shistory. - */ -add_task(function test_hashchange() { - const URL = "data:text/html;charset=utf-8,<a id=a href=%23>clickme</a>"; - - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Check that we start with a single shistory entry. - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is one shistory entry"); - - // Click the link and wait for a hashchange event. - browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a"}); - yield promiseContentMessage(browser, "ss-test:hashchange"); - - // Check that we now have two shistory entries. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there are two shistory entries"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that loading pages from the bfcache invalidates shistory. - */ -add_task(function test_pageshow() { - const URL = "data:text/html;charset=utf-8,<h1>first</h1>"; - const URL2 = "data:text/html;charset=utf-8,<h1>second</h1>"; - - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Create a second shistory entry. - browser.loadURI(URL2); - yield promiseBrowserLoaded(browser); - - // Go back to the previous url which is loaded from the bfcache. - browser.goBack(); - yield promiseContentMessage(browser, "ss-test:onFrameTreeCollected"); - is(browser.currentURI.spec, URL, "correct url after going back"); - - // Check that loading from bfcache did invalidate shistory. - yield TabStateFlusher.flush(browser); - let {index} = JSON.parse(ss.getTabState(tab)); - is(index, 1, "first history entry is selected"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that subframe navigation invalidates shistory. - */ -add_task(function test_subframes() { - const URL = "data:text/html;charset=utf-8," + - "<iframe src=http%3A//example.com/ name=t></iframe>" + - "<a id=a1 href=http%3A//example.com/1 target=t>clickme</a>" + - "<a id=a2 href=http%3A//example.com/%23 target=t>clickme</a>"; - - // Create a new tab. - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Check that we have a single shistory entry. - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is one shistory entry"); - is(entries[0].children.length, 1, "the entry has one child"); - - // Navigate the subframe. - browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a1"}); - yield promiseBrowserLoaded(browser, false /* don't ignore subframes */); - - // Check shistory. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there now are two shistory entries"); - is(entries[1].children.length, 1, "the second entry has one child"); - - // Go back in history. - browser.goBack(); - yield promiseBrowserLoaded(browser, false /* don't ignore subframes */); - - // Navigate the subframe again. - browser.messageManager.sendAsyncMessage("ss-test:click", {id: "a2"}); - yield promiseContentMessage(browser, "ss-test:hashchange"); - - // Check shistory. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there now are two shistory entries"); - is(entries[1].children.length, 1, "the second entry has one child"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that navigating from an about page invalidates shistory. - */ -add_task(function test_about_page_navigate() { - // Create a new tab. - let tab = gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Check that we have a single shistory entry. - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is one shistory entry"); - is(entries[0].url, "about:blank", "url is correct"); - - browser.loadURI("about:robots"); - yield promiseBrowserLoaded(browser); - - // Check that we have changed the history entry. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 1, "there is one shistory entry"); - is(entries[0].url, "about:robots", "url is correct"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that history.pushState and history.replaceState invalidate shistory. - */ -add_task(function test_pushstate_replacestate() { - // Create a new tab. - let tab = gBrowser.addTab("http://example.com/1"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Check that we have a single shistory entry. - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - is(entries.length, 1, "there is one shistory entry"); - is(entries[0].url, "http://example.com/1", "url is correct"); - - yield ContentTask.spawn(browser, {}, function* () { - content.window.history.pushState({}, "", 'test-entry/'); - }); - - // Check that we have added the history entry. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there is another shistory entry"); - is(entries[1].url, "http://example.com/test-entry/", "url is correct"); - - yield ContentTask.spawn(browser, {}, function* () { - content.window.history.replaceState({}, "", "test-entry2/"); - }); - - // Check that we have modified the history entry. - yield TabStateFlusher.flush(browser); - ({entries} = JSON.parse(ss.getTabState(tab))); - is(entries.length, 2, "there is still two shistory entries"); - is(entries[1].url, "http://example.com/test-entry/test-entry2/", "url is correct"); - - // Cleanup. - gBrowser.removeTab(tab); -}); - -/** - * Ensure that slow loading subframes will invalidate shistory. - */ -add_task(function test_slow_subframe_load() { - const SLOW_URL = "http://mochi.test:8888/browser/browser/components/" + - "sessionstore/test/browser_sessionHistory_slow.sjs"; - - const URL = "data:text/html;charset=utf-8," + - "<frameset cols=50%25,50%25>" + - "<frame src='" + SLOW_URL + "'>" + - "</frameset>"; - - // Add a new tab with a slow loading subframe - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - yield TabStateFlusher.flush(browser); - let {entries} = JSON.parse(ss.getTabState(tab)); - - // Check the number of children. - is(entries.length, 1, "there is one root entry ..."); - is(entries[0].children.length, 1, "... with one child entries"); - - // Check URLs. - ok(entries[0].url.startsWith("data:text/html"), "correct root url"); - is(entries[0].children[0].url, SLOW_URL, "correct url for subframe"); - - // Cleanup. - gBrowser.removeTab(tab); -}); diff --git a/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs b/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs deleted file mode 100644 index 41da3c2ad..000000000 --- a/browser/components/sessionstore/test/browser_sessionHistory_slow.sjs +++ /dev/null @@ -1,21 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -const Cc = Components.classes; -const Ci = Components.interfaces; - -const DELAY_MS = "2000"; - -let timer; - -function handleRequest(req, resp) { - resp.processAsync(); - resp.setHeader("Cache-Control", "no-cache", false); - resp.setHeader("Content-Type", "text/html;charset=utf-8", false); - - timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - timer.init(() => { - resp.write("hi"); - resp.finish(); - }, DELAY_MS, Ci.nsITimer.TYPE_ONE_SHOT); -} diff --git a/browser/components/sessionstore/test/browser_sessionStorage.html b/browser/components/sessionstore/test/browser_sessionStorage.html deleted file mode 100644 index 7e2dccf4a..000000000 --- a/browser/components/sessionstore/test/browser_sessionStorage.html +++ /dev/null @@ -1,27 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> - <head> - <meta charset="utf-8"> - <title>browser_sessionStorage.html</title> - </head> - <body> - <script type="text/javascript;version=1.8"> - let isOuter = window == window.top; - let args = window.location.search.slice(1).split("&"); - let rand = args[0]; - - if (isOuter) { - let iframe = document.createElement("iframe"); - let isSecure = args.indexOf("secure") > -1; - let scheme = isSecure ? "https" : "http"; - iframe.setAttribute("src", scheme + "://example.com" + location.pathname + "?" + rand); - document.body.appendChild(iframe); - } - - if (sessionStorage.length === 0) { - sessionStorage.test = (isOuter ? "outer" : "inner") + "-value-" + rand; - document.title = sessionStorage.test; - } - </script> - </body> -</html> diff --git a/browser/components/sessionstore/test/browser_sessionStorage.js b/browser/components/sessionstore/test/browser_sessionStorage.js deleted file mode 100644 index b580c5cc2..000000000 --- a/browser/components/sessionstore/test/browser_sessionStorage.js +++ /dev/null @@ -1,188 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const RAND = Math.random(); -const URL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_sessionStorage.html" + - "?" + RAND; - -const OUTER_VALUE = "outer-value-" + RAND; -const INNER_VALUE = "inner-value-" + RAND; - -/** - * This test ensures that setting, modifying and restoring sessionStorage data - * works as expected. - */ -add_task(function session_storage() { - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - - let {storage} = JSON.parse(ss.getTabState(tab)); - is(storage["http://example.com"].test, INNER_VALUE, - "sessionStorage data for example.com has been serialized correctly"); - is(storage["http://mochi.test:8888"].test, OUTER_VALUE, - "sessionStorage data for mochi.test has been serialized correctly"); - - // Ensure that modifying sessionStore values works for the inner frame only. - yield modifySessionStorage(browser, {test: "modified1"}, {frameIndex: 0}); - yield TabStateFlusher.flush(browser); - - ({storage} = JSON.parse(ss.getTabState(tab))); - is(storage["http://example.com"].test, "modified1", - "sessionStorage data for example.com has been serialized correctly"); - is(storage["http://mochi.test:8888"].test, OUTER_VALUE, - "sessionStorage data for mochi.test has been serialized correctly"); - - // Ensure that modifying sessionStore values works for both frames. - yield modifySessionStorage(browser, {test: "modified"}); - yield modifySessionStorage(browser, {test: "modified2"}, {frameIndex: 0}); - yield TabStateFlusher.flush(browser); - - ({storage} = JSON.parse(ss.getTabState(tab))); - is(storage["http://example.com"].test, "modified2", - "sessionStorage data for example.com has been serialized correctly"); - is(storage["http://mochi.test:8888"].test, "modified", - "sessionStorage data for mochi.test has been serialized correctly"); - - // Test that duplicating a tab works. - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser2); - - ({storage} = JSON.parse(ss.getTabState(tab2))); - is(storage["http://example.com"].test, "modified2", - "sessionStorage data for example.com has been duplicated correctly"); - is(storage["http://mochi.test:8888"].test, "modified", - "sessionStorage data for mochi.test has been duplicated correctly"); - - // Ensure that the content script retains restored data - // (by e.g. duplicateTab) and sends it along with new data. - yield modifySessionStorage(browser2, {test: "modified3"}); - yield TabStateFlusher.flush(browser2); - - ({storage} = JSON.parse(ss.getTabState(tab2))); - is(storage["http://example.com"].test, "modified2", - "sessionStorage data for example.com has been duplicated correctly"); - is(storage["http://mochi.test:8888"].test, "modified3", - "sessionStorage data for mochi.test has been duplicated correctly"); - - // Check that loading a new URL discards data. - browser2.loadURI("http://mochi.test:8888/"); - yield promiseBrowserLoaded(browser2); - yield TabStateFlusher.flush(browser2); - - ({storage} = JSON.parse(ss.getTabState(tab2))); - is(storage["http://mochi.test:8888"].test, "modified3", - "navigating retains correct storage data"); - ok(!storage["http://example.com"], "storage data was discarded"); - - // Check that loading a new URL discards data. - browser2.loadURI("about:mozilla"); - yield promiseBrowserLoaded(browser2); - yield TabStateFlusher.flush(browser2); - - let state = JSON.parse(ss.getTabState(tab2)); - ok(!state.hasOwnProperty("storage"), "storage data was discarded"); - - // Clean up. - yield promiseRemoveTab(tab); - yield promiseRemoveTab(tab2); -}); - -/** - * This test ensures that purging domain data also purges data from the - * sessionStorage data collected for tabs. - */ -add_task(function purge_domain() { - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Purge data for "mochi.test". - yield purgeDomainData(browser, "mochi.test"); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - - let {storage} = JSON.parse(ss.getTabState(tab)); - ok(!storage["http://mochi.test:8888"], - "sessionStorage data for mochi.test has been purged"); - is(storage["http://example.com"].test, INNER_VALUE, - "sessionStorage data for example.com has been preserved"); - - yield promiseRemoveTab(tab); -}); - -/** - * This test ensures that collecting sessionStorage data respects the privacy - * levels as set by the user. - */ -add_task(function respect_privacy_level() { - let tab = gBrowser.addTab(URL + "&secure"); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield promiseRemoveTab(tab); - - let [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://mochi.test:8888"].test, OUTER_VALUE, - "http sessionStorage data has been saved"); - is(storage["https://example.com"].test, INNER_VALUE, - "https sessionStorage data has been saved"); - - // Disable saving data for encrypted sites. - Services.prefs.setIntPref("browser.sessionstore.privacy_level", 1); - - tab = gBrowser.addTab(URL + "&secure"); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield promiseRemoveTab(tab); - - [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://mochi.test:8888"].test, OUTER_VALUE, - "http sessionStorage data has been saved"); - ok(!storage["https://example.com"], - "https sessionStorage data has *not* been saved"); - - // Disable saving data for any site. - Services.prefs.setIntPref("browser.sessionstore.privacy_level", 2); - - // Check that duplicating a tab copies all private data. - tab = gBrowser.addTab(URL + "&secure"); - yield promiseBrowserLoaded(tab.linkedBrowser); - let tab2 = gBrowser.duplicateTab(tab); - yield promiseTabRestored(tab2); - yield promiseRemoveTab(tab); - - // With privacy_level=2 the |tab| shouldn't have any sessionStorage data. - [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - ok(!storage, "sessionStorage data has *not* been saved"); - - // Remove all closed tabs before continuing with the next test. - // As Date.now() isn't monotonic we might sometimes check - // the wrong closedTabData entry. - while (ss.getClosedTabCount(window) > 0) { - ss.forgetClosedTab(window, 0); - } - - // Restore the default privacy level and close the duplicated tab. - Services.prefs.clearUserPref("browser.sessionstore.privacy_level"); - yield promiseRemoveTab(tab2); - - // With privacy_level=0 the duplicated |tab2| should persist all data. - [{state: {storage}}] = JSON.parse(ss.getClosedTabData(window)); - is(storage["http://mochi.test:8888"].test, OUTER_VALUE, - "http sessionStorage data has been saved"); - is(storage["https://example.com"].test, INNER_VALUE, - "https sessionStorage data has been saved"); -}); - -function purgeDomainData(browser, domain) { - return sendMessage(browser, "ss-test:purgeDomainData", domain); -} diff --git a/browser/components/sessionstore/test/browser_sessionStorage_size.js b/browser/components/sessionstore/test/browser_sessionStorage_size.js deleted file mode 100644 index d1d894611..000000000 --- a/browser/components/sessionstore/test/browser_sessionStorage_size.js +++ /dev/null @@ -1,51 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -const RAND = Math.random(); -const URL = "http://mochi.test:8888/browser/" + - "browser/components/sessionstore/test/browser_sessionStorage.html" + - "?" + RAND; - -const OUTER_VALUE = "outer-value-" + RAND; - -// Test that we record the size of messages. -add_task(function* test_telemetry() { - Services.telemetry.canRecordExtended = true; - let histogram = Services.telemetry.getHistogramById("FX_SESSION_RESTORE_DOM_STORAGE_SIZE_ESTIMATE_CHARS"); - let snap1 = histogram.snapshot(); - - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - let snap2 = histogram.snapshot(); - - Assert.ok(snap2.counts[5] > snap1.counts[5]); - yield promiseRemoveTab(tab); - Services.telemetry.canRecordExtended = false; -}); - -// Lower the size limit for DOM Storage content. Check that DOM Storage -// is not updated, but that other things remain updated. -add_task(function* test_large_content() { - Services.prefs.setIntPref("browser.sessionstore.dom_storage_limit", 5); - - let tab = gBrowser.addTab(URL); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - - // Flush to make sure chrome received all data. - yield TabStateFlusher.flush(browser); - - let state = JSON.parse(ss.getTabState(tab)); - info(JSON.stringify(state, null, "\t")); - Assert.equal(state.storage, null, "We have no storage for the tab"); - Assert.equal(state.entries[0].title, OUTER_VALUE); - yield promiseRemoveTab(tab); - - Services.prefs.clearUserPref("browser.sessionstore.dom_storage_limit"); -}); diff --git a/browser/components/sessionstore/test/browser_sessionStoreContainer.js b/browser/components/sessionstore/test/browser_sessionStoreContainer.js deleted file mode 100644 index 1bc9537e2..000000000 --- a/browser/components/sessionstore/test/browser_sessionStoreContainer.js +++ /dev/null @@ -1,141 +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"; - -add_task(function* () { - for (let i = 0; i < 3; ++i) { - let tab = gBrowser.addTab("http://example.com/", { userContextId: i }); - let browser = tab.linkedBrowser; - - yield promiseBrowserLoaded(browser); - - let tab2 = gBrowser.duplicateTab(tab); - Assert.equal(tab2.getAttribute("usercontextid"), i); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2) - - yield ContentTask.spawn(browser2, { expectedId: i }, function* (args) { - let loadContext = docShell.QueryInterface(Ci.nsILoadContext); - Assert.equal(loadContext.originAttributes.userContextId, - args.expectedId, "The docShell has the correct userContextId"); - }); - - yield promiseRemoveTab(tab); - yield promiseRemoveTab(tab2); - } -}); - -add_task(function* () { - let tab = gBrowser.addTab("http://example.com/", { userContextId: 1 }); - let browser = tab.linkedBrowser; - - yield promiseBrowserLoaded(browser); - - gBrowser.selectedTab = tab; - - let tab2 = gBrowser.duplicateTab(tab); - let browser2 = tab2.linkedBrowser; - yield promiseTabRestored(tab2) - - yield ContentTask.spawn(browser2, { expectedId: 1 }, function* (args) { - Assert.equal(docShell.getOriginAttributes().userContextId, - args.expectedId, - "The docShell has the correct userContextId"); - }); - - yield promiseRemoveTab(tab); - yield promiseRemoveTab(tab2); -}); - -add_task(function* () { - let tab = gBrowser.addTab("http://example.com/", { userContextId: 1 }); - let browser = tab.linkedBrowser; - - yield promiseBrowserLoaded(browser); - - gBrowser.removeTab(tab); - - let tab2 = ss.undoCloseTab(window, 0); - Assert.equal(tab2.getAttribute("usercontextid"), 1); - yield promiseTabRestored(tab2); - yield ContentTask.spawn(tab2.linkedBrowser, { expectedId: 1 }, function* (args) { - Assert.equal(docShell.getOriginAttributes().userContextId, - args.expectedId, - "The docShell has the correct userContextId"); - }); - - yield promiseRemoveTab(tab2); -}); - -// Opens "uri" in a new tab with the provided userContextId and focuses it. -// Returns the newly opened tab. -function* openTabInUserContext(userContextId) { - // Open the tab in the correct userContextId. - let tab = gBrowser.addTab("http://example.com", { userContextId }); - - // Select tab and make sure its browser is focused. - gBrowser.selectedTab = tab; - tab.ownerGlobal.focus(); - - let browser = gBrowser.getBrowserForTab(tab); - yield BrowserTestUtils.browserLoaded(browser); - return { tab, browser }; -} - -function waitForNewCookie() { - return new Promise(resolve => { - Services.obs.addObserver(function observer(subj, topic, data) { - let cookie = subj.QueryInterface(Ci.nsICookie2); - if (data == "added") { - Services.obs.removeObserver(observer, topic); - resolve(); - } - }, "cookie-changed", false); - }); -} - -add_task(function* test() { - const USER_CONTEXTS = [ - "default", - "personal", - "work", - ]; - - const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore); - const { TabStateFlusher } = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {}); - - // Make sure userContext is enabled. - yield SpecialPowers.pushPrefEnv({ - "set": [ [ "privacy.userContext.enabled", true ] ] - }); - - let lastSessionRestore; - for (let userContextId of Object.keys(USER_CONTEXTS)) { - // Load the page in 3 different contexts and set a cookie - // which should only be visible in that context. - let cookie = USER_CONTEXTS[userContextId]; - - // Open our tab in the given user context. - let { tab, browser } = yield* openTabInUserContext(userContextId); - - yield Promise.all([ - waitForNewCookie(), - ContentTask.spawn(browser, cookie, cookie => content.document.cookie = cookie) - ]); - - // Ensure the tab's session history is up-to-date. - yield TabStateFlusher.flush(browser); - - lastSessionRestore = ss.getWindowState(window); - - // Remove the tab. - gBrowser.removeTab(tab); - } - - let state = JSON.parse(lastSessionRestore); - is(state.windows[0].cookies.length, USER_CONTEXTS.length, - "session restore should have each container's cookie"); -}); - diff --git a/browser/components/sessionstore/test/browser_swapDocShells.js b/browser/components/sessionstore/test/browser_swapDocShells.js deleted file mode 100644 index 839f060e7..000000000 --- a/browser/components/sessionstore/test/browser_swapDocShells.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; - -add_task(function* () { - let tab = gBrowser.selectedTab = gBrowser.addTab("about:mozilla"); - yield promiseBrowserLoaded(gBrowser.selectedBrowser); - - let win = gBrowser.replaceTabWithWindow(tab); - yield promiseDelayedStartupFinished(win); - yield promiseBrowserHasURL(win.gBrowser.browsers[0], "about:mozilla"); - - win.duplicateTabIn(win.gBrowser.selectedTab, "tab"); - yield promiseTabRestored(win.gBrowser.tabs[1]); - - let browser = win.gBrowser.browsers[1]; - is(browser.currentURI.spec, "about:mozilla", "tab was duplicated"); - - yield BrowserTestUtils.closeWindow(win); -}); - -function promiseDelayedStartupFinished(win) { - let deferred = Promise.defer(); - whenDelayedStartupFinished(win, deferred.resolve); - return deferred.promise; -} - -function promiseBrowserHasURL(browser, url) { - let promise = Promise.resolve(); - - if (browser.contentDocument.readyState === "complete" && - browser.currentURI.spec === url) { - return promise; - } - - return promise.then(() => promiseBrowserHasURL(browser, url)); -} diff --git a/browser/components/sessionstore/test/browser_switch_remoteness.js b/browser/components/sessionstore/test/browser_switch_remoteness.js deleted file mode 100644 index 9eb8c260a..000000000 --- a/browser/components/sessionstore/test/browser_switch_remoteness.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; - -const URL = "http://example.com/browser_switch_remoteness_"; - -function countHistoryEntries(browser, expected) { - return ContentTask.spawn(browser, { expected }, function* (args) { - let Ci = Components.interfaces; - let webNavigation = docShell.QueryInterface(Ci.nsIWebNavigation); - let history = webNavigation.sessionHistory.QueryInterface(Ci.nsISHistoryInternal); - Assert.equal(history && history.count, args.expected, - "correct number of shistory entries"); - }); -} - -add_task(function* () { - // Open a new window. - let win = yield promiseNewWindowLoaded(); - - // Add a new tab. - let tab = win.gBrowser.addTab("about:blank"); - let browser = tab.linkedBrowser; - yield promiseBrowserLoaded(browser); - ok(browser.isRemoteBrowser, "browser is remote"); - - // Get the maximum number of preceding entries to save. - const MAX_BACK = Services.prefs.getIntPref("browser.sessionstore.max_serialize_back"); - ok(MAX_BACK > -1, "check that the default has a value that caps data"); - - // Load more pages than we would save to disk on a clean shutdown. - for (let i = 0; i < MAX_BACK + 2; i++) { - browser.loadURI(URL + i); - yield promiseBrowserLoaded(browser); - ok(browser.isRemoteBrowser, "browser is still remote"); - } - - // Check we have the right number of shistory entries. - yield countHistoryEntries(browser, MAX_BACK + 2); - - // Load a non-remote page. - browser.loadURI("about:robots"); - yield promiseTabRestored(tab); - ok(!browser.isRemoteBrowser, "browser is not remote anymore"); - - // Check that we didn't lose any shistory entries. - yield countHistoryEntries(browser, MAX_BACK + 3); - - // Cleanup. - yield BrowserTestUtils.closeWindow(win); -}); diff --git a/browser/components/sessionstore/test/browser_undoCloseById.js b/browser/components/sessionstore/test/browser_undoCloseById.js deleted file mode 100644 index f2f0f919c..000000000 --- a/browser/components/sessionstore/test/browser_undoCloseById.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; - -/** - * This test is for the undoCloseById function. - */ - -Cu.import("resource:///modules/sessionstore/SessionStore.jsm"); - -function openAndCloseTab(window, url) { - let tab = window.gBrowser.addTab(url); - yield promiseBrowserLoaded(tab.linkedBrowser, true, url); - yield TabStateFlusher.flush(tab.linkedBrowser); - yield promiseRemoveTab(tab); -} - -function* openWindow(url) { - let win = yield promiseNewWindowLoaded(); - let flags = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY; - win.gBrowser.selectedBrowser.loadURIWithFlags(url, flags); - yield promiseBrowserLoaded(win.gBrowser.selectedBrowser, true, url); - return win; -} - -function closeWindow(win) { - yield BrowserTestUtils.closeWindow(win); - // Wait 20 ms to allow SessionStorage a chance to register the closed window. - yield new Promise(resolve => setTimeout(resolve, 20)); -} - -add_task(function* test_undoCloseById() { - // Clear the lists of closed windows and tabs. - forgetClosedWindows(); - while (SessionStore.getClosedTabCount(window)) { - SessionStore.forgetClosedTab(window, 0); - } - - // Open a new window. - let win = yield openWindow("about:robots"); - - // Open and close a tab. - yield openAndCloseTab(win, "about:mozilla"); - is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab"); - - // Record the first closedId created. - let initialClosedId = SessionStore.getClosedTabData(win, false)[0].closedId; - - // Open and close another window. - let win2 = yield openWindow("about:mozilla"); - yield closeWindow(win2); // closedId == initialClosedId + 1 - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); - - // Open and close another tab in the first window. - yield openAndCloseTab(win, "about:robots"); // closedId == initialClosedId + 2 - is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab"); - - // Undo closing the second tab. - let tab = SessionStore.undoCloseById(initialClosedId + 2); - yield promiseBrowserLoaded(tab.linkedBrowser); - is(tab.linkedBrowser.currentURI.spec, "about:robots", "The expected tab was re-opened"); - - let notTab = SessionStore.undoCloseById(initialClosedId + 2); - is(notTab, undefined, "Re-opened tab cannot be unClosed again by closedId"); - - // Now the last closed object should be a window again. - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); - - // Undo closing the first tab. - let tab2 = SessionStore.undoCloseById(initialClosedId); - yield promiseBrowserLoaded(tab2.linkedBrowser); - is(tab2.linkedBrowser.currentURI.spec, "about:mozilla", "The expected tab was re-opened"); - - // Close the two tabs we re-opened. - yield promiseRemoveTab(tab); // closedId == initialClosedId + 3 - is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab"); - yield promiseRemoveTab(tab2); // closedId == initialClosedId + 4 - is(SessionStore.lastClosedObjectType, "tab", "The last closed object is a tab"); - - // Open another new window. - let win3 = yield openWindow("about:mozilla"); - - // Close both windows. - yield closeWindow(win); // closedId == initialClosedId + 5 - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); - yield closeWindow(win3); // closedId == initialClosedId + 6 - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); - - // Undo closing the second window. - win = SessionStore.undoCloseById(initialClosedId + 6); - yield BrowserTestUtils.waitForEvent(win, "load"); - - // Make sure we wait until this window is restored. - yield BrowserTestUtils.waitForEvent(win.gBrowser.tabContainer, - "SSTabRestored"); - - is(win.gBrowser.selectedBrowser.currentURI.spec, "about:mozilla", "The expected window was re-opened"); - - let notWin = SessionStore.undoCloseById(initialClosedId + 6); - is(notWin, undefined, "Re-opened window cannot be unClosed again by closedId"); - - // Close the window again. - yield closeWindow(win); - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); - - // Undo closing the first window. - win = SessionStore.undoCloseById(initialClosedId + 5); - - yield BrowserTestUtils.waitForEvent(win, "load"); - - // Make sure we wait until this window is restored. - yield BrowserTestUtils.waitForEvent(win.gBrowser.tabContainer, - "SSTabRestored"); - - is(win.gBrowser.selectedBrowser.currentURI.spec, "about:robots", "The expected window was re-opened"); - - // Close the window again. - yield closeWindow(win); - is(SessionStore.lastClosedObjectType, "window", "The last closed object is a window"); -}); diff --git a/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js b/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js deleted file mode 100644 index e46348e59..000000000 --- a/browser/components/sessionstore/test/browser_unrestored_crashedTabs.js +++ /dev/null @@ -1,69 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -/** - * Tests that if we have tabs that are still in the "click to - * restore" state, that if their browsers crash, that we don't - * show the crashed state for those tabs (since selecting them - * should restore them anyway). - */ - -const PREF = "browser.sessionstore.restore_on_demand"; -const PAGE = "data:text/html,<html><body>A%20regular,%20everyday,%20normal%20page."; - -add_task(function* test() { - yield pushPrefs([PREF, true]); - - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: PAGE, - }, function*(browser) { - yield TabStateFlusher.flush(browser); - - // We'll create a second "pending" tab. This is the one we'll - // ensure doesn't go to about:tabcrashed. We start it non-remote - // since this is how SessionStore creates all browsers before - // they are restored. - let unrestoredTab = gBrowser.addTab("about:blank", { - skipAnimation: true, - forceNotRemote: true, - }); - - let state = { - entries: [{url: PAGE}], - }; - - ss.setTabState(unrestoredTab, JSON.stringify(state)); - - ok(!unrestoredTab.hasAttribute("crashed"), "tab is not crashed"); - ok(unrestoredTab.hasAttribute("pending"), "tab is pending"); - - // Now crash the selected browser. - yield BrowserTestUtils.crashBrowser(browser); - - ok(!unrestoredTab.hasAttribute("crashed"), "tab is still not crashed"); - ok(unrestoredTab.hasAttribute("pending"), "tab is still pending"); - - // Selecting the tab should now restore it. - gBrowser.selectedTab = unrestoredTab; - yield promiseTabRestored(unrestoredTab); - - ok(!unrestoredTab.hasAttribute("crashed"), "tab is still not crashed"); - ok(!unrestoredTab.hasAttribute("pending"), "tab is no longer pending"); - - // The original tab should still be crashed - let originalTab = gBrowser.getTabForBrowser(browser); - ok(originalTab.hasAttribute("crashed"), "original tab is crashed"); - ok(!originalTab.isRemoteBrowser, "Should not be remote"); - - // We'd better be able to restore it still. - gBrowser.selectedTab = originalTab; - SessionStore.reviveCrashedTab(originalTab); - yield promiseTabRestored(originalTab); - - // Clean up. - yield BrowserTestUtils.removeTab(unrestoredTab); - }); -}); diff --git a/browser/components/sessionstore/test/browser_upgrade_backup.js b/browser/components/sessionstore/test/browser_upgrade_backup.js deleted file mode 100644 index 768671051..000000000 --- a/browser/components/sessionstore/test/browser_upgrade_backup.js +++ /dev/null @@ -1,134 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -Cu.import("resource://gre/modules/Services.jsm", this); -Cu.import("resource://gre/modules/osfile.jsm", this); -Cu.import("resource://gre/modules/Task.jsm", this); -Cu.import("resource://gre/modules/Preferences.jsm", this); - -const Paths = SessionFile.Paths; -const PREF_UPGRADE = "browser.sessionstore.upgradeBackup.latestBuildID"; -const PREF_MAX_UPGRADE_BACKUPS = "browser.sessionstore.upgradeBackup.maxUpgradeBackups"; - -/** - * Prepares tests by retrieving the current platform's build ID, clearing the - * build where the last backup was created and creating arbitrary JSON data - * for a new backup. - */ -var prepareTest = Task.async(function* () { - let result = {}; - - result.buildID = Services.appinfo.platformBuildID; - Services.prefs.setCharPref(PREF_UPGRADE, ""); - result.contents = JSON.stringify({"browser_upgrade_backup.js": Math.random()}); - - return result; -}); - -/** - * Retrieves all upgrade backups and returns them in an array. - */ -var getUpgradeBackups = Task.async(function* () { - let iterator; - let backups = []; - let upgradeBackupPrefix = Paths.upgradeBackupPrefix; - - try { - iterator = new OS.File.DirectoryIterator(Paths.backups); - - // iterate over all files in the backup directory - yield iterator.forEach(function (file) { - // check the upgradeBackupPrefix - if (file.path.startsWith(Paths.upgradeBackupPrefix)) { - // the file is a backup - backups.push(file.path); - } - }, this); - } finally { - if (iterator) { - iterator.close(); - } - } - - // return results - return backups; -}); - -add_task(function* init() { - // Wait until initialization is complete - yield SessionStore.promiseInitialized; - yield SessionFile.wipe(); -}); - -add_task(function* test_upgrade_backup() { - let test = yield prepareTest(); - info("Let's check if we create an upgrade backup"); - yield OS.File.writeAtomic(Paths.clean, test.contents); - yield SessionFile.read(); // First call to read() initializes the SessionWorker - yield SessionFile.write(""); // First call to write() triggers the backup - - is(Services.prefs.getCharPref(PREF_UPGRADE), test.buildID, "upgrade backup should be set"); - - is((yield OS.File.exists(Paths.upgradeBackup)), true, "upgrade backup file has been created"); - - let data = yield OS.File.read(Paths.upgradeBackup); - is(test.contents, (new TextDecoder()).decode(data), "upgrade backup contains the expected contents"); - - info("Let's check that we don't overwrite this upgrade backup"); - let newContents = JSON.stringify({"something else entirely": Math.random()}); - yield OS.File.writeAtomic(Paths.clean, newContents); - yield SessionFile.read(); // Reinitialize the SessionWorker - yield SessionFile.write(""); // Next call to write() shouldn't trigger the backup - data = yield OS.File.read(Paths.upgradeBackup); - is(test.contents, (new TextDecoder()).decode(data), "upgrade backup hasn't changed"); -}); - -add_task(function* test_upgrade_backup_removal() { - let test = yield prepareTest(); - let maxUpgradeBackups = Preferences.get(PREF_MAX_UPGRADE_BACKUPS, 3); - info("Let's see if we remove backups if there are too many"); - yield OS.File.writeAtomic(Paths.clean, test.contents); - - // if the nextUpgradeBackup already exists (from another test), remove it - if (OS.File.exists(Paths.nextUpgradeBackup)) { - yield OS.File.remove(Paths.nextUpgradeBackup); - } - - // create dummy backups - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20080101010101", ""); - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20090101010101", ""); - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20100101010101", ""); - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20110101010101", ""); - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20120101010101", ""); - yield OS.File.writeAtomic(Paths.upgradeBackupPrefix + "20130101010101", ""); - - // get currently existing backups - let backups = yield getUpgradeBackups(); - - // trigger new backup - yield SessionFile.read(); // First call to read() initializes the SessionWorker - yield SessionFile.write(""); // First call to write() triggers the backup and the cleanup - - // a new backup should have been created (and still exist) - is(Services.prefs.getCharPref(PREF_UPGRADE), test.buildID, "upgrade backup should be set"); - is((yield OS.File.exists(Paths.upgradeBackup)), true, "upgrade backup file has been created"); - - // get currently existing backups and check their count - let newBackups = yield getUpgradeBackups(); - is(newBackups.length, maxUpgradeBackups, "expected number of backups are present after removing old backups"); - - // find all backups that were created during the last call to `SessionFile.write("");` - // ie, filter out all the backups that have already been present before the call - newBackups = newBackups.filter(function (backup) { - return backups.indexOf(backup) < 0; - }); - - // check that exactly one new backup was created - is(newBackups.length, 1, "one new backup was created that was not removed"); - - yield SessionFile.write(""); // Second call to write() should not trigger anything - - backups = yield getUpgradeBackups(); - is(backups.length, maxUpgradeBackups, "second call to SessionFile.write() didn't create or remove more backups"); -}); - diff --git a/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js b/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js deleted file mode 100644 index 781692909..000000000 --- a/browser/components/sessionstore/test/browser_windowRestore_perwindowpb.js +++ /dev/null @@ -1,26 +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 test checks that closed private windows can't be restored - -function test() { - waitForExplicitFinish(); - - // Purging the list of closed windows - forgetClosedWindows(); - - // Load a private window, then close it - // and verify it doesn't get remembered for restoring - whenNewWindowLoaded({private: true}, function (win) { - info("The private window got loaded"); - win.addEventListener("SSWindowClosing", function onclosing() { - win.removeEventListener("SSWindowClosing", onclosing, false); - executeSoon(function () { - is(ss.getClosedWindowCount(), 0, - "The private window should not have been stored"); - }); - }, false); - BrowserTestUtils.closeWindow(win).then(finish); - }); -} diff --git a/browser/components/sessionstore/test/browser_windowStateContainer.js b/browser/components/sessionstore/test/browser_windowStateContainer.js deleted file mode 100644 index beb838088..000000000 --- a/browser/components/sessionstore/test/browser_windowStateContainer.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; - -requestLongerTimeout(2); - -add_task(function* setup() { - yield SpecialPowers.pushPrefEnv({ - set: [["dom.ipc.processCount", 1]] - }); -}); - -add_task(function* () { - let win = yield BrowserTestUtils.openNewBrowserWindow(); - - // Create 4 tabs with different userContextId. - for (let userContextId = 1; userContextId < 5; userContextId++) { - let tab = win.gBrowser.addTab("http://example.com/", {userContextId}); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - } - - // Move the default tab of window to the end. - // We want the 1st tab to have non-default userContextId, so later when we - // restore into win2 we can test restore into an existing tab with different - // userContextId. - win.gBrowser.moveTabTo(win.gBrowser.tabs[0], win.gBrowser.tabs.length - 1); - - let winState = JSON.parse(ss.getWindowState(win)); - - for (let i = 0; i < 4; i++) { - Assert.equal(winState.windows[0].tabs[i].userContextId, i + 1, - "1st Window: tabs[" + i + "].userContextId should exist."); - } - - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - - // Create tabs with different userContextId, but this time we create them with - // fewer tabs and with different order with win. - for (let userContextId = 3; userContextId > 0; userContextId--) { - let tab = win2.gBrowser.addTab("http://example.com/", {userContextId}); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - } - - ss.setWindowState(win2, JSON.stringify(winState), true); - - for (let i = 0; i < 4; i++) { - let browser = win2.gBrowser.tabs[i].linkedBrowser; - yield ContentTask.spawn(browser, { expectedId: i + 1 }, function* (args) { - Assert.equal(docShell.getOriginAttributes().userContextId, - args.expectedId, - "The docShell has the correct userContextId"); - - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, - args.expectedId, - "The document has the correct userContextId"); - }); - } - - // Test the last tab, which doesn't have userContextId. - let browser = win2.gBrowser.tabs[4].linkedBrowser; - yield ContentTask.spawn(browser, { expectedId: 0 }, function* (args) { - Assert.equal(docShell.getOriginAttributes().userContextId, - args.expectedId, - "The docShell has the correct userContextId"); - - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, - args.expectedId, - "The document has the correct userContextId"); - }); - - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(win2); -}); - -add_task(function* () { - let win = yield BrowserTestUtils.openNewBrowserWindow(); - yield TabStateFlusher.flush(win.gBrowser.selectedBrowser); - - let tab = win.gBrowser.addTab("http://example.com/", { userContextId: 1 }); - yield promiseBrowserLoaded(tab.linkedBrowser); - yield TabStateFlusher.flush(tab.linkedBrowser); - - // win should have 1 default tab, and 1 container tab. - Assert.equal(win.gBrowser.tabs.length, 2, "win should have 2 tabs"); - - let winState = JSON.parse(ss.getWindowState(win)); - - for (let i = 0; i < 2; i++) { - Assert.equal(winState.windows[0].tabs[i].userContextId, i, - "1st Window: tabs[" + i + "].userContextId should be " + i); - } - - let win2 = yield BrowserTestUtils.openNewBrowserWindow(); - - let tab2 = win2.gBrowser.addTab("http://example.com/", { userContextId : 1 }); - yield promiseBrowserLoaded(tab2.linkedBrowser); - yield TabStateFlusher.flush(tab2.linkedBrowser); - - // Move the first normal tab to end, so the first tab of win2 will be a - // container tab. - win2.gBrowser.moveTabTo(win2.gBrowser.tabs[0], win2.gBrowser.tabs.length - 1); - yield TabStateFlusher.flush(win2.gBrowser.tabs[0].linkedBrowser); - - ss.setWindowState(win2, JSON.stringify(winState), true); - - for (let i = 0; i < 2; i++) { - let browser = win2.gBrowser.tabs[i].linkedBrowser; - yield ContentTask.spawn(browser, { expectedId: i }, function* (args) { - Assert.equal(docShell.getOriginAttributes().userContextId, - args.expectedId, - "The docShell has the correct userContextId"); - - Assert.equal(content.document.nodePrincipal.originAttributes.userContextId, - args.expectedId, - "The document has the correct userContextId"); - }); - } - - yield BrowserTestUtils.closeWindow(win); - yield BrowserTestUtils.closeWindow(win2); -}); - diff --git a/browser/components/sessionstore/test/content-forms.js b/browser/components/sessionstore/test/content-forms.js deleted file mode 100644 index da7bc9c08..000000000 --- a/browser/components/sessionstore/test/content-forms.js +++ /dev/null @@ -1,133 +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"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -/** - * This frame script is only loaded for sessionstore mochitests. It contains - * a bunch of utility functions used to test form data collection and - * restoration in remote browsers. - */ - -function queryElement(data) { - let frame = content; - if (data.hasOwnProperty("frame")) { - frame = content.frames[data.frame]; - } - - let doc = frame.document; - - if (data.hasOwnProperty("id")) { - return doc.getElementById(data.id); - } - - if (data.hasOwnProperty("selector")) { - return doc.querySelector(data.selector); - } - - if (data.hasOwnProperty("xpath")) { - let xptype = Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE; - return doc.evaluate(data.xpath, doc, null, xptype, null).singleNodeValue; - } - - throw new Error("couldn't query element"); -} - -function dispatchUIEvent(input, type) { - let event = input.ownerDocument.createEvent("UIEvents"); - event.initUIEvent(type, true, true, input.ownerGlobal, 0); - input.dispatchEvent(event); -} - -function defineListener(type, cb) { - addMessageListener("ss-test:" + type, function ({data}) { - sendAsyncMessage("ss-test:" + type, cb(data)); - }); -} - -defineListener("sendKeyEvent", function (data) { - let frame = content; - if (data.hasOwnProperty("frame")) { - frame = content.frames[data.frame]; - } - - let ifreq = frame.QueryInterface(Ci.nsIInterfaceRequestor); - let utils = ifreq.getInterface(Ci.nsIDOMWindowUtils); - - let keyCode = data.key.charCodeAt(0); - let charCode = Ci.nsIDOMKeyEvent.DOM_VK_A + keyCode - "a".charCodeAt(0); - - utils.sendKeyEvent("keydown", keyCode, charCode, null); - utils.sendKeyEvent("keypress", keyCode, charCode, null); - utils.sendKeyEvent("keyup", keyCode, charCode, null); -}); - -defineListener("getInnerHTML", function (data) { - return queryElement(data).innerHTML; -}); - -defineListener("getTextContent", function (data) { - return queryElement(data).textContent; -}); - -defineListener("getInputValue", function (data) { - return queryElement(data).value; -}); - -defineListener("setInputValue", function (data) { - let input = queryElement(data); - input.value = data.value; - dispatchUIEvent(input, "input"); -}); - -defineListener("getInputChecked", function (data) { - return queryElement(data).checked; -}); - -defineListener("setInputChecked", function (data) { - let input = queryElement(data); - input.checked = data.checked; - dispatchUIEvent(input, "change"); -}); - -defineListener("getSelectedIndex", function (data) { - return queryElement(data).selectedIndex; -}); - -defineListener("setSelectedIndex", function (data) { - let input = queryElement(data); - input.selectedIndex = data.index; - dispatchUIEvent(input, "change"); -}); - -defineListener("getMultipleSelected", function (data) { - let input = queryElement(data); - return Array.map(input.options, (opt, idx) => idx) - .filter(idx => input.options[idx].selected); -}); - -defineListener("setMultipleSelected", function (data) { - let input = queryElement(data); - Array.forEach(input.options, (opt, idx) => opt.selected = data.indices.indexOf(idx) > -1); - dispatchUIEvent(input, "change"); -}); - -defineListener("getFileNameArray", function (data) { - return queryElement(data).mozGetFileNameArray(); -}); - -defineListener("setFileNameArray", function (data) { - let input = queryElement(data); - input.mozSetFileNameArray(data.names, data.names.length); - dispatchUIEvent(input, "input"); -}); - -defineListener("setFormElementValues", function (data) { - for (let elem of content.document.forms[0].elements) { - elem.value = data.value; - dispatchUIEvent(elem, "input"); - } -}); diff --git a/browser/components/sessionstore/test/content.js b/browser/components/sessionstore/test/content.js deleted file mode 100644 index e815a6783..000000000 --- a/browser/components/sessionstore/test/content.js +++ /dev/null @@ -1,222 +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"; - -var Cu = Components.utils; -var Ci = Components.interfaces; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource:///modules/sessionstore/FrameTree.jsm", this); -var gFrameTree = new FrameTree(this); - -function executeSoon(callback) { - Services.tm.mainThread.dispatch(callback, Components.interfaces.nsIThread.DISPATCH_NORMAL); -} - -gFrameTree.addObserver({ - onFrameTreeReset: function () { - sendAsyncMessage("ss-test:onFrameTreeReset"); - }, - - onFrameTreeCollected: function () { - sendAsyncMessage("ss-test:onFrameTreeCollected"); - } -}); - -var historyListener = { - OnHistoryNewEntry: function () { - sendAsyncMessage("ss-test:OnHistoryNewEntry"); - }, - - OnHistoryGoBack: function () { - sendAsyncMessage("ss-test:OnHistoryGoBack"); - return true; - }, - - OnHistoryGoForward: function () { - sendAsyncMessage("ss-test:OnHistoryGoForward"); - return true; - }, - - OnHistoryGotoIndex: function () { - sendAsyncMessage("ss-test:OnHistoryGotoIndex"); - return true; - }, - - OnHistoryPurge: function () { - sendAsyncMessage("ss-test:OnHistoryPurge"); - return true; - }, - - OnHistoryReload: function () { - sendAsyncMessage("ss-test:OnHistoryReload"); - return true; - }, - - OnHistoryReplaceEntry: function () { - sendAsyncMessage("ss-test:OnHistoryReplaceEntry"); - }, - - QueryInterface: XPCOMUtils.generateQI([ - Ci.nsISHistoryListener, - Ci.nsISupportsWeakReference - ]) -}; - -var {sessionHistory} = docShell.QueryInterface(Ci.nsIWebNavigation); -if (sessionHistory) { - sessionHistory.addSHistoryListener(historyListener); -} - -/** - * This frame script is only loaded for sessionstore mochitests. It enables us - * to modify and query docShell data when running with multiple processes. - */ - -addEventListener("hashchange", function () { - sendAsyncMessage("ss-test:hashchange"); -}); - -addMessageListener("ss-test:purgeDomainData", function ({data: domain}) { - Services.obs.notifyObservers(null, "browser:purge-domain-data", domain); - content.setTimeout(() => sendAsyncMessage("ss-test:purgeDomainData")); -}); - -addMessageListener("ss-test:getStyleSheets", function (msg) { - let sheets = content.document.styleSheets; - let titles = Array.map(sheets, ss => [ss.title, ss.disabled]); - sendSyncMessage("ss-test:getStyleSheets", titles); -}); - -addMessageListener("ss-test:enableStyleSheetsForSet", function (msg) { - let sheets = content.document.styleSheets; - let change = false; - for (let i = 0; i < sheets.length; i++) { - if (sheets[i].disabled != (msg.data.indexOf(sheets[i].title) == -1)) { - change = true; - break; - } - } - function observer() { - Services.obs.removeObserver(observer, "style-sheet-applicable-state-changed"); - - // It's possible our observer will run before the one in - // content-sessionStore.js. Therefore, we run ours a little - // later. - executeSoon(() => sendAsyncMessage("ss-test:enableStyleSheetsForSet")); - } - if (change) { - // We don't want to reply until content-sessionStore.js has seen - // the change. - Services.obs.addObserver(observer, "style-sheet-applicable-state-changed", false); - - content.document.enableStyleSheetsForSet(msg.data); - } else { - sendAsyncMessage("ss-test:enableStyleSheetsForSet"); - } -}); - -addMessageListener("ss-test:enableSubDocumentStyleSheetsForSet", function (msg) { - let iframe = content.document.getElementById(msg.data.id); - iframe.contentDocument.enableStyleSheetsForSet(msg.data.set); - sendAsyncMessage("ss-test:enableSubDocumentStyleSheetsForSet"); -}); - -addMessageListener("ss-test:getAuthorStyleDisabled", function (msg) { - let {authorStyleDisabled} = - docShell.contentViewer; - sendSyncMessage("ss-test:getAuthorStyleDisabled", authorStyleDisabled); -}); - -addMessageListener("ss-test:setAuthorStyleDisabled", function (msg) { - let markupDocumentViewer = - docShell.contentViewer; - markupDocumentViewer.authorStyleDisabled = msg.data; - sendSyncMessage("ss-test:setAuthorStyleDisabled"); -}); - -addMessageListener("ss-test:setUsePrivateBrowsing", function (msg) { - let loadContext = - docShell.QueryInterface(Ci.nsILoadContext); - loadContext.usePrivateBrowsing = msg.data; - sendAsyncMessage("ss-test:setUsePrivateBrowsing"); -}); - -addMessageListener("ss-test:getScrollPosition", function (msg) { - let frame = content; - if (msg.data.hasOwnProperty("frame")) { - frame = content.frames[msg.data.frame]; - } - let {scrollX: x, scrollY: y} = frame; - sendAsyncMessage("ss-test:getScrollPosition", {x: x, y: y}); -}); - -addMessageListener("ss-test:setScrollPosition", function (msg) { - let frame = content; - let {x, y} = msg.data; - if (msg.data.hasOwnProperty("frame")) { - frame = content.frames[msg.data.frame]; - } - frame.scrollTo(x, y); - - frame.addEventListener("scroll", function onScroll(event) { - if (frame.document == event.target) { - frame.removeEventListener("scroll", onScroll); - sendAsyncMessage("ss-test:setScrollPosition"); - } - }); -}); - -addMessageListener("ss-test:createDynamicFrames", function ({data}) { - function createIFrame(rows) { - let frames = content.document.getElementById(data.id); - frames.setAttribute("rows", rows); - - let frame = content.document.createElement("frame"); - frame.setAttribute("src", data.url); - frames.appendChild(frame); - } - - addEventListener("DOMContentLoaded", function onContentLoaded(event) { - if (content.document == event.target) { - removeEventListener("DOMContentLoaded", onContentLoaded, true); - // DOMContentLoaded is fired right after we finished parsing the document. - createIFrame("33%, 33%, 33%"); - } - }, true); - - addEventListener("load", function onLoad(event) { - if (content.document == event.target) { - removeEventListener("load", onLoad, true); - - // Creating this frame on the same tick as the load event - // means that it must not be included in the frame tree. - createIFrame("25%, 25%, 25%, 25%"); - } - }, true); - - sendAsyncMessage("ss-test:createDynamicFrames"); -}); - -addMessageListener("ss-test:removeLastFrame", function ({data}) { - let frames = content.document.getElementById(data.id); - frames.lastElementChild.remove(); - sendAsyncMessage("ss-test:removeLastFrame"); -}); - -addMessageListener("ss-test:mapFrameTree", function (msg) { - let result = gFrameTree.map(frame => ({href: frame.location.href})); - sendAsyncMessage("ss-test:mapFrameTree", result); -}); - -addMessageListener("ss-test:click", function ({data}) { - content.document.getElementById(data.id).click(); - sendAsyncMessage("ss-test:click"); -}); - -addEventListener("load", function(event) { - let subframe = event.target != content.document; - sendAsyncMessage("ss-test:loadEvent", {subframe: subframe, url: event.target.documentURI}); -}, true); diff --git a/browser/components/sessionstore/test/head.js b/browser/components/sessionstore/test/head.js deleted file mode 100644 index 5a8c5dbfc..000000000 --- a/browser/components/sessionstore/test/head.js +++ /dev/null @@ -1,564 +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 TAB_STATE_NEEDS_RESTORE = 1; -const TAB_STATE_RESTORING = 2; - -const ROOT = getRootDirectory(gTestPath); -const HTTPROOT = ROOT.replace("chrome://mochitests/content/", "http://example.com/"); -const FRAME_SCRIPTS = [ - ROOT + "content.js", - ROOT + "content-forms.js" -]; - -var mm = Cc["@mozilla.org/globalmessagemanager;1"] - .getService(Ci.nsIMessageListenerManager); - -for (let script of FRAME_SCRIPTS) { - mm.loadFrameScript(script, true); -} - -registerCleanupFunction(() => { - for (let script of FRAME_SCRIPTS) { - mm.removeDelayedFrameScript(script, true); - } -}); - -const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {}); -const {SessionStore} = Cu.import("resource:///modules/sessionstore/SessionStore.jsm", {}); -const {SessionSaver} = Cu.import("resource:///modules/sessionstore/SessionSaver.jsm", {}); -const {SessionFile} = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {}); -const {TabState} = Cu.import("resource:///modules/sessionstore/TabState.jsm", {}); -const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {}); - -const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore); - -// Some tests here assume that all restored tabs are loaded without waiting for -// the user to bring them to the foreground. We ensure this by resetting the -// related preference (see the "firefox.js" defaults file for details). -Services.prefs.setBoolPref("browser.sessionstore.restore_on_demand", false); -registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.restore_on_demand"); -}); - -// Obtain access to internals -Services.prefs.setBoolPref("browser.sessionstore.debug", true); -registerCleanupFunction(function () { - Services.prefs.clearUserPref("browser.sessionstore.debug"); -}); - - -// This kicks off the search service used on about:home and allows the -// session restore tests to be run standalone without triggering errors. -Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler).defaultArgs; - -function provideWindow(aCallback, aURL, aFeatures) { - function callbackSoon(aWindow) { - executeSoon(function executeCallbackSoon() { - aCallback(aWindow); - }); - } - - let win = openDialog(getBrowserURL(), "", aFeatures || "chrome,all,dialog=no", aURL || "about:blank"); - whenWindowLoaded(win, function onWindowLoaded(aWin) { - if (!aURL) { - info("Loaded a blank window."); - callbackSoon(aWin); - return; - } - - aWin.gBrowser.selectedBrowser.addEventListener("load", function selectedBrowserLoadListener() { - aWin.gBrowser.selectedBrowser.removeEventListener("load", selectedBrowserLoadListener, true); - callbackSoon(aWin); - }, true); - }); -} - -// This assumes that tests will at least have some state/entries -function waitForBrowserState(aState, aSetStateCallback) { - if (typeof aState == "string") { - aState = JSON.parse(aState); - } - if (typeof aState != "object") { - throw new TypeError("Argument must be an object or a JSON representation of an object"); - } - let windows = [window]; - let tabsRestored = 0; - let expectedTabsRestored = 0; - let expectedWindows = aState.windows.length; - let windowsOpen = 1; - let listening = false; - let windowObserving = false; - let restoreHiddenTabs = Services.prefs.getBoolPref( - "browser.sessionstore.restore_hidden_tabs"); - - aState.windows.forEach(function (winState) { - winState.tabs.forEach(function (tabState) { - if (restoreHiddenTabs || !tabState.hidden) - expectedTabsRestored++; - }); - }); - - // There must be only hidden tabs and restoreHiddenTabs = false. We still - // expect one of them to be restored because it gets shown automatically. - if (!expectedTabsRestored) - expectedTabsRestored = 1; - - function onSSTabRestored(aEvent) { - if (++tabsRestored == expectedTabsRestored) { - // Remove the event listener from each window - windows.forEach(function(win) { - win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true); - }); - listening = false; - info("running " + aSetStateCallback.name); - executeSoon(aSetStateCallback); - } - } - - // Used to add our listener to further windows so we can catch SSTabRestored - // coming from them when creating a multi-window state. - function windowObserver(aSubject, aTopic, aData) { - if (aTopic == "domwindowopened") { - let newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow); - newWindow.addEventListener("load", function() { - newWindow.removeEventListener("load", arguments.callee, false); - - if (++windowsOpen == expectedWindows) { - Services.ww.unregisterNotification(windowObserver); - windowObserving = false; - } - - // Track this window so we can remove the progress listener later - windows.push(newWindow); - // Add the progress listener - newWindow.gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true); - }, false); - } - } - - // We only want to register the notification if we expect more than 1 window - if (expectedWindows > 1) { - registerCleanupFunction(function() { - if (windowObserving) { - Services.ww.unregisterNotification(windowObserver); - } - }); - windowObserving = true; - Services.ww.registerNotification(windowObserver); - } - - registerCleanupFunction(function() { - if (listening) { - windows.forEach(function(win) { - win.gBrowser.tabContainer.removeEventListener("SSTabRestored", onSSTabRestored, true); - }); - } - }); - // Add the event listener for this window as well. - listening = true; - gBrowser.tabContainer.addEventListener("SSTabRestored", onSSTabRestored, true); - - // Ensure setBrowserState() doesn't remove the initial tab. - gBrowser.selectedTab = gBrowser.tabs[0]; - - // Finally, call setBrowserState - ss.setBrowserState(JSON.stringify(aState)); -} - -function promiseBrowserState(aState) { - return new Promise(resolve => waitForBrowserState(aState, resolve)); -} - -function promiseTabState(tab, state) { - if (typeof(state) != "string") { - state = JSON.stringify(state); - } - - let promise = promiseTabRestored(tab); - ss.setTabState(tab, state); - return promise; -} - -/** - * Wait for a content -> chrome message. - */ -function promiseContentMessage(browser, name) { - let mm = browser.messageManager; - - return new Promise(resolve => { - function removeListener() { - mm.removeMessageListener(name, listener); - } - - function listener(msg) { - removeListener(); - resolve(msg.data); - } - - mm.addMessageListener(name, listener); - registerCleanupFunction(removeListener); - }); -} - -function waitForTopic(aTopic, aTimeout, aCallback) { - let observing = false; - function removeObserver() { - if (!observing) - return; - Services.obs.removeObserver(observer, aTopic); - observing = false; - } - - let timeout = setTimeout(function () { - removeObserver(); - aCallback(false); - }, aTimeout); - - function observer(aSubject, aTopic, aData) { - removeObserver(); - timeout = clearTimeout(timeout); - executeSoon(() => aCallback(true)); - } - - registerCleanupFunction(function() { - removeObserver(); - if (timeout) { - clearTimeout(timeout); - } - }); - - observing = true; - Services.obs.addObserver(observer, aTopic, false); -} - -/** - * Wait until session restore has finished collecting its data and is - * has written that data ("sessionstore-state-write-complete"). - * - * @param {function} aCallback If sessionstore-state-write-complete is sent - * within buffering interval + 100 ms, the callback is passed |true|, - * otherwise, it is passed |false|. - */ -function waitForSaveState(aCallback) { - let timeout = 100 + - Services.prefs.getIntPref("browser.sessionstore.interval"); - return waitForTopic("sessionstore-state-write-complete", timeout, aCallback); -} -function promiseSaveState() { - return new Promise(resolve => { - waitForSaveState(isSuccessful => { - if (!isSuccessful) { - throw new Error("timeout"); - } - - resolve(); - }); - }); -} -function forceSaveState() { - return SessionSaver.run(); -} - -function promiseRecoveryFileContents() { - let promise = forceSaveState(); - return promise.then(function() { - return OS.File.read(SessionFile.Paths.recovery, { encoding: "utf-8" }); - }); -} - -var promiseForEachSessionRestoreFile = Task.async(function*(cb) { - for (let key of SessionFile.Paths.loadOrder) { - let data = ""; - try { - data = yield OS.File.read(SessionFile.Paths[key], { encoding: "utf-8" }); - } catch (ex) { - // Ignore missing files - if (!(ex instanceof OS.File.Error && ex.becauseNoSuchFile)) { - throw ex; - } - } - cb(data, key); - } -}); - -function promiseBrowserLoaded(aBrowser, ignoreSubFrames = true, wantLoad = null) { - return BrowserTestUtils.browserLoaded(aBrowser, !ignoreSubFrames, wantLoad); -} - -function whenWindowLoaded(aWindow, aCallback = next) { - aWindow.addEventListener("load", function windowLoadListener() { - aWindow.removeEventListener("load", windowLoadListener, false); - executeSoon(function executeWhenWindowLoaded() { - aCallback(aWindow); - }); - }, false); -} -function promiseWindowLoaded(aWindow) { - return new Promise(resolve => whenWindowLoaded(aWindow, resolve)); -} - -var gUniqueCounter = 0; -function r() { - return Date.now() + "-" + (++gUniqueCounter); -} - -function* BrowserWindowIterator() { - let windowsEnum = Services.wm.getEnumerator("navigator:browser"); - while (windowsEnum.hasMoreElements()) { - let currentWindow = windowsEnum.getNext(); - if (!currentWindow.closed) { - yield currentWindow; - } - } -} - -var gWebProgressListener = { - _callback: null, - - setCallback: function (aCallback) { - if (!this._callback) { - window.gBrowser.addTabsProgressListener(this); - } - this._callback = aCallback; - }, - - unsetCallback: function () { - if (this._callback) { - this._callback = null; - window.gBrowser.removeTabsProgressListener(this); - } - }, - - onStateChange: function (aBrowser, aWebProgress, aRequest, - aStateFlags, aStatus) { - if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && - aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && - aStateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) { - this._callback(aBrowser); - } - } -}; - -registerCleanupFunction(function () { - gWebProgressListener.unsetCallback(); -}); - -var gProgressListener = { - _callback: null, - - setCallback: function (callback) { - Services.obs.addObserver(this, "sessionstore-debug-tab-restored", false); - this._callback = callback; - }, - - unsetCallback: function () { - if (this._callback) { - this._callback = null; - Services.obs.removeObserver(this, "sessionstore-debug-tab-restored"); - } - }, - - observe: function (browser, topic, data) { - gProgressListener.onRestored(browser); - }, - - onRestored: function (browser) { - if (browser.__SS_restoreState == TAB_STATE_RESTORING) { - let args = [browser].concat(gProgressListener._countTabs()); - gProgressListener._callback.apply(gProgressListener, args); - } - }, - - _countTabs: function () { - let needsRestore = 0, isRestoring = 0, wasRestored = 0; - - for (let win of BrowserWindowIterator()) { - for (let i = 0; i < win.gBrowser.tabs.length; i++) { - let browser = win.gBrowser.tabs[i].linkedBrowser; - if (!browser.__SS_restoreState) - wasRestored++; - else if (browser.__SS_restoreState == TAB_STATE_RESTORING) - isRestoring++; - else if (browser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) - needsRestore++; - } - } - return [needsRestore, isRestoring, wasRestored]; - } -}; - -registerCleanupFunction(function () { - gProgressListener.unsetCallback(); -}); - -// Close all but our primary window. -function promiseAllButPrimaryWindowClosed() { - let windows = []; - for (let win of BrowserWindowIterator()) { - if (win != window) { - windows.push(win); - } - } - - return Promise.all(windows.map(BrowserTestUtils.closeWindow)); -} - -// Forget all closed windows. -function forgetClosedWindows() { - while (ss.getClosedWindowCount() > 0) { - ss.forgetClosedWindow(0); - } -} - -/** - * When opening a new window it is not sufficient to wait for its load event. - * We need to use whenDelayedStartupFinshed() here as the browser window's - * delayedStartup() routine is executed one tick after the window's load event - * has been dispatched. browser-delayed-startup-finished might be deferred even - * further if parts of the window's initialization process take more time than - * expected (e.g. reading a big session state from disk). - */ -function whenNewWindowLoaded(aOptions, aCallback) { - let features = ""; - let url = "about:blank"; - - if (aOptions && aOptions.private || false) { - features = ",private"; - url = "about:privatebrowsing"; - } - - let win = openDialog(getBrowserURL(), "", "chrome,all,dialog=no" + features, url); - let delayedStartup = promiseDelayedStartupFinished(win); - - let browserLoaded = new Promise(resolve => { - if (url == "about:blank") { - resolve(); - return; - } - - win.addEventListener("load", function onLoad() { - win.removeEventListener("load", onLoad); - let browser = win.gBrowser.selectedBrowser; - promiseBrowserLoaded(browser).then(resolve); - }); - }); - - Promise.all([delayedStartup, browserLoaded]).then(() => aCallback(win)); -} -function promiseNewWindowLoaded(aOptions) { - return new Promise(resolve => whenNewWindowLoaded(aOptions, resolve)); -} - -/** - * This waits for the browser-delayed-startup-finished notification of a given - * window. It indicates that the windows has loaded completely and is ready to - * be used for testing. - */ -function whenDelayedStartupFinished(aWindow, aCallback) { - Services.obs.addObserver(function observer(aSubject, aTopic) { - if (aWindow == aSubject) { - Services.obs.removeObserver(observer, aTopic); - executeSoon(aCallback); - } - }, "browser-delayed-startup-finished", false); -} -function promiseDelayedStartupFinished(aWindow) { - return new Promise(resolve => whenDelayedStartupFinished(aWindow, resolve)); -} - -function promiseEvent(element, eventType, isCapturing = false) { - return new Promise(resolve => { - element.addEventListener(eventType, function listener(event) { - element.removeEventListener(eventType, listener, isCapturing); - resolve(event); - }, isCapturing); - }); -} - -function promiseTabRestored(tab) { - return promiseEvent(tab, "SSTabRestored"); -} - -function promiseTabRestoring(tab) { - return promiseEvent(tab, "SSTabRestoring"); -} - -function sendMessage(browser, name, data = {}) { - browser.messageManager.sendAsyncMessage(name, data); - return promiseContentMessage(browser, name); -} - -// This creates list of functions that we will map to their corresponding -// ss-test:* messages names. Those will be sent to the frame script and -// be used to read and modify form data. -const FORM_HELPERS = [ - "getTextContent", - "getInputValue", "setInputValue", - "getInputChecked", "setInputChecked", - "getSelectedIndex", "setSelectedIndex", - "getMultipleSelected", "setMultipleSelected", - "getFileNameArray", "setFileNameArray", -]; - -for (let name of FORM_HELPERS) { - let msg = "ss-test:" + name; - this[name] = (browser, data) => sendMessage(browser, msg, data); -} - -// Removes the given tab immediately and returns a promise that resolves when -// all pending status updates (messages) of the closing tab have been received. -function promiseRemoveTab(tab) { - return BrowserTestUtils.removeTab(tab); -} - -// Write DOMSessionStorage data to the given browser. -function modifySessionStorage(browser, data, options = {}) { - return ContentTask.spawn(browser, [data, options], function* ([data, options]) { - let frame = content; - if (options && "frameIndex" in options) { - frame = content.frames[options.frameIndex]; - } - - let keys = new Set(Object.keys(data)); - let storage = frame.sessionStorage; - - return new Promise(resolve => { - addEventListener("MozSessionStorageChanged", function onStorageChanged(event) { - if (event.storageArea == storage) { - keys.delete(event.key); - } - - if (keys.size == 0) { - removeEventListener("MozSessionStorageChanged", onStorageChanged, true); - resolve(); - } - }, true); - - for (let key of keys) { - frame.sessionStorage[key] = data[key]; - } - }); - }); -} - -function pushPrefs(...aPrefs) { - return new Promise(resolve => { - SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve); - }); -} - -function popPrefs() { - return new Promise(resolve => { - SpecialPowers.popPrefEnv(resolve); - }); -} - -function* checkScroll(tab, expected, msg) { - let browser = tab.linkedBrowser; - yield TabStateFlusher.flush(browser); - - let scroll = JSON.parse(ss.getTabState(tab)).scroll || null; - is(JSON.stringify(scroll), JSON.stringify(expected), msg); -} diff --git a/browser/components/sessionstore/test/restore_redirect_http.html b/browser/components/sessionstore/test/restore_redirect_http.html deleted file mode 100644 index e69de29bb..000000000 --- a/browser/components/sessionstore/test/restore_redirect_http.html +++ /dev/null diff --git a/browser/components/sessionstore/test/restore_redirect_http.html^headers^ b/browser/components/sessionstore/test/restore_redirect_http.html^headers^ deleted file mode 100644 index 533bda36f..000000000 --- a/browser/components/sessionstore/test/restore_redirect_http.html^headers^ +++ /dev/null @@ -1,2 +0,0 @@ -HTTP 302 Moved Temporarily -Location: restore_redirect_target.html diff --git a/browser/components/sessionstore/test/restore_redirect_js.html b/browser/components/sessionstore/test/restore_redirect_js.html deleted file mode 100644 index 1f5f0e54c..000000000 --- a/browser/components/sessionstore/test/restore_redirect_js.html +++ /dev/null @@ -1,10 +0,0 @@ -<!DOCTYPE html> - -<html> -<head> -<script> -var newLocation = window.location.toString().replace("restore_redirect_js.html", "restore_redirect_target.html"); -window.location.replace(newLocation); -</script> -</head> -</html>
\ No newline at end of file diff --git a/browser/components/sessionstore/test/restore_redirect_target.html b/browser/components/sessionstore/test/restore_redirect_target.html deleted file mode 100644 index 6c8b3aae5..000000000 --- a/browser/components/sessionstore/test/restore_redirect_target.html +++ /dev/null @@ -1,8 +0,0 @@ -<!DOCTYPE html> - -<html> -<head> -<title>Test page</title> -</head> -<body>Test page</body> -</html> diff --git a/browser/components/sessionstore/test/unit/.eslintrc.js b/browser/components/sessionstore/test/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/sessionstore/test/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json b/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json deleted file mode 100644 index 928de6a39..000000000 --- a/browser/components/sessionstore/test/unit/data/sessionCheckpoints_all.json +++ /dev/null @@ -1 +0,0 @@ -{"profile-after-change":true,"final-ui-startup":true,"sessionstore-windows-restored":true,"quit-application-granted":true,"quit-application":true,"sessionstore-final-state-write-complete":true,"profile-change-net-teardown":true,"profile-change-teardown":true,"profile-before-change":true}
\ No newline at end of file diff --git a/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js b/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js deleted file mode 100644 index a8c3ff2ff..000000000 --- a/browser/components/sessionstore/test/unit/data/sessionstore_invalid.js +++ /dev/null @@ -1,3 +0,0 @@ -{ - "windows": // invalid json -} diff --git a/browser/components/sessionstore/test/unit/data/sessionstore_valid.js b/browser/components/sessionstore/test/unit/data/sessionstore_valid.js deleted file mode 100644 index f9511f29f..000000000 --- a/browser/components/sessionstore/test/unit/data/sessionstore_valid.js +++ /dev/null @@ -1,3 +0,0 @@ -{ - "windows": [] -}
\ No newline at end of file diff --git a/browser/components/sessionstore/test/unit/head.js b/browser/components/sessionstore/test/unit/head.js deleted file mode 100644 index b62856012..000000000 --- a/browser/components/sessionstore/test/unit/head.js +++ /dev/null @@ -1,32 +0,0 @@ -var Cu = Components.utils; -var Cc = Components.classes; -var Ci = Components.interfaces; - -Components.utils.import("resource://gre/modules/Services.jsm"); - -// Call a function once initialization of SessionStartup is complete -function afterSessionStartupInitialization(cb) { - do_print("Waiting for session startup initialization"); - let observer = function() { - try { - do_print("Session startup initialization observed"); - Services.obs.removeObserver(observer, "sessionstore-state-finalized"); - cb(); - } catch (ex) { - do_throw(ex); - } - }; - - // We need the Crash Monitor initialized for sessionstartup to run - // successfully. - Components.utils.import("resource://gre/modules/CrashMonitor.jsm"); - CrashMonitor.init(); - - // Start sessionstartup initialization. - let startup = Cc["@mozilla.org/browser/sessionstartup;1"]. - getService(Ci.nsIObserver); - Services.obs.addObserver(startup, "final-ui-startup", false); - Services.obs.addObserver(startup, "quit-application", false); - Services.obs.notifyObservers(null, "final-ui-startup", ""); - Services.obs.addObserver(observer, "sessionstore-state-finalized", false); -}; diff --git a/browser/components/sessionstore/test/unit/test_backup_once.js b/browser/components/sessionstore/test/unit/test_backup_once.js deleted file mode 100644 index fff34ad58..000000000 --- a/browser/components/sessionstore/test/unit/test_backup_once.js +++ /dev/null @@ -1,130 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var {OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); -var {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); -var {Task} = Cu.import("resource://gre/modules/Task.jsm", {}); -var {SessionWorker} = Cu.import("resource:///modules/sessionstore/SessionWorker.jsm", {}); - -var File = OS.File; -var Paths; -var SessionFile; - -// We need a XULAppInfo to initialize SessionFile -Cu.import("resource://testing-common/AppInfo.jsm", this); -updateAppInfo({ - name: "SessionRestoreTest", - ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}", - version: "1", - platformVersion: "", -}); - -function run_test() { - run_next_test(); -} - -add_task(function* init() { - // Make sure that we have a profile before initializing SessionFile - let profd = do_get_profile(); - SessionFile = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {}).SessionFile; - Paths = SessionFile.Paths; - - - let source = do_get_file("data/sessionstore_valid.js"); - source.copyTo(profd, "sessionstore.js"); - - // Finish initialization of SessionFile - yield SessionFile.read(); -}); - -var pathStore; -var pathBackup; -var decoder; - -function promise_check_exist(path, shouldExist) { - return Task.spawn(function*() { - do_print("Ensuring that " + path + (shouldExist?" exists":" does not exist")); - if ((yield OS.File.exists(path)) != shouldExist) { - throw new Error("File " + path + " should " + (shouldExist?"exist":"not exist")); - } - }); -} - -function promise_check_contents(path, expect) { - return Task.spawn(function*() { - do_print("Checking whether " + path + " has the right contents"); - let actual = yield OS.File.read(path, { encoding: "utf-8"}); - Assert.deepEqual(JSON.parse(actual), expect, `File ${path} contains the expected data.`); - }); -} - -function generateFileContents(id) { - let url = `http://example.com/test_backup_once#${id}_${Math.random()}`; - return {windows: [{tabs: [{entries: [{url}], index: 1}]}]} -} - -// Write to the store, and check that it creates: -// - $Path.recovery with the new data -// - $Path.nextUpgradeBackup with the old data -add_task(function* test_first_write_backup() { - let initial_content = generateFileContents("initial"); - let new_content = generateFileContents("test_1"); - - do_print("Before the first write, none of the files should exist"); - yield promise_check_exist(Paths.backups, false); - - yield File.makeDir(Paths.backups); - yield File.writeAtomic(Paths.clean, JSON.stringify(initial_content), { encoding: "utf-8" }); - yield SessionFile.write(new_content); - - do_print("After first write, a few files should have been created"); - yield promise_check_exist(Paths.backups, true); - yield promise_check_exist(Paths.clean, false); - yield promise_check_exist(Paths.cleanBackup, true); - yield promise_check_exist(Paths.recovery, true); - yield promise_check_exist(Paths.recoveryBackup, false); - yield promise_check_exist(Paths.nextUpgradeBackup, true); - - yield promise_check_contents(Paths.recovery, new_content); - yield promise_check_contents(Paths.nextUpgradeBackup, initial_content); -}); - -// Write to the store again, and check that -// - $Path.clean is not written -// - $Path.recovery contains the new data -// - $Path.recoveryBackup contains the previous data -add_task(function* test_second_write_no_backup() { - let new_content = generateFileContents("test_2"); - let previous_backup_content = yield File.read(Paths.recovery, { encoding: "utf-8" }); - previous_backup_content = JSON.parse(previous_backup_content); - - yield OS.File.remove(Paths.cleanBackup); - - yield SessionFile.write(new_content); - - yield promise_check_exist(Paths.backups, true); - yield promise_check_exist(Paths.clean, false); - yield promise_check_exist(Paths.cleanBackup, false); - yield promise_check_exist(Paths.recovery, true); - yield promise_check_exist(Paths.nextUpgradeBackup, true); - - yield promise_check_contents(Paths.recovery, new_content); - yield promise_check_contents(Paths.recoveryBackup, previous_backup_content); -}); - -// Make sure that we create $Paths.clean and remove $Paths.recovery* -// upon shutdown -add_task(function* test_shutdown() { - let output = generateFileContents("test_3"); - - yield File.writeAtomic(Paths.recovery, "I should disappear"); - yield File.writeAtomic(Paths.recoveryBackup, "I should also disappear"); - - yield SessionWorker.post("write", [output, { isFinalWrite: true, performShutdownCleanup: true}]); - - do_check_false((yield File.exists(Paths.recovery))); - do_check_false((yield File.exists(Paths.recoveryBackup))); - yield promise_check_contents(Paths.clean, output); -}); diff --git a/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js b/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js deleted file mode 100644 index c7d8b03ed..000000000 --- a/browser/components/sessionstore/test/unit/test_histogram_corrupt_files.js +++ /dev/null @@ -1,114 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/* - * The primary purpose of this test is to ensure that - * the sessionstore component records information about - * corrupted backup files into a histogram. - */ - -"use strict"; -Cu.import("resource://gre/modules/osfile.jsm", this); - -const Telemetry = Services.telemetry; -const Path = OS.Path; -const HistogramId = "FX_SESSION_RESTORE_ALL_FILES_CORRUPT"; - -// Prepare the session file. -var profd = do_get_profile(); -Cu.import("resource:///modules/sessionstore/SessionFile.jsm", this); - -/** - * A utility function for resetting the histogram and the contents - * of the backup directory. - */ -function reset_session(backups = {}) { - - // Reset the histogram. - Telemetry.getHistogramById(HistogramId).clear(); - - // Reset the contents of the backups directory - OS.File.makeDir(SessionFile.Paths.backups); - for (let key of SessionFile.Paths.loadOrder) { - if (backups.hasOwnProperty(key)) { - OS.File.copy(backups[key], SessionFile.Paths[key]); - } else { - OS.File.remove(SessionFile.Paths[key]); - } - } -} - -/** - * In order to use FX_SESSION_RESTORE_ALL_FILES_CORRUPT histogram - * it has to be registered in "toolkit/components/telemetry/Histograms.json". - * This test ensures that the histogram is registered and empty. - */ -add_task(function* test_ensure_histogram_exists_and_empty() { - let s = Telemetry.getHistogramById(HistogramId).snapshot(); - Assert.equal(s.sum, 0, "Initially, the sum of probes is 0"); -}); - -/** - * Makes sure that the histogram is negatively updated when no - * backup files are present. - */ -add_task(function* test_no_files_exist() { - // No session files are available to SessionFile. - reset_session(); - - yield SessionFile.read(); - // Checking if the histogram is updated negatively - let h = Telemetry.getHistogramById(HistogramId); - let s = h.snapshot(); - Assert.equal(s.counts[0], 1, "One probe for the 'false' bucket."); - Assert.equal(s.counts[1], 0, "No probes in the 'true' bucket."); -}); - -/** - * Makes sure that the histogram is negatively updated when at least one - * backup file is not corrupted. - */ -add_task(function* test_one_file_valid() { - // Corrupting some backup files. - let invalidSession = "data/sessionstore_invalid.js"; - let validSession = "data/sessionstore_valid.js"; - reset_session({ - clean : invalidSession, - cleanBackup: validSession, - recovery: invalidSession, - recoveryBackup: invalidSession - }); - - yield SessionFile.read(); - // Checking if the histogram is updated negatively. - let h = Telemetry.getHistogramById(HistogramId); - let s = h.snapshot(); - Assert.equal(s.counts[0], 1, "One probe for the 'false' bucket."); - Assert.equal(s.counts[1], 0, "No probes in the 'true' bucket."); -}); - -/** - * Makes sure that the histogram is positively updated when all - * backup files are corrupted. - */ -add_task(function* test_all_files_corrupt() { - // Corrupting all backup files. - let invalidSession = "data/sessionstore_invalid.js"; - reset_session({ - clean : invalidSession, - cleanBackup: invalidSession, - recovery: invalidSession, - recoveryBackup: invalidSession - }); - - yield SessionFile.read(); - // Checking if the histogram is positively updated. - let h = Telemetry.getHistogramById(HistogramId); - let s = h.snapshot(); - Assert.equal(s.counts[1], 1, "One probe for the 'true' bucket."); - Assert.equal(s.counts[0], 0, "No probes in the 'false' bucket."); -}); - -function run_test() { - run_next_test(); -} diff --git a/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js b/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js deleted file mode 100644 index b99e566e9..000000000 --- a/browser/components/sessionstore/test/unit/test_shutdown_cleanup.js +++ /dev/null @@ -1,127 +0,0 @@ -"use strict"; - -/** - * This test ensures that we correctly clean up the session state before - * writing to disk a last time on shutdown. For now it only tests that each - * tab's shistory is capped to a maximum number of preceding and succeeding - * entries. - */ - -const {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); -const {Task} = Cu.import("resource://gre/modules/Task.jsm", {}); -const {SessionWorker} = Cu.import("resource:///modules/sessionstore/SessionWorker.jsm", {}); - -const profd = do_get_profile(); -const {SessionFile} = Cu.import("resource:///modules/sessionstore/SessionFile.jsm", {}); -const {Paths} = SessionFile; - -const {OS} = Cu.import("resource://gre/modules/osfile.jsm", {}); -const {File} = OS; - -const MAX_ENTRIES = 9; -const URL = "http://example.com/#"; - -// We need a XULAppInfo to initialize SessionFile -Cu.import("resource://testing-common/AppInfo.jsm", this); -updateAppInfo({ - name: "SessionRestoreTest", - ID: "{230de50e-4cd1-11dc-8314-0800200c9a66}", - version: "1", - platformVersion: "", -}); - -add_task(function* setup() { - let source = do_get_file("data/sessionstore_valid.js"); - source.copyTo(profd, "sessionstore.js"); - - // Finish SessionFile initialization. - yield SessionFile.read(); - - // Reset prefs on cleanup. - do_register_cleanup(() => { - Services.prefs.clearUserPref("browser.sessionstore.max_serialize_back"); - Services.prefs.clearUserPref("browser.sessionstore.max_serialize_forward"); - }); -}); - -function createSessionState(index) { - // Generate the tab state entries and set the one-based - // tab-state index to the middle session history entry. - let tabState = {entries: [], index}; - for (let i = 0; i < MAX_ENTRIES; i++) { - tabState.entries.push({url: URL + i}); - } - - return {windows: [{tabs: [tabState]}]}; -} - -function* setMaxBackForward(back, fwd) { - Services.prefs.setIntPref("browser.sessionstore.max_serialize_back", back); - Services.prefs.setIntPref("browser.sessionstore.max_serialize_forward", fwd); - yield SessionFile.read(); -} - -function* writeAndParse(state, path, options = {}) { - yield SessionWorker.post("write", [state, options]); - return JSON.parse(yield File.read(path, {encoding: "utf-8"})); -} - -add_task(function* test_shistory_cap_none() { - let state = createSessionState(5); - - // Don't limit the number of shistory entries. - yield setMaxBackForward(-1, -1); - - // Check that no caps are applied. - let diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true}); - Assert.deepEqual(state, diskState, "no cap applied"); -}); - -add_task(function* test_shistory_cap_middle() { - let state = createSessionState(5); - yield setMaxBackForward(2, 3); - - // Cap is only applied on clean shutdown. - let diskState = yield writeAndParse(state, Paths.recovery); - Assert.deepEqual(state, diskState, "no cap applied"); - - // Check that the right number of shistory entries was discarded - // and the shistory index updated accordingly. - diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true}); - let tabState = state.windows[0].tabs[0]; - tabState.entries = tabState.entries.slice(2, 8); - tabState.index = 3; - Assert.deepEqual(state, diskState, "cap applied"); -}); - -add_task(function* test_shistory_cap_lower_bound() { - let state = createSessionState(1); - yield setMaxBackForward(5, 5); - - // Cap is only applied on clean shutdown. - let diskState = yield writeAndParse(state, Paths.recovery); - Assert.deepEqual(state, diskState, "no cap applied"); - - // Check that the right number of shistory entries was discarded. - diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true}); - let tabState = state.windows[0].tabs[0]; - tabState.entries = tabState.entries.slice(0, 6); - Assert.deepEqual(state, diskState, "cap applied"); -}); - -add_task(function* test_shistory_cap_upper_bound() { - let state = createSessionState(MAX_ENTRIES); - yield setMaxBackForward(5, 5); - - // Cap is only applied on clean shutdown. - let diskState = yield writeAndParse(state, Paths.recovery); - Assert.deepEqual(state, diskState, "no cap applied"); - - // Check that the right number of shistory entries was discarded - // and the shistory index updated accordingly. - diskState = yield writeAndParse(state, Paths.clean, {isFinalWrite: true}); - let tabState = state.windows[0].tabs[0]; - tabState.entries = tabState.entries.slice(3); - tabState.index = 6; - Assert.deepEqual(state, diskState, "cap applied"); -}); diff --git a/browser/components/sessionstore/test/unit/test_startup_invalid_session.js b/browser/components/sessionstore/test/unit/test_startup_invalid_session.js deleted file mode 100644 index 9f6df8585..000000000 --- a/browser/components/sessionstore/test/unit/test_startup_invalid_session.js +++ /dev/null @@ -1,21 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -function run_test() { - let profd = do_get_profile(); - - let sourceSession = do_get_file("data/sessionstore_invalid.js"); - sourceSession.copyTo(profd, "sessionstore.js"); - - let sourceCheckpoints = do_get_file("data/sessionCheckpoints_all.json"); - sourceCheckpoints.copyTo(profd, "sessionCheckpoints.json"); - - do_test_pending(); - let startup = Cc["@mozilla.org/browser/sessionstartup;1"]. - getService(Ci.nsISessionStartup); - - afterSessionStartupInitialization(function cb() { - do_check_eq(startup.sessionType, Ci.nsISessionStartup.NO_SESSION); - do_test_finished(); - }); -} diff --git a/browser/components/sessionstore/test/unit/test_startup_nosession_async.js b/browser/components/sessionstore/test/unit/test_startup_nosession_async.js deleted file mode 100644 index 5185b02d6..000000000 --- a/browser/components/sessionstore/test/unit/test_startup_nosession_async.js +++ /dev/null @@ -1,22 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - - -// Test nsISessionStartup.sessionType in the following scenario: -// - no sessionstore.js; -// - the session store has been loaded, so no need to go -// through the synchronous fallback - -function run_test() { - do_get_profile(); - // Initialize the profile (the session startup uses it) - - do_test_pending(); - let startup = Cc["@mozilla.org/browser/sessionstartup;1"]. - getService(Ci.nsISessionStartup); - - afterSessionStartupInitialization(function cb() { - do_check_eq(startup.sessionType, Ci.nsISessionStartup.NO_SESSION); - do_test_finished(); - }); -}
\ No newline at end of file diff --git a/browser/components/sessionstore/test/unit/test_startup_session_async.js b/browser/components/sessionstore/test/unit/test_startup_session_async.js deleted file mode 100644 index 459acf885..000000000 --- a/browser/components/sessionstore/test/unit/test_startup_session_async.js +++ /dev/null @@ -1,27 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - - -// Test nsISessionStartup.sessionType in the following scenario: -// - valid sessionstore.js; -// - valid sessionCheckpoints.json with all checkpoints; -// - the session store has been loaded - -function run_test() { - let profd = do_get_profile(); - - let sourceSession = do_get_file("data/sessionstore_valid.js"); - sourceSession.copyTo(profd, "sessionstore.js"); - - let sourceCheckpoints = do_get_file("data/sessionCheckpoints_all.json"); - sourceCheckpoints.copyTo(profd, "sessionCheckpoints.json"); - - do_test_pending(); - let startup = Cc["@mozilla.org/browser/sessionstartup;1"]. - getService(Ci.nsISessionStartup); - - afterSessionStartupInitialization(function cb() { - do_check_eq(startup.sessionType, Ci.nsISessionStartup.DEFER_SESSION); - do_test_finished(); - }); -} diff --git a/browser/components/sessionstore/test/unit/xpcshell.ini b/browser/components/sessionstore/test/unit/xpcshell.ini deleted file mode 100644 index 09980f877..000000000 --- a/browser/components/sessionstore/test/unit/xpcshell.ini +++ /dev/null @@ -1,16 +0,0 @@ -[DEFAULT] -head = head.js -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' -support-files = - data/sessionCheckpoints_all.json - data/sessionstore_invalid.js - data/sessionstore_valid.js - -[test_backup_once.js] -[test_histogram_corrupt_files.js] -[test_shutdown_cleanup.js] -[test_startup_nosession_async.js] -[test_startup_session_async.js] -[test_startup_invalid_session.js] diff --git a/browser/components/shell/test/.eslintrc.js b/browser/components/shell/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/shell/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/shell/test/browser.ini b/browser/components/shell/test/browser.ini deleted file mode 100644 index 8f18415c0..000000000 --- a/browser/components/shell/test/browser.ini +++ /dev/null @@ -1,6 +0,0 @@ -[DEFAULT] -skip-if = os != "linux" - -[browser_420786.js] -[browser_633221.js] - diff --git a/browser/components/shell/test/browser_420786.js b/browser/components/shell/test/browser_420786.js deleted file mode 100644 index ae4521890..000000000 --- a/browser/components/shell/test/browser_420786.js +++ /dev/null @@ -1,88 +0,0 @@ -const DG_BACKGROUND = "/desktop/gnome/background" -const DG_IMAGE_KEY = DG_BACKGROUND + "/picture_filename"; -const DG_OPTION_KEY = DG_BACKGROUND + "/picture_options"; -const DG_DRAW_BG_KEY = DG_BACKGROUND + "/draw_background"; - -function onPageLoad() { - gBrowser.selectedBrowser.removeEventListener("load", onPageLoad, true); - - var bs = Cc["@mozilla.org/intl/stringbundle;1"]. - getService(Ci.nsIStringBundleService); - var brandName = bs.createBundle("chrome://branding/locale/brand.properties"). - GetStringFromName("brandShortName"); - - var dirSvc = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIDirectoryServiceProvider); - var homeDir = dirSvc.getFile("Home", {}); - - var wpFile = homeDir.clone(); - wpFile.append(brandName + "_wallpaper.png"); - - // Backup the existing wallpaper so that this test doesn't change the user's - // settings. - var wpFileBackup = homeDir.clone() - wpFileBackup.append(brandName + "_wallpaper.png.backup"); - - if (wpFileBackup.exists()) - wpFileBackup.remove(false); - - if (wpFile.exists()) - wpFile.copyTo(null, wpFileBackup.leafName); - - var shell = Cc["@mozilla.org/browser/shell-service;1"]. - getService(Ci.nsIShellService); - var gconf = Cc["@mozilla.org/gnome-gconf-service;1"]. - getService(Ci.nsIGConfService); - - var prevImageKey = gconf.getString(DG_IMAGE_KEY); - var prevOptionKey = gconf.getString(DG_OPTION_KEY); - var prevDrawBgKey = gconf.getBool(DG_DRAW_BG_KEY); - - var image = content.document.images[0]; - - function checkWallpaper(position, expectedGConfPosition) { - shell.setDesktopBackground(image, position); - ok(wpFile.exists(), "Wallpaper was written to disk"); - is(gconf.getString(DG_IMAGE_KEY), wpFile.path, - "Wallpaper file GConf key is correct"); - is(gconf.getString(DG_OPTION_KEY), expectedGConfPosition, - "Wallpaper position GConf key is correct"); - } - - checkWallpaper(Ci.nsIShellService.BACKGROUND_TILE, "wallpaper"); - checkWallpaper(Ci.nsIShellService.BACKGROUND_STRETCH, "stretched"); - checkWallpaper(Ci.nsIShellService.BACKGROUND_CENTER, "centered"); - checkWallpaper(Ci.nsIShellService.BACKGROUND_FILL, "zoom"); - checkWallpaper(Ci.nsIShellService.BACKGROUND_FIT, "scaled"); - - // Restore GConf and wallpaper - - gconf.setString(DG_IMAGE_KEY, prevImageKey); - gconf.setString(DG_OPTION_KEY, prevOptionKey); - gconf.setBool(DG_DRAW_BG_KEY, prevDrawBgKey); - - wpFile.remove(false); - if (wpFileBackup.exists()) - wpFileBackup.moveTo(null, wpFile.leafName); - - gBrowser.removeCurrentTab(); - finish(); -} - -function test() { - try { - // If GSettings is available, then the GConf tests - // will fail - Cc["@mozilla.org/gsettings-service;1"]. - getService(Ci.nsIGSettingsService). - getCollectionForSchema("org.gnome.desktop.background"); - todo(false, "This test doesn't work when GSettings is available"); - return; - } catch (e) { } - - gBrowser.selectedTab = gBrowser.addTab(); - gBrowser.selectedBrowser.addEventListener("load", onPageLoad, true); - content.location = "about:logo"; - - waitForExplicitFinish(); -} diff --git a/browser/components/shell/test/browser_633221.js b/browser/components/shell/test/browser_633221.js deleted file mode 100644 index 7929e8098..000000000 --- a/browser/components/shell/test/browser_633221.js +++ /dev/null @@ -1,7 +0,0 @@ -Components.utils.import("resource:///modules/ShellService.jsm"); - -function test() { - ShellService.setDefaultBrowser(true, false); - ok(ShellService.isDefaultBrowser(true, false), "we got here and are the default browser"); - ok(ShellService.isDefaultBrowser(true, true), "we got here and are the default browser"); -} diff --git a/browser/components/shell/test/unit/.eslintrc.js b/browser/components/shell/test/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/shell/test/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/shell/test/unit/test_421977.js b/browser/components/shell/test/unit/test_421977.js deleted file mode 100644 index 637db4b91..000000000 --- a/browser/components/shell/test/unit/test_421977.js +++ /dev/null @@ -1,123 +0,0 @@ -var Cc = Components.classes; -var Ci = Components.interfaces; -var Cr = Components.results; - -const GCONF_BG_COLOR_KEY = "/desktop/gnome/background/primary_color"; - -var gShell; -var gGConf; - -/** - * Converts from a rgb numerical color valule (r << 16 | g << 8 | b) - * into a hex string in #RRGGBB format. - */ -function colorToHex(aColor) { - const rMask = 4294901760; - const gMask = 65280; - const bMask = 255; - - var r = (aColor & rMask) >> 16; - var g = (aColor & gMask) >> 8; - var b = (aColor & bMask); - - return "#" + [r, g, b].map(aInt => - aInt.toString(16).replace(/^(.)$/, "0$1")) - .join("").toUpperCase(); -} - -/** - * Converts a color string in #RRGGBB format to a rgb numerical color value - * (r << 16 | g << 8 | b). - */ -function hexToColor(aString) { - return parseInt(aString.substring(1, 3), 16) << 16 | - parseInt(aString.substring(3, 5), 16) << 8 | - parseInt(aString.substring(5, 7), 16); -} - -/** - * Checks that setting the GConf background key to aGConfColor will - * result in the Shell component returning a background color equals - * to aExpectedShellColor in #RRGGBB format. - */ -function checkGConfToShellColor(aGConfColor, aExpectedShellColor) { - - gGConf.setString(GCONF_BG_COLOR_KEY, aGConfColor); - var shellColor = colorToHex(gShell.desktopBackgroundColor); - - do_check_eq(shellColor, aExpectedShellColor); -} - -/** - * Checks that setting the background color (in #RRGGBB format) using the Shell - * component will result in having a GConf key for the background color set to - * aExpectedGConfColor. - */ -function checkShellToGConfColor(aShellColor, aExpectedGConfColor) { - - gShell.desktopBackgroundColor = hexToColor(aShellColor); - var gconfColor = gGConf.getString(GCONF_BG_COLOR_KEY); - - do_check_eq(gconfColor, aExpectedGConfColor); -} - -function run_test() { - - // This test is Linux specific for now - if (!("@mozilla.org/gnome-gconf-service;1" in Cc)) - return; - - try { - // If GSettings is available, then the GConf tests - // will fail - Cc["@mozilla.org/gsettings-service;1"]. - getService(Ci.nsIGSettingsService). - getCollectionForSchema("org.gnome.desktop.background"); - return; - } catch (e) { } - - gGConf = Cc["@mozilla.org/gnome-gconf-service;1"]. - getService(Ci.nsIGConfService); - - gShell = Cc["@mozilla.org/browser/shell-service;1"]. - getService(Ci.nsIShellService); - - // Save the original background color so that we can restore it - // after the test. - var origGConfColor = gGConf.getString(GCONF_BG_COLOR_KEY); - - try { - - checkGConfToShellColor("#000", "#000000"); - checkGConfToShellColor("#00f", "#0000FF"); - checkGConfToShellColor("#b2f", "#BB22FF"); - checkGConfToShellColor("#fff", "#FFFFFF"); - - checkGConfToShellColor("#000000", "#000000"); - checkGConfToShellColor("#0000ff", "#0000FF"); - checkGConfToShellColor("#b002f0", "#B002F0"); - checkGConfToShellColor("#ffffff", "#FFFFFF"); - - checkGConfToShellColor("#000000000", "#000000"); - checkGConfToShellColor("#00f00f00f", "#000000"); - checkGConfToShellColor("#aaabbbccc", "#AABBCC"); - checkGConfToShellColor("#fffffffff", "#FFFFFF"); - - checkGConfToShellColor("#000000000000", "#000000"); - checkGConfToShellColor("#000f000f000f", "#000000"); - checkGConfToShellColor("#00ff00ff00ff", "#000000"); - checkGConfToShellColor("#aaaabbbbcccc", "#AABBCC"); - checkGConfToShellColor("#111122223333", "#112233"); - checkGConfToShellColor("#ffffffffffff", "#FFFFFF"); - - checkShellToGConfColor("#000000", "#000000000000"); - checkShellToGConfColor("#0000FF", "#00000000ffff"); - checkShellToGConfColor("#FFFFFF", "#ffffffffffff"); - checkShellToGConfColor("#0A0B0C", "#0a0a0b0b0c0c"); - checkShellToGConfColor("#A0B0C0", "#a0a0b0b0c0c0"); - checkShellToGConfColor("#AABBCC", "#aaaabbbbcccc"); - - } finally { - gGConf.setString(GCONF_BG_COLOR_KEY, origGConfColor); - } -} diff --git a/browser/components/shell/test/unit/xpcshell.ini b/browser/components/shell/test/unit/xpcshell.ini deleted file mode 100644 index be00037e0..000000000 --- a/browser/components/shell/test/unit/xpcshell.ini +++ /dev/null @@ -1,7 +0,0 @@ -[DEFAULT] -head = -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_421977.js] diff --git a/browser/components/syncedtabs/test/browser/.eslintrc.js b/browser/components/syncedtabs/test/browser/.eslintrc.js deleted file mode 100644 index 7c8021192..000000000 --- a/browser/components/syncedtabs/test/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/syncedtabs/test/browser/browser.ini b/browser/components/syncedtabs/test/browser/browser.ini deleted file mode 100644 index 02fa364f1..000000000 --- a/browser/components/syncedtabs/test/browser/browser.ini +++ /dev/null @@ -1,4 +0,0 @@ -[DEFAULT] -support-files = head.js - -[browser_sidebar_syncedtabslist.js] diff --git a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js deleted file mode 100644 index afbc00282..000000000 --- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js +++ /dev/null @@ -1,410 +0,0 @@ -"use strict"; - -const FIXTURE = [ - { - "id": "7cqCr77ptzX3", - "type": "client", - "name": "zcarter's Nightly on MacBook-Pro-25", - "isMobile": false, - "tabs": [ - { - "type": "tab", - "title": "Firefox for Android — Mobile Web browser — More ways to customize and protect your privacy — Mozilla", - "url": "https://www.mozilla.org/en-US/firefox/android/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar", - "icon": "chrome://mozapps/skin/places/defaultFavicon.png", - "client": "7cqCr77ptzX3", - "lastUsed": 1452124677 - } - ] - }, - { - "id": "2xU5h-4bkWqA", - "type": "client", - "name": "laptop", - "isMobile": false, - "tabs": [ - { - "type": "tab", - "title": "Firefox for iOS — Mobile Web browser for your iPhone, iPad and iPod touch — Mozilla", - "url": "https://www.mozilla.org/en-US/firefox/ios/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar", - "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico", - "client": "2xU5h-4bkWqA", - "lastUsed": 1451519425 - }, - { - "type": "tab", - "title": "Firefox Nightly First Run Page", - "url": "https://www.mozilla.org/en-US/firefox/nightly/firstrun/?oldversion=45.0a1", - "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon-nightly.560395bbb2e1.png", - "client": "2xU5h-4bkWqA", - "lastUsed": 1451519420 - }, - { - // Should appear first for this client. - "type": "tab", - "title": "Mozilla Developer Network", - "url": "https://developer.mozilla.org/en-US/", - "icon": "moz-anno:favicon:https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png", - "client": "2xU5h-4bkWqA", - "lastUsed": 1451519725 - } - ] - }, - { - "id": "OL3EJCsdb2JD", - "type": "client", - "name": "desktop", - "isMobile": false, - "tabs": [] - } -]; - -let originalSyncedTabsInternal = null; - -function* testClean() { - let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent; - let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs; - syncedTabsDeckComponent._accountStatus.restore(); - SyncedTabs._internal.getTabClients.restore(); - SyncedTabs._internal = originalSyncedTabsInternal; - - yield new Promise(resolve => { - window.SidebarUI.browser.contentWindow.addEventListener("unload", function listener() { - window.SidebarUI.browser.contentWindow.removeEventListener("unload", listener); - resolve(); - }); - SidebarUI.hide(); - }); -} - -add_task(function* testSyncedTabsSidebarList() { - yield SidebarUI.show('viewTabsSidebar'); - - Assert.equal(SidebarUI.currentID, "viewTabsSidebar", "Sidebar should have SyncedTabs loaded"); - - let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent; - let SyncedTabs = SidebarUI.browser.contentWindow.SyncedTabs; - - Assert.ok(syncedTabsDeckComponent, "component exists"); - - originalSyncedTabsInternal = SyncedTabs._internal; - SyncedTabs._internal = { - isConfiguredToSyncTabs: true, - hasSyncedThisSession: true, - getTabClients() { return Promise.resolve([]) }, - syncTabs() { return Promise.resolve(); }, - }; - - sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true)); - sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {}))); - - yield syncedTabsDeckComponent.updatePanel(); - // This is a hacky way of waiting for the view to render. The view renders - // after the following promise (a different instance of which is triggered - // in updatePanel) resolves, so we wait for it here as well - yield syncedTabsDeckComponent.tabListComponent._store.getData(); - - Assert.ok(SyncedTabs._internal.getTabClients.called, "get clients called"); - - let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - - - Assert.ok(selectedPanel.classList.contains("tabs-container"), - "tabs panel is selected"); - - Assert.equal(selectedPanel.querySelectorAll(".tab").length, 4, - "four tabs listed"); - Assert.equal(selectedPanel.querySelectorAll(".client").length, 3, - "three clients listed"); - Assert.equal(selectedPanel.querySelectorAll(".client")[2].querySelectorAll(".empty").length, 1, - "third client is empty"); - - // Verify that the tabs are sorted by last used time. - var expectedTabIndices = [[0], [2, 0, 1]]; - Array.prototype.forEach.call(selectedPanel.querySelectorAll(".client"), (clientNode, i) => { - checkItem(clientNode, FIXTURE[i]); - Array.prototype.forEach.call(clientNode.querySelectorAll(".tab"), (tabNode, j) => { - let tabIndex = expectedTabIndices[i][j]; - checkItem(tabNode, FIXTURE[i].tabs[tabIndex]); - }); - }); - -}); - -add_task(testClean); - -add_task(function* testSyncedTabsSidebarFilteredList() { - yield SidebarUI.show('viewTabsSidebar'); - let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent; - let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs; - - Assert.ok(syncedTabsDeckComponent, "component exists"); - - originalSyncedTabsInternal = SyncedTabs._internal; - SyncedTabs._internal = { - isConfiguredToSyncTabs: true, - hasSyncedThisSession: true, - getTabClients() { return Promise.resolve([]) }, - syncTabs() { return Promise.resolve(); }, - }; - - sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true)); - sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {}))); - - yield syncedTabsDeckComponent.updatePanel(); - // This is a hacky way of waiting for the view to render. The view renders - // after the following promise (a different instance of which is triggered - // in updatePanel) resolves, so we wait for it here as well - yield syncedTabsDeckComponent.tabListComponent._store.getData(); - - let filterInput = syncedTabsDeckComponent._window.document.querySelector(".tabsFilter"); - filterInput.value = "filter text"; - filterInput.blur(); - - yield syncedTabsDeckComponent.tabListComponent._store.getData("filter text"); - - let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("tabs-container"), - "tabs panel is selected"); - - Assert.equal(selectedPanel.querySelectorAll(".tab").length, 4, - "four tabs listed"); - Assert.equal(selectedPanel.querySelectorAll(".client").length, 0, - "no clients are listed"); - - Assert.equal(filterInput.value, "filter text", - "filter text box has correct value"); - - // Tabs should not be sorted when filter is active. - let FIXTURE_TABS = FIXTURE.reduce((prev, client) => prev.concat(client.tabs), []); - - Array.prototype.forEach.call(selectedPanel.querySelectorAll(".tab"), (tabNode, i) => { - checkItem(tabNode, FIXTURE_TABS[i]); - }); - - // Removing the filter should resort tabs. - FIXTURE_TABS.sort((a, b) => b.lastUsed - a.lastUsed); - yield syncedTabsDeckComponent.tabListComponent._store.getData(); - Array.prototype.forEach.call(selectedPanel.querySelectorAll(".tab"), (tabNode, i) => { - checkItem(tabNode, FIXTURE_TABS[i]); - }); -}); - -add_task(testClean); - -add_task(function* testSyncedTabsSidebarStatus() { - let accountExists = false; - - yield SidebarUI.show('viewTabsSidebar'); - let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent; - let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs; - - originalSyncedTabsInternal = SyncedTabs._internal; - SyncedTabs._internal = { - isConfiguredToSyncTabs: false, - hasSyncedThisSession: false, - getTabClients() {}, - syncTabs() { return Promise.resolve(); }, - }; - - Assert.ok(syncedTabsDeckComponent, "component exists"); - - sinon.spy(syncedTabsDeckComponent, "updatePanel"); - sinon.spy(syncedTabsDeckComponent, "observe"); - - sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.reject("Test error")); - yield syncedTabsDeckComponent.updatePanel(); - - let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("notAuthedInfo"), - "not-authed panel is selected on auth error"); - - syncedTabsDeckComponent._accountStatus.restore(); - sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(accountExists)); - yield syncedTabsDeckComponent.updatePanel(); - selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("notAuthedInfo"), - "not-authed panel is selected"); - - accountExists = true; - yield syncedTabsDeckComponent.updatePanel(); - selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("tabs-disabled"), - "tabs disabled panel is selected"); - - SyncedTabs._internal.isConfiguredToSyncTabs = true; - yield syncedTabsDeckComponent.updatePanel(); - selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("tabs-fetching"), - "tabs fetch panel is selected"); - - SyncedTabs._internal.hasSyncedThisSession = true; - sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve([])); - yield syncedTabsDeckComponent.updatePanel(); - selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("singleDeviceInfo"), - "tabs fetch panel is selected"); - - SyncedTabs._internal.getTabClients.restore(); - sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve([{id: "mock"}])); - yield syncedTabsDeckComponent.updatePanel(); - selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected"); - Assert.ok(selectedPanel.classList.contains("tabs-container"), - "tabs panel is selected"); -}); - -add_task(testClean); - -add_task(function* testSyncedTabsSidebarContextMenu() { - yield SidebarUI.show('viewTabsSidebar'); - let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent; - let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs; - - Assert.ok(syncedTabsDeckComponent, "component exists"); - - originalSyncedTabsInternal = SyncedTabs._internal; - SyncedTabs._internal = { - isConfiguredToSyncTabs: true, - hasSyncedThisSession: true, - getTabClients() { return Promise.resolve([]) }, - syncTabs() { return Promise.resolve(); }, - }; - - sinon.stub(syncedTabsDeckComponent, "_accountStatus", () => Promise.resolve(true)); - sinon.stub(SyncedTabs._internal, "getTabClients", () => Promise.resolve(Cu.cloneInto(FIXTURE, {}))); - - yield syncedTabsDeckComponent.updatePanel(); - // This is a hacky way of waiting for the view to render. The view renders - // after the following promise (a different instance of which is triggered - // in updatePanel) resolves, so we wait for it here as well - yield syncedTabsDeckComponent.tabListComponent._store.getData(); - - info("Right-clicking the search box should show text-related actions"); - let filterMenuItems = [ - "menuitem[cmd=cmd_undo]", - "menuseparator", - // We don't check whether the commands are enabled due to platform - // differences. On OS X and Windows, "cut" and "copy" are always enabled - // for HTML inputs; on Linux, they're only enabled if text is selected. - "menuitem[cmd=cmd_cut]", - "menuitem[cmd=cmd_copy]", - "menuitem[cmd=cmd_paste]", - "menuitem[cmd=cmd_delete]", - "menuseparator", - "menuitem[cmd=cmd_selectAll]", - "menuseparator", - "menuitem#syncedTabsRefreshFilter", - ]; - yield* testContextMenu(syncedTabsDeckComponent, - "#SyncedTabsSidebarTabsFilterContext", - ".tabsFilter", - filterMenuItems); - - info("Right-clicking a tab should show additional actions"); - let tabMenuItems = [ - ["menuitem#syncedTabsOpenSelected", { hidden: false }], - ["menuitem#syncedTabsOpenSelectedInTab", { hidden: false }], - ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: false }], - ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: false }], - ["menuseparator", { hidden: false }], - ["menuitem#syncedTabsBookmarkSelected", { hidden: false }], - ["menuitem#syncedTabsCopySelected", { hidden: false }], - ["menuseparator", { hidden: false }], - ["menuitem#syncedTabsRefresh", { hidden: false }], - ]; - yield* testContextMenu(syncedTabsDeckComponent, - "#SyncedTabsSidebarContext", - "#tab-7cqCr77ptzX3-0", - tabMenuItems); - - info("Right-clicking a client shouldn't show any actions"); - let sidebarMenuItems = [ - ["menuitem#syncedTabsOpenSelected", { hidden: true }], - ["menuitem#syncedTabsOpenSelectedInTab", { hidden: true }], - ["menuitem#syncedTabsOpenSelectedInWindow", { hidden: true }], - ["menuitem#syncedTabsOpenSelectedInPrivateWindow", { hidden: true }], - ["menuseparator", { hidden: true }], - ["menuitem#syncedTabsBookmarkSelected", { hidden: true }], - ["menuitem#syncedTabsCopySelected", { hidden: true }], - ["menuseparator", { hidden: true }], - ["menuitem#syncedTabsRefresh", { hidden: false }], - ]; - yield* testContextMenu(syncedTabsDeckComponent, - "#SyncedTabsSidebarContext", - "#item-OL3EJCsdb2JD", - sidebarMenuItems); -}); - -add_task(testClean); - -function checkItem(node, item) { - Assert.ok(node.classList.contains("item"), - "Node should have .item class"); - if (item.client) { - // tab items - Assert.equal(node.querySelector(".item-title").textContent, item.title, - "Node's title element's text should match item title"); - Assert.ok(node.classList.contains("tab"), - "Node should have .tab class"); - Assert.equal(node.dataset.url, item.url, - "Node's URL should match item URL"); - Assert.equal(node.getAttribute("title"), item.title + "\n" + item.url, - "Tab node should have correct title attribute"); - } else { - // client items - Assert.equal(node.querySelector(".item-title").textContent, item.name, - "Node's title element's text should match client name"); - Assert.ok(node.classList.contains("client"), - "Node should have .client class"); - Assert.equal(node.dataset.id, item.id, - "Node's ID should match item ID"); - } -} - -function* testContextMenu(syncedTabsDeckComponent, contextSelector, triggerSelector, menuSelectors) { - let contextMenu = document.querySelector(contextSelector); - let triggerElement = syncedTabsDeckComponent._window.document.querySelector(triggerSelector); - let isClosed = triggerElement.classList.contains("closed"); - - let promisePopupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); - - let chromeWindow = triggerElement.ownerGlobal.top; - let rect = triggerElement.getBoundingClientRect(); - let contentRect = chromeWindow.SidebarUI.browser.getBoundingClientRect(); - // The offsets in `rect` are relative to the content window, but - // `synthesizeMouseAtPoint` calls `nsIDOMWindowUtils.sendMouseEvent`, - // which interprets the offsets relative to the containing *chrome* window. - // This means we need to account for the width and height of any elements - // outside the `browser` element, like `sidebarheader`. - let offsetX = contentRect.x + rect.x + (rect.width / 2); - let offsetY = contentRect.y + rect.y + (rect.height / 4); - - yield EventUtils.synthesizeMouseAtPoint(offsetX, offsetY, { - type: "contextmenu", - button: 2, - }, chromeWindow); - yield promisePopupShown; - is(triggerElement.classList.contains("closed"), isClosed, - "Showing the context menu shouldn't toggle the tab list"); - checkChildren(contextMenu, menuSelectors); - - let promisePopupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden"); - contextMenu.hidePopup(); - yield promisePopupHidden; -} - -function checkChildren(node, selectors) { - is(node.children.length, selectors.length, "Menu item count doesn't match"); - for (let index = 0; index < node.children.length; index++) { - let child = node.children[index]; - let [selector, props] = [].concat(selectors[index]); - ok(selector, `Node at ${index} should have selector`); - ok(child.matches(selector), `Node ${ - index} should match ${selector}`); - if (props) { - Object.keys(props).forEach(prop => { - is(child[prop], props[prop], `${prop} value at ${index} should match`); - }); - } - } -} diff --git a/browser/components/syncedtabs/test/browser/head.js b/browser/components/syncedtabs/test/browser/head.js deleted file mode 100644 index 40e36123e..000000000 --- a/browser/components/syncedtabs/test/browser/head.js +++ /dev/null @@ -1,19 +0,0 @@ -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); -Cu.import("resource://gre/modules/Promise.jsm"); - - -// Load mocking/stubbing library, sinon -// docs: http://sinonjs.org/docs/ -/* global sinon */ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader); -loader.loadSubScript("resource://testing-common/sinon-1.16.1.js"); - -registerCleanupFunction(function*() { - // Cleanup window or the test runner will throw an error - delete window.sinon; - delete window.setImmediate; - delete window.clearImmediate; -}); diff --git a/browser/components/syncedtabs/test/xpcshell/.eslintrc.js b/browser/components/syncedtabs/test/xpcshell/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/syncedtabs/test/xpcshell/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/syncedtabs/test/xpcshell/head.js b/browser/components/syncedtabs/test/xpcshell/head.js deleted file mode 100644 index 00055231c..000000000 --- a/browser/components/syncedtabs/test/xpcshell/head.js +++ /dev/null @@ -1,29 +0,0 @@ -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); - -XPCOMUtils.defineLazyGetter(this, "FxAccountsCommon", function () { - return Components.utils.import("resource://gre/modules/FxAccountsCommon.js", {}); -}); - -Cu.import("resource://gre/modules/Timer.jsm"); - -do_get_profile(); // fxa needs a profile directory for storage. - -// Create a window polyfill so sinon can load -let window = { - document: {}, - location: {}, - setTimeout: setTimeout, - setInterval: setInterval, - clearTimeout: clearTimeout, - clearinterval: clearInterval -}; -let self = window; - -// Load mocking/stubbing library, sinon -// docs: http://sinonjs.org/docs/ -/* global sinon */ -let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader); -loader.loadSubScript("resource://testing-common/sinon-1.16.1.js"); diff --git a/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js b/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js deleted file mode 100644 index bc73ac621..000000000 --- a/browser/components/syncedtabs/test/xpcshell/test_EventEmitter.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; - -let { EventEmitter } = Cu.import("resource:///modules/syncedtabs/EventEmitter.jsm", {}); - -add_task(function* testSingleListener() { - let eventEmitter = new EventEmitter(); - let spy = sinon.spy(); - - eventEmitter.on("click", spy); - eventEmitter.emit("click", "foo", "bar"); - Assert.ok(spy.calledOnce); - Assert.ok(spy.calledWith("foo", "bar")); - - eventEmitter.off("click", spy); - eventEmitter.emit("click"); - Assert.ok(spy.calledOnce); -}); - -add_task(function* testMultipleListeners() { - let eventEmitter = new EventEmitter(); - let spy1 = sinon.spy(); - let spy2 = sinon.spy(); - - eventEmitter.on("some_event", spy1); - eventEmitter.on("some_event", spy2); - eventEmitter.emit("some_event"); - Assert.ok(spy1.calledOnce); - Assert.ok(spy2.calledOnce); - - eventEmitter.off("some_event", spy1); - eventEmitter.emit("some_event"); - Assert.ok(spy1.calledOnce); - Assert.ok(spy2.calledTwice); -}); - diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js deleted file mode 100644 index 3d748b33c..000000000 --- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckComponent.js +++ /dev/null @@ -1,218 +0,0 @@ -"use strict"; - -let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {}); -let { SyncedTabsDeckComponent } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckComponent.js", {}); -let { TabListComponent } = Cu.import("resource:///modules/syncedtabs/TabListComponent.js", {}); -let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {}); -let { SyncedTabsDeckStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckStore.js", {}); -let { TabListView } = Cu.import("resource:///modules/syncedtabs/TabListView.js", {}); -let { DeckView } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckView.js", {}); - - -add_task(function* testInitUninit() { - let deckStore = new SyncedTabsDeckStore(); - let listComponent = {}; - - let ViewMock = sinon.stub(); - let view = {render: sinon.spy(), destroy: sinon.spy(), container: {}}; - ViewMock.returns(view); - - sinon.stub(SyncedTabs, "syncTabs", () => Promise.resolve()); - - sinon.spy(deckStore, "on"); - sinon.stub(deckStore, "setPanels"); - - let component = new SyncedTabsDeckComponent({ - window, - deckStore, - listComponent, - SyncedTabs, - DeckView: ViewMock, - }); - - sinon.stub(component, "updatePanel"); - - component.init(); - - Assert.ok(SyncedTabs.syncTabs.called); - SyncedTabs.syncTabs.restore(); - - Assert.ok(ViewMock.calledWithNew(), "view is instantiated"); - Assert.equal(ViewMock.args[0][0], window); - Assert.equal(ViewMock.args[0][1], listComponent); - Assert.ok(ViewMock.args[0][2].onAndroidClick, - "view is passed onAndroidClick prop"); - Assert.ok(ViewMock.args[0][2].oniOSClick, - "view is passed oniOSClick prop"); - Assert.ok(ViewMock.args[0][2].onSyncPrefClick, - "view is passed onSyncPrefClick prop"); - - Assert.equal(component.container, view.container, - "component returns view's container"); - - Assert.ok(deckStore.on.calledOnce, "listener is added to store"); - Assert.equal(deckStore.on.args[0][0], "change"); - // Object.values only in nightly - let values = Object.keys(component.PANELS).map(k => component.PANELS[k]); - Assert.ok(deckStore.setPanels.calledWith(values), - "panels are set on deck store"); - - Assert.ok(component.updatePanel.called); - - deckStore.emit("change", "mock state"); - Assert.ok(view.render.calledWith("mock state"), - "view.render is called on state change"); - - component.uninit(); - - Assert.ok(view.destroy.calledOnce, "view is destroyed on uninit"); -}); - - -function waitForObserver() { - return new Promise((resolve, reject) => { - Services.obs.addObserver((subject, topic) => { - resolve(); - }, SyncedTabs.TOPIC_TABS_CHANGED, false); - }); -} - -add_task(function* testObserver() { - let deckStore = new SyncedTabsDeckStore(); - let listStore = new SyncedTabsListStore(SyncedTabs); - let listComponent = {}; - - let ViewMock = sinon.stub(); - let view = {render: sinon.spy(), destroy: sinon.spy(), container: {}}; - ViewMock.returns(view); - - sinon.stub(SyncedTabs, "syncTabs", () => Promise.resolve()); - - sinon.spy(deckStore, "on"); - sinon.stub(deckStore, "setPanels"); - - sinon.stub(listStore, "getData"); - - let component = new SyncedTabsDeckComponent({ - window, - deckStore, - listStore, - listComponent, - SyncedTabs, - DeckView: ViewMock, - }); - - sinon.spy(component, "observe"); - sinon.stub(component, "updatePanel"); - - component.init(); - SyncedTabs.syncTabs.restore(); - Assert.ok(component.updatePanel.called, "triggers panel update during init"); - - Services.obs.notifyObservers(null, SyncedTabs.TOPIC_TABS_CHANGED, ""); - - Assert.ok(component.observe.calledWith(null, SyncedTabs.TOPIC_TABS_CHANGED, ""), - "component is notified"); - - Assert.ok(listStore.getData.called, "gets list data"); - Assert.ok(component.updatePanel.calledTwice, "triggers panel update"); - - Services.obs.notifyObservers(null, FxAccountsCommon.ONLOGIN_NOTIFICATION, ""); - - Assert.ok(component.observe.calledWith(null, FxAccountsCommon.ONLOGIN_NOTIFICATION, ""), - "component is notified of login"); - Assert.equal(component.updatePanel.callCount, 3, "triggers panel update again"); -}); - -add_task(function* testPanelStatus() { - let deckStore = new SyncedTabsDeckStore(); - let listStore = new SyncedTabsListStore(); - let listComponent = {}; - let fxAccounts = { - accountStatus() {} - }; - let SyncedTabsMock = { - getTabClients() {} - }; - - sinon.stub(listStore, "getData"); - - - let component = new SyncedTabsDeckComponent({ - fxAccounts, - deckStore, - listComponent, - SyncedTabs: SyncedTabsMock, - }); - - let isAuthed = false; - sinon.stub(fxAccounts, "accountStatus", () => Promise.resolve(isAuthed)); - let result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.NOT_AUTHED_INFO); - - isAuthed = true; - - SyncedTabsMock.isConfiguredToSyncTabs = false; - result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.TABS_DISABLED); - - SyncedTabsMock.isConfiguredToSyncTabs = true; - - SyncedTabsMock.hasSyncedThisSession = false; - result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.TABS_FETCHING); - - SyncedTabsMock.hasSyncedThisSession = true; - - let clients = []; - sinon.stub(SyncedTabsMock, "getTabClients", () => Promise.resolve(clients)); - result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.SINGLE_DEVICE_INFO); - - clients = ["mock-client"]; - result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.TABS_CONTAINER); - - fxAccounts.accountStatus.restore(); - sinon.stub(fxAccounts, "accountStatus", () => Promise.reject("err")); - result = yield component.getPanelStatus(); - Assert.equal(result, component.PANELS.NOT_AUTHED_INFO); - - sinon.stub(component, "getPanelStatus", () => Promise.resolve("mock-panelId")); - sinon.spy(deckStore, "selectPanel"); - yield component.updatePanel(); - Assert.ok(deckStore.selectPanel.calledWith("mock-panelId")); -}); - -add_task(function* testActions() { - let windowMock = { - openUILink() {}, - }; - let chromeWindowMock = { - gSyncUI: { - openSetup() {} - } - }; - sinon.spy(windowMock, "openUILink"); - sinon.spy(chromeWindowMock.gSyncUI, "openSetup"); - - let getChromeWindowMock = sinon.stub(); - getChromeWindowMock.returns(chromeWindowMock); - - let component = new SyncedTabsDeckComponent({ - window: windowMock, - getChromeWindowMock - }); - - let href = Services.prefs.getCharPref("identity.mobilepromo.android") + "synced-tabs-sidebar"; - component.openAndroidLink("mock-event"); - Assert.ok(windowMock.openUILink.calledWith(href, "mock-event")); - - href = Services.prefs.getCharPref("identity.mobilepromo.ios") + "synced-tabs-sidebar"; - component.openiOSLink("mock-event"); - Assert.ok(windowMock.openUILink.calledWith(href, "mock-event")); - - component.openSyncPrefs(); - Assert.ok(getChromeWindowMock.calledWith(windowMock)); - Assert.ok(chromeWindowMock.gSyncUI.openSetup.called); -}); diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js deleted file mode 100644 index 69abb4024..000000000 --- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsDeckStore.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; - -let { SyncedTabsDeckStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsDeckStore.js", {}); - -add_task(function* testSelectUnkownPanel() { - let deckStore = new SyncedTabsDeckStore(); - let spy = sinon.spy(); - - deckStore.on("change", spy); - deckStore.selectPanel("foo"); - - Assert.ok(!spy.called); -}); - -add_task(function* testSetPanels() { - let deckStore = new SyncedTabsDeckStore(); - let spy = sinon.spy(); - - deckStore.on("change", spy); - deckStore.setPanels(["panel1", "panel2"]); - - Assert.ok(spy.calledWith({ - panels: [ - { id: "panel1", selected: false }, - { id: "panel2", selected: false }, - ], - isUpdatable: false - })); -}); - -add_task(function* testSelectPanel() { - let deckStore = new SyncedTabsDeckStore(); - let spy = sinon.spy(); - - deckStore.setPanels(["panel1", "panel2"]); - - deckStore.on("change", spy); - deckStore.selectPanel("panel2"); - - Assert.ok(spy.calledWith({ - panels: [ - { id: "panel1", selected: false }, - { id: "panel2", selected: true }, - ], - isUpdatable: true - })); - - deckStore.selectPanel("panel2"); - Assert.ok(spy.calledOnce, "doesn't trigger unless panel changes"); -}); - -add_task(function* testSetPanelsSameArray() { - let deckStore = new SyncedTabsDeckStore(); - let spy = sinon.spy(); - deckStore.on("change", spy); - - let panels = ["panel1", "panel2"]; - - deckStore.setPanels(panels); - deckStore.setPanels(panels); - - Assert.ok(spy.calledOnce, "doesn't trigger unless set of panels changes"); -}); - diff --git a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js deleted file mode 100644 index 51580235f..000000000 --- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js +++ /dev/null @@ -1,266 +0,0 @@ -"use strict"; - -let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {}); -let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {}); - -const FIXTURE = [ - { - "id": "2xU5h-4bkWqA", - "type": "client", - "name": "laptop", - "isMobile": false, - "tabs": [ - { - "type": "tab", - "title": "Firefox for iOS — Mobile Web browser for your iPhone, iPad and iPod touch — Mozilla", - "url": "https://www.mozilla.org/en-US/firefox/ios/?utm_source=firefox-browser&utm_medium=firefox-browser&utm_campaign=synced-tabs-sidebar", - "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico", - "client": "2xU5h-4bkWqA", - "lastUsed": 1451519425 - }, - { - "type": "tab", - "title": "Firefox Nightly First Run Page", - "url": "https://www.mozilla.org/en-US/firefox/nightly/firstrun/?oldversion=45.0a1", - "icon": "moz-anno:favicon:https://www.mozilla.org/media/img/firefox/favicon-nightly.560395bbb2e1.png", - "client": "2xU5h-4bkWqA", - "lastUsed": 1451519420 - } - ] - }, - { - "id": "OL3EJCsdb2JD", - "type": "client", - "name": "desktop", - "isMobile": false, - "tabs": [] - } -]; - -add_task(function* testGetDataEmpty() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve([]); - }); - store.on("change", spy); - - yield store.getData(); - - Assert.ok(SyncedTabs.getTabClients.calledWith("")); - Assert.ok(spy.calledWith({ - clients: [], - canUpdateAll: false, - canUpdateInput: false, - filter: "", - inputFocused: false - })); - - yield store.getData("filter"); - - Assert.ok(SyncedTabs.getTabClients.calledWith("filter")); - Assert.ok(spy.calledWith({ - clients: [], - canUpdateAll: false, - canUpdateInput: true, - filter: "filter", - inputFocused: false - })); - - SyncedTabs.getTabClients.restore(); -}); - -add_task(function* testRowSelectionWithoutFilter() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve(FIXTURE); - }); - - yield store.getData(); - SyncedTabs.getTabClients.restore(); - - store.on("change", spy); - - store.selectRow(0, -1); - Assert.ok(spy.args[0][0].canUpdateAll, "can update the whole view"); - Assert.ok(spy.args[0][0].clients[0].selected, "first client is selected"); - - store.moveSelectionUp(); - Assert.ok(spy.calledOnce, - "can't move up past first client, no change triggered"); - - store.selectRow(0, 0); - Assert.ok(spy.args[1][0].clients[0].tabs[0].selected, - "first tab of first client is selected"); - - store.selectRow(0, 0); - Assert.ok(spy.calledTwice, "selecting same row doesn't trigger change"); - - store.selectRow(0, 1); - Assert.ok(spy.args[2][0].clients[0].tabs[1].selected, - "second tab of first client is selected"); - - store.selectRow(1); - Assert.ok(spy.args[3][0].clients[1].selected, "second client is selected"); - - store.moveSelectionDown(); - Assert.equal(spy.callCount, 4, - "can't move selection down past last client, no change triggered"); - - store.moveSelectionUp(); - Assert.equal(spy.callCount, 5, - "changed"); - Assert.ok(spy.args[4][0].clients[0].tabs[FIXTURE[0].tabs.length - 1].selected, - "move selection up from client selects last tab of previous client"); - - store.moveSelectionUp(); - Assert.ok(spy.args[5][0].clients[0].tabs[FIXTURE[0].tabs.length - 2].selected, - "move selection up from tab selects previous tab of client"); -}); - - -add_task(function* testToggleBranches() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve(FIXTURE); - }); - - yield store.getData(); - SyncedTabs.getTabClients.restore(); - - store.selectRow(0); - store.on("change", spy); - - let clientId = FIXTURE[0].id; - store.closeBranch(clientId); - Assert.ok(spy.args[0][0].clients[0].closed, "first client is closed"); - - store.openBranch(clientId); - Assert.ok(!spy.args[1][0].clients[0].closed, "first client is open"); - - store.toggleBranch(clientId); - Assert.ok(spy.args[2][0].clients[0].closed, "first client is toggled closed"); - - store.moveSelectionDown(); - Assert.ok(spy.args[3][0].clients[1].selected, - "selection skips tabs if client is closed"); - - store.moveSelectionUp(); - Assert.ok(spy.args[4][0].clients[0].selected, - "selection skips tabs if client is closed"); -}); - - -add_task(function* testRowSelectionWithFilter() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve(FIXTURE); - }); - - yield store.getData("filter"); - SyncedTabs.getTabClients.restore(); - - store.on("change", spy); - - store.selectRow(0); - Assert.ok(spy.args[0][0].clients[0].tabs[0].selected, "first tab is selected"); - - store.moveSelectionUp(); - Assert.ok(spy.calledOnce, - "can't move up past first tab, no change triggered"); - - store.moveSelectionDown(); - Assert.ok(spy.args[1][0].clients[0].tabs[1].selected, - "selection skips tabs if client is closed"); - - store.moveSelectionDown(); - Assert.equal(spy.callCount, 2, - "can't move selection down past last tab, no change triggered"); - - store.selectRow(1); - Assert.equal(spy.callCount, 2, - "doesn't trigger change if same row selected"); - -}); - - -add_task(function* testFilterAndClearFilter() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve(FIXTURE); - }); - store.on("change", spy); - - yield store.getData("filter"); - - Assert.ok(SyncedTabs.getTabClients.calledWith("filter")); - Assert.ok(!spy.args[0][0].canUpdateAll, "can't update all"); - Assert.ok(spy.args[0][0].canUpdateInput, "can update just input"); - - store.selectRow(0); - - Assert.equal(spy.args[1][0].filter, "filter"); - Assert.ok(spy.args[1][0].clients[0].tabs[0].selected, - "tab is selected"); - - yield store.clearFilter(); - - Assert.ok(SyncedTabs.getTabClients.calledWith("")); - Assert.ok(!spy.args[2][0].canUpdateAll, "can't update all"); - Assert.ok(!spy.args[2][0].canUpdateInput, "can't just update input"); - - Assert.equal(spy.args[2][0].filter, ""); - Assert.ok(!spy.args[2][0].clients[0].tabs[0].selected, - "tab is no longer selected"); - - SyncedTabs.getTabClients.restore(); -}); - -add_task(function* testFocusBlurInput() { - let store = new SyncedTabsListStore(SyncedTabs); - let spy = sinon.spy(); - - sinon.stub(SyncedTabs, "getTabClients", () => { - return Promise.resolve(FIXTURE); - }); - store.on("change", spy); - - yield store.getData(); - SyncedTabs.getTabClients.restore(); - - Assert.ok(!spy.args[0][0].canUpdateAll, "must rerender all"); - - store.selectRow(0); - Assert.ok(!spy.args[1][0].inputFocused, - "input is not focused"); - Assert.ok(spy.args[1][0].clients[0].selected, - "client is selected"); - Assert.ok(spy.args[1][0].clients[0].focused, - "client is focused"); - - store.focusInput(); - Assert.ok(spy.args[2][0].inputFocused, - "input is focused"); - Assert.ok(spy.args[2][0].clients[0].selected, - "client is still selected"); - Assert.ok(!spy.args[2][0].clients[0].focused, - "client is no longer focused"); - - store.blurInput(); - Assert.ok(!spy.args[3][0].inputFocused, - "input is not focused"); - Assert.ok(spy.args[3][0].clients[0].selected, - "client is selected"); - Assert.ok(spy.args[3][0].clients[0].focused, - "client is focused"); -}); - diff --git a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js b/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js deleted file mode 100644 index 0b0665a1b..000000000 --- a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js +++ /dev/null @@ -1,155 +0,0 @@ -"use strict"; - -let { SyncedTabs } = Cu.import("resource://services-sync/SyncedTabs.jsm", {}); -let { TabListComponent } = Cu.import("resource:///modules/syncedtabs/TabListComponent.js", {}); -let { SyncedTabsListStore } = Cu.import("resource:///modules/syncedtabs/SyncedTabsListStore.js", {}); -let { View } = Cu.import("resource:///modules/syncedtabs/TabListView.js", {}); - -const ACTION_METHODS = [ - "onSelectRow", - "onOpenTab", - "onOpenTabs", - "onMoveSelectionDown", - "onMoveSelectionUp", - "onToggleBranch", - "onBookmarkTab", - "onSyncRefresh", - "onFilter", - "onClearFilter", - "onFilterFocus", - "onFilterBlur", -]; - -add_task(function* testInitUninit() { - let store = new SyncedTabsListStore(); - let ViewMock = sinon.stub(); - let view = {render() {}, destroy() {}}; - - ViewMock.returns(view); - - sinon.spy(view, 'render'); - sinon.spy(view, 'destroy'); - - sinon.spy(store, "on"); - sinon.stub(store, "getData"); - sinon.stub(store, "focusInput"); - - let component = new TabListComponent({window, store, View: ViewMock, SyncedTabs}); - - for (let action of ACTION_METHODS) { - sinon.stub(component, action); - } - - component.init(); - - Assert.ok(ViewMock.calledWithNew(), "view is instantiated"); - Assert.ok(store.on.calledOnce, "listener is added to store"); - Assert.equal(store.on.args[0][0], "change"); - Assert.ok(view.render.calledWith({clients: []}), - "render is called on view instance"); - Assert.ok(store.getData.calledOnce, "store gets initial data"); - Assert.ok(store.focusInput.calledOnce, "input field is focused"); - - for (let method of ACTION_METHODS) { - let action = ViewMock.args[0][1][method]; - Assert.ok(action, method + " action is passed to View"); - action("foo", "bar"); - Assert.ok(component[method].calledWith("foo", "bar"), - method + " action passed to View triggers the component method with args"); - } - - store.emit("change", "mock state"); - Assert.ok(view.render.secondCall.calledWith("mock state"), - "view.render is called on state change"); - - component.uninit(); - Assert.ok(view.destroy.calledOnce, "view is destroyed on uninit"); -}); - -add_task(function* testActions() { - let store = new SyncedTabsListStore(); - let chromeWindowMock = { - gBrowser: { - loadTabs() {}, - }, - }; - let getChromeWindowMock = sinon.stub(); - getChromeWindowMock.returns(chromeWindowMock); - let clipboardHelperMock = { - copyString() {}, - }; - let windowMock = { - top: { - PlacesCommandHook: { - bookmarkLink() { return Promise.resolve(); } - }, - PlacesUtils: { bookmarksMenuFolderId: "id" } - }, - getBrowserURL() {}, - openDialog() {}, - openUILinkIn() {} - }; - let component = new TabListComponent({ - window: windowMock, store, View: null, SyncedTabs, - clipboardHelper: clipboardHelperMock, - getChromeWindow: getChromeWindowMock }); - - sinon.stub(store, "getData"); - component.onFilter("query"); - Assert.ok(store.getData.calledWith("query")); - - sinon.stub(store, "clearFilter"); - component.onClearFilter(); - Assert.ok(store.clearFilter.called); - - sinon.stub(store, "focusInput"); - component.onFilterFocus(); - Assert.ok(store.focusInput.called); - - sinon.stub(store, "blurInput"); - component.onFilterBlur(); - Assert.ok(store.blurInput.called); - - sinon.stub(store, "selectRow"); - component.onSelectRow([-1, -1]); - Assert.ok(store.selectRow.calledWith(-1, -1)); - - sinon.stub(store, "moveSelectionDown"); - component.onMoveSelectionDown(); - Assert.ok(store.moveSelectionDown.called); - - sinon.stub(store, "moveSelectionUp"); - component.onMoveSelectionUp(); - Assert.ok(store.moveSelectionUp.called); - - sinon.stub(store, "toggleBranch"); - component.onToggleBranch("foo-id"); - Assert.ok(store.toggleBranch.calledWith("foo-id")); - - sinon.spy(windowMock.top.PlacesCommandHook, "bookmarkLink"); - component.onBookmarkTab("uri", "title"); - Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][1], "uri"); - Assert.equal(windowMock.top.PlacesCommandHook.bookmarkLink.args[0][2], "title"); - - sinon.spy(windowMock, "openUILinkIn"); - component.onOpenTab("uri", "where", "params"); - Assert.ok(windowMock.openUILinkIn.calledWith("uri", "where", "params")); - - sinon.spy(chromeWindowMock.gBrowser, "loadTabs"); - let tabsToOpen = ["uri1", "uri2"]; - component.onOpenTabs(tabsToOpen, "where"); - Assert.ok(getChromeWindowMock.calledWith(windowMock)); - Assert.ok(chromeWindowMock.gBrowser.loadTabs.calledWith(tabsToOpen, false, false)); - component.onOpenTabs(tabsToOpen, "tabshifted"); - Assert.ok(chromeWindowMock.gBrowser.loadTabs.calledWith(tabsToOpen, true, false)); - - sinon.spy(clipboardHelperMock, "copyString"); - component.onCopyTabLocation("uri"); - Assert.ok(clipboardHelperMock.copyString.calledWith("uri")); - - sinon.stub(SyncedTabs, "syncTabs"); - component.onSyncRefresh(); - Assert.ok(SyncedTabs.syncTabs.calledWith(true)); - SyncedTabs.syncTabs.restore(); -}); - diff --git a/browser/components/syncedtabs/test/xpcshell/xpcshell.ini b/browser/components/syncedtabs/test/xpcshell/xpcshell.ini deleted file mode 100644 index 1cb8dcb7a..000000000 --- a/browser/components/syncedtabs/test/xpcshell/xpcshell.ini +++ /dev/null @@ -1,10 +0,0 @@ -[DEFAULT] -head = head.js -tail = -firefox-appdir = browser - -[test_EventEmitter.js] -[test_SyncedTabsDeckStore.js] -[test_SyncedTabsListStore.js] -[test_SyncedTabsDeckComponent.js] -[test_TabListComponent.js] diff --git a/browser/components/tests/browser/.eslintrc.js b/browser/components/tests/browser/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/tests/browser/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/tests/browser/browser.ini b/browser/components/tests/browser/browser.ini deleted file mode 100644 index 6d00b69fa..000000000 --- a/browser/components/tests/browser/browser.ini +++ /dev/null @@ -1,4 +0,0 @@ -[DEFAULT] - -[browser_bug538331.js] -[browser_contentpermissionprompt.js] diff --git a/browser/components/tests/browser/browser_bug538331.js b/browser/components/tests/browser/browser_bug538331.js deleted file mode 100644 index fce3790a0..000000000 --- a/browser/components/tests/browser/browser_bug538331.js +++ /dev/null @@ -1,426 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ts=2 et sw=2 tw=80: */ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ - */ - -const PREF_POSTUPDATE = "app.update.postupdate"; -const PREF_MSTONE = "browser.startup.homepage_override.mstone"; -const PREF_OVERRIDE_URL = "startup.homepage_override_url"; - -const DEFAULT_PREF_URL = "http://pref.example.com/"; -const DEFAULT_UPDATE_URL = "http://example.com/"; - -const XML_EMPTY = "<?xml version=\"1.0\"?><updates xmlns=" + - "\"http://www.mozilla.org/2005/app-update\"></updates>"; - -const XML_PREFIX = "<updates xmlns=\"http://www.mozilla.org/2005/app-update\"" + - "><update appVersion=\"1.0\" buildID=\"20080811053724\" " + - "channel=\"nightly\" displayVersion=\"Version 1.0\" " + - "extensionVersion=\"1.0\" installDate=\"1238441400314\" " + - "isCompleteUpdate=\"true\" name=\"Update Test 1.0\" " + - "serviceURL=\"https://example.com/\" showNeverForVersion=" + - "\"false\" showPrompt=\"false\" type=" + - "\"minor\" version=\"version 1.0\" detailsURL=" + - "\"http://example.com/\" previousAppVersion=\"1.0\" " + - "statusText=\"The Update was successfully installed\" " + - "foregroundDownload=\"true\""; - -const XML_SUFFIX = "><patch type=\"complete\" URL=\"http://example.com/\" " + - "hashFunction=\"MD5\" hashValue=" + - "\"6232cd43a1c77e30191c53a329a3f99d\" size=\"775\" " + - "selected=\"true\" state=\"succeeded\"/></update></updates>"; - -// nsBrowserContentHandler.js defaultArgs tests -const BCH_TESTS = [ - { - description: "no mstone change and no update", - noPostUpdatePref: true, - noMstoneChange: true - }, { - description: "mstone changed and no update", - noPostUpdatePref: true, - prefURL: DEFAULT_PREF_URL - }, { - description: "no mstone change and update with 'showURL' for actions", - actions: "showURL", - noMstoneChange: true - }, { - description: "update without actions", - prefURL: DEFAULT_PREF_URL - }, { - description: "update with 'showURL' for actions", - actions: "showURL", - prefURL: DEFAULT_PREF_URL - }, { - description: "update with 'showURL' for actions and openURL", - actions: "showURL", - openURL: DEFAULT_UPDATE_URL - }, { - description: "update with 'showURL showAlert' for actions", - actions: "showAlert showURL", - prefURL: DEFAULT_PREF_URL - }, { - description: "update with 'showAlert showURL' for actions and openURL", - actions: "showAlert showURL", - openURL: DEFAULT_UPDATE_URL - }, { - description: "update with 'showURL showNotification' for actions", - actions: "showURL showNotification", - prefURL: DEFAULT_PREF_URL - }, { - description: "update with 'showNotification showURL' for actions and " + - "openURL", - actions: "showNotification showURL", - openURL: DEFAULT_UPDATE_URL - }, { - description: "update with 'showAlert showURL showNotification' for actions", - actions: "showAlert showURL showNotification", - prefURL: DEFAULT_PREF_URL - }, { - description: "update with 'showNotification showURL showAlert' for " + - "actions and openURL", - actions: "showNotification showURL showAlert", - openURL: DEFAULT_UPDATE_URL - }, { - description: "update with 'showAlert' for actions", - actions: "showAlert" - }, { - description: "update with 'showAlert showNotification' for actions", - actions: "showAlert showNotification" - }, { - description: "update with 'showNotification' for actions", - actions: "showNotification" - }, { - description: "update with 'showNotification showAlert' for actions", - actions: "showNotification showAlert" - }, { - description: "update with 'silent' for actions", - actions: "silent" - }, { - description: "update with 'silent showURL showAlert showNotification' " + - "for actions and openURL", - actions: "silent showURL showAlert showNotification" - } -]; - -var gOriginalMStone; -var gOriginalOverrideURL; - -this.__defineGetter__("gBG", function() { - delete this.gBG; - return this.gBG = Cc["@mozilla.org/browser/browserglue;1"]. - getService(Ci.nsIObserver); -}); - -function test() -{ - waitForExplicitFinish(); - - // Reset the startup page pref since it may have been set by other tests - // and we will assume it is default. - Services.prefs.clearUserPref('browser.startup.page'); - - if (gPrefService.prefHasUserValue(PREF_MSTONE)) { - gOriginalMStone = gPrefService.getCharPref(PREF_MSTONE); - } - - if (gPrefService.prefHasUserValue(PREF_OVERRIDE_URL)) { - gOriginalOverrideURL = gPrefService.getCharPref(PREF_OVERRIDE_URL); - } - - testDefaultArgs(); -} - -var gWindowCatcher = { - windowsOpen: 0, - finishCalled: false, - start: function() { - Services.ww.registerNotification(this); - }, - - finish: function(aFunc) { - Services.ww.unregisterNotification(this); - this.finishFunc = aFunc; - if (this.windowsOpen > 0) - return; - - this.finishFunc(); - }, - - closeWindow: function (win) { - info("window catcher closing window: " + win.document.documentURI); - win.close(); - this.windowsOpen--; - if (this.finishFunc) { - this.finish(this.finishFunc); - } - }, - - windowLoad: function (win) { - executeSoon(this.closeWindow.bind(this, win)); - }, - - observe: function(subject, topic, data) { - if (topic != "domwindowopened") - return; - - this.windowsOpen++; - let win = subject.QueryInterface(Ci.nsIDOMWindow); - info("window catcher caught window opening: " + win.document.documentURI); - win.addEventListener("load", function () { - win.removeEventListener("load", arguments.callee, false); - gWindowCatcher.windowLoad(win); - }, false); - } -}; - -function finish_test() -{ - // Reset browser.startup.homepage_override.mstone to the original value or - // clear it if it didn't exist. - if (gOriginalMStone) { - gPrefService.setCharPref(PREF_MSTONE, gOriginalMStone); - } else if (gPrefService.prefHasUserValue(PREF_MSTONE)) { - gPrefService.clearUserPref(PREF_MSTONE); - } - - // Reset startup.homepage_override_url to the original value or clear it if - // it didn't exist. - if (gOriginalOverrideURL) { - gPrefService.setCharPref(PREF_OVERRIDE_URL, gOriginalOverrideURL); - } else if (gPrefService.prefHasUserValue(PREF_OVERRIDE_URL)) { - gPrefService.clearUserPref(PREF_OVERRIDE_URL); - } - - writeUpdatesToXMLFile(XML_EMPTY); - reloadUpdateManagerData(); - - finish(); -} - -// Test the defaultArgs returned by nsBrowserContentHandler after an update -function testDefaultArgs() -{ - // Clear any pre-existing override in defaultArgs that are hanging around. - // This will also set the browser.startup.homepage_override.mstone preference - // if it isn't already set. - Cc["@mozilla.org/browser/clh;1"].getService(Ci.nsIBrowserHandler).defaultArgs; - - let originalMstone = gPrefService.getCharPref(PREF_MSTONE); - - gPrefService.setCharPref(PREF_OVERRIDE_URL, DEFAULT_PREF_URL); - - writeUpdatesToXMLFile(XML_EMPTY); - reloadUpdateManagerData(); - - for (let i = 0; i < BCH_TESTS.length; i++) { - let test = BCH_TESTS[i]; - ok(true, "Test nsBrowserContentHandler " + (i + 1) + ": " + test.description); - - if (test.actions) { - let actionsXML = " actions=\"" + test.actions + "\""; - if (test.openURL) { - actionsXML += " openURL=\"" + test.openURL + "\""; - } - writeUpdatesToXMLFile(XML_PREFIX + actionsXML + XML_SUFFIX); - } else { - writeUpdatesToXMLFile(XML_EMPTY); - } - - reloadUpdateManagerData(); - - let noOverrideArgs = Cc["@mozilla.org/browser/clh;1"]. - getService(Ci.nsIBrowserHandler).defaultArgs; - - let overrideArgs = ""; - if (test.prefURL) { - overrideArgs = test.prefURL; - } else if (test.openURL) { - overrideArgs = test.openURL; - } - - if (overrideArgs == "" && noOverrideArgs) { - overrideArgs = noOverrideArgs; - } else if (noOverrideArgs) { - overrideArgs += "|" + noOverrideArgs; - } - - if (test.noMstoneChange === undefined) { - gPrefService.setCharPref(PREF_MSTONE, "PreviousMilestone"); - } - - if (test.noPostUpdatePref == undefined) { - gPrefService.setBoolPref(PREF_POSTUPDATE, true); - } - - let defaultArgs = Cc["@mozilla.org/browser/clh;1"]. - getService(Ci.nsIBrowserHandler).defaultArgs; - is(defaultArgs, overrideArgs, "correct value returned by defaultArgs"); - - if (test.noMstoneChange === undefined || test.noMstoneChange != true) { - let newMstone = gPrefService.getCharPref(PREF_MSTONE); - is(originalMstone, newMstone, "preference " + PREF_MSTONE + - " should have been updated"); - } - - if (gPrefService.prefHasUserValue(PREF_POSTUPDATE)) { - gPrefService.clearUserPref(PREF_POSTUPDATE); - } - } - - testShowNotification(); -} - -// nsBrowserGlue.js _showUpdateNotification notification tests -const BG_NOTIFY_TESTS = [ - { - description: "'silent showNotification' actions should not display a notification", - actions: "silent showNotification" - }, { - description: "'showNotification' for actions should display a notification", - actions: "showNotification" - }, { - description: "no actions and empty updates.xml", - }, { - description: "'showAlert' for actions should not display a notification", - actions: "showAlert" - }, { - // This test MUST be the last test in the array to test opening the url - // provided by the updates.xml. - description: "'showNotification' for actions with custom notification " + - "attributes should display a notification", - actions: "showNotification", - notificationText: "notification text", - notificationURL: DEFAULT_UPDATE_URL, - notificationButtonLabel: "button label", - notificationButtonAccessKey: "b" - } -]; - -// Test showing a notification after an update -// _showUpdateNotification in nsBrowserGlue.js -function testShowNotification() -{ - let notifyBox = document.getElementById("high-priority-global-notificationbox"); - - // Catches any windows opened by these tests (e.g. alert windows) and closes - // them - gWindowCatcher.start(); - - for (let i = 0; i < BG_NOTIFY_TESTS.length; i++) { - let test = BG_NOTIFY_TESTS[i]; - ok(true, "Test showNotification " + (i + 1) + ": " + test.description); - - if (test.actions) { - let actionsXML = " actions=\"" + test.actions + "\""; - if (test.notificationText) { - actionsXML += " notificationText=\"" + test.notificationText + "\""; - } - if (test.notificationURL) { - actionsXML += " notificationURL=\"" + test.notificationURL + "\""; - } - if (test.notificationButtonLabel) { - actionsXML += " notificationButtonLabel=\"" + test.notificationButtonLabel + "\""; - } - if (test.notificationButtonAccessKey) { - actionsXML += " notificationButtonAccessKey=\"" + test.notificationButtonAccessKey + "\""; - } - writeUpdatesToXMLFile(XML_PREFIX + actionsXML + XML_SUFFIX); - } else { - writeUpdatesToXMLFile(XML_EMPTY); - } - - reloadUpdateManagerData(); - gPrefService.setBoolPref(PREF_POSTUPDATE, true); - - gBG.observe(null, "browser-glue-test", "post-update-notification"); - - let updateBox = notifyBox.getNotificationWithValue("post-update-notification"); - if (test.actions && test.actions.indexOf("showNotification") != -1 && - test.actions.indexOf("silent") == -1) { - ok(updateBox, "Update notification box should have been displayed"); - if (updateBox) { - if (test.notificationText) { - is(updateBox.label, test.notificationText, "Update notification box " + - "should have the label provided by the update"); - } - if (test.notificationButtonLabel) { - var button = updateBox.getElementsByTagName("button").item(0); - is(button.label, test.notificationButtonLabel, "Update notification " + - "box button should have the label provided by the update"); - if (test.notificationButtonAccessKey) { - let accessKey = button.getAttribute("accesskey"); - is(accessKey, test.notificationButtonAccessKey, "Update " + - "notification box button should have the accesskey " + - "provided by the update"); - } - } - // The last test opens an url and verifies the url from the updates.xml - // is correct. - if (i == (BG_NOTIFY_TESTS.length - 1)) { - // Wait for any windows caught by the windowcatcher to close - gWindowCatcher.finish(function () { - BrowserTestUtils.waitForNewTab(gBrowser).then(testNotificationURL); - button.click(); - }); - } else { - notifyBox.removeAllNotifications(true); - } - } else if (i == (BG_NOTIFY_TESTS.length - 1)) { - // If updateBox is null the test has already reported errors so bail - finish_test(); - } - } else { - ok(!updateBox, "Update notification box should not have been displayed"); - } - - let prefHasUserValue = gPrefService.prefHasUserValue(PREF_POSTUPDATE); - is(prefHasUserValue, false, "preference " + PREF_POSTUPDATE + - " shouldn't have a user value"); - } -} - -// Test opening the url provided by the updates.xml in the last test -function testNotificationURL() -{ - ok(true, "Test testNotificationURL: clicking the notification button " + - "opened the url specified by the update"); - let href = gBrowser.currentURI.spec; - let expectedURL = BG_NOTIFY_TESTS[BG_NOTIFY_TESTS.length - 1].notificationURL; - is(href, expectedURL, "The url opened from the notification should be the " + - "url provided by the update"); - gBrowser.removeCurrentTab(); - window.focus(); - finish_test(); -} - -/* Reloads the update metadata from disk */ -function reloadUpdateManagerData() -{ - Cc["@mozilla.org/updates/update-manager;1"].getService(Ci.nsIUpdateManager). - QueryInterface(Ci.nsIObserver).observe(null, "um-reload-update-data", ""); -} - - -function writeUpdatesToXMLFile(aText) -{ - const PERMS_FILE = 0o644; - - const MODE_WRONLY = 0x02; - const MODE_CREATE = 0x08; - const MODE_TRUNCATE = 0x20; - - let file = Cc["@mozilla.org/file/directory_service;1"]. - getService(Ci.nsIProperties). - get("UpdRootD", Ci.nsIFile); - file.append("updates.xml"); - let fos = Cc["@mozilla.org/network/file-output-stream;1"]. - createInstance(Ci.nsIFileOutputStream); - if (!file.exists()) { - file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE); - } - fos.init(file, MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE, PERMS_FILE, 0); - fos.write(aText, aText.length); - fos.close(); -} diff --git a/browser/components/tests/browser/browser_contentpermissionprompt.js b/browser/components/tests/browser/browser_contentpermissionprompt.js deleted file mode 100644 index 054aa22e8..000000000 --- a/browser/components/tests/browser/browser_contentpermissionprompt.js +++ /dev/null @@ -1,166 +0,0 @@ -/** - * These tests test nsBrowserGlue's nsIContentPermissionPrompt - * implementation behaviour with various types of - * nsIContentPermissionRequests. - */ - -"use strict"; - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Integration.jsm", this); - -XPCOMUtils.defineLazyServiceGetter(this, "ContentPermissionPrompt", - "@mozilla.org/content-permission/prompt;1", - "nsIContentPermissionPrompt"); - -/** - * This is a partial implementation of nsIContentPermissionType. - * - * @param {string} type - * The string defining what type of permission is being requested. - * Example: "geo", "desktop-notification". - * @return nsIContentPermissionType implementation. - */ -function MockContentPermissionType(type) { - this.type = type; -} - -MockContentPermissionType.prototype = { - QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionType]), - // We expose the wrappedJSObject so that we can be sure - // in some of our tests that we're passing the right - // nsIContentPermissionType around. - wrappedJSObject: this, -}; - -/** - * This is a partial implementation of nsIContentPermissionRequest. - * - * @param {Array<nsIContentPermissionType>} typesArray - * The types to assign to this nsIContentPermissionRequest, - * in order. You probably want to use MockContentPermissionType. - * @return nsIContentPermissionRequest implementation. - */ -function MockContentPermissionRequest(typesArray) { - this.types = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray); - for (let type of typesArray) { - this.types.appendElement(type, false); - } -} - -MockContentPermissionRequest.prototype = { - QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionRequest]), - // We expose the wrappedJSObject so that we can be sure - // in some of our tests that we're passing the right - // nsIContentPermissionRequest around. - wrappedJSObject: this, - // For some of our tests, we want to make sure that the - // request is cancelled, so we add some instrumentation here - // to check that cancel() is called. - cancel() { - this.cancelled = true; - }, - cancelled: false, -}; - -/** - * Tests that if the nsIContentPermissionRequest has an empty - * types array, that NS_ERROR_UNEXPECTED is thrown, and the - * request is cancelled. - */ -add_task(function* test_empty_types() { - let mockRequest = new MockContentPermissionRequest([]); - Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); }, - /NS_ERROR_UNEXPECTED/, - "Should have thrown NS_ERROR_UNEXPECTED."); - Assert.ok(mockRequest.cancelled, "Should have cancelled the request."); -}); - -/** - * Tests that if the nsIContentPermissionRequest has more than - * one type, that NS_ERROR_UNEXPECTED is thrown, and the request - * is cancelled. - */ -add_task(function* test_multiple_types() { - let mockRequest = new MockContentPermissionRequest([ - new MockContentPermissionType("test1"), - new MockContentPermissionType("test2"), - ]); - - Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); }, - /NS_ERROR_UNEXPECTED/); - Assert.ok(mockRequest.cancelled, "Should have cancelled the request."); -}); - -/** - * Tests that if the nsIContentPermissionRequest has a type that - * does not implement nsIContentPermissionType that NS_NOINTERFACE - * is thrown, and the request is cancelled. - */ -add_task(function* test_not_permission_type() { - let mockRequest = new MockContentPermissionRequest([ - { QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports]) }, - ]); - - Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); }, - /NS_NOINTERFACE/); - Assert.ok(mockRequest.cancelled, "Should have cancelled the request."); -}); - -/** - * Tests that if the nsIContentPermissionRequest is for a type - * that is not recognized, that NS_ERROR_FAILURE is thrown and - * the request is cancelled. - */ -add_task(function* test_unrecognized_type() { - let mockRequest = new MockContentPermissionRequest([ - new MockContentPermissionType("test1"), - ]); - - Assert.throws(() => { ContentPermissionPrompt.prompt(mockRequest); }, - /NS_ERROR_FAILURE/); - Assert.ok(mockRequest.cancelled, "Should have cancelled the request."); -}); - -/** - * Tests that if we meet the minimal requirements for a - * nsIContentPermissionRequest, that it will be passed to - * ContentPermissionIntegration's createPermissionPrompt - * method. - */ -add_task(function* test_working_request() { - let mockType = new MockContentPermissionType("test-permission-type"); - let mockRequest = new MockContentPermissionRequest([mockType]); - - // mockPermissionPrompt is what createPermissionPrompt - // will return. Returning some kind of object should be - // enough to convince nsBrowserGlue that everything went - // okay. - let didPrompt = false; - let mockPermissionPrompt = { - prompt() { - didPrompt = true; - } - }; - - let integration = (base) => ({ - createPermissionPrompt(type, request) { - Assert.equal(type, "test-permission-type"); - Assert.ok(Object.is(request.wrappedJSObject, mockRequest.wrappedJSObject)); - return mockPermissionPrompt; - }, - }); - - // Register an integration so that we can capture the - // calls into ContentPermissionIntegration. - try { - Integration.contentPermission.register(integration); - - ContentPermissionPrompt.prompt(mockRequest); - Assert.ok(!mockRequest.cancelled, - "Should not have cancelled the request."); - Assert.ok(didPrompt, "Should have tried to show the prompt"); - } finally { - Integration.contentPermission.unregister(integration); - } -}); diff --git a/browser/components/tests/unit/.eslintrc.js b/browser/components/tests/unit/.eslintrc.js deleted file mode 100644 index fee088c17..000000000 --- a/browser/components/tests/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/tests/unit/data/engine-de-DE.xml b/browser/components/tests/unit/data/engine-de-DE.xml deleted file mode 100644 index b9fa0a464..000000000 --- a/browser/components/tests/unit/data/engine-de-DE.xml +++ /dev/null @@ -1,8 +0,0 @@ -<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/"> -<ShortName>Google</ShortName> -<Description>override-de-DE</Description> -<InputEncoding>UTF-8</InputEncoding> -<Url type="text/html" method="GET" template="http://searchtest.local"> - <Param name="search" value="{searchTerms}"/> -</Url> -</SearchPlugin> diff --git a/browser/components/tests/unit/distribution.ini b/browser/components/tests/unit/distribution.ini deleted file mode 100644 index d7d298808..000000000 --- a/browser/components/tests/unit/distribution.ini +++ /dev/null @@ -1,58 +0,0 @@ -# Distribution Configuration File -# Test of distribution preferences - -[Global] -id=disttest -version=1.0 -about=Test distribution file -about.en-US=TÃ¨Æ¨Æ Î´Ã¯Æ¨ÆřïβúÆïôñ ƒïℓè - -[Preferences] -distribution.test.string="Test String" -distribution.test.string.noquotes=Test String -distribution.test.int=777 -distribution.test.bool.true=true -distribution.test.bool.false=false -distribution.test.empty= - -distribution.test.pref.locale="%LOCALE%" -distribution.test.pref.language.reset="Preference Set" -distribution.test.pref.locale.reset="Preference Set" -distribution.test.pref.locale.set="Preference Set" -distribution.test.pref.language.set="Preference Set" - -[Preferences-en] -distribution.test.pref.language.en="en" -distribution.test.pref.language.reset= -distribution.test.pref.language.set="Language Set" -distribution.test.pref.locale.set="Language Set" - -[Preferences-en-US] -distribution.test.pref.locale.en-US="en-US" -distribution.test.pref.locale.reset= -distribution.test.pref.locale.set="Locale Set" - - -[Preferences-de] -distribution.test.pref.language.de="de" - -[LocalizablePreferences] -distribution.test.locale="%LOCALE%" -distribution.test.language.reset="Preference Set" -distribution.test.locale.reset="Preference Set" -distribution.test.locale.set="Preference Set" -distribution.test.language.set="Preference Set" - -[LocalizablePreferences-en] -distribution.test.language.en="en" -distribution.test.language.reset= -distribution.test.language.set="Language Set" -distribution.test.locale.set="Language Set" - -[LocalizablePreferences-en-US] -distribution.test.locale.en-US="en-US" -distribution.test.locale.reset= -distribution.test.locale.set="Locale Set" - -[LocalizablePreferences-de] -distribution.test.language.de="de" diff --git a/browser/components/tests/unit/head.js b/browser/components/tests/unit/head.js deleted file mode 100644 index 3d4e23452..000000000 --- a/browser/components/tests/unit/head.js +++ /dev/null @@ -1,9 +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 {interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components; - -Cu.import("resource://gre/modules/Services.jsm"); - -var gProfD = do_get_profile().QueryInterface(Ci.nsILocalFile); diff --git a/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js b/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js deleted file mode 100644 index a68503db3..000000000 --- a/browser/components/tests/unit/test_browserGlue_migration_loop_cleanup.js +++ /dev/null @@ -1,32 +0,0 @@ -const UI_VERSION = 41; -const TOPIC_BROWSERGLUE_TEST = "browser-glue-test"; -const TOPICDATA_BROWSERGLUE_TEST = "force-ui-migration"; - -var gBrowserGlue = Cc["@mozilla.org/browser/browserglue;1"] - .getService(Ci.nsIObserver); - -Services.prefs.setIntPref("browser.migration.version", UI_VERSION - 1); - -add_task(function* test_check_cleanup_loop_prefs() { - Services.prefs.setBoolPref("loop.createdRoom", true); - Services.prefs.setBoolPref("loop1.createdRoom", true); - Services.prefs.setBoolPref("loo.createdRoom", true); - - // Simulate a migration. - gBrowserGlue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_BROWSERGLUE_TEST); - - Assert.throws(() => Services.prefs.getBoolPref("loop.createdRoom"), - /NS_ERROR_UNEXPECTED/, - "should have cleared old loop preference 'loop.createdRoom'"); - Assert.ok(Services.prefs.getBoolPref("loop1.createdRoom"), - "should have left non-loop pref 'loop1.createdRoom' untouched"); - Assert.ok(Services.prefs.getBoolPref("loo.createdRoom"), - "should have left non-loop pref 'loo.createdRoom' untouched"); -}); - -do_register_cleanup(() => { - Services.prefs.clearUserPref("browser.migration.version"); - Services.prefs.clearUserPref("loop.createdRoom"); - Services.prefs.clearUserPref("loop1.createdRoom"); - Services.prefs.clearUserPref("loo.createdRoom"); -}); diff --git a/browser/components/tests/unit/test_distribution.js b/browser/components/tests/unit/test_distribution.js deleted file mode 100644 index 183ab85d6..000000000 --- a/browser/components/tests/unit/test_distribution.js +++ /dev/null @@ -1,152 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that preferences are properly set by distribution.ini - */ - -Cu.import("resource://gre/modules/LoadContextInfo.jsm"); - -// Import common head. -var commonFile = do_get_file("../../../../toolkit/components/places/tests/head_common.js", false); -/* import-globals-from ../../../../toolkit/components/places/tests/head_common.js */ -if (commonFile) { - let uri = Services.io.newFileURI(commonFile); - Services.scriptloader.loadSubScript(uri.spec, this); -} - -const TOPICDATA_DISTRIBUTION_CUSTOMIZATION = "force-distribution-customization"; -const TOPIC_BROWSERGLUE_TEST = "browser-glue-test"; - -/** - * Copy the engine-distribution.xml engine to a fake distribution - * created in the profile, and registered with the directory service. - * Create an empty en-US directory to make sure it isn't used. - */ -function installDistributionEngine() { - const XRE_APP_DISTRIBUTION_DIR = "XREAppDist"; - - let dir = gProfD.clone(); - dir.append("distribution"); - let distDir = dir.clone(); - - dir.append("searchplugins"); - dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - - dir.append("locale"); - dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - let localeDir = dir.clone(); - - dir.append("en-US"); - dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - - localeDir.append("de-DE"); - localeDir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); - - do_get_file("data/engine-de-DE.xml").copyTo(localeDir, "engine-de-DE.xml"); - - Services.dirsvc.registerProvider({ - getFile: function(aProp, aPersistent) { - aPersistent.value = true; - if (aProp == XRE_APP_DISTRIBUTION_DIR) - return distDir.clone(); - return null; - } - }); -} - -function run_test() { - // Set special pref to load distribution.ini from the profile folder. - Services.prefs.setBoolPref("distribution.testing.loadFromProfile", true); - - // Copy distribution.ini file to the profile dir. - let distroDir = gProfD.clone(); - distroDir.leafName = "distribution"; - let iniFile = distroDir.clone(); - iniFile.append("distribution.ini"); - if (iniFile.exists()) { - iniFile.remove(false); - print("distribution.ini already exists, did some test forget to cleanup?"); - } - - let testDistributionFile = gTestDir.clone(); - testDistributionFile.append("distribution.ini"); - testDistributionFile.copyTo(distroDir, "distribution.ini"); - Assert.ok(testDistributionFile.exists()); - - installDistributionEngine(); - - run_next_test(); -} - -do_register_cleanup(function () { - // Remove the distribution dir, even if the test failed, otherwise all - // next tests will use it. - let distDir = gProfD.clone(); - distDir.append("distribution"); - distDir.remove(true); - Assert.ok(!distDir.exists()); -}); - -add_task(function* () { - // Force distribution. - let glue = Cc["@mozilla.org/browser/browserglue;1"].getService(Ci.nsIObserver) - glue.observe(null, TOPIC_BROWSERGLUE_TEST, TOPICDATA_DISTRIBUTION_CUSTOMIZATION); - - var defaultBranch = Services.prefs.getDefaultBranch(null); - - Assert.equal(defaultBranch.getCharPref("distribution.id"), "disttest"); - Assert.equal(defaultBranch.getCharPref("distribution.version"), "1.0"); - Assert.equal(defaultBranch.getComplexValue("distribution.about", Ci.nsISupportsString).data, "TÃ¨Æ¨Æ Î´Ã¯Æ¨ÆřïβúÆïôñ ƒïℓè"); - - Assert.equal(defaultBranch.getCharPref("distribution.test.string"), "Test String"); - Assert.equal(defaultBranch.getCharPref("distribution.test.string.noquotes"), "Test String"); - Assert.equal(defaultBranch.getIntPref("distribution.test.int"), 777); - Assert.equal(defaultBranch.getBoolPref("distribution.test.bool.true"), true); - Assert.equal(defaultBranch.getBoolPref("distribution.test.bool.false"), false); - - Assert.throws(() => defaultBranch.getCharPref("distribution.test.empty")); - Assert.throws(() => defaultBranch.getIntPref("distribution.test.empty")); - Assert.throws(() => defaultBranch.getBoolPref("distribution.test.empty")); - - Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale"), "en-US"); - Assert.equal(defaultBranch.getCharPref("distribution.test.pref.language.en"), "en"); - Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale.en-US"), "en-US"); - Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.language.de")); - // This value was never set because of the empty language specific pref - Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.language.reset")); - // This value was never set because of the empty locale specific pref - Assert.throws(() => defaultBranch.getCharPref("distribution.test.pref.locale.reset")); - // This value was overridden by a locale specific setting - Assert.equal(defaultBranch.getCharPref("distribution.test.pref.locale.set"), "Locale Set"); - // This value was overridden by a language specific setting - Assert.equal(defaultBranch.getCharPref("distribution.test.pref.language.set"), "Language Set"); - // Language should not override locale - Assert.notEqual(defaultBranch.getCharPref("distribution.test.pref.locale.set"), "Language Set"); - - Assert.equal(defaultBranch.getComplexValue("distribution.test.locale", Ci.nsIPrefLocalizedString).data, "en-US"); - Assert.equal(defaultBranch.getComplexValue("distribution.test.language.en", Ci.nsIPrefLocalizedString).data, "en"); - Assert.equal(defaultBranch.getComplexValue("distribution.test.locale.en-US", Ci.nsIPrefLocalizedString).data, "en-US"); - Assert.throws(() => defaultBranch.getComplexValue("distribution.test.language.de", Ci.nsIPrefLocalizedString)); - // This value was never set because of the empty language specific pref - Assert.throws(() => defaultBranch.getComplexValue("distribution.test.language.reset", Ci.nsIPrefLocalizedString)); - // This value was never set because of the empty locale specific pref - Assert.throws(() => defaultBranch.getComplexValue("distribution.test.locale.reset", Ci.nsIPrefLocalizedString)); - // This value was overridden by a locale specific setting - Assert.equal(defaultBranch.getComplexValue("distribution.test.locale.set", Ci.nsIPrefLocalizedString).data, "Locale Set"); - // This value was overridden by a language specific setting - Assert.equal(defaultBranch.getComplexValue("distribution.test.language.set", Ci.nsIPrefLocalizedString).data, "Language Set"); - // Language should not override locale - Assert.notEqual(defaultBranch.getComplexValue("distribution.test.locale.set", Ci.nsIPrefLocalizedString).data, "Language Set"); - - do_test_pending(); - - Services.prefs.setCharPref("distribution.searchplugins.defaultLocale", "de-DE"); - - Services.search.init(function() { - Assert.equal(Services.search.isInitialized, true); - var engine = Services.search.getEngineByName("Google"); - Assert.equal(engine.description, "override-de-DE"); - do_test_finished(); - }); -}); diff --git a/browser/components/tests/unit/xpcshell.ini b/browser/components/tests/unit/xpcshell.ini deleted file mode 100644 index c2f461966..000000000 --- a/browser/components/tests/unit/xpcshell.ini +++ /dev/null @@ -1,10 +0,0 @@ -[DEFAULT] -head = head.js -firefox-appdir = browser -skip-if = toolkit == 'android' -support-files = - distribution.ini - data/engine-de-DE.xml - -[test_distribution.js] -[test_browserGlue_migration_loop_cleanup.js] diff --git a/browser/components/translation/test/.eslintrc.js b/browser/components/translation/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/translation/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/translation/test/bing.sjs b/browser/components/translation/test/bing.sjs deleted file mode 100644 index ce3b96855..000000000 --- a/browser/components/translation/test/bing.sjs +++ /dev/null @@ -1,234 +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 {classes: Cc, interfaces: Ci, Constructor: CC} = Components; -const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); - -function handleRequest(req, res) { - try { - reallyHandleRequest(req, res); - } catch (ex) { - res.setStatusLine("1.0", 200, "AlmostOK"); - let msg = "Error handling request: " + ex + "\n" + ex.stack; - log(msg); - res.write(msg); - } -} - -function log(msg) { - // dump("BING-SERVER-MOCK: " + msg + "\n"); -} - -const statusCodes = { - 400: "Bad Request", - 401: "Unauthorized", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 500: "Internal Server Error", - 501: "Not Implemented", - 503: "Service Unavailable" -}; - -function HTTPError(code = 500, message) { - this.code = code; - this.name = statusCodes[code] || "HTTPError"; - this.message = message || this.name; -} -HTTPError.prototype = new Error(); -HTTPError.prototype.constructor = HTTPError; - -function sendError(res, err) { - if (!(err instanceof HTTPError)) { - err = new HTTPError(typeof err == "number" ? err : 500, - err.message || typeof err == "string" ? err : ""); - } - res.setStatusLine("1.1", err.code, err.name); - res.write(err.message); -} - -function parseQuery(query) { - let ret = {}; - for (let param of query.replace(/^[?&]/, "").split("&")) { - param = param.split("="); - if (!param[0]) - continue; - ret[unescape(param[0])] = unescape(param[1]); - } - return ret; -} - -function getRequestBody(req) { - let avail; - let bytes = []; - let body = new BinaryInputStream(req.bodyInputStream); - - while ((avail = body.available()) > 0) - Array.prototype.push.apply(bytes, body.readByteArray(avail)); - - return String.fromCharCode.apply(null, bytes); -} - -function sha1(str) { - let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); - converter.charset = "UTF-8"; - // `result` is an out parameter, `result.value` will contain the array length. - let result = {}; - // `data` is an array of bytes. - let data = converter.convertToByteArray(str, result); - let ch = Cc["@mozilla.org/security/hash;1"] - .createInstance(Ci.nsICryptoHash); - ch.init(ch.SHA1); - ch.update(data, data.length); - let hash = ch.finish(false); - - // Return the two-digit hexadecimal code for a byte. - function toHexString(charCode) { - return ("0" + charCode.toString(16)).slice(-2); - } - - // Convert the binary hash data to a hex string. - return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); -} - -function parseXml(body) { - let DOMParser = Cc["@mozilla.org/xmlextras/domparser;1"] - .createInstance(Ci.nsIDOMParser); - let xml = DOMParser.parseFromString(body, "text/xml"); - if (xml.documentElement.localName == "parsererror") - throw new Error("Invalid XML"); - return xml; -} - -function getInputStream(path) { - let file = Cc["@mozilla.org/file/directory_service;1"] - .getService(Ci.nsIProperties) - .get("CurWorkD", Ci.nsILocalFile); - for (let part of path.split("/")) - file.append(part); - let fileStream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); - fileStream.init(file, 1, 0, false); - return fileStream; -} - -function checkAuth(req) { - let err = new Error("Authorization failed"); - err.code = 401; - - if (!req.hasHeader("Authorization")) - throw new HTTPError(401, "No Authorization header provided."); - - let auth = req.getHeader("Authorization"); - if (!auth.startsWith("Bearer ")) - throw new HTTPError(401, "Invalid Authorization header content: '" + auth + "'"); - - // Rejecting inactive subscriptions. - if (auth.includes("inactive")) { - const INACTIVE_STATE_RESPONSE = "<html><body><h1>TranslateApiException</h1><p>Method: TranslateArray()</p><p>Message: The Azure Market Place Translator Subscription associated with the request credentials is not in an active state.</p><code></code><p>message id=5641.V2_Rest.TranslateArray.48CC6470</p></body></html>"; - throw new HTTPError(401, INACTIVE_STATE_RESPONSE); - } - -} - -function reallyHandleRequest(req, res) { - log("method: " + req.method); - if (req.method != "POST") { - sendError(res, "Bing only deals with POST requests, not '" + req.method + "'."); - return; - } - - let body = getRequestBody(req); - log("body: " + body); - - // First, we'll see if we're dealing with an XML body: - let contentType = req.hasHeader("Content-Type") ? req.getHeader("Content-Type") : null; - log("contentType: " + contentType); - - if (contentType.startsWith("text/xml")) { - try { - // For all these requests the client needs to supply the correct - // authentication headers. - checkAuth(req); - - let xml = parseXml(body); - let method = xml.documentElement.localName; - log("invoking method: " + method); - // If the requested method is supported, delegate it to its handler. - if (methodHandlers[method]) - methodHandlers[method](res, xml); - else - throw new HTTPError(501); - } catch (ex) { - sendError(res, ex, ex.code); - } - } else { - // Not XML, so it must be a query-string. - let params = parseQuery(body); - - // Delegate an authentication request to the correct handler. - if ("grant_type" in params && params.grant_type == "client_credentials") - methodHandlers.authenticate(res, params); - else - sendError(res, 501); - } -} - -const methodHandlers = { - authenticate: function(res, params) { - // Validate a few required parameters. - if (params.scope != "http://api.microsofttranslator.com") { - sendError(res, "Invalid scope."); - return; - } - if (!params.client_id) { - sendError(res, "Missing client_id param."); - return; - } - if (!params.client_secret) { - sendError(res, "Missing client_secret param."); - return; - } - - // Defines the tokens for certain client ids. - const TOKEN_MAP = { - 'testInactive' : 'inactive', - 'testClient' : 'test' - }; - let token = 'test'; // Default token. - if((params.client_id in TOKEN_MAP)){ - token = TOKEN_MAP[params.client_id]; - } - let content = JSON.stringify({ - access_token: token, - expires_in: 600 - }); - - res.setStatusLine("1.1", 200, "OK"); - res.setHeader("Content-Length", String(content.length)); - res.setHeader("Content-Type", "application/json"); - res.write(content); - }, - - TranslateArrayRequest: function(res, xml, body) { - let from = xml.querySelector("From").firstChild.nodeValue; - let to = xml.querySelector("To").firstChild.nodeValue - log("translating from '" + from + "' to '" + to + "'"); - - res.setStatusLine("1.1", 200, "OK"); - res.setHeader("Content-Type", "text/xml"); - - let hash = sha1(body).substr(0, 10); - log("SHA1 hash of content: " + hash); - let inputStream = getInputStream( - "browser/browser/components/translation/test/fixtures/result-" + hash + ".txt"); - res.bodyOutputStream.writeFrom(inputStream, inputStream.available()); - inputStream.close(); - } -}; diff --git a/browser/components/translation/test/browser.ini b/browser/components/translation/test/browser.ini deleted file mode 100644 index 59e481855..000000000 --- a/browser/components/translation/test/browser.ini +++ /dev/null @@ -1,13 +0,0 @@ -[DEFAULT] -support-files = - bing.sjs - yandex.sjs - fixtures/bug1022725-fr.html - fixtures/result-da39a3ee5e.txt - fixtures/result-yandex-d448894848.json - -[browser_translation_bing.js] -[browser_translation_yandex.js] -[browser_translation_telemetry.js] -[browser_translation_infobar.js] -[browser_translation_exceptions.js] diff --git a/browser/components/translation/test/browser_translation_bing.js b/browser/components/translation/test/browser_translation_bing.js deleted file mode 100644 index 399a67022..000000000 --- a/browser/components/translation/test/browser_translation_bing.js +++ /dev/null @@ -1,133 +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 Bing Translator client against a mock Bing service, bing.sjs. - -"use strict"; - -const kClientIdPref = "browser.translation.bing.clientIdOverride"; -const kClientSecretPref = "browser.translation.bing.apiKeyOverride"; - -const {BingTranslator} = Cu.import("resource:///modules/translation/BingTranslator.jsm", {}); -const {TranslationDocument} = Cu.import("resource:///modules/translation/TranslationDocument.jsm", {}); -const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {}); - -add_task(function* setup() { - Services.prefs.setCharPref(kClientIdPref, "testClient"); - Services.prefs.setCharPref(kClientSecretPref, "testSecret"); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref(kClientIdPref); - Services.prefs.clearUserPref(kClientSecretPref); - }); -}); - -/** - * Checks if the translation is happening. - */ -add_task(function* test_bing_translation() { - - // Ensure the correct client id is used for authentication. - Services.prefs.setCharPref(kClientIdPref, "testClient"); - - // Loading the fixture page. - let url = constructFixtureURL("bug1022725-fr.html"); - let tab = yield promiseTestPageLoad(url); - - // Translating the contents of the loaded tab. - gBrowser.selectedTab = tab; - let browser = tab.linkedBrowser; - - yield ContentTask.spawn(browser, null, function*() { - Cu.import("resource:///modules/translation/BingTranslator.jsm"); - Cu.import("resource:///modules/translation/TranslationDocument.jsm"); - - let client = new BingTranslator( - new TranslationDocument(content.document), "fr", "en"); - let result = yield client.translate(); - - // XXXmikedeboer; here you would continue the test/ content inspection. - Assert.ok(result, "There should be a result"); - }); - - gBrowser.removeTab(tab); -}); - -/** - * Ensures that the BingTranslator handles out-of-valid-key response - * correctly. Sometimes Bing Translate replies with - * "request credentials is not in an active state" error. BingTranslator - * should catch this error and classify it as Service Unavailable. - * - */ -add_task(function* test_handling_out_of_valid_key_error() { - - // Simulating request from inactive subscription. - Services.prefs.setCharPref(kClientIdPref, "testInactive"); - - // Loading the fixture page. - let url = constructFixtureURL("bug1022725-fr.html"); - let tab = yield promiseTestPageLoad(url); - - // Translating the contents of the loaded tab. - gBrowser.selectedTab = tab; - let browser = tab.linkedBrowser; - - yield ContentTask.spawn(browser, null, function*() { - Cu.import("resource:///modules/translation/BingTranslator.jsm"); - Cu.import("resource:///modules/translation/TranslationDocument.jsm"); - - let client = new BingTranslator( - new TranslationDocument(content.document), "fr", "en"); - client._resetToken(); - try { - yield client.translate(); - } catch (ex) { - // It is alright that the translation fails. - } - client._resetToken(); - - // Checking if the client detected service and unavailable. - Assert.ok(client._serviceUnavailable, "Service should be detected unavailable."); - }); - - // Cleaning up. - Services.prefs.setCharPref(kClientIdPref, "testClient"); - gBrowser.removeTab(tab); -}); - -/** - * A helper function for constructing a URL to a page stored in the - * local fixture folder. - * - * @param filename Name of a fixture file. - */ -function constructFixtureURL(filename) { - // Deduce the Mochitest server address in use from a pref that was pre-processed. - let server = Services.prefs.getCharPref("browser.translation.bing.authURL") - .replace("http://", ""); - server = server.substr(0, server.indexOf("/")); - let url = "http://" + server + - "/browser/browser/components/translation/test/fixtures/" + filename; - return url; -} - -/** - * A helper function to open a new tab and wait for its content to load. - * - * @param String url A URL to be loaded in the new tab. - */ -function promiseTestPageLoad(url) { - let deferred = Promise.defer(); - let tab = gBrowser.selectedTab = gBrowser.addTab(url); - let browser = gBrowser.selectedBrowser; - browser.addEventListener("load", function listener() { - if (browser.currentURI.spec == "about:blank") - return; - info("Page loaded: " + browser.currentURI.spec); - browser.removeEventListener("load", listener, true); - deferred.resolve(tab); - }, true); - return deferred.promise; -} diff --git a/browser/components/translation/test/browser_translation_exceptions.js b/browser/components/translation/test/browser_translation_exceptions.js deleted file mode 100644 index bf6875768..000000000 --- a/browser/components/translation/test/browser_translation_exceptions.js +++ /dev/null @@ -1,327 +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/. */ - -// tests the translation infobar, using a fake 'Translation' implementation. - -var tmp = {}; -Cu.import("resource:///modules/translation/Translation.jsm", tmp); -Cu.import("resource://gre/modules/Promise.jsm", tmp); -var {Translation, Promise} = tmp; - -const kLanguagesPref = "browser.translation.neverForLanguages"; -const kShowUIPref = "browser.translation.ui.show"; - -function test() { - waitForExplicitFinish(); - - Services.prefs.setBoolPref(kShowUIPref, true); - let tab = gBrowser.addTab(); - gBrowser.selectedTab = tab; - registerCleanupFunction(function () { - gBrowser.removeTab(tab); - Services.prefs.clearUserPref(kShowUIPref); - }); - tab.linkedBrowser.addEventListener("load", function onload() { - tab.linkedBrowser.removeEventListener("load", onload, true); - Task.spawn(function* () { - for (let test of gTests) { - info(test.desc); - yield test.run(); - } - }).then(finish, ex => { - ok(false, "Unexpected Exception: " + ex); - finish(); - }); - }, true); - - content.location = "http://example.com/"; -} - -function getLanguageExceptions() { - let langs = Services.prefs.getCharPref(kLanguagesPref); - return langs ? langs.split(",") : []; -} - -function getDomainExceptions() { - let results = []; - let enumerator = Services.perms.enumerator; - while (enumerator.hasMoreElements()) { - let perm = enumerator.getNext().QueryInterface(Ci.nsIPermission); - - if (perm.type == "translate" && - perm.capability == Services.perms.DENY_ACTION) - results.push(perm.principal); - } - - return results; -} - -function getInfoBar() { - let deferred = Promise.defer(); - let infobar = - gBrowser.getNotificationBox().getNotificationWithValue("translation"); - - if (!infobar) { - deferred.resolve(); - } else { - // Wait for all animations to finish - Promise.all(infobar.getAnimations().map(animation => animation.finished)) - .then(() => deferred.resolve(infobar)); - } - - return deferred.promise; -} - -function openPopup(aPopup) { - let deferred = Promise.defer(); - - aPopup.addEventListener("popupshown", function popupShown() { - aPopup.removeEventListener("popupshown", popupShown); - deferred.resolve(); - }); - - aPopup.focus(); - // One down event to open the popup. - EventUtils.synthesizeKey("VK_DOWN", - { altKey: !navigator.platform.includes("Mac") }); - - return deferred.promise; -} - -function waitForWindowLoad(aWin) { - let deferred = Promise.defer(); - - aWin.addEventListener("load", function onload() { - aWin.removeEventListener("load", onload, true); - deferred.resolve(); - }, true); - - return deferred.promise; -} - - -var gTests = [ - -{ - desc: "clean exception lists at startup", - run: function checkNeverForLanguage() { - is(getLanguageExceptions().length, 0, - "we start with an empty list of languages to never translate"); - is(getDomainExceptions().length, 0, - "we start with an empty list of sites to never translate"); - } -}, - -{ - desc: "never for language", - run: function* checkNeverForLanguage() { - // Show the infobar for example.com and fr. - Translation.documentStateReceived(gBrowser.selectedBrowser, - {state: Translation.STATE_OFFER, - originalShown: true, - detectedLanguage: "fr"}); - let notif = yield getInfoBar(); - ok(notif, "the infobar is visible"); - let ui = gBrowser.selectedBrowser.translationUI; - let uri = gBrowser.selectedBrowser.currentURI; - ok(ui.shouldShowInfoBar(uri, "fr"), - "check shouldShowInfoBar initially returns true"); - - // Open the "options" drop down. - yield openPopup(notif._getAnonElt("options")); - ok(notif._getAnonElt("options").getAttribute("open"), - "the options menu is open"); - - // Check that the item is not disabled. - ok(!notif._getAnonElt("neverForLanguage").disabled, - "The 'Never translate <language>' item isn't disabled"); - - // Click the 'Never for French' item. - notif._getAnonElt("neverForLanguage").click(); - notif = yield getInfoBar(); - ok(!notif, "infobar hidden"); - - // Check this has been saved to the exceptions list. - let langs = getLanguageExceptions(); - is(langs.length, 1, "one language in the exception list"); - is(langs[0], "fr", "correct language in the exception list"); - ok(!ui.shouldShowInfoBar(uri, "fr"), - "the infobar wouldn't be shown anymore"); - - // Reopen the infobar. - PopupNotifications.getNotification("translate").anchorElement.click(); - notif = yield getInfoBar(); - // Open the "options" drop down. - yield openPopup(notif._getAnonElt("options")); - ok(notif._getAnonElt("neverForLanguage").disabled, - "The 'Never translate French' item is disabled"); - - // Cleanup. - Services.prefs.setCharPref(kLanguagesPref, ""); - notif.close(); - } -}, - -{ - desc: "never for site", - run: function* checkNeverForSite() { - // Show the infobar for example.com and fr. - Translation.documentStateReceived(gBrowser.selectedBrowser, - {state: Translation.STATE_OFFER, - originalShown: true, - detectedLanguage: "fr"}); - let notif = yield getInfoBar(); - ok(notif, "the infobar is visible"); - let ui = gBrowser.selectedBrowser.translationUI; - let uri = gBrowser.selectedBrowser.currentURI; - ok(ui.shouldShowInfoBar(uri, "fr"), - "check shouldShowInfoBar initially returns true"); - - // Open the "options" drop down. - yield openPopup(notif._getAnonElt("options")); - ok(notif._getAnonElt("options").getAttribute("open"), - "the options menu is open"); - - // Check that the item is not disabled. - ok(!notif._getAnonElt("neverForSite").disabled, - "The 'Never translate site' item isn't disabled"); - - // Click the 'Never for French' item. - notif._getAnonElt("neverForSite").click(); - notif = yield getInfoBar(); - ok(!notif, "infobar hidden"); - - // Check this has been saved to the exceptions list. - let sites = getDomainExceptions(); - is(sites.length, 1, "one site in the exception list"); - is(sites[0].origin, "http://example.com", "correct site in the exception list"); - ok(!ui.shouldShowInfoBar(uri, "fr"), - "the infobar wouldn't be shown anymore"); - - // Reopen the infobar. - PopupNotifications.getNotification("translate").anchorElement.click(); - notif = yield getInfoBar(); - // Open the "options" drop down. - yield openPopup(notif._getAnonElt("options")); - ok(notif._getAnonElt("neverForSite").disabled, - "The 'Never translate French' item is disabled"); - - // Cleanup. - Services.perms.remove(makeURI("http://example.com"), "translate"); - notif.close(); - } -}, - -{ - desc: "language exception list", - run: function* checkLanguageExceptions() { - // Put 2 languages in the pref before opening the window to check - // the list is displayed on load. - Services.prefs.setCharPref(kLanguagesPref, "fr,de"); - - // Open the translation exceptions dialog. - let win = openDialog("chrome://browser/content/preferences/translation.xul", - "Browser:TranslationExceptions", - "", null); - yield waitForWindowLoad(win); - - // Check that the list of language exceptions is loaded. - let getById = win.document.getElementById.bind(win.document); - let tree = getById("languagesTree"); - let remove = getById("removeLanguage"); - let removeAll = getById("removeAllLanguages"); - is(tree.view.rowCount, 2, "The language exceptions list has 2 items"); - ok(remove.disabled, "The 'Remove Language' button is disabled"); - ok(!removeAll.disabled, "The 'Remove All Languages' button is enabled"); - - // Select the first item. - tree.view.selection.select(0); - ok(!remove.disabled, "The 'Remove Language' button is enabled"); - - // Click the 'Remove' button. - remove.click(); - is(tree.view.rowCount, 1, "The language exceptions now contains 1 item"); - is(getLanguageExceptions().length, 1, "One exception in the pref"); - - // Clear the pref, and check the last item is removed from the display. - Services.prefs.setCharPref(kLanguagesPref, ""); - is(tree.view.rowCount, 0, "The language exceptions list is empty"); - ok(remove.disabled, "The 'Remove Language' button is disabled"); - ok(removeAll.disabled, "The 'Remove All Languages' button is disabled"); - - // Add an item and check it appears. - Services.prefs.setCharPref(kLanguagesPref, "fr"); - is(tree.view.rowCount, 1, "The language exceptions list has 1 item"); - ok(remove.disabled, "The 'Remove Language' button is disabled"); - ok(!removeAll.disabled, "The 'Remove All Languages' button is enabled"); - - // Click the 'Remove All' button. - removeAll.click(); - is(tree.view.rowCount, 0, "The language exceptions list is empty"); - ok(remove.disabled, "The 'Remove Language' button is disabled"); - ok(removeAll.disabled, "The 'Remove All Languages' button is disabled"); - is(Services.prefs.getCharPref(kLanguagesPref), "", "The pref is empty"); - - win.close(); - } -}, - -{ - desc: "domains exception list", - run: function* checkDomainExceptions() { - // Put 2 exceptions before opening the window to check the list is - // displayed on load. - let perms = Services.perms; - perms.add(makeURI("http://example.org"), "translate", perms.DENY_ACTION); - perms.add(makeURI("http://example.com"), "translate", perms.DENY_ACTION); - - // Open the translation exceptions dialog. - let win = openDialog("chrome://browser/content/preferences/translation.xul", - "Browser:TranslationExceptions", - "", null); - yield waitForWindowLoad(win); - - // Check that the list of language exceptions is loaded. - let getById = win.document.getElementById.bind(win.document); - let tree = getById("sitesTree"); - let remove = getById("removeSite"); - let removeAll = getById("removeAllSites"); - is(tree.view.rowCount, 2, "The sites exceptions list has 2 items"); - ok(remove.disabled, "The 'Remove Site' button is disabled"); - ok(!removeAll.disabled, "The 'Remove All Sites' button is enabled"); - - // Select the first item. - tree.view.selection.select(0); - ok(!remove.disabled, "The 'Remove Site' button is enabled"); - - // Click the 'Remove' button. - remove.click(); - is(tree.view.rowCount, 1, "The site exceptions now contains 1 item"); - is(getDomainExceptions().length, 1, "One exception in the permissions"); - - // Clear the permissions, and check the last item is removed from the display. - perms.remove(makeURI("http://example.org"), "translate"); - perms.remove(makeURI("http://example.com"), "translate"); - is(tree.view.rowCount, 0, "The site exceptions list is empty"); - ok(remove.disabled, "The 'Remove Site' button is disabled"); - ok(removeAll.disabled, "The 'Remove All Site' button is disabled"); - - // Add an item and check it appears. - perms.add(makeURI("http://example.com"), "translate", perms.DENY_ACTION); - is(tree.view.rowCount, 1, "The site exceptions list has 1 item"); - ok(remove.disabled, "The 'Remove Site' button is disabled"); - ok(!removeAll.disabled, "The 'Remove All Sites' button is enabled"); - - // Click the 'Remove All' button. - removeAll.click(); - is(tree.view.rowCount, 0, "The site exceptions list is empty"); - ok(remove.disabled, "The 'Remove Site' button is disabled"); - ok(removeAll.disabled, "The 'Remove All Sites' button is disabled"); - is(getDomainExceptions().length, 0, "No exceptions in the permissions"); - - win.close(); - } -} - -]; diff --git a/browser/components/translation/test/browser_translation_infobar.js b/browser/components/translation/test/browser_translation_infobar.js deleted file mode 100644 index c16b3939c..000000000 --- a/browser/components/translation/test/browser_translation_infobar.js +++ /dev/null @@ -1,216 +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/. */ - -// tests the translation infobar, using a fake 'Translation' implementation. - -var tmp = {}; -Cu.import("resource:///modules/translation/Translation.jsm", tmp); -var {Translation} = tmp; - -const kShowUIPref = "browser.translation.ui.show"; - -function waitForCondition(condition, nextTest, errorMsg) { - var tries = 0; - var interval = setInterval(function() { - if (tries >= 30) { - ok(false, errorMsg); - moveOn(); - } - var conditionPassed; - try { - conditionPassed = condition(); - } catch (e) { - ok(false, e + "\n" + e.stack); - conditionPassed = false; - } - if (conditionPassed) { - moveOn(); - } - tries++; - }, 100); - var moveOn = function() { clearInterval(interval); nextTest(); }; -} - -var TranslationStub = { - translate: function(aFrom, aTo) { - this.state = Translation.STATE_TRANSLATING; - this.translatedFrom = aFrom; - this.translatedTo = aTo; - }, - - _reset: function() { - this.translatedFrom = ""; - this.translatedTo = ""; - }, - - failTranslation: function() { - this.state = Translation.STATE_ERROR; - this._reset(); - }, - - finishTranslation: function() { - this.showTranslatedContent(); - this.state = Translation.STATE_TRANSLATED; - this._reset(); - } -}; - -function showTranslationUI(aDetectedLanguage) { - let browser = gBrowser.selectedBrowser; - Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER, - originalShown: true, - detectedLanguage: aDetectedLanguage}); - let ui = browser.translationUI; - for (let name of ["translate", "_reset", "failTranslation", "finishTranslation"]) - ui[name] = TranslationStub[name]; - return ui.notificationBox.getNotificationWithValue("translation"); -} - -function hasTranslationInfoBar() { - return !!gBrowser.getNotificationBox().getNotificationWithValue("translation"); -} - -function test() { - waitForExplicitFinish(); - - Services.prefs.setBoolPref(kShowUIPref, true); - let tab = gBrowser.addTab(); - gBrowser.selectedTab = tab; - tab.linkedBrowser.addEventListener("load", function onload() { - tab.linkedBrowser.removeEventListener("load", onload, true); - TranslationStub.browser = gBrowser.selectedBrowser; - registerCleanupFunction(function () { - gBrowser.removeTab(tab); - Services.prefs.clearUserPref(kShowUIPref); - }); - run_tests(() => { - finish(); - }); - }, true); - - content.location = "data:text/plain,test page"; -} - -function checkURLBarIcon(aExpectTranslated = false) { - is(!PopupNotifications.getNotification("translate"), aExpectTranslated, - "translate icon " + (aExpectTranslated ? "not " : "") + "shown"); - is(!!PopupNotifications.getNotification("translated"), aExpectTranslated, - "translated icon " + (aExpectTranslated ? "" : "not ") + "shown"); -} - -function run_tests(aFinishCallback) { - info("Show an info bar saying the current page is in French"); - let notif = showTranslationUI("fr"); - is(notif.state, Translation.STATE_OFFER, "the infobar is offering translation"); - is(notif._getAnonElt("detectedLanguage").value, "fr", "The detected language is displayed"); - checkURLBarIcon(); - - info("Click the 'Translate' button"); - notif._getAnonElt("translate").click(); - is(notif.state, Translation.STATE_TRANSLATING, "the infobar is in the translating state"); - ok(!!notif.translation.translatedFrom, "Translation.translate has been called"); - is(notif.translation.translatedFrom, "fr", "from language correct"); - is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "from language correct"); - checkURLBarIcon(); - - info("Make the translation fail and check we are in the error state."); - notif.translation.failTranslation(); - is(notif.state, Translation.STATE_ERROR, "infobar in the error state"); - checkURLBarIcon(); - - info("Click the try again button"); - notif._getAnonElt("tryAgain").click(); - is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state"); - ok(!!notif.translation.translatedFrom, "Translation.translate has been called"); - is(notif.translation.translatedFrom, "fr", "from language correct"); - is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "from language correct"); - checkURLBarIcon(); - - info("Make the translation succeed and check we are in the 'translated' state."); - notif.translation.finishTranslation(); - is(notif.state, Translation.STATE_TRANSLATED, "infobar in the translated state"); - checkURLBarIcon(true); - - info("Test 'Show original' / 'Show Translation' buttons."); - // First check 'Show Original' is visible and 'Show Translation' is hidden. - ok(!notif._getAnonElt("showOriginal").hidden, "'Show Original' button visible"); - ok(notif._getAnonElt("showTranslation").hidden, "'Show Translation' button hidden"); - // Click the button. - notif._getAnonElt("showOriginal").click(); - // Check that the url bar icon shows the original content is displayed. - checkURLBarIcon(); - // And the 'Show Translation' button is now visible. - ok(notif._getAnonElt("showOriginal").hidden, "'Show Original' button hidden"); - ok(!notif._getAnonElt("showTranslation").hidden, "'Show Translation' button visible"); - // Click the 'Show Translation' button - notif._getAnonElt("showTranslation").click(); - // Check that the url bar icon shows the page is translated. - checkURLBarIcon(true); - // Check that the 'Show Original' button is visible again. - ok(!notif._getAnonElt("showOriginal").hidden, "'Show Original' button visible"); - ok(notif._getAnonElt("showTranslation").hidden, "'Show Translation' button hidden"); - - info("Check that changing the source language causes a re-translation"); - let from = notif._getAnonElt("fromLanguage"); - from.value = "es"; - from.doCommand(); - is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state"); - ok(!!notif.translation.translatedFrom, "Translation.translate has been called"); - is(notif.translation.translatedFrom, "es", "from language correct"); - is(notif.translation.translatedTo, Translation.defaultTargetLanguage, "to language correct"); - // We want to show the 'translated' icon while re-translating, - // because we are still displaying the previous translation. - checkURLBarIcon(true); - notif.translation.finishTranslation(); - checkURLBarIcon(true); - - info("Check that changing the target language causes a re-translation"); - let to = notif._getAnonElt("toLanguage"); - to.value = "pl"; - to.doCommand(); - is(notif.state, Translation.STATE_TRANSLATING, "infobar in the translating state"); - ok(!!notif.translation.translatedFrom, "Translation.translate has been called"); - is(notif.translation.translatedFrom, "es", "from language correct"); - is(notif.translation.translatedTo, "pl", "to language correct"); - checkURLBarIcon(true); - notif.translation.finishTranslation(); - checkURLBarIcon(true); - - // Cleanup. - notif.close(); - - info("Reopen the info bar to check that it's possible to override the detected language."); - notif = showTranslationUI("fr"); - is(notif.state, Translation.STATE_OFFER, "the infobar is offering translation"); - is(notif._getAnonElt("detectedLanguage").value, "fr", "The detected language is displayed"); - // Change the language and click 'Translate' - notif._getAnonElt("detectedLanguage").value = "ja"; - notif._getAnonElt("translate").click(); - is(notif.state, Translation.STATE_TRANSLATING, "the infobar is in the translating state"); - ok(!!notif.translation.translatedFrom, "Translation.translate has been called"); - is(notif.translation.translatedFrom, "ja", "from language correct"); - notif.close(); - - info("Reopen to check the 'Not Now' button closes the notification."); - notif = showTranslationUI("fr"); - is(hasTranslationInfoBar(), true, "there's a 'translate' notification"); - notif._getAnonElt("notNow").click(); - is(hasTranslationInfoBar(), false, "no 'translate' notification after clicking 'not now'"); - - info("Reopen to check the url bar icon closes the notification."); - notif = showTranslationUI("fr"); - is(hasTranslationInfoBar(), true, "there's a 'translate' notification"); - PopupNotifications.getNotification("translate").anchorElement.click(); - is(hasTranslationInfoBar(), false, "no 'translate' notification after clicking the url bar icon"); - - info("Check that clicking the url bar icon reopens the info bar"); - checkURLBarIcon(); - // Clicking the anchor element causes a 'showing' event to be sent - // asynchronously to our callback that will then show the infobar. - PopupNotifications.getNotification("translate").anchorElement.click(); - waitForCondition(hasTranslationInfoBar, () => { - ok(hasTranslationInfoBar(), "there's a 'translate' notification"); - aFinishCallback(); - }, "timeout waiting for the info bar to reappear"); -} diff --git a/browser/components/translation/test/browser_translation_telemetry.js b/browser/components/translation/test/browser_translation_telemetry.js deleted file mode 100644 index e60bc17ef..000000000 --- a/browser/components/translation/test/browser_translation_telemetry.js +++ /dev/null @@ -1,300 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var tmp = {}; -Cu.import("resource:///modules/translation/Translation.jsm", tmp); -var {Translation, TranslationTelemetry} = tmp; -const Telemetry = Services.telemetry; - -var MetricsChecker = { - HISTOGRAMS: { - OPPORTUNITIES : Services.telemetry.getHistogramById("TRANSLATION_OPPORTUNITIES"), - OPPORTUNITIES_BY_LANG : Services.telemetry.getKeyedHistogramById("TRANSLATION_OPPORTUNITIES_BY_LANGUAGE"), - PAGES : Services.telemetry.getHistogramById("TRANSLATED_PAGES"), - PAGES_BY_LANG : Services.telemetry.getKeyedHistogramById("TRANSLATED_PAGES_BY_LANGUAGE"), - CHARACTERS : Services.telemetry.getHistogramById("TRANSLATED_CHARACTERS"), - DENIED : Services.telemetry.getHistogramById("DENIED_TRANSLATION_OFFERS"), - AUTO_REJECTED : Services.telemetry.getHistogramById("AUTO_REJECTED_TRANSLATION_OFFERS"), - SHOW_ORIGINAL : Services.telemetry.getHistogramById("REQUESTS_OF_ORIGINAL_CONTENT"), - TARGET_CHANGES : Services.telemetry.getHistogramById("CHANGES_OF_TARGET_LANGUAGE"), - DETECTION_CHANGES : Services.telemetry.getHistogramById("CHANGES_OF_DETECTED_LANGUAGE"), - SHOW_UI : Services.telemetry.getHistogramById("SHOULD_TRANSLATION_UI_APPEAR"), - DETECT_LANG : Services.telemetry.getHistogramById("SHOULD_AUTO_DETECT_LANGUAGE"), - }, - - reset: function() { - for (let i of Object.keys(this.HISTOGRAMS)) { - this.HISTOGRAMS[i].clear(); - } - this.updateMetrics(); - }, - - updateMetrics: function () { - this._metrics = { - opportunitiesCount: this.HISTOGRAMS.OPPORTUNITIES.snapshot().sum || 0, - pageCount: this.HISTOGRAMS.PAGES.snapshot().sum || 0, - charCount: this.HISTOGRAMS.CHARACTERS.snapshot().sum || 0, - deniedOffers: this.HISTOGRAMS.DENIED.snapshot().sum || 0, - autoRejectedOffers: this.HISTOGRAMS.AUTO_REJECTED.snapshot().sum || 0, - showOriginal: this.HISTOGRAMS.SHOW_ORIGINAL.snapshot().sum || 0, - detectedLanguageChangedBefore: this.HISTOGRAMS.DETECTION_CHANGES.snapshot().counts[1] || 0, - detectedLanguageChangeAfter: this.HISTOGRAMS.DETECTION_CHANGES.snapshot().counts[0] || 0, - targetLanguageChanged: this.HISTOGRAMS.TARGET_CHANGES.snapshot().sum || 0, - showUI: this.HISTOGRAMS.SHOW_UI.snapshot().sum || 0, - detectLang: this.HISTOGRAMS.DETECT_LANG.snapshot().sum || 0, - // Metrics for Keyed histograms are estimated below. - opportunitiesCountByLang: {}, - pageCountByLang: {} - }; - - let opportunities = this.HISTOGRAMS.OPPORTUNITIES_BY_LANG.snapshot(); - let pages = this.HISTOGRAMS.PAGES_BY_LANG.snapshot(); - for (let source of Translation.supportedSourceLanguages) { - this._metrics.opportunitiesCountByLang[source] = opportunities[source] ? - opportunities[source].sum : 0; - for (let target of Translation.supportedTargetLanguages) { - if (source === target) continue; - let key = source + " -> " + target; - this._metrics.pageCountByLang[key] = pages[key] ? pages[key].sum : 0; - } - } - }, - - /** - * A recurrent loop for making assertions about collected metrics. - */ - _assertionLoop: function (prevMetrics, metrics, additions) { - for (let metric of Object.keys(additions)) { - let addition = additions[metric]; - // Allows nesting metrics. Useful for keyed histograms. - if (typeof addition === 'object') { - this._assertionLoop(prevMetrics[metric], metrics[metric], addition); - continue; - } - Assert.equal(prevMetrics[metric] + addition, metrics[metric]); - } - }, - - checkAdditions: function (additions) { - let prevMetrics = this._metrics; - this.updateMetrics(); - this._assertionLoop(prevMetrics, this._metrics, additions); - } - -}; - -function getInfobarElement(browser, anonid) { - let notif = browser.translationUI - .notificationBox.getNotificationWithValue("translation"); - return notif._getAnonElt(anonid); -} - -var offerTranslationFor = Task.async(function*(text, from) { - // Create some content to translate. - const dataUrl = "data:text/html;charset=utf-8," + text; - let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, dataUrl); - - let browser = gBrowser.getBrowserForTab(tab); - - // Send a translation offer. - Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER, - originalShown: true, - detectedLanguage: from}); - - return tab; -}); - -var acceptTranslationOffer = Task.async(function*(tab) { - let browser = tab.linkedBrowser; - getInfobarElement(browser, "translate").doCommand(); - yield waitForMessage(browser, "Translation:Finished"); -}); - -var translate = Task.async(function*(text, from, closeTab = true) { - let tab = yield offerTranslationFor(text, from); - yield acceptTranslationOffer(tab); - if (closeTab) { - gBrowser.removeTab(tab); - return null; - } - return tab; -}); - -function waitForMessage({messageManager}, name) { - return new Promise(resolve => { - messageManager.addMessageListener(name, function onMessage() { - messageManager.removeMessageListener(name, onMessage); - resolve(); - }); - }); -} - -function simulateUserSelectInMenulist(menulist, value) { - menulist.value = value; - menulist.doCommand(); -} - -add_task(function* setup() { - const setupPrefs = prefs => { - let prefsBackup = {}; - for (let p of prefs) { - prefsBackup[p] = Services.prefs.setBoolPref; - Services.prefs.setBoolPref(p, true); - } - return prefsBackup; - }; - - const restorePrefs = (prefs, backup) => { - for (let p of prefs) { - Services.prefs.setBoolPref(p, backup[p]); - } - }; - - const prefs = [ - "toolkit.telemetry.enabled", - "browser.translation.detectLanguage", - "browser.translation.ui.show" - ]; - - let prefsBackup = setupPrefs(prefs); - - let oldCanRecord = Telemetry.canRecordExtended; - Telemetry.canRecordExtended = true; - - registerCleanupFunction(() => { - restorePrefs(prefs, prefsBackup); - Telemetry.canRecordExtended = oldCanRecord; - }); - - // Reset histogram metrics. - MetricsChecker.reset(); -}); - -add_task(function* test_telemetry() { - // Translate a page. - yield translate("<h1>Привет, мир!</h1>", "ru"); - - // Translate another page. - yield translate("<h1>Hallo Welt!</h1><h1>Bratwurst!</h1>", "de"); - yield MetricsChecker.checkAdditions({ - opportunitiesCount: 2, - opportunitiesCountByLang: { "ru" : 1, "de" : 1 }, - pageCount: 1, - pageCountByLang: { "de -> en" : 1 }, - charCount: 21, - deniedOffers: 0 - }); -}); - -add_task(function* test_deny_translation_metric() { - function* offerAndDeny(elementAnonid) { - let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "de", "en"); - getInfobarElement(tab.linkedBrowser, elementAnonid).doCommand(); - yield MetricsChecker.checkAdditions({ deniedOffers: 1 }); - gBrowser.removeTab(tab); - } - - yield offerAndDeny("notNow"); - yield offerAndDeny("neverForSite"); - yield offerAndDeny("neverForLanguage"); - yield offerAndDeny("closeButton"); - - // Test that the close button doesn't record a denied translation if - // the infobar is not in its "offer" state. - let tab = yield translate("<h1>Hallo Welt!</h1>", "de", false); - yield MetricsChecker.checkAdditions({ deniedOffers: 0 }); - gBrowser.removeTab(tab); -}); - -add_task(function* test_show_original() { - let tab = - yield translate("<h1>Hallo Welt!</h1><h1>Bratwurst!</h1>", "de", false); - yield MetricsChecker.checkAdditions({ pageCount: 1, showOriginal: 0 }); - getInfobarElement(tab.linkedBrowser, "showOriginal").doCommand(); - yield MetricsChecker.checkAdditions({ pageCount: 0, showOriginal: 1 }); - gBrowser.removeTab(tab); -}); - -add_task(function* test_language_change() { - // This is run 4 times, the total additions are checked afterwards. - for (let i of Array(4)) { // eslint-disable-line no-unused-vars - let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "fr"); - let browser = tab.linkedBrowser; - // In the offer state, translation is executed by the Translate button, - // so we expect just a single recoding. - let detectedLangMenulist = getInfobarElement(browser, "detectedLanguage"); - simulateUserSelectInMenulist(detectedLangMenulist, "de"); - simulateUserSelectInMenulist(detectedLangMenulist, "it"); - simulateUserSelectInMenulist(detectedLangMenulist, "de"); - yield acceptTranslationOffer(tab); - - // In the translated state, a change in the form or to menulists - // triggers re-translation right away. - let fromLangMenulist = getInfobarElement(browser, "fromLanguage"); - simulateUserSelectInMenulist(fromLangMenulist, "it"); - simulateUserSelectInMenulist(fromLangMenulist, "de"); - - // Selecting the same item shouldn't count. - simulateUserSelectInMenulist(fromLangMenulist, "de"); - - let toLangMenulist = getInfobarElement(browser, "toLanguage"); - simulateUserSelectInMenulist(toLangMenulist, "fr"); - simulateUserSelectInMenulist(toLangMenulist, "en"); - simulateUserSelectInMenulist(toLangMenulist, "it"); - - // Selecting the same item shouldn't count. - simulateUserSelectInMenulist(toLangMenulist, "it"); - - // Setting the target language to the source language is a no-op, - // so it shouldn't count. - simulateUserSelectInMenulist(toLangMenulist, "de"); - - gBrowser.removeTab(tab); - } - yield MetricsChecker.checkAdditions({ - detectedLanguageChangedBefore: 4, - detectedLanguageChangeAfter: 8, - targetLanguageChanged: 12 - }); -}); - -add_task(function* test_never_offer_translation() { - Services.prefs.setCharPref("browser.translation.neverForLanguages", "fr"); - - let tab = yield offerTranslationFor("<h1>Hallo Welt!</h1>", "fr"); - - yield MetricsChecker.checkAdditions({ - autoRejectedOffers: 1, - }); - - gBrowser.removeTab(tab); - Services.prefs.clearUserPref("browser.translation.neverForLanguages"); -}); - -add_task(function* test_translation_preferences() { - - let preferenceChecks = { - "browser.translation.ui.show" : [ - {value: false, expected: {showUI: 0}}, - {value: true, expected: {showUI: 1}} - ], - "browser.translation.detectLanguage" : [ - {value: false, expected: {detectLang: 0}}, - {value: true, expected: {detectLang: 1}} - ], - }; - - for (let preference of Object.keys(preferenceChecks)) { - for (let check of preferenceChecks[preference]) { - MetricsChecker.reset(); - Services.prefs.setBoolPref(preference, check.value); - // Preference metrics are collected once when the provider is initialized. - TranslationTelemetry.init(); - yield MetricsChecker.checkAdditions(check.expected); - } - Services.prefs.clearUserPref(preference); - } - -}); diff --git a/browser/components/translation/test/browser_translation_yandex.js b/browser/components/translation/test/browser_translation_yandex.js deleted file mode 100644 index 6e0af18e6..000000000 --- a/browser/components/translation/test/browser_translation_yandex.js +++ /dev/null @@ -1,130 +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 Yandex Translator client against a mock Yandex service, yandex.sjs. - -"use strict"; - -const kEnginePref = "browser.translation.engine"; -const kApiKeyPref = "browser.translation.yandex.apiKeyOverride"; -const kShowUIPref = "browser.translation.ui.show"; - -const {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {}); -const {Translation} = Cu.import("resource:///modules/translation/Translation.jsm", {}); - -add_task(function* setup() { - Services.prefs.setCharPref(kEnginePref, "yandex"); - Services.prefs.setCharPref(kApiKeyPref, "yandexValidKey"); - Services.prefs.setBoolPref(kShowUIPref, true); - - registerCleanupFunction(function () { - Services.prefs.clearUserPref(kEnginePref); - Services.prefs.clearUserPref(kApiKeyPref); - Services.prefs.clearUserPref(kShowUIPref); - }); -}); - -/** - * Ensure that the translation engine behaives as expected when translating - * a sample page. - */ -add_task(function* test_yandex_translation() { - - // Loading the fixture page. - let url = constructFixtureURL("bug1022725-fr.html"); - let tab = yield promiseTestPageLoad(url); - - // Translating the contents of the loaded tab. - gBrowser.selectedTab = tab; - let browser = tab.linkedBrowser; - - yield ContentTask.spawn(browser, null, function*() { - Cu.import("resource:///modules/translation/TranslationDocument.jsm"); - Cu.import("resource:///modules/translation/YandexTranslator.jsm"); - - let client = new YandexTranslator( - new TranslationDocument(content.document), "fr", "en"); - let result = yield client.translate(); - - Assert.ok(result, "There should be a result."); - }); - - gBrowser.removeTab(tab); -}); - -/** - * Ensure that Yandex.Translate is propertly attributed. - */ -add_task(function* test_yandex_attribution() { - // Loading the fixture page. - let url = constructFixtureURL("bug1022725-fr.html"); - let tab = yield promiseTestPageLoad(url); - - info("Show an info bar saying the current page is in French"); - let notif = showTranslationUI(tab, "fr"); - let attribution = notif._getAnonElt("translationEngine").selectedIndex; - Assert.equal(attribution, 1, "Yandex attribution should be shown."); - - gBrowser.removeTab(tab); -}); - - -add_task(function* test_preference_attribution() { - - let prefUrl = "about:preferences#content"; - let tab = yield promiseTestPageLoad(prefUrl); - - let browser = gBrowser.getBrowserForTab(tab); - let win = browser.contentWindow; - let bingAttribution = win.document.getElementById("bingAttribution"); - ok(bingAttribution, "Bing attribution should exist."); - ok(bingAttribution.hidden, "Bing attribution should be hidden."); - - gBrowser.removeTab(tab); - -}); - -/** - * A helper function for constructing a URL to a page stored in the - * local fixture folder. - * - * @param filename Name of a fixture file. - */ -function constructFixtureURL(filename) { - // Deduce the Mochitest server address in use from a pref that was pre-processed. - let server = Services.prefs.getCharPref("browser.translation.yandex.translateURLOverride") - .replace("http://", ""); - server = server.substr(0, server.indexOf("/")); - let url = "http://" + server + - "/browser/browser/components/translation/test/fixtures/" + filename; - return url; -} - -/** - * A helper function to open a new tab and wait for its content to load. - * - * @param String url A URL to be loaded in the new tab. - */ -function promiseTestPageLoad(url) { - let deferred = Promise.defer(); - let tab = gBrowser.selectedTab = gBrowser.addTab(url); - let browser = gBrowser.selectedBrowser; - browser.addEventListener("load", function listener() { - if (browser.currentURI.spec == "about:blank") - return; - info("Page loaded: " + browser.currentURI.spec); - browser.removeEventListener("load", listener, true); - deferred.resolve(tab); - }, true); - return deferred.promise; -} - -function showTranslationUI(tab, aDetectedLanguage) { - let browser = gBrowser.selectedBrowser; - Translation.documentStateReceived(browser, {state: Translation.STATE_OFFER, - originalShown: true, - detectedLanguage: aDetectedLanguage}); - let ui = browser.translationUI; - return ui.notificationBox.getNotificationWithValue("translation"); -} diff --git a/browser/components/translation/test/fixtures/bug1022725-fr.html b/browser/components/translation/test/fixtures/bug1022725-fr.html deleted file mode 100644 index f30edf52e..000000000 --- a/browser/components/translation/test/fixtures/bug1022725-fr.html +++ /dev/null @@ -1,15 +0,0 @@ -<!doctype html> -<html lang="fr"> - <head> - <!-- - - Text retrieved from http://fr.wikipedia.org/wiki/Coupe_du_monde_de_football_de_2014 - - at 06/13/2014, Creative Commons Attribution-ShareAlike License. - --> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <title>test</title> - </head> - <body> - <h1>Coupe du monde de football de 2014</h1> - <div>La Coupe du monde de football de 2014 est la 20e édition de la Coupe du monde de football, compétition organisée par la FIFA et qui réunit les trente-deux meilleures sélections nationales. Sa phase finale a lieu à l'été 2014 au Brésil. Avec le pays organisateur, toutes les équipes championnes du monde depuis 1930 (Uruguay, Italie, Allemagne, Angleterre, Argentine, France et Espagne) se sont qualifiées pour cette compétition. Elle est aussi la première compétition internationale de la Bosnie-Herzégovine.</div> - </body> -</html> diff --git a/browser/components/translation/test/fixtures/result-da39a3ee5e.txt b/browser/components/translation/test/fixtures/result-da39a3ee5e.txt deleted file mode 100644 index d2d14c788..000000000 --- a/browser/components/translation/test/fixtures/result-da39a3ee5e.txt +++ /dev/null @@ -1,22 +0,0 @@ -<ArrayOfTranslateArrayResponse xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> - <TranslateArrayResponse> - <From>fr</From> - <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> - <a:int>34</a:int> - </OriginalTextSentenceLengths> - <TranslatedText>Football's 2014 World Cup</TranslatedText> - <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> - <a:int>25</a:int> - </TranslatedTextSentenceLengths> - </TranslateArrayResponse> - <TranslateArrayResponse> - <From>fr</From> - <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> - <a:int>508</a:int> - </OriginalTextSentenceLengths> - <TranslatedText>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus diam sem, porttitor eget neque sit amet, ultricies posuere metus. Cras placerat rutrum risus, nec dignissim magna dictum vitae. Fusce eleifend fermentum lacinia. Nulla sagittis cursus nibh. Praesent adipiscing, elit at pulvinar dapibus, neque massa tincidunt sapien, eu consectetur lectus metus sit amet odio. Proin blandit consequat porttitor. Pellentesque vehicula justo sed luctus vestibulum. Donec metus.</TranslatedText> - <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> - <a:int>475</a:int> - </TranslatedTextSentenceLengths> - </TranslateArrayResponse> -</ArrayOfTranslateArrayResponse> diff --git a/browser/components/translation/test/fixtures/result-yandex-d448894848.json b/browser/components/translation/test/fixtures/result-yandex-d448894848.json deleted file mode 100644 index de2f5650e..000000000 --- a/browser/components/translation/test/fixtures/result-yandex-d448894848.json +++ /dev/null @@ -1 +0,0 @@ -{"code":200,"lang":"fr-en","text":["Football's 2014 World Cup","Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus diam sem, porttitor eget neque sit amet, ultricies posuere metus. Cras placerat rutrum risus, nec dignissim magna dictum vitae. Fusce eleifend fermentum lacinia. Nulla sagittis cursus nibh. Praesent adipiscing, elit at pulvinar dapibus, neque massa tincidunt sapien, eu consectetur lectus metus sit amet odio. Proin blandit consequat porttitor. Pellentesque vehicula justo sed luctus vestibulum. Donec metus."]} diff --git a/browser/components/translation/test/unit/.eslintrc.js b/browser/components/translation/test/unit/.eslintrc.js deleted file mode 100644 index d35787cd2..000000000 --- a/browser/components/translation/test/unit/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../../testing/xpcshell/xpcshell.eslintrc.js" - ] -}; diff --git a/browser/components/translation/test/unit/test_cld2.js b/browser/components/translation/test/unit/test_cld2.js deleted file mode 100644 index 9ebc4d766..000000000 --- a/browser/components/translation/test/unit/test_cld2.js +++ /dev/null @@ -1,463 +0,0 @@ -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// -// Author: dsites@google.com (Dick Sites) -// -// Unit test compact language detector, CLD2 -// - -// Test strings. -const kTeststr_en = - "confiscation of goods is assigned as the penalty part most of the courts " + - "consist of members and when it is necessary to bring public cases before a " + - "jury of members two courts combine for the purpose the most important cases " + - "of all are brought jurors or"; - -const kTeststr_aa_Latn = " nagay tanito nagay tanto nagayna naharsi nahrur nake nala nammay nammay haytu nanu narig ne ni num numu o obare obe obe obisse oggole ogli olloyta ongorowe orbise othoga r rabe rade ra e rage rakub rasitte rasu reyta rog ruddi ruga s sa al bada sa ala"; -const kTeststr_ab_Cyrl = " а зуа абзиара дақәшәоит ан лыбзиабара ахә амаӡам ауаҩы игәы иÒоу ихы иҿы ианубаалоит Ð°Ò§Ò³Ó™Ñ‹Ñ Ò§ÑˆÓ¡Ð° ахацәа лышьÒоуп аҿааÑÒа лара дрышьÒоуп"; -const kTeststr_af_Latn = " aam skukuza die naam beteken hy wat skoonvee of hy wat alles onderstebo keer wysig bosveldkampe boskampe is kleiner afgeleë ruskampe wat oor min fasiliteite beskik daar is geen restaurante of winkels nie en slegs oornagbesoekers word toegelaat bateleur"; -const kTeststr_ak_Latn = "WÉ”woo Hilla Limann Mumu-ƆpÉ›nimba 12 afe 1934. WÉ”woo no wÉ” Gwollu wÉ” Sisala Mantaw mu Nna ne maame yÉ› Mma Hayawah. Ne papa so nna É”yÉ› Babini Yomu. Ɔwarr Fulera Limann ? Ne mba yÉ› esuon-- Lariba Montia [wÉ”woo no Limann]; Baba Limann; Sibi Andan [wÉ”woo no Limann]; Lida Limann; Danni Limann; Zilla Limann na Salma Limann. Ɔtenaa ase kÉ”pemm Sanda-Kwakwa da É›tÉ” so 23 wÉ” afe 1998 wÉ” ?."; -const kTeststr_am_Ethi = " ለመጠá‹á‰… ወደ እስáŠáŠ•á‹µáˆá‹« ላኩዋቸá‹áŠ“ የእስáŠáŠ•á‹µáˆá‹« ጳጳስ አቴናስዮስ áሬáˆáŠ•áŒ¦áˆµáŠ• እራሳቸá‹áŠ• ሾመዠáˆáŠ¨á‹‹áˆ ከዚያ እስከ á‹“ ሠድረስ የኢትዮጵያ አቡáŠ"; -const kTeststr_ar_Arab = "اØتيالية بيع أي Øساب"; -const kTeststr_as_Beng = "অঞà§à¦šà¦² নতà§à¦¨ সদসà§à¦¯à¦¬à§ƒà¦¨à§à¦¦ সকলোৱে à¦à§°à§à¦¤à¦¿ হব পাৰে মà§à¦² পৃষà§à¦ া জন লেখক গà§à¦— ল দল সাৰাংশ ই পতà§à§° টা বাৰà§à¦¤à¦¾ à¦à¦œà¦¨"; -const kTeststr_ay_Latn = " aru wijar aru ispañula ukaran aru witanam aru kurti aru kalis aru warani aru malta aru yatiyawi niya jakitanaka isluwiñ aru lmir phuran aru masirunan aru purtukal aru kruwat aru jakira urtu aru inklisa pirsan aru suyku aru malay aru jisk aptayma thaya"; -const kTeststr_az_Arab = " آذربایجان دا انسان Øاقلاری ائوی آچیلاجاق ب Ù… ت ائلچيسي برمه موخاليÙتي نين ليدئري ايله گؤروشه بيليب ترس شوونيسم Ùارس از آزادي ملتهاي تورکمن"; -const kTeststr_az_Latn = " a az qalıb breyn rinq intellektual oyunu üzrÉ™ yarışın zona mÉ™rhÉ™lÉ™lÉ™ri keçirilib miq un qalıqlarının dÉ™nizdÉ™n çıxarılması davam edir mÉ™hÉ™mmÉ™d peyÄŸÉ™mbÉ™rin karikaturalarını çap edÉ™n qÉ™zetin baÅŸ redaktoru iÅŸ otağında ölüb"; -const kTeststr_ba_Cyrl = " арналђан бындай ђилми Ñш тіркињлњ тњјге тапєыр нњшер ителњ ғинуар бєхет именлектє етешлектє ауыл ўќмерџєре хеџмєт юлын ћайлаѓанда"; -const kTeststr_be_Cyrl = " а друкаваць Ñ–Ñ… не было Ñ‚Ñхнічна магчыма бліжÑй за вільню тым Ñамым чаÑам нÑмецкае кіраўніцтва прапаноўвала апроч ўвÑÐ´Ð·ÐµÐ½Ð½Ñ Ð»Ð°Ñ†Ñ–Ð½ÐºÑ– Ñе"; -const kTeststr_bg_Cyrl = " а дума попада в ÑÑŠÑтоÑние на изпитание ключовите думи Ñ Ð¿Ñ€ÐµÐ´Ñказана малко под то изиÑкване на Ñтраниците за Ñ‚ÑŠÑ€Ñене в"; -// From 10% testing part of new lang=bh scrape -const kTeststr_bh_Deva = "काल में उनका हमला से बचे खाती à¤à¤¹à¤¿à¤œà¤¾ à¤à¤¾à¤— के अइले आ à¤à¥‹à¤œà¤ªà¥à¤° नाम से नगर बसवले. à¤à¤•à¤°à¤¾ बारे में विसà¥à¤¤à¤¾à¤° से जानकारी नीचे दीहल गइल बा. बाकिर आशà¥à¤šà¤°à¥à¤¯à¤œà¤¨à¤• रूप से मालवा के राजा à¤à¥‹à¤œ के बिहार आवे आ à¤à¥‹à¤œà¤ªà¥à¤° नगर बसावे आ चाहे à¤à¥‹à¤œà¤ªà¥à¤°à¥€ के साथे उनकर कवनो संबंध होखे के कवनो जानकारी à¤à¥‹à¤ªà¤¾à¤² के à¤à¥‹à¤œ संसà¥à¤¥à¤¾à¤¨ आ चाहे मधà¥à¤¯ पà¥à¤°à¤¦à¥‡à¤¶ के इतिहासकार लोगन के तनिको नइखे. हालांकि ऊ सब लोग à¤à¤¹ बात के मानत बा कि à¤à¤•à¤°à¤¾ बारे में अबहीं तकले मूरà¥à¤¤à¤¿ बनवइलें. राजा à¤à¥‹à¤œ के जवना जगहा पऽ वागà¥à¤¦à¥‡à¤µà¥€ के दरà¥à¤¶à¤¨ à¤à¤‡à¤² रहे, ओही सà¥à¤¥à¤¾à¤¨ पऽ à¤à¤¹ मूरà¥à¤¤à¤¿ के सà¥à¤¥à¤¾à¤ªà¤¨à¤¾ कइल गइल. अब अगर à¤à¤¹ मंदिर के à¤à¤¹ शिलालेख के तसà¥à¤µà¥€à¤° (पृषà¥à¤ संखà¥à¤¯à¤¾ 33 पऽ पà¥à¤°à¤•à¤¾à¤¶à¤¿à¤¤) रउआ धेयान से देखीं तऽ à¤à¤•à¤°à¤¾ पऽ कैथी लिपि में -सीताराम- लिखल साफ लउकत बा. कैथी à¤à¥‹à¤œà¤ªà¥à¤°à¥€ के बहà¥à¤¤ पà¥à¤°à¤šà¤²à¤¿à¤¤ लिपि रहल बिया. à¤à¤•à¤°à¤¾ बारे में कवनो शंका संदेह बिहार-यूपी के जानकार लोगन में नइखे. à¤à¤². à¤à¤¸. à¤à¤¸. वो माले के लिखल पढ़ीं "; - -const kTeststr_bi_Latn = " king wantaem nomo hem i sakem setan mo ol rabis enjel blong hem oli aot long heven oli kamdaon long wol taswe ol samting oli kam nogud olgeta long wol ya stat long revelesen ol faet kakae i sot ol sik mo fasin blong brekem loa oli kam antap olgeta samting"; -const kTeststr_blu_Latn = " Kuv hlub koj txawm lub ntuj yuav si ntshi nphaus los kuv tsis ua siab nkaug txawm ntiab teb yuav si ntshi nphaus los kuv tseem ua lon tsaug vim kuv hlub koj tag lub siab"; -const kTeststr_blu_Latn2 = "Kuv hnov Txhiaj Xeeb Vaj, co-owner of Hmong Village Shopping Center, hais ua hnub ua hmo tias kom Hmoob yuav tsum txhawb Hmoob thiab listed cov mini-shops uas nyob rau hauv nws lub MALL txhua txhua kom sawv daws mus txhawb, tiam sis uas cas zaum twg twb pom nws mus kav kiav hauv taj laj qhabmeem (Sun Foods) xwb tiag. Nag hmo kuv pom nws mus shopping nrog nws poj niam hauv Sun Foods. Thaum tawm mus txog nraum parking lot kuv thiaj txhob txwm mus ze ze seb ua li nws mus yuav dab tsi tiag, thiab seb tej uas nws yuav ntawd puas muaj nyob ntawm tej kiab khw Hmoob. Surprised!!! Vuag.... txhua yam nws yuav hauv Sun Foods peb Hmoob cov khw yeej muaj tag nrho. Peb niaj hnub nqua hu kom Hmoob yuav tsum pab Hmoob yog pab li no lod?"; -// From 10% testing part of new lang=bn scrape -const kTeststr_bn_Beng = "গà§à¦¯à¦¾à¦²à¦¾à¦°à¦¿à¦° ৩৮ বছর পূরà§à¦¤à¦¿à¦¤à§‡ মূলà§à¦¯à¦›à¦¾à§œ অরà§à¦¥à¦¨à§€à¦¤à¦¿ বিà¦à¦¨à¦ªà¦¿à¦° ওয়াক আউট তপন চৌধà§à¦°à§€ হারবাল অà§à¦¯à¦¾à¦¸à§‹à¦¸à¦¿à§Ÿà§‡à¦¶à¦¨à§‡à¦° সà¦à¦¾à¦ªà¦¤à¦¿ আনà§à¦¤à¦°à§à¦œà¦¾à¦¤à¦¿à¦• পরামরà§à¦¶à¦• বোরà§à¦¡ দিয়ে শরিয়াহৠইননà§à¦¡à§‡à¦•à§à¦¸ করবে সিà¦à¦¸à¦‡ মালিকপকà§à¦·à§‡à¦° কানà§à¦¨à¦¾, শà§à¦°à¦®à¦¿à¦•à§‡à¦° অনিশà§à¦šà§Ÿà¦¤à¦¾ মতিà¦à¦¿à¦²à§‡ সমাবেশ নিষিদà§à¦§: à¦à¦«à¦¬à¦¿à¦¸à¦¿à¦¸à¦¿à¦†à¦‡à§Ÿà§‡à¦° ধনà§à¦¯à¦¬à¦¾à¦¦ বিনোদন বিশেষ পà§à¦°à¦¤à¦¿à¦¬à§‡à¦¦à¦¨ বাংলালিংকের গà§à¦°à§à¦¯à¦¾à¦¨à§à¦¡à¦®à¦¾à¦¸à§à¦Ÿà¦¾à¦° সিজন-৩ বà§à¦°à¦¾à¦œà¦¿à¦²à§‡ বিশà§à¦¬à¦•à¦¾à¦ª ফà§à¦Ÿà¦¬à¦² আয়োজনবিরোধী বিকà§à¦·à§‹à¦ দেশের নিরাপতà§à¦¤à¦¾à¦° চেয়ে অনেক বেশি সচেতন । পà§à¦°à¦¾à¦°à§à¦¥à§€à¦¦à§‡à¦° দকà§à¦·à¦¤à¦¾ ও যোগà§à¦¯à¦¤à¦¾à¦° পাশাপাশি তারা জাতীয় ইসà§à¦¯à§à¦—à§à¦²à§‹à¦¤à§‡ পà§à¦°à¦¾à¦§à¦¾à¦¨à§à¦¯ দিয়েছেন । †পাà¦à¦šà¦Ÿà¦¿ সিটিতে ২০ লাখ à¦à§‹à¦Ÿà¦¾à¦°à¦¦à§‡à¦° দিয়ে জাতীয় নিরà§à¦¬à¦¾à¦šà¦¨à§‡ ৮ কোটি à¦à§‹à¦Ÿà¦¾à¦°à¦¦à§‡à¦° সঙà§à¦—ে তà§à¦²à¦¨à¦¾ করা যাবে কি à¦à¦•à¦œà¦¨ দরà§à¦¶à¦•à§‡à¦° à¦à¦®à¦¨ পà§à¦°à¦¶à§à¦¨à§‡ জবাবে আবà§à¦¦à§à¦²à§à¦²à¦¾à¦¹ আল নোমান বলেন , “ à¦à¦‡ পাà¦à¦šà¦Ÿà¦¿ সিটি করà§à¦ªà§‹à¦°à§‡à¦¶à¦¨ নিরà§à¦¬à¦¾à¦šà¦¨ দেশের পাà¦à¦šà¦Ÿà¦¿ বড় বিà¦à¦¾à¦—ের পà§à¦°à¦¤à¦¿à¦¨à¦¿à¦§à¦¿à¦¤à§à¦¬ করছে । à¦à¦›à¦¾à§œà¦¾ à¦à¦–ানকার à¦à§‹à¦Ÿà¦¾à¦° রা সবাই সচেতন । তারা"; - -// From 10% testing part of new lang=bo scrape -const kTeststr_bo_Tibt = " ་གྱིས་à½à¼‹à½†à½ºà½ ི་ཕྱག་འཚལ་à½à½„་ཞིག་བཤིག་སྲིད་པ༠ཡར་ཀླུང་གཙང་པོར་ཆ ུ་མཛོང་བརྒྱག་རྒྱུའི་ལས་འཆར་ལ་རྒྱ་གར་གྱི་སེམས་ཚབས༠རྒྱ་གརགྱི་མཚོ་འོག་དམག་གྲུར་སྦར་གས་བྱུང་བ༠པ་ཀི་སི་à½à½“་གྱིས་རྒྱ་གར་ལ་མི་སེར་བསད་པའི་སà¾à¾±à½¼à½“་འཛུགས་བྱས་པ༠རྩོམ་ཡིག་མང་བ༠འབྲེལ་མà½à½´à½‘་བརྒྱུད་ལམ༠à½à½¼à½“་སà¾à¾±à½ºà½‘་དང་སྲི་ཞུ༠་à½à½¼à½‚་དེབ་བཞི་ དཔར་འགྲེམས་གནང་ཡོད་པ་དང་བོད་ཡིག་དྲ་ཚིགས་à½à½‚་ནང་ལ་ཡང་རྩོམ་ཡང་ཡང་བྲིས་གནང་མà½à½“་རེད༠ལེ་ཚན་à½à½‚ ལེ་ཚན་à½à½‚ འབྲེལ་ཡོད༠འགྲེམ་སྟོན༠རྒྱུད་ལམ་སྣ་མང་ཡིག་མཛོད༠བཀོལ་སྤྱོད་པའི་འཇོག་ཡུལ་དྲ་ངོས༠སྔོན་མ༠རྗེས་མ༠བསྟན་འཛིན་བདེ་སà¾à¾±à½²à½‘༠ཚེ་རིང་རྣམ་རྒྱལ༠བསྟན་འཛིན་ངག་དབང་༠ཡོལ་གདོང་ཚེ་རིང་ལྷག་པ༠་དབང་ ཕྱུག་གཉིས་ཀྱིས་བརྗོད་གཞི་བྱེ་བྲག་པ་ཞིག་ལ་བགྲོ་གླེང་གà½à½²à½„་ཟབ་བྱེད་པའི་གཟའ་ འà½à½¼à½¢à¼‹à½‚ཉིས་རེའི་མཚམས་ཀྱི་ལེ་ཚན་ཞིག་ཡིན༠དཔྱད་ཞིབ་ཀྱིས་རྒྱ་ནག་ནང་à½à½´à½£à¼‹à½‚ྱི་འགྱུར་ལྡོག་དང༌༠རྒྱ་ནག་དང་རྒྱལ་སྤྱིའི་འབྲེལ་བར་དམིགས་སུ་བཀར་ནས་བགྲོ་གླེང་བྱེད་ཀྱི་ཡོདà¼à¼ རྒྱང་སྲིང་དུས་ཚོདà¼"; - -const kTeststr_br_Latn = " a chom met leuskel a ra e blas da jack irons dilabour hag aet kuit eus what is this dibab a reont da c houde michael beinhorn evit produiñ an trede pladenn kavet e vez ar ganaouennoù buhan ha buhan ganto setu stummet ar bladenn adkavet e vez enni funk"; -const kTeststr_bs_Cyrl = "иÑторија боÑне књ иÑторија боÑне књ иÑторија боÑне књ иÑторија боÑне књ "; -// From 10% testing part of new lang=bs scrape -const kTeststr_bs_Latn = "Novi predsjednik MeÅ¡ihata Islamske zajednice u Srbiji (IZuS) i muftija dr. Mevlud ef. Dudić izjavio je u intervjuu za Anadolu Agency (AA) kako je uvjeren da će doći do vraćanja jedinstva meÄ‘u muslimanima i unutar Islamske zajednice na prostoru Sandžaka, te da je njegova ruka pružena za povratak svih u okrilje Islamske zajednice u Srbiji nakon skoro sedam godina podjela u tom dijelu Srbije. Dudić je za predsjednika MeÅ¡ihata IZ u Srbiji izabran 4. januara, a zvaniÄna inauguracija će biti obavljena u prvoj polovini februara. Kako se oÄekuje, prisustvovat će joj i reisu-l-ulema Islamske zajednice u Srbiji Husein ef. Kavazović koji će i zvaniÄno promovirati Dudića u novog prvog Äovjeka IZ u Srbiji. Dudić će danas boraviti u prvoj zvaniÄnoj posjeti reisu Kavazoviću, Å¡to je njegov privi simboliÄni potez nakon imenovanja. "; - -const kTeststr_ca_Latn = "al final en un únic lloc nhorabona l correu electrònic està concebut com a eina de productivitat aleshores per què perdre el temps arxivant missatges per després intentar recordar on els veu desar i per què heu d eliminar missatges importants per l"; -const kTeststr_ceb_Latn = "Ang Sugbo usa sa mga labing ugmad nga lalawigan sa nasod. Kini ang sentro sa komersyo, edukasyon ug industriya sa sentral ug habagatang dapit sa kapupod-an. Ang mipadayag sa Sugbo isip ikapito nga labing nindot nga pulo sa , ang nag-inusarang pulo sa Pilipinas nga napasidunggan sa maong magasin sukad pa sa tuig"; -const kTeststr_ceb_Latn2 = "Ang mga komyun sa Pransiya duol-duol sa inkorporadong mga lungsod ug mga dakbayan sa Estados Unidos. Wala kini susamang istruktura sa Hiniusang Gingharian (UK) tungod kay ang estado niini taliwala sa di-metropolitan nga distrito ug sa sibil nga parokya. Wala usab kini susamang istruktura sa Pilipinas."; -const kTeststr_chr_Cher = "ᎠᎢáᎩ ᎠáŸáŽ¶áá— á¥á„áá›áŽ© ᎦᎫáá›á…Ꭿ ᎾᎥᎢ"; -const kTeststr_co_Latn = " a prupusitu di risultati for utilizà a scatula per ricercà ind issi risultati servore errore u servore ha incuntratu una errore pruvisoria é ùn ha pussutu compie a vostra dumanda per piacè acimenta dinò ind una minuta tuttu listessu ligami truvà i"; -const kTeststr_crs_Latn = "Sesel ou menm nou sel patri. Kot nou viv dan larmoni. Lazwa, lanmour ek lape. Nou remersye Bondye. Preserv labote nou pei. Larises nou losean. En leritaz byen presye. Pour boner nou zanfan. Reste touzour dan linite. Fer monte nou paviyon. Ansanm pou tou leternite. Koste Seselwa!"; -const kTeststr_cs_Latn = " a akci opakujte film uložen vykreslit gmail tokio smazat obsah adresáře nelze naÄÃst systémový profil jednotky smoot okud použÃváte pro urÄenà polokoule znaÄky z západ nebo v východ použÃvejte nezáporné hodnoty zemÄ›pisné délky nelze"; -const kTeststr_cy_Latn = " a chofrestru eich cyfrif ymwelwch a unwaith i chi greu eich cyfrif mi fydd yn cael ei hysbysu o ch cyfeiriad ebost newydd fel eich bod yn gallu cadw mewn cysylltiad drwy gmail os nad ydych chi wedi clywed yn barod am gmail mae n gwasanaeth gwebost"; -const kTeststr_da_Latn = " a z tallene og punktummer der er tilladte log ud angiv den ønskede adgangskode igen november gem personlige oplysninger kontrolspørgsmÃ¥l det sidste tegn i dit brugernavn skal være et bogstav a z eller tal skriv de tegn du kan se i billedet nedenfor"; -const kTeststr_de_Latn = " abschnitt ordner aktivieren werden die ordnereinstellungen im farbabschnitt deaktiviert öchten sie wirklich fortfahren eldtypen angeben optional n diesem schritt geben sie für jedesfeld aus dem datenset den typ an ieser schritt ist optional eldtypen"; -const kTeststr_dv_Thaa = " Þ€Þ¨Þ‚Þ°Þ‹Þ© Þ„Þ¦Þ€ÞªÞ‚Þ° ÞˆÞ§Þ€Þ¦Þ†Þ¦ Þ‹Þ¦Þ‡Þ°Þ†Þ§Þ‡Þ¨ÞƒÞª Þ‹Þ¬ÞˆÞ¦Þ‚Þ¦ Þ„Þ¦Þ€Þ¬Þ‡Þ°ÞŽÞ¬ ގޮތުގައާއި Þ‡Þ¬Þ‚Þ«Þ‚Þ° ގޮތްގޮތުން Þ€Þ¨Þ‚Þ°Þ‹Þ© Þ„Þ¦Þ€ÞªÞ‚Þ° ÞˆÞ§Þ€Þ¦Þ†Þ¦ Þ‹Þ¦Þ‡Þ°Þ†Þ§ Þ‰Þ©Þ€ÞªÞ‚Þ°ÞŽÞ¬ Þ‡Þ¦Þ‹Þ¦Þ‹Þª Þ‰Þ¨ÞÞ¨Þ‡Þ¦Þ‚Þ¦ÞÞ°"; -const kTeststr_dz_Tibt = " རྩིས བརà¾à¾±à½– ཚུལ ལྡན དང ངེས བདེན སྦ སྟོན ནིའི དོན ལུ à½à¾±à½¼à½‘ གུག ཤད ལག ལེན འà½à½– དགོ ག དང ཨིན པུཊི གྲལ à½à½²à½‚ གུ"; -const kTeststr_ee_Latn = "Yi (Di tanya sia) tatia akÉ” wò ayi axa yeye dzi kple tanya si sÉ” kple esi wòŋlÉ” É–e goa me, negbe axaa É–e li kpakple tanya mawo xoxo ko. TeÆ’e le axa yeye sia dzi si wòateÅ‹u atia na kpekpeÉ–eÅ‹u kple nuwoÅ‹lɔŋlÉ” ne anÉ” hahiãm na wò. Mehiã be na gbugbÉ” ava afii na axa yeye gÉ”medzedze o. WoateÅ‹u adze wo gÉ”me kple nuŋɔŋlÉ” dzẽwo tatia. Megavɔ̃ na nuyeyewo gÉ”medzedze kroa o."; -const kTeststr_el_Grek = " ή αÏνητική αναζήτηση λÎξης ÎºÎ»ÎµÎ¹Î´Î¹Î¿Ï ÎºÎ±Ï„Î±ÏƒÏ„Î®ÏƒÏ„Îµ τις μεμονωμÎνες λÎξεις κλειδιά πεÏισσότεÏο στοχοθετημÎνες με τη μετατÏοπή τους σε"; -const kTeststr_en_Latn = " a backup credit card by visiting your billing preferences page or visit the adwords help centre for more details https adwords google com support bin answer py answer hl en we were unable to process the payment of for your outstanding google adwords"; -const kTeststr_eo_Latn = " a jarcento refoje per enmetado de koncerna pastro tiam de reformita konfesio ekde refoje ekzistis luteranaj komunumanoj tamen tiuj fondis propran komunumon nur en ambaÅ apartenis ekde al la evangela eklezio en prusio resp ties rejnlanda provinceklezio en"; -const kTeststr_es_Latn = " a continuación haz clic en el botón obtener ruta también puedes desplazarte hasta el final de la página para cambiar tus opciones de búsqueda gráfico y detalles ésta es una lista de los vÃdeos que te recomendamos nuestras recomendaciones se basan"; -const kTeststr_et_Latn = " a niipea kui sinu maksimaalne igakuine krediidi limiit on meie poolt heaks kiidetud on sinu kohustuseks see krediidilimiit"; -const kTeststr_eu_Latn = " a den eraso bat honen kontra hortaz eragiketa bakarrik behar dituen eraso batek aes apurtuko luke nahiz eta oraingoz eraso bideraezina izan gaur egungo teknologiaren mugak direla eta oraingoz kezka hauek alde batera utzi daitezke orain arteko indar"; -const kTeststr_fa_Arab = " آب خوردن عجله Ù…ÛŒ کردند به جای باز ÛŒ کتک کاری Ù…ÛŒ کردند Ùˆ همه چيز مثل قبل بود Ùقط من ماندم Ùˆ ÙŠÚ© دنيا Øر٠و انتظار تا عاقبت رسيد اØضاريه ÛŒ ای با"; -const kTeststr_fi_Latn = " a joilla olet käynyt tämä kerro meille kuka ä olet ei tunnistettavia käyttötietoja kuten virheraportteja käytetään google desktopin parantamiseen etsi näyttää mukautettuja uutisia google desktop keskivaihto leikkaa voit kaksoisnapsauttaa"; -const kTeststr_fj_Latn = " i kina na i iri ka duatani na matana main a meke wesi se meke mada na meke ni yaqona oqo na meke ka dau vakayagataki ena yaqona vakaturaga e dau caka toka ga kina na vucu ka dau lagati tiko kina na ka e yaco tiko na talo ni wai ni yaqona na lewai ni wai"; -const kTeststr_fo_Latn = " at verða átaluverdar óhóskandi ella áloypandi vit kunnu ikki garanterða at google leitanin ikki finnur naka sum er áloypandi óhóskandi ella átaluvert og google tekur onga ábyrgd yvir tær sÃður sum koma við à okkara leitiskipan fá tær ein"; -const kTeststr_fr_Latn = " a accès aux collections et aux frontaux qui lui ont été attribués il peut consulter et modifier ses collections et exporter des configurations de collection toutefois il ne peut pas créer ni supprimer des collections enfin il a accès aux fonctions"; -const kTeststr_fy_Latn = " adfertinsjes gewoan lytse adfertinsjes mei besibbe siden dy t fan belang binne foar de ynhâld fan jo berjochten wolle jo mear witte fan gmail foardat jo jo oanmelde gean dan nei wy wurkje eltse dei om gmail te ferbetterjen dêrta sille wy jo sa út en"; -const kTeststr_ga_Latn = " a bhfuil na focail go léir i do cheist le fáil orthu nà gá ach focail breise a chur leis na cinn a cuardaÃodh cheana chun an cuardach a bheachtú nó a chúngú má chuirtear focal breise isteach aimseofar fo aicme ar leith de na torthaà a fuarthas"; -const kTeststr_gaa_Latn = "Akε mlawookpeehe kε MaÅ‹hiεnyiεl×› oshikif×›×› lε eba naagbee ni maÅ‹ lε nitsum×› ni kwεכ oshikif×›×› n×› lε ets×›×› m×› ni ye kunim ni akε lε eta esεŋ n×›. Dani nomεi baaba n×› lε, maÅ‹ n×›kwεm×› kui wuji eny×› ni y×›×› w×› maÅ‹ lε mli, NPP kε NDC mli bii f×›f×›i wiem×›i kεmaje majee amεhe. Ekomεi kwraa po yafee hiεkwεm×›i ni ha ni gidigidi, pilam×› kε la shishwiem×› aaba yε heikomεi. "; -const kTeststr_gd_Latn = " air son is gum bi casg air a h uile briosgaid no gum faigh thu brath nuair a tha briosgaid a tighinn gad rannsachadh ghoogle gu ceart mura bheil briosgaidean ceadaichte cuiridh google briosgaid dha do neach cleachdaidh fa leth tha google a cleachdadh"; -const kTeststr_gl_Latn = " debe ser como mÃnimo taranto tendas de venda polo miúdo cociñas servizos bordado canadá viaxes parques de vehÃculos de recreo hotel oriental habitación recibir unha postal no enderezo indicado anteriormente"; -const kTeststr_gn_Latn = " aháta añe ë ne mbo ehára ndive ajeruréta chupe oporandujey haÄua peëme mba épa pekaru ha áÄa oporandúvo nde eréta avei re paraguaýpe kachÃke he i leúpe ndépa re úma kure tatakuápe ha leu ombohovái héë ha ujepéma kachÃke he ijey"; -const kTeststr_gu_Gujr = " આના પરિણામ પà«àª°àª®àª¾àª£àª¸àª° ફોનà«àªŸ અવતરણ ચિનà«àª¹àªµàª¾àª³àª¾ પાઠને છà«àªªàª¾àªµà«‹ બધા સમૂહો શોધાયા હાલનો જ સંદેશ વિષયની"; -const kTeststr_gv_Latn = " and not ripe as i thought yn assyl yn shynnagh as yn lion the ass the fox and the lion va assyl as shynnagh ayns commee son nyn vendeilys as sauchys hie ad magh ayns y cheyll dy shelg cha row ad er gholl feer foddey tra veeit ad rish lion yn shynnagh"; -const kTeststr_ha_Latn = " a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako daga guda daga ranar zuwa a kan sakamako daga shafukan daga ranar zuwa a kan sakamako daga guda a cikin last hour a kan sakamako daga guda daga kafar"; -const kTeststr_haw_Latn = "He puke noiÊ»i kÅ«Ê»ikena kÅ«noa Ê»o Wikipikia. E Ê»oluÊ»olu nÅ, e hÄÊ»awi mai i kÄu Ê»ike, kÄu manaÊ»o, a me kou leo no ke kÅ«kulu Ê»ana a me ke kÄkoÊ»o Ê»ana mai i ka Wikipikia HawaiÊ»i. He kahua pÅ«naewele HawaiÊ»i kÄ“ia no ka hoÊ»oulu Ê»ana i ka Ê»ike HawaiÊ»i. InÄ hiki iÄ Ê»oe ke Ê»Ålelo HawaiÊ»i, e Ê»oluÊ»olu nÅ, e kÅkua mai a e hoÊ»ololi i nÄ Ê»atikala ma Ê»aneÊ»i, a pono e haÊ»i aku i kou mau hoa aloha e pili ana i ka Wikipikia HawaiÊ»i. E ola mau nÅ ka Ê»Ålelo HawaiÊ»i a mau loa aku."; -const kTeststr_hi_Deva = " ं à¤à¤¡à¤µà¤°à¥à¤¡à¥à¤¸ विजà¥à¤žà¤¾à¤ªà¤¨à¥‹à¤‚ के अनà¥à¤à¤µ पर आधारित हैं और इनकी मदद से आपको अपने विजà¥à¤žà¤¾à¤ªà¤¨à¥‹à¤‚ का अधिकतम लाà¤"; -const kTeststr_hr_Latn = "Posljednja dva vladara su Kijaksar (ΚυαξαÏης; 625-585 prije Krista), fraortov sin koji će proÅ¡iriti teritorij Medije i Astijag. Kijaksar je imao kćer ili unuku koja se zvala Amitis a postala je ženom Nabukodonosora II. kojoj je ovaj izgradio Viseće vrtove Babilona. Kijaksar je modernizirao svoju vojsku i uniÅ¡tio Ninivu 612. prije Krista. Naslijedio ga je njegov sin, posljednji medijski kralj, Astijag, kojega je detronizirao (sruÅ¡io sa vlasti) njegov unuk Kir Veliki. Zemljom su zavladali Perzijanci."; -const kTeststr_ht_Latn = " ak pitit tout sosyete a chita se pou sa leta dwe pwoteje yo nimewo leta fèt pou li pwoteje tout paran ak pitit nan peyi a menm jan kit paran yo marye kit yo pa marye tout manman ki fè pitit leta fèt pou ba yo konkoul menm jan tou pou timoun piti ak pou"; -const kTeststr_hu_Latn = " a felhasználóim a google azonosÃtó szöveget ikor látják a felhasználóim a google azonosÃtó szöveget felhasználók a google azonosÃtó szöveget fogják látni minden tranzakció után ha a vásárlását regisztrációját oldalunk"; -const kTeststr_hy_Armn = " Õ¡ Õµ Õ¥Õ¾ Õ¶Õ¡ Õ°Õ«Õ¡ÖÕ¡Õ® Õ¡Õ¹Ö„Õ¥Ö€Õ¸Õ¾ Õ¶Õ¡ÕµÕ¸Ö‚Õ´ Õ§ Õ°Õ«Õ¶Õ£Õ°Õ¡Ö€Õ¯Õ¡Õ¶Õ« Õ·Õ¥Õ¶Ö„Õ« Õ¿Õ¡Ö€Ö…Ö€Õ«Õ¶Õ¡Õ¯ ÖƒÕ¸Ö„Ö€Õ«Õ¯ Ö„Õ¡Õ¼Õ¡Õ¯Õ¸Ö‚Õ½Õ« ÕºÕ¡Õ¿Õ¸Ö‚Õ°Õ¡Õ¶Õ¶Õ¥Ö€Õ«Õ¶ Õ¤Õ¥Õ¼ Õ´Õ¥Õ¶Ö„ Õ·Õ¡Õ¿ Õ¥Õ¶Ö„ Õ°Õ¥Õ¿Õ¡Õ´Õ¶Õ¡Ö Õ¡Õ½Õ¸Ö‚Õ´ Õ§ Õ¶Õ¡ Õ¡ÕµÕ½ÕºÕ¥Õ½ Õ§"; -const kTeststr_ia_Latn = " super le sitos que tu visita isto es necessari pro render disponibile alcun functionalitates del barra de utensiles a fin que nos pote monstrar informationes ulterior super un sito le barra de utensiles debe dicer a nos le"; -// From 10% testing part of new lang=id scrape -const kTeststr_id_Latn = "berdiri setelah pengurusnya yang berusia 83 tahun, Fayzrahman Satarov, mendeklarasikan diri sebagai nabi dan rumahnya sebagai negara Islam Satarov digambarkan sebagai mantan ulama Islam tahun 1970-an. Pengikutnya didorong membaca manuskripnya dan kebanyakan dilarang meninggalkan tempat persembunyian bawah tanah di dasar gedung delapan lantai mereka. Jaksa membuka penyelidikan kasus kriminal pada kelompok itu dan menyatakan akan membubarkan kelompok kalau tetap melakukan kegiatan ilegal seperti mencegah anggotanya mencari bantuan medis atau pendidikan. Sampai sekarang pihak berwajib belum melakukan penangkapan meskipun polisi mencurigai adanya tindak kekerasan pada anak. Pengadilan selanjutnya akan memutuskan apakah anak-anak diizinkan tetap tinggal dengan orang tua mereka. Kazan yang berada sekitar 800 kilometer di timur Moskow merupakan wilayah Tatarstan yang"; - -const kTeststr_ie_Latn = " abhorre exceptiones in li derivation plu cardinal por un l i es li regularità del flexion conjugation ples comparar latino sine flexione e li antiqui projectes naturalistic queles have quasi null regules de derivation ma si on nu examina li enunciationes"; -const kTeststr_ig_Latn = "Chineke bụ aha á»zá» ndï omenala Igbo kpá»ro Chukwu. Mgbe ndị bekee bịara, ha mee ya nke ndi Christian. N'echiche ndi ekpere chi Omenala Ndi Igbo, Christianity, Judaism, ma Islam, Chineke nwere á»tụtụ utu aha, ma nwee nanị otu aha. Ụzá» abụỠe si akpá» aha ahụ bụ Jehovah ma Ọ bụ Yahweh. Na á»tụtụ Akwụkwá» Nsá», e wepụla aha Chineke ma jiri utu aha bụ Onyenwe Anyị ma á» bụ Chineke dochie ya. Ma mgbe e dere akwụkwá» nsá», aha ahụ bụ Jehova pụtara n’ime ya, ihe dị ka ugboro pụkụ asaa(7,000)."; -// From 10% testing part of new lang=ik scrape -const kTeststr_ik_Latn = "sabvaqjuktuq sabvaba atiqaqpa atiqaqpa ibiq iebiq ixafich niuqtulgiññatif uvani natural gas tatpikka ufasiksigiruaq maaffa savaannafarufa mi tatkivani navy qanuqjugugguuq taaptuma inna uqsrunik ivaqjiqhutik taktuk allualiuqtuq sigukun nanuq puuvraatuq taktuum amugaa kalumnitigun nanuq agliruq allualiuqtuq"; - -const kTeststr_is_Latn = " a afköst leitarorða þinna leitarorð neikvæð leitarorð auglýsingahópa byggja upp aðallista yfir ný leitarorð fyrir auglýsingahópana og skoða Ãtarleg gögn um árangur leitarorða eins og samkeppni auglýsenda og leitarmagn er krafist notkun"; -const kTeststr_it_Latn = " a causa di un intervento di manutenzione del sistema fino alle ore circa ora legale costa del pacifico del novembre le campagne esistenti continueranno a essere pubblicate come di consueto anche durante questo breve periodo di inattività ci scusiamo per"; -const kTeststr_iu_Cans = "áƒá‘¯á’ªá’»á’ªá‘¦ ᕿᓈá–á“ᓇᓲᖑᒻᒪᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ ᑎᑦᕆáŠá‘á“á–ᑦᑕᑎᑦ ᑎᑎᖅᑕᑉá±á‘¦ ᓯᕗᓂᖓᓂ ᑎᑎᖅᖃᖅ ᑎᑎᕆáŠá‘á“á–á‘•áƒá‘¦ ᕿᓂᓲᖑᔪá’ᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ"; -const kTeststr_he_Hebr = " ×ו לערוך ×ת העדפות ההפצה ×× × ×¢×§×•×‘ ×חרי ×”×©×œ×‘×™× ×”×‘××™× ×›× ×¡ לחשבון ×”×ישי שלך ב"; -const kTeststr_ja_Hani = " ã“ã®ãƒš ジã§ã¯ アカウントã«æŒ‡å®šã•ã‚ŒãŸäºˆç®—ã®å±¥æ´ã‚’一覧ã«ã—ã¦ã„ã¾ã™ ãã‚Œãžã‚Œã®é …ç›®ã«ã¯ 予算é¡ã¨ç‰¹å®šæœŸé–“ã®ã‚¹ãƒ† タスãŒè¡¨ç¤ºã•ã‚Œã¾ã™ ç¾åœ¨ã¾ãŸã¯ä»Šå¾Œã®äºˆç®—ã‚’è¨å®šã™ã‚‹ã«ã¯"; -const kTeststr_jw_Latn = " account ten server niki kalian username meniko tanpo judul cacahe account nggonanmu wes pol pesen mu wes diguwak pesenan mu wes di simpen sante wae pesenan mu wes ke kirim mbuh tekan ora pesenan e ke kethok pesenan mu wes ke kirim mbuh tekan ora pesenan"; -const kTeststr_ka_Geor = " რბირთვიდáƒáƒœ მიღებული ელემენტი მენდელეევის პერიáƒáƒ“ულ სიტემáƒáƒ¨áƒ˜ გáƒáƒ“áƒáƒ˜áƒœáƒáƒªáƒ•áƒšáƒ”ბს áƒáƒ ი უჯრით"; -const kTeststr_kha_Latn = " kaba jem jai sa sngap thuh ia ki bynta ba sharum naka sohbuin jong phi nangta sa pynhiar ia ka kti kadiang jong phi sha ka krung jong phi bad da kaba pyndonkam kumjuh ia ki shympriahti jong phi sa sngap thuh shapoh ka tohtit jong phi pyndonkam ia kajuh ka"; -const kTeststr_kk_Arab = " ﺎ ﻗﻴﺎﻧﺎﺕ ﺑﻮﻟﻤﺎﻳﺪﻯ ïº‘ï¯˜ï» ï˜ïº®ï»ïº—ﺴﻪﺳﯩﻦ ﻳﺎﻋﻨﻲ ﻗﺎﻻ ï»ï»£ï¯©ïº®ï¯¨ï»¨ïºªï»© ﻗﺎﺯïºï»• Ø¡ ïº—ï¯©ï» ï¯©ï»¨ï¯©ï¯” ﻗﻮﻟﺪïºï»§ï¯©ï» ﻤﺎﯞﻯ ﻗﺎﺯïºï»• ﺟﻪïºï¯¨ï»¨ïºªï»©"; -const kTeststr_kk_Cyrl = " а билердің өзіне Ñ€Ò±Ò›Ñат берілмеген егер халық талап етÑе ғана хан келіÑім берген өздеріңіз білеÑіздер қр қыл Ð¼Ñ‹Ñ Ñ‚Ñ‹Ò› кодекÑінде жазаның"; -const kTeststr_kk_Latn = " bolsa da otanyna qaityp keledi al oralmandar basqa elderde diasporasy ote az bolghandyqtan bir birine komektesip bauyrmal bolady birde men poezben oralmandardyng qazaqstangha keluin kordim monghol qazaqtary poezdan tuse sala jerdi suip jylap keletin biraq"; -const kTeststr_kl_Latn = " at nittartakkalli uani toqqarsimasatta akornanni nittartakkanut allanut ingerlaqqittoqarsinnaavoq kanukoka tassaavoq kommuneqarfiit kattuffiat nuna tamakkerlugu kommunit nittartagaannut ingerlaqqiffiusinnaasoq kisitsiserpassuit nunatsinnut tunngasut"; -const kTeststr_km_Khmr = " ក áž áž‚ ឃ áž„ áž… ឆ ជ ឈ ញ ដ áž‹ ឌ ហណ áž áž áž‘ áž’ áž“ áž” áž• áž– áž— ម áž™ ážš áž› ážœ ស áž áž¡ អ ឥ ឦ ឧ ឪ áž« ឬ ឯ áž± ទាំងអស់"; -const kTeststr_kn_Knda = " ಂಠಯà³à²¯à²¨à²µà²°à³ ತà³à²®à²•à³‚ರೠಜಿಲà³à²²à³†à²¯ ಚಿಕà³à²•à²¨à²¾à²¯à²•à²¨à²¹à²³à³à²³à²¿ ತಾಲà³à²²à³‚ಕಿನ ತೀರà³à²¥à²ªà³à²° ವೆಂಬ ಸಾಧಾರಣ ಹಳà³à²³à²¿à²¯ ಶà³à²¯à²¾à²¨à³à²à³‹à²—ರ"; -const kTeststr_ko_Hani = " 개별ì 으로 리í¬íŠ¸ 액세스 ê¶Œí•œì„ ë¶€ì—¬í• ìˆ˜ 있습니다 액세스 권한 부여사용ìžì—게 프로필 리í¬íŠ¸ì— ì•¡ì„¸ìŠ¤í• ìˆ˜ 있는 ê¶Œí•œì„ ë¶€ì—¬í•˜ì‹œë ¤ë©´ 가용 프로필 ìƒìžì—ì„œ 프로필 ì´ë¦„ì„ ì„ íƒí•œ 다ìŒ"; -// From 10% testing part of new lang=ks scrape -const kTeststr_ks_Arab = " ژماں سرابن منز گرٲن Ú†Ú¾ÙÛ Ø®Ø§Ø¨Ù•Ú© کھلونÛÙ• ؤڈراواں تÙلتÙÚ¾ Ù†Ùیَس تÛÙ• گوشÛ٠گوشÛ٠مندچھاوى۪س دÙلس Ú†Ú¾ÙÛ ÙˆÙˆÙ†Ù˜Øª ÙˆÙچھان از ستم قلم صبوÙرٕ وول مسٲÙر لیۆکھÙÙ† بێتابن منز ورل سوال Ú†Ú¾ÙÛ ØªØ±Ø§ÙˆØ§Úº جوابن منز کالÛÙ• پھۯستÛÙ• پھن٘ب Ù¾Ú¯ÙŽÛÛ Ù¾Û Ù¾Û†Øª نظر دÙÚ˜ Ù†ÛÙ• ژھالÛÙ• مٔت آرن مٲنز مسول متھان Ú†Ú¾Û’Ùš مس والن ÙˆÛ…Ù† Ú†Ú¾Û’Ùš غارن تÛ٠نارٕ Ú˜Ú¾Ù¹Ú¾ ژاپان رێش تۅرگ تراوٕÛÙ† تÛÙ• ون رٹÛÙ• ÛÙ† ÛوشÛÙ ÛÛŽÛ†Ú†Ú¾ Ù†ÛÙ• پوشنوÙلس Ù†ÙØ´ Ù…Û…Ûرٕ دی دی زٕلاں چھ٠زى۪و ØرÙÙ† لۆدرٕ Ù¾Ú¾Ù”Ù„ Ûى۪تھ ملر عازمؔ سۆدرٕ Ú©Ú¾Û…Ù†Û٠منز منگاں Ú†Ú¾ÙÛ Ù†Ø¯Ø±Ù‰ÛªÙ† پن Ú˜Û’ تھى۪کی ÛŒÛ٠مسٲÙر پنن ÙˆÙÚˆÙˆ تÛÙ• پڑاو گٕتَو گٕتَو Ú†Ú¾Û’Ùš ÛŒÛÙ Ú©Û…Ù„ بÙتھ تÛÙ• بانÛÙ• سٕÛÛ Ú¯Û…Ø±Ø¯Ù• Ú†Ú¾Û٠سپداں دمÛÙ• Ù¾ÙÚ¾Ù¹ Ú†Ú¾ÙÙ¹Û Ù¾ÙˆÙ†Ù¾Ø± Ù¾Ú©Ú¾ÛÙ• داران سÙÛ ÛŒØªÙ‰ÛªÙ† تۯاو٠کم نظر دۯاکھ تÛÙ• باسیوے سÙÛ Ù…Û†Û Ûیو یێران Ù…Û’Ùš ژى۪تÙرمÙت Ú†Ú¾ÙÛ Ø³ÙÙ„ÛŒ تس Ú†Ú¾Û’Ùš کتى۪ن تھپھ شاد مس کراں ÙˆÙÚ†Ú¾ Ù…Û’Ùš خون Ú˜Ù• خبر کیاز٠کراں دۯاکھ تمÙس پى۪ٹھ ماتم أز Ú©Û٠شبÛÙ• آو Ù…Û’Ùš بێیÛ٠پیش سÙر زانÛ٠خدا دار٠پى۪ٹھ ژٲنگ Ûنا تھو ز٠ژے Ú†Ú¾Û’Ùš مێون أنÛÙ• کپٹاں Ú†Ú¾ÙÛ Ø²Ù•Ú˜Ù† سون مظÙّر عازمؔ Ù¾ÙˆØ´Û Ø¨Ø±Ú¯Ù† Ú†Ú¾ÙÛ Ø³Ùواں چاکھ سÙÛ Ø§Ù„Ù…Ø§Ø³ قلم لو٠کٔ Úˆ نو٠سرٕ سونتس Ú©Ù„ پرو٠بۆر Ø¨ÛŽÛŒÛ Ø§Ø² بانبر٠Ûۆت یمبرزلÛ٠ٹارى۪ن منز نار وزملÛ٠کۅسÛÙ• کتھ کٔر اظÛار Ú©Ú†Ú¾Û٠منزٕ ÙˆÙ”Ù† رووÙÙ… اچھÛ٠چشمو ژوپÙÙ… Ú©Ù”Ù†Úˆ انبار تماشÛÙ Ú†Ú¾Û٠تگاں"; - -const kTeststr_ks_Deva = "नमसà¥à¤¤à¥‡ शारदे देवि काशà¥à¤®à¤¿à¤°à¤ªà¥à¤°à¥à¤µà¤¾à¤¸à¤¿à¤¨à¤¿ तà¥à¤µà¤¾à¤®à¤¹à¤® पà¥à¤°à¤¾à¤°à¥à¤¥à¤¯à¥‡ देवि विदà¥à¤¯ दानम च देहि मे कॉशà¥à¤° लेख॒नà¥à¤• सारिव॒य खॊत॒ आसान तरीक॒ छॠयि देवनागरी टाइपराइटर इसà¥à¤¤à¤¿à¤®à¤¾à¤² करà¥à¤¨. अथ मंज़ छि कॉशà¥à¤° लेख॒न॒चि सारॆय मातà¥à¤°à¤¾à¤¯à¤¿. अमि अलाव॒ हॆकिव तॊहà¥à¤¯à¥ यिम॒ यूनिकोड à¤à¤¡à¤¿à¤Ÿà¤° ति वरतॉविथ मगर कॉशिरि मातà¥à¤°à¤¾à¤¯à¤¿ लेख॒नस गछ़ि हना दिकथ: अकà¥à¤·à¤°à¤®à¤¾à¤²à¤¾à¤›à¥ अख मà¥à¤«à¤¼à¥à¤¤ त॒ सॅहॅल सोफà¥à¤Ÿà¤µà¥‡à¤° यॆमि स॒तà¥à¤¯à¥ यà¥à¤¨à¤¿à¤•à¥‹à¤¡ देवनागरी मंज़ ITRANS scheme स॒तà¥à¤¯à¥ छॠयिवान लेख॒न॒. वà¥à¤›à¤¿à¤µ: सहायता. अथ स॒तà¥à¤¯à¥ जà¥à¤¡à¤¿à¤¥ जालपृषà¥à¤ (वेबपेज) (सॉरी अà¤à¤—à¥à¤°à¥€à¤œà¤¼à¥€ पॉठà¥à¤¯)"; -const kTeststr_ku_Arab = " بۆ به ڕێوه بردنی نامه ÛŒ Ú©Ù‡ دێتن ڕاسته وخۆ Ú•Ù‡ وان بکه نامه کانی Ú¯ مایل بۆ Øسابی پۆستێکی تر هێنانی په یوه ندکاره کان له"; -const kTeststr_ku_Latn = " be zmaneki ter le inglis werdegeretewe em srvise heshta le cor beta daye wate hest a taqi dekrete u bashtr dekret tewawwzmanekan wernegrawnetewe u ne hemu laperakn ke eme pshtiwan dekayn be teaweti wergerawete nermwalley wergeran teksti new wene nasnatewe"; -const kTeststr_ky_Arab = " جانا انى تانۇۇ ۇلۇتۇن تانۇۇ قىرعىزدى بئلۉۉ دەگەندىك اچىق ايتساق ماناستى تاانىعاندىق ۅزۉÚدۉ تاانىعاندىق بۉگۉن تەما جۉكتۅمۅ Ù‚ Ù‰ رع Ù‰ ز ت Ù‰ Ù„ Ù‰"; -const kTeststr_ky_Cyrl = " агай Ñле оболу мен ÑÐ°Ð´Ñ‹Ð±Ð°ÐºÐ°Ñ Ð°Ð³Ð°Ð½Ñ‹Ð½ өзү менен ÑÐ¼ÐµÑ Ñмгектери менен тааныштым жылдары ташкенде өзбекÑтан илимдер академиÑÑынын баÑны"; -const kTeststr_la_Latn = " a deo qui enim nocendi causa mentiri solet si iam consulendi causa mentiatur multum profecit sed aliud est quod per se ipsum laudabile proponitur aliud quod in deterioris comparatione praeponitur aliter enim gratulamur cum sanus est homo aliter cum melius"; -const kTeststr_lb_Latn = " a gewerkschaften och hei gefuerdert dir dammen an dir häre vun de gewerkschaften denkt un déi aarm wann der äer fuerderunge formuléiert d sechst congés woch an aarbechtszäitverkierzung hëllefen hinnen net d unhiewe vun de steigerungssäz bei de"; -const kTeststr_lg_Latn = " abaana ba bani lukaaga mu ana mu babiri abaana ba bebayi lukaaga mu abiri mu basatu abaana ba azugaadi lukumi mu ebikumi bibiri mu abiri mu babiri abaana ba adonikamu lukaaga mu nltaaga mu mukaaga abaana ba biguvaayi enkumi bbiri mu ataano mu mukaaga"; -const kTeststr_lif_Limb = "á¤á¤¡á¤–ᤠᤳ ᤕᤠᤰᤌᤢᤱ ᤆᤢᤶᤗᤢᤱᤖᤧ ᤛᤥᤎᤢᤱᤃᤧᤴ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤆᤧᤶᤈᤱᤗᤧ á¤á¤¢á¤”ᤡᤱᤅᤥ á¤á¤ ᤈᤡᤖᤡ ᤋᤱᤒᤣ ᥈᥆᥆᥉ ᤒᤠᤈá¤á¤˜á¤–ᤡ ᤗᤠá¤á¤¢á¤€á¤ ᤱ á¤á¤¹á¤á¤ ᤋᤱᤒᤣ á¤á¤ ᤰ á¤á¤ ᤺ᤳᤋᤢ ᤕᤢᤖᤢᤒᤠᤀᤡᤔᤠᤴᤛᤡᤱ ᤋᤱᤃᤡᤵᤛᤡᤱ ᤌᤡᤶᤒᤣᤴ ᤂᤠᤃᤴ ᤛᤡᤛᤣ᤺ᤰᤗᤠ᥇ᥠᤂᤧᤴ ᤀᤡᤛᤡᤰ ᥇ ᤈá¤á¤˜á¤–ᤡ ᥈᥆᥆᥊ ᤀᤥ á¤á¤ ᤛᤢᤵ ᤆᤥ᤺ᤰᤔᤠᤌᤡᤶᤒᤣ ᤋᤱᤃᤠᤶᤛᤡᤱᤗ á¤á¤³á¤á¤ ᤀᤡᤱᤄᤱ ᤘᤠ᤹"; -const kTeststr_ln_Latn = " abakisamaki ndenge esengeli moyebami abongisamaki solo mpenza kombo ya moyebami elonguamaki kombo ya bayebami elonguamaki kombo eleki molayi po na esika epesameli limbisa esika ya kotia ba kombo esuki boye esengeli olimbola ndako na yo ya mikanda kombo"; -const kTeststr_lo_Laoo = " àºàº«àº²àº—ົ່ວທັງເວັບ à»àº¥àº°à»ƒàº™à»€àº§àº±àºšà»„ຮ້ສາຠທຳàºàº´àº”ໃຫ້ທຳàºàº²àº™àºŠàºàºàº«àº²àºà»ˆàºàº™ ຈາàºàº™àº±à»‰àº™ ໃຫ້àºàº»àº”ປຸ່ມເມນູ ໃນໜ້າຜົນໄດ້"; -const kTeststr_lt_Latn = " a iÅ¡sijungia mano idÄ—ja dÄ—l geriausio laiko po pastarųjų savo santykių pasimokiau penki dalykai be kurių negaliu gyventi mano miegamajame tu surasi ideali pora iÅ¡silavinimas aukÅ¡toji mokykla koledžas universitetas pagrindinis laipsnis metai"; -const kTeststr_lv_Latn = " a gadskÄrtÄ“jÄ izpÄrdoÅ¡ana slÄ“poÅ¡ana jÄņi atlaide izmaiņas trafikÄ kas saistÄ«tas ar sezonas izpÄrdoÅ¡anu speciÄlajÄm atlaidÄ“m u c ir parastas un atslÄ“gvÄrdi kas ir populÄri noteiktos laika posmos Å¡ajÄ laikÄ saņems lielÄku klikÅ¡Ä·u"; -const kTeststr_mfe_Latn = "Anz dir mwa, Sa bann delo ki to trouve la, kot fam prostitie asize, samem bann pep, bann lafoul dimoun, bann nasion ek bann langaz. Sa dis korn ki to finn trouve, ansam avek bebet la, zot pou ena laenn pou prostitie la; zot pou pran tou seki li ena e met li touni, zot pou manz so laser e bril seki reste dan dife. Parski Bondie finn met dan zot leker proze pou realiz so plan. Zot pou met zot dakor pou sed zot pouvwar bebet la ziska ki parol Bondie fini realize."; -const kTeststr_mg_Latn = " amporisihin i ianao mba hijery ny dika teksta ranofotsiny an ity lahatsoratra ity tsy ilaina ny opérateur efa karohina daholo ny teny rehetra nosoratanao ampiasao anaovana dokambarotra i google telugu datin ny takelaka fikarohana sary renitakelak i"; -const kTeststr_mi_Latn = " haere ki te kainga o o haere ki te kainga o o haere ki te kainga o te rapunga ahua o haere ki te kainga o ka tangohia he ki to rapunga kaore au mohio te tikanga whakatiki o te ra he whakaharuru te pai rapunga a te rapunga ahua a e kainga o nga awhina o te"; -const kTeststr_mk_Cyrl = " глаÑовите коалицијата на вмро дпмне како партија Ñо најмногу оÑвоени глаÑови ќе добие евра а на Ñметката на коализијата за македонија"; -const kTeststr_ml_Mlym = " à´‚ à´…à´™àµà´™à´¨àµ† à´žà´™àµà´™à´³àµ അവരàµà´Ÿàµ† à´®àµà´®àµà´ªà´¿à´²àµ നിനàµà´¨àµ ഔടàµà´‚ ഉടനെ നിങàµà´™à´³àµ പതിയിരിപàµà´ªà´¿à´²àµ നിനàµà´¨àµ à´Žà´´àµà´¨àµà´¨àµ‡à´±àµà´±àµ"; -const kTeststr_mn_Cyrl = " а боловÑронгуй болгох орон нутгийн ажил үйлÑийг уÑлдуулж зохицуулах дүрÑм журам боловÑруулах орон нутгийн өмч хөрөнгө Ñанхүүгийн"; -const kTeststr_mn_Mong = "á ¦á á ¡â€¯á µá ¢á ¨ á ´á ¢á ¨á á Žá á ¬á ¦á ¨á ³á ¡á ¢â€¯á µá ¢ á ¢á ¯á á á ¬á £"; -const kTeststr_mr_Deva = "हैदराबाद उचà¥à¤šà¤¾à¤° à¤à¤•à¤¾ (सहायà¥à¤¯Â·à¤®à¤¾à¤¹à¤¿à¤¤à¥€)तेलà¥à¤—ू: హైదరాబాదౠ, उरà¥à¤¦à¥‚: Øیدر آباد हे à¤à¤¾à¤°à¤¤à¤¾à¤¤à¥€à¤² आंधà¥à¤° पà¥à¤°à¤¦à¥‡à¤¶ राजà¥à¤¯à¤¾à¤šà¥à¤¯à¤¾ राजधानीचे शहर आहे. हैदराबादची लोकसंखà¥à¤¯à¤¾ à¥à¥ लाख ४० हजार ३३४ आहे. मोतà¥à¤¯à¤¾à¤‚चे शहर अशी à¤à¤•à¥‡à¤•à¤¾à¤³à¥€ ओळख असलेलà¥à¤¯à¤¾ या शहराला à¤à¤¤à¤¿à¤¹à¤¾à¤¸à¤¿à¤•, सांसà¥à¤•à¥ƒà¤¤à¤¿à¤• आणि सà¥à¤¥à¤¾à¤ªà¤¤à¥à¤¯à¤¶à¤¾à¤¸à¥à¤¤à¥à¤°à¥€à¤¯ वारसा लाà¤à¤²à¤¾ आहे. १९९० नंतर शिकà¥à¤·à¤£ आणि माहिती तंतà¥à¤°à¤œà¥à¤žà¤¾à¤¨ तà¥à¤¯à¤¾à¤šà¤ªà¥à¤°à¤®à¤¾à¤£à¥‡ औषधनिरà¥à¤®à¤¿à¤¤à¥€ आणि जैवतंतà¥à¤°à¤œà¥à¤žà¤¾à¤¨ कà¥à¤·à¥‡à¤¤à¥à¤°à¤¾à¤¤à¥€à¤² उदà¥à¤¯à¥‹à¤—धंदà¥à¤¯à¤¾à¤‚ची वाढ शहरात à¤à¤¾à¤²à¥€. दकà¥à¤·à¤¿à¤£ मधà¥à¤¯ à¤à¤¾à¤°à¤¤à¤¾à¤¤à¥€à¤² परà¥à¤¯à¤Ÿà¤¨ आणि तेलà¥à¤—ू चितà¥à¤°à¤ªà¤Ÿà¤¨à¤¿à¤°à¥à¤®à¤¿à¤¤à¥€à¤šà¥‡ हैदराबाद हे केंदà¥à¤° आहे"; -// From 10% testing part of new lang=ms scrape -const kTeststr_ms_Latn = "pengampunan beramai-ramai supaya mereka pulang ke rumah masing-masing. Orang-orang besarnya enggan mengiktiraf sultan yang dilantik oleh Belanda sebagai Yang DiPertuan Selangor. Orang ramai pula tidak mahu menjalankan perniagaan bijih timah dengan Belanda, selagi raja yang berhak tidak ditabalkan. Perdagang yang lain dibekukan terus kerana untuk membalas jasa beliau yang membantu Belanda menentang Riau, Johor dan Selangor. Di antara tiga orang Sultan juga dipandang oleh rakyat sebagai seorang sultan yang paling gigih. 1 | 2 SULTAN Sebagai ganti Sultan Ibrahim ditabalkan Raja Muhammad iaitu Raja Muda. Walaupun baginda bukan anak isteri pertama bergelar Sultan Muhammad bersemayam di Kuala Selangor juga. Pentadbiran baginda yang lemah itu menyebabkan Kuala Selangor menjadi sarang ioleh Cina di Lukut tidak diambil tindakan, sedangkan baginda sendiri banyak berhutang kepada 1"; - -const kTeststr_ms_Latn2 = "bilik sebelah berkata julai pada pm ladymariah hmm sume ni terpulang kepada individu mungkin anda bernasib baik selama ini dalam membeli hp yang bagus deli berkata julai pada pm walaupun bukan bahsa baku tp tetap bahasa melayu kan perubahan boleh dibuat"; -const kTeststr_mt_Latn = " ata ikteb messaÄ¡Ä¡ lil indirizzi differenti billi tagħżilhom u tagħfas il buttuna ikteb żid numri tfittxijja tal kotba mur print home kotba minn pagni ghal pagna minn ghall ktieb ta aÄ‹Ä‹essa stieden habib iehor grazzi it tim tal gruppi google"; -const kTeststr_my_Latn = " jyk ef oif gawgodcsifayvdrfhrnf bmawgrsm topf dsvj g mail tamumif avhvm atmif txjwgif yxrqhk avhvm efae m pwifavhvm ef ufkyfwdky help center odkyvmyg drsm ar avh dswjhar cgef rsm udkawdkifygw f tajzawgudk smedkifygw f jyd awmh g mail cool features rsm"; -const kTeststr_my_Mymr = " á€á€€á€¹á€€á€žá€¯á€á€œá€¹ မ္ဟ ပ္ရန္ လာ္ရပီးေနာက္ န္ဟစ္ အရ္á€á€šá€¹ ဦးသန္ ့သည္ ပန္ းá€á€”ော္ အမ္ယုá€á€¸á€žá€¬á€¸ ေက္ယာင္ း"; -const kTeststr_na_Latn = " arcol obabakaen riringa itorere ibibokiei ababaro min kuduwa airumena baoin tokin rowiowet itiket keram damadamit eigirow etoreiy row keitsito boney ibingo itsiw dorerin naoerodelaporte s nauruan dictionary a c a c d g h o p s t y aiquen ion eins aiquen"; -const kTeststr_ne_Deva = "अरू ठाऊà¤à¤¬à¤¾à¤Ÿà¤ªà¤¨à¤¿ खà¥à¤²à¥‡à¤•à¥‹ छ यो खाता अर अरू ठाऊà¤à¤¬à¤¾à¤Ÿà¤ªà¤¨à¤¿ खà¥à¤²à¥‡à¤•à¥‹ छ यो खाता अर ू"; -const kTeststr_nl_Latn = " a als volgt te werk om een configuratiebestand te maken sitemap gen py ebruik filters om de s op te geven die moeten worden toegevoegd of uitgesloten op basis van de opmaaktaal elke sitemap mag alleen de s bevatten voor een bepaalde opmaaktaal dit"; -const kTeststr_nn_Latn = " a for verktylina til Ã¥ hjelpa deg Ã¥ nÃ¥ oss merk at pagerank syninga ikkje automatisk kjem til Ã¥ henta inn informasjon frÃ¥ sider med argument dvs frÃ¥ sider med eit i en dersom datamaskina di er plassert bak ein mellomtenar for vevsider kan det verka"; -const kTeststr_no_Latn = " a er obligatorisk tidsforskyvning plassering av katalogsøk planinformasjon loggfilbane gruppenavn kontoinformasjon passord domene gruppeinformasjon alle kampanjesporing alternativ bruker grupper oppgaveplanlegger oppgavehistorikk kontosammendrag antall"; -const kTeststr_nr_Latn = "ikomiti elawulako yegatja emhlanganweni walo ]imithetho mgomo ye anc ibekwa malunga wayo begodu ubudosiphambili kugandelela lokho okutjhiwo yi lokha nayithi abantu ngibo "; - -const kTeststr_nso_Latn = "Bophara bja Asia ekaba 8.6% bja lefase goba 29.4% bja naga ya lefase (ntle le mawatle). Asia enale badudu bao bakabago dimillione millione tÅ¡e nne (4 billion) yeo e bago 60% ya badudi ba lefase ka bophara. A bapolelwa rena sefapanong mehleng ya Pontius Pilatus. A hlokofatÅ¡wa, A bolokwa, A tsoga ka letÅ¡atÅ¡i la boraro, ka mo mangwalo a bolelago ka gona, a rotogela magodimong, "; -const kTeststr_ny_Latn = "Boma ndi gawo la dziko lomwe linapangidwa ndi cholinga chothandiza ntchito yolamulira. Kuŵalako kulikuunikabe mandita, Edipo nyima unalephera kugonjetsa kuŵalako."; -const kTeststr_oc_Latn = " Pasmens, la classificacion pus admesa uei (segon Juli Ronjat e Pèire Bèc) agropa lei parlars deis Aups dins l'occitan vivaroaupenc e non dins lo dialècte provençau."; -const kTeststr_om_Latn = " afaan katalaa bork bork bork hiikaa jira hin argamne gareen barbaadame hin argamne gargarsa qube en gar bayee jira garee walitti firooman gareewwan walitti firooman fuula web akka tartiiba qubeetiin agarsiisi akka tartiiba qubeetiin agarsiisaa jira akka"; -const kTeststr_or_Orya = "ଅକàଟà‹à¬¬à¬° ଡିସà‡à¬®àବର"; -const kTeststr_pa_Guru = " ਂ ਦਿਨਾਂ ਵਿਚ à¨à¨¾à¨ˆ ਸਾਹਿਬ ਦੀ ਬà©à©±à¨šà©œ ਗੋਬਿੰਦ ਰਾਮ ਨਾਲ ਅੜਫਸ ਚੱਲ ਰਹੀ ਸੀ ਗੋਬਿੰਦ ਰਾਮ ਨੇ à¨à¨¾à¨ˆ ਸਾਹਿਬ ਦੀਆਂ à¨à©ˆà¨£à¨¾"; -const kTeststr_pl_Latn = " a australii bÄ™dzie widziaÅ‚ inne reklamy niż użytkownik z kanady kierowanie geograficzne sprawia że reklamy sÄ… lepiej dopasowane do użytkownika twojej strony oznacza to także że możesz nie zobaczyć wszystkich reklam które sÄ… wyÅ›wietlane na"; -const kTeststr_ps_Arab = " اتو مستقل رياست جوړ شو او د پخواني ادبي انجمن Ú…Ø§Ù†Ú«Û Ø¯Ø¯Û Ø±ÙŠØ§Ø³Øª جز شوی او Ø¯Ø¯Û Ø§Ù†Ø¬Ù…Ù† د Ú˜Ø¨Û Ù…Ø¯ÙŠØ±ÙŠØª د پښتو Ù¼ÙˆÙ„Ù†Û Ù¾Ù‡ لوی مديريت واوښت لوی مدير ÙŠÛ Ø¯"; -const kTeststr_pt_Latn = " a abit prevê que a entrada desses produtos estrangeiros no mercado têxtil e vestuário do brasil possa reduzir os preços em cerca de a partir de má notÃcia para os empresários que terão que lutar para garantir suas margens de lucro mas boa notÃcia"; -const kTeststr_qu_Latn = " is t ipanakunatapis rikuchinankupaq qanpa simiykipi noqaykoqpa uya jllanakunamanta kunan jamoq simikunaman qelqan tiyan watukuy qpa uyata qanpa llaqtaykipi llank anakuna simimanta yanapakuna simimanta mayqen llaqtallapis kay simimanta t ijray qpa qelqa"; -const kTeststr_rm_Latn = " Cur ch’il chantun Turitg ha dà il dretg da votar a las dunnas (1970) è ella vegnida elegida en il cussegl da vischnanca da Zumikon per la Partida liberaldemocratica svizra (PLD). Da 1974 enfin 1982 è ella stada presidenta da vischnanca da Zumikon. L’onn 1979 è Elisabeth Kopp vegnida elegida en il Cussegl naziunal e reelegida quatter onns pli tard cun in resultat da sur 100 000 vuschs. L’onn 1984 è ella daventada vicepresidenta da la PLD."; -const kTeststr_rn_Latn = " ishaka mu ndero y abana bawe ganira n abigisha nimba hari ingorane izo ari zo zose ushobora gusaba kubonana n umwigisha canke kuvugana nawe kuri terefone inyuma y uko babarungikira urutonde rw amanota i muhira mu bisanzwe amashure aratumira abavyeyi"; -const kTeststr_ro_Latn = " a anunÅ£urilor reÅ£ineÅ£i nu plătiÅ£i pentru clicuri sau impresii ci numai atunci când pe site ul dvs survine o acÅ£iune dorită site urile negative nu pot avea uri de destinaÅ£ie daÅ£i instrucÅ£iuni societăţii dvs bancare sau constructoare să"; -const kTeststr_ro_Cyrl = "Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ñ Ð° органелор ши инÑтитуциилор екзекутиве ши а органелор жудичиаре але путерий де Ñтат фиекÑруй орган ал путерий де Ñтат и Ñе"; -const kTeststr_ru_Cyrl = " а неправильный формат идентификатора дн назад"; -const kTeststr_rw_Latn = " dore ibyo ukeneye kumenya ukwo watubona ibibazo byinshi abandi babaza ububonero byibibina google onjela ho izina dyikyibina kyawe onjela ho yawe mulugo kulaho ibyandiko byawe shyilaho tegula yawe tulubaka tukongeraho iyanya mishya buliko tulambula"; -const kTeststr_sa_Deva = " ं क रà¥à¤®à¤£à¤¸à¥ त सà¥à¤¯ य तà¥à¤•à¤¿ ङà¥à¤šà¥‡à¤¹ करो तà¥à¤¯à¤¯ ं त सà¥à¤®à¤¾à¤²à¥ लोका तà¥à¤ªà¥ नरै ति असà¥à¤®à¥ˆ लोका य क रà¥à¤®à¤£ इ ति नॠकाम"; -const kTeststr_sa_Latn = " brahmÄ tatraivÄntaradhÄ«yata tataḥ saÅ›iá¹£yo vÄlmÄ«kir munir vismayam Äyayau tasya Å›iá¹£yÄs tataḥ sarve jaguḥ Å›lokam imaṃ punaḥ muhur muhuḥ prÄ«yamÄṇÄḥ prÄhuÅ› ca bhṛśavismitÄḥ samÄká¹£araiÅ› caturbhir yaḥ pÄdair gÄ«to"; -const kTeststr_sco_Latn = " a gless an geordie runciman ower a gless an tamson their man preached a hale hoor aboot the glorious memories o forty three an backsliders an profane persons like esau an aboot jeroboam the son o nebat that gaed stravagin to anither kirk an made aa israel"; -const kTeststr_sd_Arab = " اضاÙÙˆ ٿي ٿيو پر اها خبر عثمان Ú©ÙŠ بعد پيئي ته سگريٽ ڇڪيندڙ مسلمان نه هو بلڪ هندو هو دڪان تي پهچي عثمان ڪسبت کولي گراهڪن جي سيرب لاهڻ شروع ڪئي پر"; -const kTeststr_sg_Latn = " atâa na âkotta zo me lâkwê angbâ gï tarrango nî âkotta zo tî koddoro nî âde agbû tenne nî na kate töngana mbênî kotta kpalle tî nzönî dutï tî halëzo pëpe atâa sô âla lü gbâ tî ândya tî mâi na sahngo asâra gbâ tî"; -const kTeststr_si_Sinh = " අනුරà·à¶° මිහිඳුකුල නමින් සකුර෠ට ලිපියක් à¶à·à¶´à·‘ලෙන් එව෠à¶à·’බුණ෠කි à·Š රස්ටි ෂෙල්ටන් ප à·Š රනà·à¶±à·Šà¶¯à·” ද"; -const kTeststr_sit_NP = " dialekten in de roerstreek pierre bakkes oet roerstreek blz bewirk waordebook zónjig oktoeaber is t ieëste mofers waordebook oetgekaome dit waordebook is samegestèldj"; -const kTeststr_sk_Latn = " a aktivovaÅ¥ reklamnú kampaň ak chcete kampaň pred spustenÃm eÅ¡te prispôsobiÅ¥ uložte ju ako Å¡ablónu a pokraÄujte v úprave vyberte si jednu z možnostà nižšie a kliknite na tlaÄidlo uložiÅ¥ kampaň nastavenia kampane môžete ľubovoľne"; -const kTeststr_sl_Latn = " adsense stanje prijave za google adsense google adsense raÄun je bil zaÄasno zamrznjen pozdravljeni hvala za vaÅ¡e zanimanje v google adsense po pregledu vaÅ¡e prijavnice so naÅ¡i strokovnjaki ugotovili da spletna stran ki je trenutno povezana z vaÅ¡im"; -const kTeststr_sm_Latn = " autu mea o lo totonu le e le minaomia matou te tuu i totonu i le faamatalaina o le suesuega i taimi uma mea o lo totonu fuafua i mea e tatau fa afoi tala mai le newsgroup mataupu fa afoi mai tala e ai le mataupu e ai totonu tusitala o le itu o faamatalaga"; -const kTeststr_sn_Latn = " chete vanyori vanotevera vakabatsira kunyora zvikamu zvino kumba home tinyorere tsamba chikamu chakumbirwa hachina kuwanikwa chikamu ichi cheninge chakayiswa kuimwe nzvimbo mudhairekitori rino chimwe chikamu chopadhuze pane chinhu chatadza kushanda bad"; -const kTeststr_so_Latn = " a oo maanta bogga koobaad ugu qoran yahey beesha caalamka laakiin si kata oo beesha caalamku ula guntato soomaaliya waxa aan shaki ku jirin in aakhirataanka dadka soomaalida oo kaliya ay yihiin ku soomaaliya ka saari kara dhibka ay ku jirto"; -const kTeststr_sq_Latn = " a do të kërkoni nga beogradi që të njohë pavarësinë e kosovës zoti thaçi prishtina është gati ta njoh pavarësinë e serbisë ndërsa natyrisht se do të kërkohet një gjë e tillë që edhe beogradi ta njoh shtetin e pavarur dhe sovran të"; -const kTeststr_sr_Cyrl = "балчак балчак на мапи Ñрбије уреди демографија у наÑељу балчак живи пунолетна Ñтановника а проÑечна ÑтароÑÑ‚ Ñтановништва изноÑи година"; -const kTeststr_sr_Latn = "DruÅ¡tvo | Äetvrtak 1.08.2013 | 13:43 Krade se i izvorska voda Izvor: Gornji Milanovac -- U gružanskom selu Belo Polje proÅ¡le noći ukradeno je viÅ¡e od 10.000 litara kojima je obijen bazen. Bazen je bio zakljuÄan i propisno obezbeÄ‘en."; - -const kTeststr_sr_ME_Latn = "savjet pobjeda a radi bržeg rada poÅ¡to rom radi sporije nego ram izvorni rom se iskljuÄuje a dio ram a se rezerviÅ¡e te se u njega ne ploÄa procesor ram memorija grafiÄka kartica zvuÄna kartica modem mrežna kartica napojna jedinica ureÄ‘aji za pohranjivanje"; -const kTeststr_ss_Latn = " bakhokhintsela yesikhashana bafake imininingwane ye akhawunti leliciniso kulelifomu nangabe akukafakwa imininingwane leliciniso imali lekhokhiwe angeke ifakwe kumkhokhintsela lofanele imininingwane ye akhawunti ime ngalendlela lelandzelako inombolo"; -const kTeststr_st_Latn = " bang ba nang le thahasello matshwao a sehlooho thuto e thehilweng hodima diphetho ke tsela ya ho ruta le ho ithuta e totobatsang hantle seo baithuti ba lokelang ho se fihlella ntlhatheo eo e sebetsang ka yona ke ya hore titjhere o hlakisa pele seo"; -const kTeststr_su_Latn = "Nu ngatur kahirupan warga, keur kapentingan pamarentahan diatur ku RT, RW jeung Kepala Dusun, sedengkeun urusan adat dipupuhuan ku Kuncen jeung kepala adat. Sanajan Kampung Kuta teu pati anggang jeung lembur sejenna nu aya di wewengkon Desa Pasir Angin, tapi boh wangunan imah atawa tradisi kahirupan masarakatna nenggang ti nu lian."; -const kTeststr_sv_Latn = " a bort objekt frÃ¥n google desktop post äldst meny öretag dress etaljer alternativ för vad är inne yaste google skrivbord plugin program för nyheter google visa nyheter som är anpassade efter de artiklar som du läser om du till exempel läser"; -const kTeststr_sw_Latn = " a ujumbe mpya jumla unda tafuta na angalia vikundi vya kujadiliana na kushiriki mawazo iliyopangwa kwa tarehe watumiaji wapya futa orodha hizi lugha hoja vishikanisho vilivyo dhaminiwa ujumbe sanaa na tamasha toka udhibitisho wa neno kwa haraka fikia"; -const kTeststr_syr_Syrc = "ÜܕܪÜÜ£ ܓܛܘ ܫܘܪÜÜ Ü¡Ü¢ Ü¦ÜªÜ¢Ü£Ü Ü¡Ü¢ ÜܣܦܢÜÜ ÜšÜÜªÜ˜Ü¬Ü Ü’Üܕܪ Ü’Ü¢Üܣܢ Ü«Ü›ÜÜšÜ˜Ü¬Ü ÜŸÜ Ü¢ÜÜ Ü¡ÜÌˆÜ Ü’Ü¥Ü Ü¡Ü"; -const kTeststr_ta_Taml = " à®…à®™à¯à®•à¯ ராஜேநà¯à®¤à®¿à®° சோழனால௠கடà¯à®Ÿà®ªà¯à®ªà®Ÿà¯à®Ÿ பிரமà¯à®®à®¾à®£à¯à®Ÿà®®à®¾à®© சிவன௠கோவில௠ஒனà¯à®±à¯à®®à¯ உளà¯à®³à®¤à¯ தொகà¯"; -const kTeststr_te_Telu = " ఠదనర జయించిన తతà±à°µ మరసి చూడఠదాన యగà±à°¨à± రాజయోగి యిటà±à°²à± తేజరిలà±à°²à±à°šà± à°¨à±à°‚డౠవిశà±à°µà°¦à°¾à°à°¿à°°à°¾à°® వినర వేమ"; -const kTeststr_tg_Arab = "رادیو Ùردا راديوى آزادى"; -const kTeststr_tg_Cyrl = " адолат ва инÑондӯÑтиро бар фашизм нажодпараÑÑ‚Ó£ ва адоват тарҷеҳ додааÑÑ‚ чоп кунед ба дигарон фириÑтед чоп кунед ба дигарон фириÑтед"; -const kTeststr_th_Thai = " à¸à¸à¹ƒà¸™à¸à¸²à¸£à¸„้นหา หรืà¸à¸«à¸™à¹‰à¸²à¹€à¸™à¸·à¹‰à¸à¸«à¸² หาà¸à¸—่านเลืà¸à¸à¸¥à¸‡à¹‚ฆษณา ท่านà¸à¸²à¸ˆà¸ˆà¸°à¸›à¸£à¸±à¸šà¸•à¹‰à¸à¸‡à¹€à¸žà¸´à¹ˆà¸¡à¸‡à¸šà¸›à¸£à¸°à¸¡à¸²à¸“รายวันตา"; -const kTeststr_ti_Ethi = " ሃገሠተረáŽáˆ ዘለዉ ኢትዮጵያá‹á‹«áŠ• ኣብቲ áˆáˆµ ኢትዮጵያ á‹á‹³á‹á‰¥ ኣá‹áˆ«áŒƒ ደቡብ ንኽáŠá‰¥áˆ© ኣá‹áቀደሎáˆáŠ• እዩ ካብ ሃገሠንኽትወጽእ ዜጋ ኹን ወጻእተኛ ናá‹"; -const kTeststr_tk_Cyrl = " айдÑнларына ынанÑрмыка Ñхли боз мейданлары Ñурулип гутарылан тебигы ота гарып гумлукларда миллиондан да артыкмач ири шахлы малы миллиона"; -const kTeststr_tk_Latn = " akyllylyk çyn söýgi üçin böwet däl de tebigylykdyr duýgularyň gödeňsiligi aç açanlygy bahyllygy söýgini betnyÅŸanlyk derejesine düşürýändir söýeni söý söýmedige süýkenme özüni söýmeýändigini görmek ýigit üçin uly"; -const kTeststr_tl_Latn = " a na ugma sa google ay nakaka bantog sa gitna nang kliks na nangyayari sa pamamagitan nang ordinaryong paggagamit at sa kliks na likha nang pandaraya o hindi tunay na paggamit bunga nito nasasala namin ang mga kliks na hindi kailangan o hindi gusto nang"; -const kTeststr_tl_Tglg = " ᜋᜇ᜔ áœáœ“ᜎᜆ᜔ ᜃ ᜈᜅ᜔ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜂᜉᜅ᜔᜔ ᜋáœáœˆáœŒáœ” ᜎᜅ᜔ áœáœ ᜉᜅ᜔ ᜀᜃ᜔ᜎᜆ᜔ ᜆᜓᜅ᜔ᜃᜓᜎ᜔ ᜠᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜠᜆᜒᜅᜒᜈ᜔ ᜃᜓ"; -const kTeststr_tlh_Latn = " a ghuv bid soh naq jih lodni yisov chich wo vamvo qeylis lunge pu chah povpu vodleh a dah ghah cho ej dah wo che pujwi bommu tlhegh darinmohlahchu pu majqa horey so lom qa ip quv law may vad suvtahbogh wa sanid utlh quv pus datu pu a vitu chu pu johwi tar"; -const kTeststr_tn_Latn = " go etela batla ditsebe tsa web tse di nang le le batla ditsebe tse di golaganya le tswang mo leka go batla web yotlhe batla mo web yotlhe go bona home page ya google batla mo a o ne o batla gore a o ne o batla ditsebe tsa bihari batla mo re maswabi ga go"; -const kTeststr_to_Latn = " a ke kumi oku ikai ke ma u vakai ki hono hokohoko faka alafapeti api pe ko e uluaki peesi a ho o fekumi faka malatihi fekumi ki he lea oku fakaha atu pe ko ha fonua fekumi ki he fekumi ki he peesi oku ngaahi me a oku sai imisi alu ki he ki he ulu aki"; -const kTeststr_tr_Latn = " a ayarlarınızı görmeniz ve yönetmeniz içindir eÄŸer kampanyanız için günlük bütçenizi gözden geçirebileceÄŸiniz yeri arıyorsanız kampanya yönetimi ne gidin kampanyanızı seçin ve kampanya ayarlarını düzenle yi tıklayın sunumu"; -const kTeststr_ts_Latn = " a ku na timhaka leti nga ta vulavuriwa na google google yi hlonipha yi tlhela yi sirheleta vanhu hinkwavo lava tirhisaka google toolbar ku dyondza hi vusireleli eka system ya hina hi kombela u hlaya vusireleli bya hina eka toolbar mbulavulo wu tshikiwile"; -const kTeststr_tt_Cyrl = "ачарга да бирмәде чәт чәт килеп тора безнең абыйнымы олы абыйнымы Ñштән"; -const kTeststr_tt_Latn = " alarnı eÅŸkärtü proÄŸramnarın eÅŸläwen däwam itü tatar söylämen buldıru wä sizep alu sistemnarın eÅŸläwen däwat itü häm baÅŸqalar yılnıñ mayında tatar internetı ictimağıy oyışması milli ts isemle berençe däräcäle häm tat"; -const kTeststr_tw_Latn = " amammui tumidifo no bÉ›tow ahyÉ› atoro som so mpofirim na wÉ”asÉ›e no pasaa ma ayÉ› nwonwa dÉ›n na É›bÉ›ka wÉ”n ma wÉ”ayÉ› saa bible no ma ho mmuae wÉ” adiyisÉ›m nhoma no mu sÉ› onyankopÉ”n na É”de hyɛɛ wÉ”n komam sÉ› wÉ”mma ne nsusuwii mmra mu"; -const kTeststr_ug_Arab = " Ø¦Ø§Ù„Û•Ù…Ù„Û•Ø±Ù†Ù‰Ú Ù¾Û•Ø±Û‹Û•Ø±Ø¯Ù‰Ú¯Ø§Ø±Ù‰Ø¯Ù‰Ù† تىلەيمەن سىلەر بۇ يەرلەردە باغچىلاردىن بۇلاقلاردىن زىرائەتلەردىن يۇمشاق پىشقان خورمىلاردىن بەھرىمەن بولۇپ"; -const kTeststr_ug_Cyrl = " а башлиди әмма бу қетимқи канада мәтбуатлириниң хәвәрлиридә илгирикидәк хитай һөкүмәт мәтбуатлиридин нәқил алидиған вә уни көчүрүп"; -const kTeststr_ug_Latn = " adawet bolghachqa hazir musherrepmu bu ikki partiyining birleshme hökümet qurushta pikir birliki hasil qilalmasliqini kütüwatqan iken wehalenki pakistan xelq partiyisining rehbiri asif eli zerdari pakistandiki bashqa ushshaq partiyilerning rehberliri"; -const kTeststr_uk_Cyrl = " а більший бюджет щоб забезпечити Ñобі макÑимум прибутків від переходів відÑтежуйте Ñвої об Ñви за датою географічним розташуваннÑм"; -const kTeststr_ur_Arab = " آپ Ú©Ùˆ Ú©Ù… سے Ú©Ù… Ù…Ù…Ú©Ù†Û Ø±Ù‚Ù… چارج کرتا ÛÛ’ اس Ú©ÛŒ مثال Ú©Û’ طور پر Ùرض کریں اگر آپ Ú©ÛŒ Ø²ÛŒØ§Ø¯Û Ø³Û’ Ø²ÛŒØ§Ø¯Û Ù‚ÛŒÙ…Øª ÙÛŒ Ú©Ù„ÙÚ© امریکی ڈالر اور Ú©Ù„ÙÚ© کرنے Ú©ÛŒ Ø´Ø±Ø ÛÙˆ تو"; -const kTeststr_uz_Arab = " آرقلی بوتون سیاسی Øزب Ùˆ گروه لرÙعالیتیگه رخصت بیرگن اخبارات واسطه لری شو ییل مدتیده مثال سیز ترقی تاپکن Ùˆ اهالی نینگ اقتصادی وضعیتی اوتمیش"; -const kTeststr_uz_Cyrl = " а гапирадиган бўлÑак бунинг иккита йўли бор биринчиÑи мана шу қуриган Ñатҳини қумликларни тўхтатиш учун Ñкотизимни муÑтаҳкамлаш қумга"; -const kTeststr_uz_Latn = " abadiylashtirildi aqsh ayol prezidentga tayyormi markaziy osiyo afg onistonga qanday yordam berishi mumkin ukrainada o zbekistonlik muhojirlar tazyiqdan shikoyat qilmoqda gruziya va ukraina hozircha natoga qabul qilinmaydi afg oniston o zbekistonni g"; -const kTeststr_ve_Latn = "Vho á¹±anganedzwa kha Wikipedia nga tshiVenḓa. Vhadivhi vha manwalo a TshiVenda vha talusa divhazwakale na vhubvo ha Vhavenda ngau fhambana. Vha tikedza mbuno dzavho uya nga mawanwa a thoduluso dze vha ita. Vhanwe vha vhatodulusi vhari Vhavenda vho tumbuka Afrika vhukati vha tshimbila vha tshiya Tshipembe ha Afrika, Rhodesia hune ha vho vhidzwa Zimbagwe namusi."; -const kTeststr_vi_Latn = " adsense cho nội dung nhaÌ€ cung câÌp diÌ£ch vuÌ£ di động xaÌc minh tiÌn duÌ£ng thay đổi nhãn kg caÌc ô xem chi phiÌ cho tÆ°Ì€ chôÌi caÌc Ä‘Æ¡n đặt haÌ€ng daÌ£ng câÌp dữ liệu aÌc minh trang web của baÌ£n để xem"; -const kTeststr_vo_Latn = " brefik se volapükavol nüm balid äpubon ün dü lif lölik okas redakans älaipübons gasedi at nomöfiko äd ai mu kuratiko pläo timü koup nedäna fa ns deutän kü päproibon fa koupanef me gased at ästeifülom ad propagidön volapüki as sam ün"; -const kTeststr_war_Latn = "Amo ini an balay han Winaray o Binisaya nga Lineyte-Samarnon nga Wikipedia, an libre ngan gawasnon nga ensayklopedya nga bisan hin-o puyde magliwat o mag-edit. An Wikipedia syahan gintikang ha Iningles nga yinaknan han tuig 2001. Ini nga bersyon Winaray gintikang han ika-25 han Septyembre 2005 ngan ha yana mayda 514,613 nga artikulo. Kon karuyag niyo magsari o magprobar, pakadto ha . An Gastrotheca pulchra[2] in uska species han Anura nga ginhulagway ni Ulisses Caramaschi ngan Rodrigues hadton 2007. An Gastrotheca pulchra in nahilalakip ha genus nga Gastrotheca, ngan familia nga Hemiphractidae.[3][4] Ginklasipika han IUCN an species komo kulang hin datos.[1] Waray hini subspecies nga nakalista.[3]"; -const kTeststr_wo_Latn = " am ak dëgg dëggam ak gëm aji bind ji te gëstu ko te jëfandikoo tegtalu xel ci saxal ko sokraat nag jëfandikoo woon na xeltu ngir tas jikko yu rafet ci biir nit ñi ak dëggu ak soppante sokraat nag ñëw na mook aflaton platon sukkandiku ci ñaari"; -const kTeststr_xh_Latn = " a naynga zonke futhi libhengezwa kwiwebsite yebond yasemzantsi afrika izinga elisebenzayo xa usenza olu tyalo mali liya kusebenza de liphele ixesha lotyalo mali lwakho inzala ihlawulwa rhoqo emva kweenyanga ezintandathu ngomhla wamashumi amathathu ananye"; -const kTeststr_xx_Bugi = "ᨄᨛᨑᨊᨒ ᨑᨗ ᨔᨒᨗᨓᨛ ᨕᨗᨋᨗᨔᨗ ᨒᨛᨄ ᨑᨛᨔᨛᨆᨗᨊ"; -const kTeststr_xx_Goth = "ðŒ° ðŒ°ðŒ±ð‚ðŒ°ðŒ·ðŒ°ðŒ¼ ðŒ°ðŒ²ðŒ²ðŒ¹ðŒ»ðŒ¹ðƒðŒºðƒ ðŒ¸ðŒ¹ðŒ¿ðŒ³ðŒ¹ðƒðŒºðƒ ð†ð‚ðŒ°ðŒ²ðŒºðŒ¹ðƒðŒºðƒ"; -const kTeststr_yi_Hebr = "×ון פ×× ×˜××–×™×¢ ער ××™×– ב×ק×× ×˜ ×¦×™× ×ž×¢×¨×¡×˜×Ÿ פ×ר ×–×™×™× ×¢ ב×ַל×ַדעס ער ×”×ָט ×’×¢×•×•×•×™× ×˜ ×ין וו×רשע יעס פ×ריס ליווערפול ×ון ל×× ×“×ן סוף כל סוף ××™×– ער"; -const kTeststr_yo_Latn = " abinibi han ikawe alantakun le ni opolopo ede abinibi ti a to lesese bi eniyan to fe lo se fe lati se atunse jowo mo pe awon oju iwe itakunagbaye miran ti ako ni oniruru ede abinibi le faragba nipa atunse ninu se iwadi blogs ni ori itakun agbaye ti e ba"; -const kTeststr_za_Hani = " 两个宾è¯çš„å—数较少时 åªå¸¦ä¸€ä¸ªåŠ¨è¯ å¦åˆ™å°±å¸¦ä¸¤ä¸ªåŠ¨è¯ 三å¥åç±» 从å¥åæ–¹é¢åŽ»è°ˆæ±‰ 壮è¯ç»“æž„æ ¼å¼ç›¸å¼‚的类型的 å«å¥åç±» 汉 壮è¯ä¸ å¥åç±»ç»“æž„æ ¼å¼æœ‰å·®åˆ«çš„自然ä¸å°‘"; -const kTeststr_za_Latn = " dih yinzminz ndaej daengz bujbienq youjyau dih cingzyin caeuq cinhingz diuz daihit boux boux ma daengz lajmbwn couh miz cwyouz cinhyenz caeuq genzli bouxboux bingzdaengj gyoengq vunz miz lijsing caeuq liengzsim wngdang daih gyoengq de lumj beixnuengx"; -const kTeststr_zh_Hans = "产å“的简报和公告 æ交该申请åŽæ— 法进行更改 请确认您的选择是æ£ç¡®çš„ 对于è¦æ交的图书 我确认 我是版æƒæ‰€æœ‰è€…或已得到版æƒæ‰€æœ‰è€…çš„æŽˆæƒ è¦æ›´æ”¹æ‚¨çš„国家 地区 请在æ¤è¡¨çš„最上端更改您的"; -const kTeststr_zh_Hant = " 之å‰ç‚º 帳單交易作æ¥å€ 已變更 廣告內容 之å‰ç‚º 銷售代表 之å‰ç‚º 張貼日期為 百分比之å‰ç‚º åˆç´„ 為 目標å°è±¡æ¢ä»¶å·²åˆªé™¤ çµæŸæ—¥æœŸä¹‹å‰ç‚º"; -const kTeststr_zu_Latn = " ana engu uma inkinga iqhubeka siza ubike kwi isexwayiso ngenxa yephutha lomlekeleli sikwazi ukubuyisela emuva kuphela imiphumela engaqediwe ukuthola imiphumela eqediwe zama ukulayisha kabusha leli khasi emizuzwini engu uma inkinga iqhubeka siza uthumele"; -const kTeststr_zzb_Latn = "becoose a ve a leemit qooereees tu vurds um gesh dee bork bork nu peges vere a fuoond cunteeening is a fery cummun vurd und ves nut inclooded in yuoor seerch zee ooperetur is unnecessery ve a incloode a ell seerch terms by deffoolt um de hur de hur de hur"; -const kTeststr_zze_Latn = " a diffewent type of seawch send feedback about google wiwewess seawch to wap google com wesuwts found on de entiwe web fow wesuwts found on de mobiwe web fow de functionawity of de toolbar up button has been expanded swightwy it now considews fow exampwe"; -const kTeststr_zzh_Latn = " b x z un b e t und rs n a dr ss p as ry an th r a dr ss ry us n a l ss mb gu us c ti n l ke a z p c d n a dr ss nt r d pl as en r n a dr ss y ur s ar h f r n ar d d n t m tch ny l c ti n w th n m l s nd m r r at d p g s th l c ti ns b l w w r ut m t ca y"; -const kTeststr_zzp_Latn = " away ackupbay editcray ardcay ybay isitingvay ouryay illingbay eferencespray agepay orway isitvay ethay adwordsway elphay entrecay orfay oremay etailsday adwordsway ooglegay omcay upportsay"; - -// Two very close Wikipedia page beginnings -const kTeststr_ms_close = "sukiyaki wikipedia bahasa melayu ensiklopedia bebas sukiyaki dari wikipedia bahasa melayu ensiklopedia bebas lompat ke navigasi gelintar sukiyaki sukiyaki hirisan tipis daging lembu sayur sayuran dan tauhu di dalam periuk besi yang dimasak di atas meja makan dengan cara rebusan sukiyaki dimakan dengan mence"; -const kTeststr_id_close = "sukiyaki wikipedia indonesia ensiklopedia bebas berbahasa bebas berbahasa indonesia langsung ke navigasi cari untuk pengertian lain dari sukiyaki lihat sukiyaki irisan tipis daging sapi sayur sayuran dan tahu di dalam panci besi yang dimasak di atas meja makan dengan cara direbus sukiyaki dimakan dengan mence"; - -// Simple intermixed French/English text -const kTeststr_fr_en_Latn = "France is the largest country in Western Europe and the third-largest in Europe as a whole. " + - "A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter " + - "Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, " + - "Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus." + - "Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog"; - -// This can be used to cross-check the build date of the main quadgram table -const kTeststr_version = "qpdbmrmxyzptlkuuddlrlrbas las les qpdbmrmxyzptlkuuddlrlrbas el la qpdbmrmxyzptlkuuddlrlrbas"; - -const kTestPairs = [ -// A simple case to begin - ["en", "ENGLISH", kTeststr_en], - -// 20 languages recognized via Unicode script - ["hy", "ARMENIAN", kTeststr_hy_Armn], - ["chr", "CHEROKEE", kTeststr_chr_Cher], - ["dv", "DHIVEHI", kTeststr_dv_Thaa], - ["ka", "GEORGIAN", kTeststr_ka_Geor], - ["el", "GREEK", kTeststr_el_Grek], - ["gu", "GUJARATI", kTeststr_gu_Gujr], - ["iu", "INUKTITUT", kTeststr_iu_Cans], - ["kn", "KANNADA", kTeststr_kn_Knda], - ["km", "KHMER", kTeststr_km_Khmr], - ["lo", "LAOTHIAN", kTeststr_lo_Laoo], - ["lif", "LIMBU", kTeststr_lif_Limb], - ["ml", "MALAYALAM", kTeststr_ml_Mlym], - ["or", "ORIYA", kTeststr_or_Orya], - ["pa", "PUNJABI", kTeststr_pa_Guru], - ["si", "SINHALESE", kTeststr_si_Sinh], - ["syr", "SYRIAC", kTeststr_syr_Syrc], - ["tl", "TAGALOG", kTeststr_tl_Tglg], // Also in quadgram list below - ["ta", "TAMIL", kTeststr_ta_Taml], - ["te", "TELUGU", kTeststr_te_Telu], - ["th", "THAI", kTeststr_th_Thai], - -// 4 languages regognized via single letters - ["zh", "CHINESE", kTeststr_zh_Hans], - ["zh-Hant", "CHINESET", kTeststr_zh_Hant], - ["ja", "JAPANESE", kTeststr_ja_Hani], - ["ko", "KOREAN", kTeststr_ko_Hani], - -// 60 languages recognized via combinations of four letters - ["af", "AFRIKAANS", kTeststr_af_Latn], - ["sq", "ALBANIAN", kTeststr_sq_Latn], - ["ar", "ARABIC", kTeststr_ar_Arab], - ["az", "AZERBAIJANI", kTeststr_az_Latn], - ["eu", "BASQUE", kTeststr_eu_Latn], - ["be", "BELARUSIAN", kTeststr_be_Cyrl], - ["bn", "BENGALI", kTeststr_bn_Beng], // No Assamese in subset - ["bh", "BIHARI", kTeststr_bh_Deva], - ["bg", "BULGARIAN", kTeststr_bg_Cyrl], - ["ca", "CATALAN", kTeststr_ca_Latn], - ["ceb", "CEBUANO", kTeststr_ceb_Latn], - ["hr", "CROATIAN", kTeststr_hr_Latn, [false, 0, "el", 4]], - ["cs", "CZECH", kTeststr_cs_Latn], - ["da", "DANISH", kTeststr_da_Latn], - ["nl", "DUTCH", kTeststr_nl_Latn], - ["en", "ENGLISH", kTeststr_en_Latn], - ["et", "ESTONIAN", kTeststr_et_Latn], - ["fi", "FINNISH", kTeststr_fi_Latn], - ["fr", "FRENCH", kTeststr_fr_Latn], - ["gl", "GALICIAN", kTeststr_gl_Latn], - ["lg", "GANDA", kTeststr_lg_Latn], - ["de", "GERMAN", kTeststr_de_Latn], - ["ht", "HAITIAN_CREOLE", kTeststr_ht_Latn], - ["he", "HEBREW", kTeststr_he_Hebr], - ["hi", "HINDI", kTeststr_hi_Deva], - ["hmn", "HMONG", kTeststr_blu_Latn], - ["hu", "HUNGARIAN", kTeststr_hu_Latn], - ["is", "ICELANDIC", kTeststr_is_Latn], - ["id", "INDONESIAN", kTeststr_id_Latn], - ["ga", "IRISH", kTeststr_ga_Latn], - ["it", "ITALIAN", kTeststr_it_Latn], - ["jw", "JAVANESE", kTeststr_jw_Latn], - ["rw", "KINYARWANDA", kTeststr_rw_Latn], - ["lv", "LATVIAN", kTeststr_lv_Latn], - ["lt", "LITHUANIAN", kTeststr_lt_Latn], - ["mk", "MACEDONIAN", kTeststr_mk_Cyrl], - ["ms", "MALAY", kTeststr_ms_Latn], - ["mt", "MALTESE", kTeststr_mt_Latn], - ["mr", "MARATHI", kTeststr_mr_Deva, [false, 0, "te", 3]], - ["ne", "NEPALI", kTeststr_ne_Deva], - ["no", "NORWEGIAN", kTeststr_no_Latn], - ["fa", "PERSIAN", kTeststr_fa_Arab], - ["pl", "POLISH", kTeststr_pl_Latn], - ["pt", "PORTUGUESE", kTeststr_pt_Latn], - ["ro", "ROMANIAN", kTeststr_ro_Latn], - ["ro", "ROMANIAN", kTeststr_ro_Cyrl], - ["ru", "RUSSIAN", kTeststr_ru_Cyrl], - ["gd", "SCOTS_GAELIC", kTeststr_gd_Latn], - ["sr", "SERBIAN", kTeststr_sr_Cyrl], - ["sr", "SERBIAN", kTeststr_sr_Latn], - ["sk", "SLOVAK", kTeststr_sk_Latn], - ["sl", "SLOVENIAN", kTeststr_sl_Latn], - ["es", "SPANISH", kTeststr_es_Latn], - ["sw", "SWAHILI", kTeststr_sw_Latn], - ["sv", "SWEDISH", kTeststr_sv_Latn], - ["tl", "TAGALOG", kTeststr_tl_Latn], - ["tr", "TURKISH", kTeststr_tr_Latn], - ["uk", "UKRAINIAN", kTeststr_uk_Cyrl], - ["ur", "URDU", kTeststr_ur_Arab], - ["vi", "VIETNAMESE", kTeststr_vi_Latn], - ["cy", "WELSH", kTeststr_cy_Latn], - ["yi", "YIDDISH", kTeststr_yi_Hebr], - - // Added 2013.08.31 so-Latn ig-Latn ha-Latn yo-Latn zu-Latn - ["so", "SOMALI", kTeststr_so_Latn], - ["ig", "IGBO", kTeststr_ig_Latn], - ["ha", "HAUSA", kTeststr_ha_Latn], - ["yo", "YORUBA", kTeststr_yo_Latn], - ["zu", "ZULU", kTeststr_zu_Latn], - // Added 2014.01.22 bs-Latn - ["bs", "BOSNIAN", kTeststr_bs_Latn], - -// 2 statistically-close languages - ["id", "INDONESIAN", kTeststr_id_close, [true, 80], []], - ["ms", "MALAY", kTeststr_ms_close], - -// Simple intermixed French/English text - ["fr", "FRENCH", kTeststr_fr_en_Latn, [false, 80, "en", 32]], - -// Cross-check the main quadgram table build date -// Change the expected language each time it is rebuilt - ["az", "AZERBAIJANI", kTeststr_version] // 2014.01.31 -]; - -Components.utils.import("resource://gre/modules/Timer.jsm"); -let detectorModule = Components.utils.import("resource:///modules/translation/LanguageDetector.jsm"); - -function check_result(result, langCode, expected) { - equal(result.language, langCode, "Expected language code"); - - // Round percentage up to the nearest 5%, since most strings are - // detected at slightly less than 100%, and we don't want to - // encode each exact value. - let percent = result.languages[0].percent; - percent = Math.ceil(percent / 20) * 20; - - equal(result.languages[0].languageCode, langCode, "Expected first guess language code"); - equal(percent, expected[1] || 100, "Expected first guess language percent"); - - if (expected.length < 3) { - // We're not expecting a second language. - equal(result.languages.length, 1, "Expected only one language result"); - } else { - equal(result.languages.length, 2, "Expected two language results"); - - equal(result.languages[1].languageCode, expected[2], "Expected second guess language code"); - equal(result.languages[1].percent, expected[3], "Expected second guess language percent"); - } - - equal(result.confident, !expected[0], "Expected confidence"); -} - -add_task(function* test_pairs() { - for (let item of kTestPairs) { - let params = [item[2], - { text: item[2], tld: "com", language: item[0], encoding: "utf-8" }] - - for (let [i, param] of params.entries()) { - // For test items with different expected results when using the - // language hint, use those for the hinted version of the API. - // Otherwise, fall back to the first set of expected values. - let expected = item[3 + i] || item[3] || []; - - let result = yield LanguageDetector.detectLanguage(param); - check_result(result, item[0], expected); - } - } -}); - -// Test that the worker is flushed shortly after processing a large -// string. -add_task(function* test_worker_flush() { - let test_string = kTeststr_fr_en_Latn; - let test_item = kTestPairs.find(item => item[2] == test_string); - - // Set shorter timeouts and lower string lengths to make things easier - // on the test infrastructure. - detectorModule.LARGE_STRING = test_string.length - 1; - detectorModule.IDLE_TIMEOUT = 1000; - - equal(detectorModule.workerManager._idleTimeout, null, - "Should have no idle timeout to start with"); - - let result = yield LanguageDetector.detectLanguage(test_string); - - // Make sure the results are still correct. - check_result(result, test_item[0], test_item[3]); - - // We should have an idle timeout after processing the string. - ok(detectorModule.workerManager._idleTimeout != null, - "Should have an idle timeout"); - ok(detectorModule.workerManager._worker != null, - "Should have a worker instance"); - ok(detectorModule.workerManager._workerReadyPromise != null, - "Should have a worker promise"); - - // Wait for the idle timeout to elapse. - yield new Promise(resolve => setTimeout(resolve, detectorModule.IDLE_TIMEOUT)); - - equal(detectorModule.workerManager._idleTimeout, null, - "Should have no idle timeout after it has elapsed"); - equal(detectorModule.workerManager._worker, null, - "Should have no worker instance after idle timeout"); - equal(detectorModule.workerManager._workerReadyPromise, null, - "Should have no worker promise after idle timeout"); - - // We should still be able to use the language detector after its - // worker has been flushed. - result = yield LanguageDetector.detectLanguage(test_string); - - // Make sure the results are still correct. - check_result(result, test_item[0], test_item[3]); -}); diff --git a/browser/components/translation/test/unit/xpcshell.ini b/browser/components/translation/test/unit/xpcshell.ini deleted file mode 100644 index 8431a8c4e..000000000 --- a/browser/components/translation/test/unit/xpcshell.ini +++ /dev/null @@ -1,7 +0,0 @@ -[DEFAULT] -head = -tail = -firefox-appdir = browser -skip-if = toolkit == 'android' - -[test_cld2.js] diff --git a/browser/components/translation/test/yandex.sjs b/browser/components/translation/test/yandex.sjs deleted file mode 100644 index ed515beab..000000000 --- a/browser/components/translation/test/yandex.sjs +++ /dev/null @@ -1,199 +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 {classes: Cc, interfaces: Ci, Constructor: CC} = Components; -const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", - "nsIBinaryInputStream", - "setInputStream"); - -function handleRequest(req, res) { - try { - reallyHandleRequest(req, res); - } catch (ex) { - res.setStatusLine("1.0", 200, "AlmostOK"); - let msg = "Error handling request: " + ex + "\n" + ex.stack; - log(msg); - res.write(msg); - } -} - -function log(msg) { - dump("YANDEX-SERVER-MOCK: " + msg + "\n"); -} - -const statusCodes = { - 400: "Bad Request", - 401: "Invalid API key", - 402: "This API key has been blocked", - 403: "Daily limit for requests reached", - 404: "Daily limit for chars reached", - 413: "The text size exceeds the maximum", - 422: "The text could not be translated", - 500: "Internal Server Error", - 501: "The specified translation direction is not supported", - 503: "Service Unavailable" -}; - -function HTTPError(code = 500, message) { - this.code = code; - this.name = statusCodes[code] || "HTTPError"; - this.message = message || this.name; -} -HTTPError.prototype = new Error(); -HTTPError.prototype.constructor = HTTPError; - -function sendError(res, err) { - if (!(err instanceof HTTPError)) { - err = new HTTPError(typeof err == "number" ? err : 500, - err.message || typeof err == "string" ? err : ""); - } - res.setStatusLine("1.1", err.code, err.name); - res.write(err.message); -} - -// Based on the code borrowed from: -// http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript -function parseQuery(query) { - let match, - params = {}, - pl = /\+/g, - search = /([^&=]+)=?([^&]*)/g, - decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }; - - while (match = search.exec(query)) { - let k = decode(match[1]), - v = decode(match[2]); - if (k in params) { - if(params[k] instanceof Array) - params[k].push(v); - else - params[k] = [params[k], v]; - } else { - params[k] = v; - } - } - - return params; -} - -function sha1(str) { - let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"] - .createInstance(Ci.nsIScriptableUnicodeConverter); - converter.charset = "UTF-8"; - // `result` is an out parameter, `result.value` will contain the array length. - let result = {}; - // `data` is an array of bytes. - let data = converter.convertToByteArray(str, result); - let ch = Cc["@mozilla.org/security/hash;1"] - .createInstance(Ci.nsICryptoHash); - ch.init(ch.SHA1); - ch.update(data, data.length); - let hash = ch.finish(false); - - // Return the two-digit hexadecimal code for a byte. - function toHexString(charCode) { - return ("0" + charCode.toString(16)).slice(-2); - } - - // Convert the binary hash data to a hex string. - return Array.from(hash, (c, i) => toHexString(hash.charCodeAt(i))).join(""); -} - -function getRequestBody(req) { - let avail; - let bytes = []; - let body = new BinaryInputStream(req.bodyInputStream); - - while ((avail = body.available()) > 0) - Array.prototype.push.apply(bytes, body.readByteArray(avail)); - - return String.fromCharCode.apply(null, bytes); -} - -function getInputStream(path) { - let file = Cc["@mozilla.org/file/directory_service;1"] - .getService(Ci.nsIProperties) - .get("CurWorkD", Ci.nsILocalFile); - for (let part of path.split("/")) - file.append(part); - let fileStream = Cc["@mozilla.org/network/file-input-stream;1"] - .createInstance(Ci.nsIFileInputStream); - fileStream.init(file, 1, 0, false); - return fileStream; -} - -/** - * Yandex Requests have to be signed with an API Key. This mock server - * supports the following keys: - * - * yandexValidKey Always passes the authentication, - * yandexInvalidKey Never passes authentication and fails with 401 code, - * yandexBlockedKey Never passes authentication and fails with 402 code, - * yandexOutOfRequestsKey Never passes authentication and fails with 403 code, - * yandexOutOfCharsKey Never passes authentication and fails with 404 code. - * - * If any other key is used the server reponds with 401 error code. - */ -function checkAuth(params) { - if(!("key" in params)) - throw new HTTPError(400); - - let key = params.key; - if(key === "yandexValidKey") - return true; - - let invalidKeys = { - "yandexInvalidKey" : 401, - "yandexBlockedKey" : 402, - "yandexOutOfRequestsKey" : 403, - "yandexOutOfCharsKey" : 404, - }; - - if(key in invalidKeys) - throw new HTTPError(invalidKeys[key]); - - throw new HTTPError(401); -} - -function reallyHandleRequest(req, res) { - - try { - - // Preparing the query parameters. - let params = {}; - if(req.method == 'POST') { - params = parseQuery(getRequestBody(req)); - } - - // Extracting the API key and attempting to authenticate the request. - log(JSON.stringify(params)); - - checkAuth(params); - methodHandlers['translate'](res, params); - - } catch (ex) { - sendError(res, ex, ex.code); - } - -} - -const methodHandlers = { - translate: function(res, params) { - res.setStatusLine("1.1", 200, "OK"); - res.setHeader("Content-Type", "application/json"); - - let hash = sha1(JSON.stringify(params)).substr(0, 10); - log("SHA1 hash of content: " + hash); - - let fixture = "browser/browser/components/translation/test/fixtures/result-yandex-" + hash + ".json"; - log("PATH: " + fixture); - - let inputStream = getInputStream(fixture); - res.bodyOutputStream.writeFrom(inputStream, inputStream.available()); - inputStream.close(); - } - -}; diff --git a/browser/components/uitour/test/.eslintrc.js b/browser/components/uitour/test/.eslintrc.js deleted file mode 100644 index c764b133d..000000000 --- a/browser/components/uitour/test/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../../../../testing/mochitest/browser.eslintrc.js" - ] -}; diff --git a/browser/components/uitour/test/browser.ini b/browser/components/uitour/test/browser.ini deleted file mode 100644 index ae027a738..000000000 --- a/browser/components/uitour/test/browser.ini +++ /dev/null @@ -1,49 +0,0 @@ -[DEFAULT] -support-files = - head.js - image.png - uitour.html - ../UITour-lib.js - -[browser_backgroundTab.js] -[browser_closeTab.js] -[browser_fxa.js] -skip-if = debug || asan # updateAppMenuItem leaks -[browser_no_tabs.js] -[browser_openPreferences.js] -[browser_openSearchPanel.js] -skip-if = true # Bug 1113038 - Intermittent "Popup was opened" -[browser_trackingProtection.js] -skip-if = os == "linux" # Intermittent NS_ERROR_NOT_AVAILABLE [nsIUrlClassifierDBService.beginUpdate] -tag = trackingprotection -support-files = - !/browser/base/content/test/general/benignPage.html - !/browser/base/content/test/general/trackingPage.html -[browser_trackingProtection_tour.js] -tag = trackingprotection -[browser_showMenu_controlCenter.js] -tag = trackingprotection -[browser_UITour.js] -skip-if = os == "linux" # Intermittent failures, bug 951965 -[browser_UITour2.js] -[browser_UITour3.js] -skip-if = os == "linux" # Linux: Bug 986760, Bug 989101. -[browser_UITour_availableTargets.js] -[browser_UITour_annotation_size_attributes.js] -[browser_UITour_defaultBrowser.js] -[browser_UITour_detach_tab.js] -[browser_UITour_forceReaderMode.js] -[browser_UITour_heartbeat.js] -skip-if = os == "win" # Bug 1277107 -[browser_UITour_modalDialog.js] -skip-if = os != "mac" # modal dialog disabling only working on OS X. -[browser_UITour_observe.js] -[browser_UITour_panel_close_annotation.js] -skip-if = true # Disabled due to frequent failures, bugs 1026310 and 1032137 -[browser_UITour_pocket.js] -skip-if = true # Disabled pending removal of pocket UI Tour -[browser_UITour_registerPageID.js] -[browser_UITour_resetProfile.js] -[browser_UITour_showNewTab.js] -[browser_UITour_sync.js] -[browser_UITour_toggleReaderMode.js] diff --git a/browser/components/uitour/test/browser_UITour.js b/browser/components/uitour/test/browser_UITour.js deleted file mode 100644 index 964be0215..000000000 --- a/browser/components/uitour/test/browser_UITour.js +++ /dev/null @@ -1,408 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -Components.utils.import("resource://testing-common/TelemetryArchiveTesting.jsm", this); - -function test() { - UITourTest(); -} - -var tests = [ - function test_untrusted_host(done) { - loadUITourTestPage(function() { - let bookmarksMenu = document.getElementById("bookmarks-menu-button"); - is(bookmarksMenu.open, false, "Bookmark menu should initially be closed"); - - gContentAPI.showMenu("bookmarks"); - is(bookmarksMenu.open, false, "Bookmark menu should not open on a untrusted host"); - - done(); - }, "http://mochi.test:8888/"); - }, - function test_testing_host(done) { - // Add two testing origins intentionally surrounded by whitespace to be ignored. - Services.prefs.setCharPref("browser.uitour.testingOrigins", - "https://test1.example.org, https://test2.example.org:443 "); - - registerCleanupFunction(() => { - Services.prefs.clearUserPref("browser.uitour.testingOrigins"); - }); - function callback(result) { - ok(result, "Callback should be called on a testing origin"); - done(); - } - - loadUITourTestPage(function() { - gContentAPI.getConfiguration("appinfo", callback); - }, "https://test2.example.org/"); - }, - function test_unsecure_host(done) { - loadUITourTestPage(function() { - let bookmarksMenu = document.getElementById("bookmarks-menu-button"); - is(bookmarksMenu.open, false, "Bookmark menu should initially be closed"); - - gContentAPI.showMenu("bookmarks"); - is(bookmarksMenu.open, false, "Bookmark menu should not open on a unsecure host"); - - done(); - }, "http://example.org/"); - }, - function test_unsecure_host_override(done) { - Services.prefs.setBoolPref("browser.uitour.requireSecure", false); - loadUITourTestPage(function() { - let highlight = document.getElementById("UITourHighlight"); - is_element_hidden(highlight, "Highlight should initially be hidden"); - - gContentAPI.showHighlight("urlbar"); - waitForElementToBeVisible(highlight, done, "Highlight should be shown on a unsecure host when override pref is set"); - - Services.prefs.setBoolPref("browser.uitour.requireSecure", true); - }, "http://example.org/"); - }, - function test_disabled(done) { - Services.prefs.setBoolPref("browser.uitour.enabled", false); - - let bookmarksMenu = document.getElementById("bookmarks-menu-button"); - is(bookmarksMenu.open, false, "Bookmark menu should initially be closed"); - - gContentAPI.showMenu("bookmarks"); - is(bookmarksMenu.open, false, "Bookmark menu should not open when feature is disabled"); - - Services.prefs.setBoolPref("browser.uitour.enabled", true); - done(); - }, - function test_highlight(done) { - function test_highlight_2() { - let highlight = document.getElementById("UITourHighlight"); - gContentAPI.hideHighlight(); - - waitForElementToBeHidden(highlight, test_highlight_3, "Highlight should be hidden after hideHighlight()"); - } - function test_highlight_3() { - is_element_hidden(highlight, "Highlight should be hidden after hideHighlight()"); - - gContentAPI.showHighlight("urlbar"); - waitForElementToBeVisible(highlight, test_highlight_4, "Highlight should be shown after showHighlight()"); - } - function test_highlight_4() { - let highlight = document.getElementById("UITourHighlight"); - gContentAPI.showHighlight("backForward"); - waitForElementToBeVisible(highlight, done, "Highlight should be shown after showHighlight()"); - } - - let highlight = document.getElementById("UITourHighlight"); - is_element_hidden(highlight, "Highlight should initially be hidden"); - - gContentAPI.showHighlight("urlbar"); - waitForElementToBeVisible(highlight, test_highlight_2, "Highlight should be shown after showHighlight()"); - }, - function test_highlight_circle(done) { - function check_highlight_size() { - let panel = highlight.parentElement; - let anchor = panel.anchorNode; - let anchorRect = anchor.getBoundingClientRect(); - info("addons target: width: " + anchorRect.width + " height: " + anchorRect.height); - let maxDimension = Math.round(Math.max(anchorRect.width, anchorRect.height)); - let highlightRect = highlight.getBoundingClientRect(); - info("highlight: width: " + highlightRect.width + " height: " + highlightRect.height); - is(Math.round(highlightRect.width), maxDimension, "The width of the highlight should be equal to the largest dimension of the target"); - is(Math.round(highlightRect.height), maxDimension, "The height of the highlight should be equal to the largest dimension of the target"); - is(Math.round(highlightRect.height), Math.round(highlightRect.width), "The height and width of the highlight should be the same to create a circle"); - is(highlight.style.borderRadius, "100%", "The border-radius should be 100% to create a circle"); - done(); - } - let highlight = document.getElementById("UITourHighlight"); - is_element_hidden(highlight, "Highlight should initially be hidden"); - - gContentAPI.showHighlight("addons"); - waitForElementToBeVisible(highlight, check_highlight_size, "Highlight should be shown after showHighlight()"); - }, - function test_highlight_customize_auto_open_close(done) { - let highlight = document.getElementById("UITourHighlight"); - gContentAPI.showHighlight("customize"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Move the highlight outside which should close the app menu. - gContentAPI.showHighlight("appMenu"); - waitForElementToBeVisible(highlight, function checkPanelIsClosed() { - isnot(PanelUI.panel.state, "open", - "Panel should have closed after the highlight moved elsewhere."); - done(); - }, "Highlight should move to the appMenu button"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - function test_highlight_customize_manual_open_close(done) { - let highlight = document.getElementById("UITourHighlight"); - // Manually open the app menu then show a highlight there. The menu should remain open. - let shownPromise = promisePanelShown(window); - gContentAPI.showMenu("appMenu"); - shownPromise.then(() => { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - gContentAPI.showHighlight("customize"); - - waitForElementToBeVisible(highlight, function checkPanelIsStillOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should still be open"); - - // Move the highlight outside which shouldn't close the app menu since it was manually opened. - gContentAPI.showHighlight("appMenu"); - waitForElementToBeVisible(highlight, function () { - isnot(PanelUI.panel.state, "closed", - "Panel should remain open since UITour didn't open it in the first place"); - gContentAPI.hideMenu("appMenu"); - done(); - }, "Highlight should move to the appMenu button"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }).then(null, Components.utils.reportError); - }, - function test_highlight_effect(done) { - function waitForHighlightWithEffect(highlightEl, effect, next, error) { - return waitForCondition(() => highlightEl.getAttribute("active") == effect, - next, - error); - } - function checkDefaultEffect() { - is(highlight.getAttribute("active"), "none", "The default should be no effect"); - - gContentAPI.showHighlight("urlbar", "none"); - waitForHighlightWithEffect(highlight, "none", checkZoomEffect, "There should be no effect"); - } - function checkZoomEffect() { - gContentAPI.showHighlight("urlbar", "zoom"); - waitForHighlightWithEffect(highlight, "zoom", () => { - let style = window.getComputedStyle(highlight); - is(style.animationName, "uitour-zoom", "The animation-name should be uitour-zoom"); - checkSameEffectOnDifferentTarget(); - }, "There should be a zoom effect"); - } - function checkSameEffectOnDifferentTarget() { - gContentAPI.showHighlight("appMenu", "wobble"); - waitForHighlightWithEffect(highlight, "wobble", () => { - highlight.addEventListener("animationstart", function onAnimationStart(aEvent) { - highlight.removeEventListener("animationstart", onAnimationStart); - ok(true, "Animation occurred again even though the effect was the same"); - checkRandomEffect(); - }); - gContentAPI.showHighlight("backForward", "wobble"); - }, "There should be a wobble effect"); - } - function checkRandomEffect() { - function waitForActiveHighlight(highlightEl, next, error) { - return waitForCondition(() => highlightEl.hasAttribute("active"), - next, - error); - } - - gContentAPI.hideHighlight(); - gContentAPI.showHighlight("urlbar", "random"); - waitForActiveHighlight(highlight, () => { - ok(highlight.hasAttribute("active"), "The highlight should be active"); - isnot(highlight.getAttribute("active"), "none", "A random effect other than none should have been chosen"); - isnot(highlight.getAttribute("active"), "random", "The random effect shouldn't be 'random'"); - isnot(UITour.highlightEffects.indexOf(highlight.getAttribute("active")), -1, "Check that a supported effect was randomly chosen"); - done(); - }, "There should be an active highlight with a random effect"); - } - - let highlight = document.getElementById("UITourHighlight"); - is_element_hidden(highlight, "Highlight should initially be hidden"); - - gContentAPI.showHighlight("urlbar"); - waitForElementToBeVisible(highlight, checkDefaultEffect, "Highlight should be shown after showHighlight()"); - }, - function test_highlight_effect_unsupported(done) { - function checkUnsupportedEffect() { - is(highlight.getAttribute("active"), "none", "No effect should be used when an unsupported effect is requested"); - done(); - } - - let highlight = document.getElementById("UITourHighlight"); - is_element_hidden(highlight, "Highlight should initially be hidden"); - - gContentAPI.showHighlight("urlbar", "__UNSUPPORTED__"); - waitForElementToBeVisible(highlight, checkUnsupportedEffect, "Highlight should be shown after showHighlight()"); - }, - function test_info_1(done) { - let popup = document.getElementById("UITourTooltip"); - let title = document.getElementById("UITourTooltipTitle"); - let desc = document.getElementById("UITourTooltipDescription"); - let icon = document.getElementById("UITourTooltipIcon"); - let buttons = document.getElementById("UITourTooltipButtons"); - - popup.addEventListener("popupshown", function onPopupShown() { - popup.removeEventListener("popupshown", onPopupShown); - is(popup.popupBoxObject.anchorNode, document.getElementById("urlbar"), "Popup should be anchored to the urlbar"); - is(title.textContent, "test title", "Popup should have correct title"); - is(desc.textContent, "test text", "Popup should have correct description text"); - is(icon.src, "", "Popup should have no icon"); - is(buttons.hasChildNodes(), false, "Popup should have no buttons"); - - popup.addEventListener("popuphidden", function onPopupHidden() { - popup.removeEventListener("popuphidden", onPopupHidden); - - popup.addEventListener("popupshown", function onPopupShown() { - popup.removeEventListener("popupshown", onPopupShown); - done(); - }); - - gContentAPI.showInfo("urlbar", "test title", "test text"); - - }); - gContentAPI.hideInfo(); - }); - - gContentAPI.showInfo("urlbar", "test title", "test text"); - }, - taskify(function* test_info_2() { - let popup = document.getElementById("UITourTooltip"); - let title = document.getElementById("UITourTooltipTitle"); - let desc = document.getElementById("UITourTooltipDescription"); - let icon = document.getElementById("UITourTooltipIcon"); - let buttons = document.getElementById("UITourTooltipButtons"); - - yield showInfoPromise("urlbar", "urlbar title", "urlbar text"); - - is(popup.popupBoxObject.anchorNode, document.getElementById("urlbar"), "Popup should be anchored to the urlbar"); - is(title.textContent, "urlbar title", "Popup should have correct title"); - is(desc.textContent, "urlbar text", "Popup should have correct description text"); - is(icon.src, "", "Popup should have no icon"); - is(buttons.hasChildNodes(), false, "Popup should have no buttons"); - - yield showInfoPromise("search", "search title", "search text"); - - is(popup.popupBoxObject.anchorNode, document.getElementById("searchbar"), "Popup should be anchored to the searchbar"); - is(title.textContent, "search title", "Popup should have correct title"); - is(desc.textContent, "search text", "Popup should have correct description text"); - }), - function test_getConfigurationVersion(done) { - function callback(result) { - let props = ["defaultUpdateChannel", "version"]; - for (let property of props) { - ok(typeof(result[property]) !== "undefined", "Check " + property + " isn't undefined."); - is(result[property], Services.appinfo[property], "Should have the same " + property + " property."); - } - done(); - } - - gContentAPI.getConfiguration("appinfo", callback); - }, - function test_getConfigurationDistribution(done) { - gContentAPI.getConfiguration("appinfo", (result) => { - ok(typeof(result.distribution) !== "undefined", "Check distribution isn't undefined."); - is(result.distribution, "default", "Should be \"default\" without preference set."); - - let defaults = Services.prefs.getDefaultBranch("distribution."); - let testDistributionID = "TestDistribution"; - defaults.setCharPref("id", testDistributionID); - gContentAPI.getConfiguration("appinfo", (result) => { - ok(typeof(result.distribution) !== "undefined", "Check distribution isn't undefined."); - is(result.distribution, testDistributionID, "Should have the distribution as set in preference."); - - done(); - }); - }); - }, - function test_addToolbarButton(done) { - let placement = CustomizableUI.getPlacementOfWidget("panic-button"); - is(placement, null, "default UI has panic button in the palette"); - - gContentAPI.getConfiguration("availableTargets", (data) => { - let available = (data.targets.indexOf("forget") != -1); - ok(!available, "Forget button should not be available by default"); - - gContentAPI.addNavBarWidget("forget", () => { - info("addNavBarWidget callback successfully called"); - - let placement = CustomizableUI.getPlacementOfWidget("panic-button"); - is(placement.area, CustomizableUI.AREA_NAVBAR); - - gContentAPI.getConfiguration("availableTargets", (data) => { - let available = (data.targets.indexOf("forget") != -1); - ok(available, "Forget button should now be available"); - - // Cleanup - CustomizableUI.removeWidgetFromArea("panic-button"); - done(); - }); - }); - }); - }, - function test_search(done) { - Services.search.init(rv => { - if (!Components.isSuccessCode(rv)) { - ok(false, "search service init failed: " + rv); - done(); - return; - } - let defaultEngine = Services.search.defaultEngine; - gContentAPI.getConfiguration("search", data => { - let visibleEngines = Services.search.getVisibleEngines(); - let expectedEngines = visibleEngines.filter((engine) => engine.identifier) - .map((engine) => "searchEngine-" + engine.identifier); - - let engines = data.engines; - ok(Array.isArray(engines), "data.engines should be an array"); - is(engines.sort().toString(), expectedEngines.sort().toString(), - "Engines should be as expected"); - - is(data.searchEngineIdentifier, defaultEngine.identifier, - "the searchEngineIdentifier property should contain the defaultEngine's identifier"); - - let someOtherEngineID = data.engines.filter(t => t != "searchEngine-" + defaultEngine.identifier)[0]; - someOtherEngineID = someOtherEngineID.replace(/^searchEngine-/, ""); - - let observe = function (subject, topic, verb) { - info("browser-search-engine-modified: " + verb); - if (verb == "engine-current") { - is(Services.search.defaultEngine.identifier, someOtherEngineID, "correct engine was switched to"); - done(); - } - }; - Services.obs.addObserver(observe, "browser-search-engine-modified", false); - registerCleanupFunction(() => { - // Clean up - Services.obs.removeObserver(observe, "browser-search-engine-modified"); - Services.search.defaultEngine = defaultEngine; - }); - - gContentAPI.setDefaultSearchEngine(someOtherEngineID); - }); - }); - }, - taskify(function* test_treatment_tag() { - let ac = new TelemetryArchiveTesting.Checker(); - yield ac.promiseInit(); - yield gContentAPI.setTreatmentTag("foobar", "baz"); - // Wait until the treatment telemetry is sent before looking in the archive. - yield BrowserTestUtils.waitForContentEvent(gTestTab.linkedBrowser, "mozUITourNotification", false, - event => event.detail.event === "TreatmentTag:TelemetrySent"); - yield new Promise((resolve) => { - gContentAPI.getTreatmentTag("foobar", (data) => { - is(data.value, "baz", "set and retrieved treatmentTag"); - ac.promiseFindPing("uitour-tag", [ - [["payload", "tagName"], "foobar"], - [["payload", "tagValue"], "baz"], - ]).then((found) => { - ok(found, "Telemetry ping submitted for setTreatmentTag"); - resolve(); - }, (err) => { - ok(false, "Exception finding uitour telemetry ping: " + err); - resolve(); - }); - }); - }); - }), - - // Make sure this test is last in the file so the appMenu gets left open and done will confirm it got tore down. - taskify(function* cleanupMenus() { - let shownPromise = promisePanelShown(window); - gContentAPI.showMenu("appMenu"); - yield shownPromise; - }), -]; diff --git a/browser/components/uitour/test/browser_UITour2.js b/browser/components/uitour/test/browser_UITour2.js deleted file mode 100644 index e74a71afa..000000000 --- a/browser/components/uitour/test/browser_UITour2.js +++ /dev/null @@ -1,83 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -function test() { - UITourTest(); -} - -var tests = [ - function test_info_customize_auto_open_close(done) { - let popup = document.getElementById("UITourTooltip"); - gContentAPI.showInfo("customize", "Customization", "Customize me please!"); - UITour.getTarget(window, "customize").then((customizeTarget) => { - waitForPopupAtAnchor(popup, customizeTarget.node, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened before the popup anchored"); - ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been set"); - - // Move the info outside which should close the app menu. - gContentAPI.showInfo("appMenu", "Open Me", "You know you want to"); - UITour.getTarget(window, "appMenu").then((target) => { - waitForPopupAtAnchor(popup, target.node, function checkPanelIsClosed() { - isnot(PanelUI.panel.state, "open", - "Panel should have closed after the info moved elsewhere."); - ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up on close"); - done(); - }, "Info should move to the appMenu button"); - }); - }, "Info panel should be anchored to the customize button"); - }); - }, - function test_info_customize_manual_open_close(done) { - let popup = document.getElementById("UITourTooltip"); - // Manually open the app menu then show an info panel there. The menu should remain open. - let shownPromise = promisePanelShown(window); - gContentAPI.showMenu("appMenu"); - shownPromise.then(() => { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been set"); - gContentAPI.showInfo("customize", "Customization", "Customize me please!"); - - UITour.getTarget(window, "customize").then((customizeTarget) => { - waitForPopupAtAnchor(popup, customizeTarget.node, function checkMenuIsStillOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should still be open"); - ok(PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should still be set"); - - // Move the info outside which shouldn't close the app menu since it was manually opened. - gContentAPI.showInfo("appMenu", "Open Me", "You know you want to"); - UITour.getTarget(window, "appMenu").then((target) => { - waitForPopupAtAnchor(popup, target.node, function checkMenuIsStillOpen() { - isnot(PanelUI.panel.state, "closed", - "Menu should remain open since UITour didn't open it in the first place"); - waitForElementToBeHidden(window.PanelUI.panel, () => { - ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up on close"); - done(); - }); - gContentAPI.hideMenu("appMenu"); - }, "Info should move to the appMenu button"); - }); - }, "Info should be shown after showInfo() for fixed menu panel items"); - }); - }).then(null, Components.utils.reportError); - }, - taskify(function* test_bookmarks_menu() { - let bookmarksMenuButton = document.getElementById("bookmarks-menu-button"); - - is(bookmarksMenuButton.open, false, "Menu should initially be closed"); - gContentAPI.showMenu("bookmarks"); - - yield waitForConditionPromise(() => { - return bookmarksMenuButton.open; - }, "Menu should be visible after showMenu()"); - - gContentAPI.hideMenu("bookmarks"); - yield waitForConditionPromise(() => { - return !bookmarksMenuButton.open; - }, "Menu should be hidden after hideMenu()"); - }), -]; diff --git a/browser/components/uitour/test/browser_UITour3.js b/browser/components/uitour/test/browser_UITour3.js deleted file mode 100644 index b852339f1..000000000 --- a/browser/components/uitour/test/browser_UITour3.js +++ /dev/null @@ -1,181 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -requestLongerTimeout(2); - -add_task(setup_UITourTest); - -add_UITour_task(function* test_info_icon() { - let popup = document.getElementById("UITourTooltip"); - let title = document.getElementById("UITourTooltipTitle"); - let desc = document.getElementById("UITourTooltipDescription"); - let icon = document.getElementById("UITourTooltipIcon"); - let buttons = document.getElementById("UITourTooltipButtons"); - - // Disable the animation to prevent the mouse clicks from hitting the main - // window during the transition instead of the buttons in the popup. - popup.setAttribute("animate", "false"); - - yield showInfoPromise("urlbar", "a title", "some text", "image.png"); - - is(title.textContent, "a title", "Popup should have correct title"); - is(desc.textContent, "some text", "Popup should have correct description text"); - - let imageURL = getRootDirectory(gTestPath) + "image.png"; - imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/"); - is(icon.src, imageURL, "Popup should have correct icon shown"); - - is(buttons.hasChildNodes(), false, "Popup should have no buttons"); -}), - -add_UITour_task(function* test_info_buttons_1() { - let popup = document.getElementById("UITourTooltip"); - let title = document.getElementById("UITourTooltipTitle"); - let desc = document.getElementById("UITourTooltipDescription"); - let icon = document.getElementById("UITourTooltipIcon"); - - yield showInfoPromise("urlbar", "another title", "moar text", "./image.png", "makeButtons"); - - is(title.textContent, "another title", "Popup should have correct title"); - is(desc.textContent, "moar text", "Popup should have correct description text"); - - let imageURL = getRootDirectory(gTestPath) + "image.png"; - imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/"); - is(icon.src, imageURL, "Popup should have correct icon shown"); - - let buttons = document.getElementById("UITourTooltipButtons"); - is(buttons.childElementCount, 4, "Popup should have four buttons"); - - is(buttons.childNodes[0].nodeName, "label", "Text label should be a <label>"); - is(buttons.childNodes[0].getAttribute("value"), "Regular text", "Text label should have correct value"); - is(buttons.childNodes[0].getAttribute("image"), "", "Text should have no image"); - is(buttons.childNodes[0].className, "", "Text should have no class"); - - is(buttons.childNodes[1].nodeName, "button", "Link should be a <button>"); - is(buttons.childNodes[1].getAttribute("label"), "Link", "Link should have correct label"); - is(buttons.childNodes[1].getAttribute("image"), "", "Link should have no image"); - is(buttons.childNodes[1].className, "button-link", "Check link class"); - - is(buttons.childNodes[2].nodeName, "button", "Button 1 should be a <button>"); - is(buttons.childNodes[2].getAttribute("label"), "Button 1", "First button should have correct label"); - is(buttons.childNodes[2].getAttribute("image"), "", "First button should have no image"); - is(buttons.childNodes[2].className, "", "Button 1 should have no class"); - - is(buttons.childNodes[3].nodeName, "button", "Button 2 should be a <button>"); - is(buttons.childNodes[3].getAttribute("label"), "Button 2", "Second button should have correct label"); - is(buttons.childNodes[3].getAttribute("image"), imageURL, "Second button should have correct image"); - is(buttons.childNodes[3].className, "button-primary", "Check button 2 class"); - - let promiseHidden = promisePanelElementHidden(window, popup); - EventUtils.synthesizeMouseAtCenter(buttons.childNodes[2], {}, window); - yield promiseHidden; - - ok(true, "Popup should close automatically"); - - let returnValue = yield waitForCallbackResultPromise(); - is(returnValue.result, "button1", "Correct callback should have been called"); -}); - -add_UITour_task(function* test_info_buttons_2() { - let popup = document.getElementById("UITourTooltip"); - let title = document.getElementById("UITourTooltipTitle"); - let desc = document.getElementById("UITourTooltipDescription"); - let icon = document.getElementById("UITourTooltipIcon"); - - yield showInfoPromise("urlbar", "another title", "moar text", "./image.png", "makeButtons"); - - is(title.textContent, "another title", "Popup should have correct title"); - is(desc.textContent, "moar text", "Popup should have correct description text"); - - let imageURL = getRootDirectory(gTestPath) + "image.png"; - imageURL = imageURL.replace("chrome://mochitests/content/", "https://example.org/"); - is(icon.src, imageURL, "Popup should have correct icon shown"); - - let buttons = document.getElementById("UITourTooltipButtons"); - is(buttons.childElementCount, 4, "Popup should have four buttons"); - - is(buttons.childNodes[1].getAttribute("label"), "Link", "Link should have correct label"); - is(buttons.childNodes[1].getAttribute("image"), "", "Link should have no image"); - ok(buttons.childNodes[1].classList.contains("button-link"), "Link should have button-link class"); - - is(buttons.childNodes[2].getAttribute("label"), "Button 1", "First button should have correct label"); - is(buttons.childNodes[2].getAttribute("image"), "", "First button should have no image"); - - is(buttons.childNodes[3].getAttribute("label"), "Button 2", "Second button should have correct label"); - is(buttons.childNodes[3].getAttribute("image"), imageURL, "Second button should have correct image"); - - let promiseHidden = promisePanelElementHidden(window, popup); - EventUtils.synthesizeMouseAtCenter(buttons.childNodes[3], {}, window); - yield promiseHidden; - - ok(true, "Popup should close automatically"); - - let returnValue = yield waitForCallbackResultPromise(); - - is(returnValue.result, "button2", "Correct callback should have been called"); -}), - -add_UITour_task(function* test_info_close_button() { - let closeButton = document.getElementById("UITourTooltipClose"); - - yield showInfoPromise("urlbar", "Close me", "X marks the spot", null, null, "makeInfoOptions"); - - EventUtils.synthesizeMouseAtCenter(closeButton, {}, window); - - let returnValue = yield waitForCallbackResultPromise(); - - is(returnValue.result, "closeButton", "Close button callback called"); -}), - -add_UITour_task(function* test_info_target_callback() { - let popup = document.getElementById("UITourTooltip"); - - yield showInfoPromise("appMenu", "I want to know when the target is clicked", "*click*", null, null, "makeInfoOptions"); - - yield PanelUI.show(); - - let returnValue = yield waitForCallbackResultPromise(); - - is(returnValue.result, "target", "target callback called"); - is(returnValue.data.target, "appMenu", "target callback was from the appMenu"); - is(returnValue.data.type, "popupshown", "target callback was from the mousedown"); - - // Cleanup. - yield hideInfoPromise(); - - popup.removeAttribute("animate"); -}), - -add_UITour_task(function* test_getConfiguration_selectedSearchEngine() { - yield new Promise((resolve) => { - Services.search.init(Task.async(function*(rv) { - ok(Components.isSuccessCode(rv), "Search service initialized"); - let engine = Services.search.defaultEngine; - let data = yield getConfigurationPromise("selectedSearchEngine"); - is(data.searchEngineIdentifier, engine.identifier, "Correct engine identifier"); - resolve(); - })); - }); -}); - -add_UITour_task(function* test_setSearchTerm() { - const TERM = "UITour Search Term"; - yield gContentAPI.setSearchTerm(TERM); - - let searchbar = document.getElementById("searchbar"); - // The UITour gets to the searchbar element through a promise, so the value setting - // only happens after a tick. - yield waitForConditionPromise(() => searchbar.value == TERM, "Correct term set"); -}); - -add_UITour_task(function* test_clearSearchTerm() { - yield gContentAPI.setSearchTerm(""); - - let searchbar = document.getElementById("searchbar"); - // The UITour gets to the searchbar element through a promise, so the value setting - // only happens after a tick. - yield waitForConditionPromise(() => searchbar.value == "", "Search term cleared"); -}); diff --git a/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js b/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js deleted file mode 100644 index dbdeb9589..000000000 --- a/browser/components/uitour/test/browser_UITour_annotation_size_attributes.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Test that width and height attributes don't get set by widget code on the highlight panel. - */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var highlight = document.getElementById("UITourHighlightContainer"); -var tooltip = document.getElementById("UITourTooltip"); - -add_task(setup_UITourTest); - -add_UITour_task(function* test_highlight_size_attributes() { - yield gContentAPI.showHighlight("appMenu"); - yield elementVisiblePromise(highlight, - "Highlight should be shown after showHighlight() for the appMenu"); - yield gContentAPI.showHighlight("urlbar"); - yield elementVisiblePromise(highlight, "Highlight should be moved to the urlbar"); - yield new Promise((resolve) => { - SimpleTest.executeSoon(() => { - is(highlight.height, "", "Highlight panel should have no explicit height set"); - is(highlight.width, "", "Highlight panel should have no explicit width set"); - resolve(); - }); - }); -}); - -add_UITour_task(function* test_info_size_attributes() { - yield gContentAPI.showInfo("appMenu", "test title", "test text"); - yield elementVisiblePromise(tooltip, "Tooltip should be shown after showInfo() for the appMenu"); - yield gContentAPI.showInfo("urlbar", "new title", "new text"); - yield elementVisiblePromise(tooltip, "Tooltip should be moved to the urlbar"); - yield new Promise((resolve) => { - SimpleTest.executeSoon(() => { - is(tooltip.height, "", "Info panel should have no explicit height set"); - is(tooltip.width, "", "Info panel should have no explicit width set"); - resolve(); - }); - }); -}); diff --git a/browser/components/uitour/test/browser_UITour_availableTargets.js b/browser/components/uitour/test/browser_UITour_availableTargets.js deleted file mode 100644 index a6e96e31f..000000000 --- a/browser/components/uitour/test/browser_UITour_availableTargets.js +++ /dev/null @@ -1,114 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -var hasWebIDE = Services.prefs.getBoolPref("devtools.webide.widget.enabled"); -var hasPocket = Services.prefs.getBoolPref("extensions.pocket.enabled"); - -requestLongerTimeout(2); -add_task(setup_UITourTest); - -add_UITour_task(function* test_availableTargets() { - let data = yield getConfigurationPromise("availableTargets"); - ok_targets(data, [ - "accountStatus", - "addons", - "appMenu", - "backForward", - "bookmarks", - "customize", - "help", - "home", - "devtools", - ...(hasPocket ? ["pocket"] : []), - "privateWindow", - "quit", - "readerMode-urlBar", - "search", - "searchIcon", - "trackingProtection", - "urlbar", - ...(hasWebIDE ? ["webide"] : []) - ]); - - ok(UITour.availableTargetsCache.has(window), - "Targets should now be cached"); -}); - -add_UITour_task(function* test_availableTargets_changeWidgets() { - CustomizableUI.removeWidgetFromArea("bookmarks-menu-button"); - ok(!UITour.availableTargetsCache.has(window), - "Targets should be evicted from cache after widget change"); - let data = yield getConfigurationPromise("availableTargets"); - ok_targets(data, [ - "accountStatus", - "addons", - "appMenu", - "backForward", - "customize", - "help", - "devtools", - "home", - ...(hasPocket ? ["pocket"] : []), - "privateWindow", - "quit", - "readerMode-urlBar", - "search", - "searchIcon", - "trackingProtection", - "urlbar", - ...(hasWebIDE ? ["webide"] : []) - ]); - - ok(UITour.availableTargetsCache.has(window), - "Targets should now be cached again"); - CustomizableUI.reset(); - ok(!UITour.availableTargetsCache.has(window), - "Targets should not be cached after reset"); -}); - -add_UITour_task(function* test_availableTargets_exceptionFromGetTarget() { - // The query function for the "search" target will throw if it's not found. - // Make sure the callback still fires with the other available targets. - CustomizableUI.removeWidgetFromArea("search-container"); - let data = yield getConfigurationPromise("availableTargets"); - // Default minus "search" and "searchIcon" - ok_targets(data, [ - "accountStatus", - "addons", - "appMenu", - "backForward", - "bookmarks", - "customize", - "help", - "home", - "devtools", - ...(hasPocket ? ["pocket"] : []), - "privateWindow", - "quit", - "readerMode-urlBar", - "trackingProtection", - "urlbar", - ...(hasWebIDE ? ["webide"] : []) - ]); - - CustomizableUI.reset(); -}); - -function ok_targets(actualData, expectedTargets) { - // Depending on how soon after page load this is called, the selected tab icon - // may or may not be showing the loading throbber. Check for its presence and - // insert it into expectedTargets if it's visible. - let selectedTabIcon = - document.getAnonymousElementByAttribute(gBrowser.selectedTab, - "anonid", - "tab-icon-image"); - if (selectedTabIcon && UITour.isElementVisible(selectedTabIcon)) - expectedTargets.push("selectedTabIcon"); - - ok(Array.isArray(actualData.targets), "data.targets should be an array"); - is(actualData.targets.sort().toString(), expectedTargets.sort().toString(), - "Targets should be as expected"); -} diff --git a/browser/components/uitour/test/browser_UITour_defaultBrowser.js b/browser/components/uitour/test/browser_UITour_defaultBrowser.js deleted file mode 100644 index 5ebf553b0..000000000 --- a/browser/components/uitour/test/browser_UITour_defaultBrowser.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var setDefaultBrowserCalled = false; - -Cc["@mozilla.org/moz/jssubscript-loader;1"] - .getService(Ci.mozIJSSubScriptLoader) - .loadSubScript("chrome://mochikit/content/tests/SimpleTest/MockObjects.js", this); - -function MockShellService() {} -MockShellService.prototype = { - QueryInterface: XPCOMUtils.generateQI([Ci.nsIShellService]), - isDefaultBrowser: function(aStartupCheck, aForAllTypes) { return false; }, - setDefaultBrowser: function(aClaimAllTypes, aForAllUsers) { - setDefaultBrowserCalled = true; - }, - shouldCheckDefaultBrowser: false, - canSetDesktopBackground: false, - BACKGROUND_TILE : 1, - BACKGROUND_STRETCH : 2, - BACKGROUND_CENTER : 3, - BACKGROUND_FILL : 4, - BACKGROUND_FIT : 5, - setDesktopBackground: function(aElement, aPosition) {}, - APPLICATION_MAIL : 0, - APPLICATION_NEWS : 1, - openApplication: function(aApplication) {}, - desktopBackgroundColor: 0, - openApplicationWithURI: function(aApplication, aURI) {}, - defaultFeedReader: 0, -}; - -var mockShellService = new MockObjectRegisterer("@mozilla.org/browser/shell-service;1", - MockShellService); - -// Temporarily disabled, see note at test_setDefaultBrowser. -// mockShellService.register(); - -add_task(setup_UITourTest); - -/* This test is disabled (bug 1180714) since the MockObjectRegisterer - is not actually replacing the original ShellService. -add_UITour_task(function* test_setDefaultBrowser() { - try { - yield gContentAPI.setConfiguration("defaultBrowser"); - ok(setDefaultBrowserCalled, "setDefaultBrowser called"); - } finally { - mockShellService.unregister(); - } -}); -*/ - -add_UITour_task(function* test_isDefaultBrowser() { - let shell = Components.classes["@mozilla.org/browser/shell-service;1"] - .getService(Components.interfaces.nsIShellService); - let isDefault = shell.isDefaultBrowser(false); - let data = yield getConfigurationPromise("appinfo"); - is(isDefault, data.defaultBrowser, "gContentAPI result should match shellService.isDefaultBrowser"); -}); diff --git a/browser/components/uitour/test/browser_UITour_detach_tab.js b/browser/components/uitour/test/browser_UITour_detach_tab.js deleted file mode 100644 index b8edf6dc4..000000000 --- a/browser/components/uitour/test/browser_UITour_detach_tab.js +++ /dev/null @@ -1,94 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Detaching a tab to a new window shouldn't break the menu panel. - */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var gContentDoc; - -function test() { - registerCleanupFunction(function() { - gContentDoc = null; - }); - UITourTest(); -} - -/** - * When tab is changed we're tearing the tour down. So the UITour client has to always be aware of this - * fact and therefore listens to visibilitychange events. - * In particular this scenario happens for detaching the tab (ie. moving it to a new window). - */ -var tests = [ - taskify(function* test_move_tab_to_new_window() { - const myDocIdentifier = "Hello, I'm a unique expando to identify this document."; - - let highlight = document.getElementById("UITourHighlight"); - let windowDestroyedDeferred = Promise.defer(); - let onDOMWindowDestroyed = (aWindow) => { - if (gContentWindow && aWindow == gContentWindow) { - Services.obs.removeObserver(onDOMWindowDestroyed, "dom-window-destroyed", false); - windowDestroyedDeferred.resolve(); - } - }; - - let browserStartupDeferred = Promise.defer(); - Services.obs.addObserver(function onBrowserDelayedStartup(aWindow) { - Services.obs.removeObserver(onBrowserDelayedStartup, "browser-delayed-startup-finished"); - browserStartupDeferred.resolve(aWindow); - }, "browser-delayed-startup-finished", false); - - yield ContentTask.spawn(gBrowser.selectedBrowser, myDocIdentifier, myDocIdentifier => { - let onVisibilityChange = () => { - if (!content.document.hidden) { - let win = Cu.waiveXrays(content); - win.Mozilla.UITour.showHighlight("appMenu"); - } - }; - content.document.addEventListener("visibilitychange", onVisibilityChange); - content.document.myExpando = myDocIdentifier; - }); - gContentAPI.showHighlight("appMenu"); - - yield elementVisiblePromise(highlight); - - gContentWindow = gBrowser.replaceTabWithWindow(gBrowser.selectedTab); - yield browserStartupDeferred.promise; - - // This highlight should be shown thanks to the visibilitychange listener. - let newWindowHighlight = gContentWindow.document.getElementById("UITourHighlight"); - yield elementVisiblePromise(newWindowHighlight); - - let selectedTab = gContentWindow.gBrowser.selectedTab; - yield ContentTask.spawn(selectedTab.linkedBrowser, myDocIdentifier, myDocIdentifier => { - is(content.document.myExpando, myDocIdentifier, "Document should be selected in new window"); - }); - ok(UITour.tourBrowsersByWindow && UITour.tourBrowsersByWindow.has(gContentWindow), "Window should be known"); - ok(UITour.tourBrowsersByWindow.get(gContentWindow).has(selectedTab.linkedBrowser), "Selected browser should be known"); - - // Need this because gContentAPI in e10s land will try to use gTestTab to - // spawn a content task, which doesn't work if the tab is dead, for obvious - // reasons. - gTestTab = gContentWindow.gBrowser.selectedTab; - - let shownPromise = promisePanelShown(gContentWindow); - gContentAPI.showMenu("appMenu"); - yield shownPromise; - - isnot(gContentWindow.PanelUI.panel.state, "closed", "Panel should be open"); - ok(gContentWindow.PanelUI.contents.children.length > 0, "Panel contents should have children"); - gContentAPI.hideHighlight(); - gContentAPI.hideMenu("appMenu"); - gTestTab = null; - - Services.obs.addObserver(onDOMWindowDestroyed, "dom-window-destroyed", false); - gContentWindow.close(); - - yield windowDestroyedDeferred.promise; - }), -]; diff --git a/browser/components/uitour/test/browser_UITour_forceReaderMode.js b/browser/components/uitour/test/browser_UITour_forceReaderMode.js deleted file mode 100644 index 5b5e883c3..000000000 --- a/browser/components/uitour/test/browser_UITour_forceReaderMode.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -add_UITour_task(function*() { - ok(!gBrowser.selectedBrowser.isArticle, "Should not be an article when we start"); - ok(document.getElementById("reader-mode-button").hidden, "Button should be hidden."); - yield gContentAPI.forceShowReaderIcon(); - yield waitForConditionPromise(() => gBrowser.selectedBrowser.isArticle); - ok(gBrowser.selectedBrowser.isArticle, "Should suddenly be an article."); - ok(!document.getElementById("reader-mode-button").hidden, "Button should now be visible."); -}); - diff --git a/browser/components/uitour/test/browser_UITour_heartbeat.js b/browser/components/uitour/test/browser_UITour_heartbeat.js deleted file mode 100644 index 61be1d44b..000000000 --- a/browser/components/uitour/test/browser_UITour_heartbeat.js +++ /dev/null @@ -1,755 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -function getHeartbeatNotification(aId, aChromeWindow = window) { - let notificationBox = aChromeWindow.document.getElementById("high-priority-global-notificationbox"); - // UITour.jsm prefixes the notification box ID with "heartbeat-" to prevent collisions. - return notificationBox.getNotificationWithValue("heartbeat-" + aId); -} - -/** - * Simulate a click on a rating element in the Heartbeat notification. - * - * @param aId - * The id of the notification box. - * @param aScore - * The score related to the rating element we want to click on. - */ -function simulateVote(aId, aScore) { - let notification = getHeartbeatNotification(aId); - - let ratingContainer = notification.childNodes[0]; - ok(ratingContainer, "The notification has a valid rating container."); - - let ratingElement = ratingContainer.getElementsByAttribute("data-score", aScore); - ok(ratingElement[0], "The rating container contains the requested rating element."); - - ratingElement[0].click(); -} - -/** - * Simulate a click on the learn-more link. - * - * @param aId - * The id of the notification box. - */ -function clickLearnMore(aId) { - let notification = getHeartbeatNotification(aId); - - let learnMoreLabel = notification.childNodes[2]; - ok(learnMoreLabel, "The notification has a valid learn more label."); - - learnMoreLabel.click(); -} - -/** - * Remove the notification box. - * - * @param aId - * The id of the notification box to remove. - * @param [aChromeWindow=window] - * The chrome window the notification box is in. - */ -function cleanUpNotification(aId, aChromeWindow = window) { - let notification = getHeartbeatNotification(aId, aChromeWindow); - notification.close(); -} - -/** - * Check telemetry payload for proper format and expected content. - * - * @param aPayload - * The Telemetry payload to verify - * @param aFlowId - * Expected value of the flowId field. - * @param aExpectedFields - * Array of expected fields. No other fields are allowed. - */ -function checkTelemetry(aPayload, aFlowId, aExpectedFields) { - // Basic payload format - is(aPayload.version, 1, "Telemetry ping must have heartbeat version=1"); - is(aPayload.flowId, aFlowId, "Flow ID in the Telemetry ping must match"); - - // Check for superfluous fields - let extraKeys = new Set(Object.keys(aPayload)); - extraKeys.delete("version"); - extraKeys.delete("flowId"); - - // Check for expected fields - for (let field of aExpectedFields) { - ok(field in aPayload, "The payload should have the field '" + field + "'"); - if (field.endsWith("TS")) { - let ts = aPayload[field]; - ok(Number.isInteger(ts) && ts > 0, "Timestamp '" + field + "' must be a natural number"); - } - extraKeys.delete(field); - } - - is(extraKeys.size, 0, "No unexpected fields in the Telemetry payload"); -} - -/** - * Waits for an UITour notification dispatched through |UITour.notify|. This should be - * done with |gContentAPI.observe|. Unfortunately, in e10s, |gContentAPI.observe| doesn't - * allow for multiple calls to the same callback, allowing to catch just the first - * notification. - * - * @param aEventName - * The notification name to wait for. - * @return {Promise} Resolved with the data that comes with the event. - */ -function promiseWaitHeartbeatNotification(aEventName) { - return ContentTask.spawn(gTestTab.linkedBrowser, { aEventName }, - function({ aEventName }) { - return new Promise(resolve => { - addEventListener("mozUITourNotification", function listener(event) { - if (event.detail.event !== aEventName) { - return; - } - removeEventListener("mozUITourNotification", listener, false); - resolve(event.detail.params); - }, false); - }); - }); -} - -/** - * Waits for UITour notifications dispatched through |UITour.notify|. This works like - * |promiseWaitHeartbeatNotification|, but waits for all the passed notifications to - * be received before resolving. If it receives an unaccounted notification, it rejects. - * - * @param events - * An array of expected notification names to wait for. - * @return {Promise} Resolved with the data that comes with the event. Rejects with the - * name of an undesired notification if received. - */ -function promiseWaitExpectedNotifications(events) { - return ContentTask.spawn(gTestTab.linkedBrowser, { events }, - function({ events }) { - let stillToReceive = events; - return new Promise((res, rej) => { - addEventListener("mozUITourNotification", function listener(event) { - if (stillToReceive.includes(event.detail.event)) { - // Filter out the received event. - stillToReceive = stillToReceive.filter(x => x !== event.detail.event); - } else { - removeEventListener("mozUITourNotification", listener, false); - rej(event.detail.event); - } - // We still need to catch some notifications. Don't do anything. - if (stillToReceive.length > 0) { - return; - } - // We don't need to listen for other notifications. Resolve the promise. - removeEventListener("mozUITourNotification", listener, false); - res(); - }, false); - }); - }); -} - -function validateTimestamp(eventName, timestamp) { - info("'" + eventName + "' notification received (timestamp " + timestamp.toString() + ")."); - ok(Number.isFinite(timestamp), "Timestamp must be a number."); -} - -add_task(function* test_setup() { - yield setup_UITourTest(); - requestLongerTimeout(2); - registerCleanupFunction(() => { - Services.prefs.clearUserPref("browser.uitour.surveyDuration"); - }); -}); - -/** - * Check that the "stars" heartbeat UI correctly shows and closes. - */ -add_UITour_task(function* test_heartbeat_stars_show() { - let flowId = "ui-ratefirefox-" + Math.random(); - let engagementURL = "http://example.com"; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications( - ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Close the heartbeat notification. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - cleanUpNotification(flowId); - - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received"); - checkTelemetry(data, flowId, ["offeredTS", "closedTS"]); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Check that the heartbeat UI correctly takes optional icon URL. - */ -add_UITour_task(function* test_heartbeat_take_optional_icon_URL() { - let flowId = "ui-ratefirefox-" + Math.random(); - let engagementURL = "http://example.com"; - let iconURL = "chrome://branding/content/icon48.png"; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications( - ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, { - iconURL: iconURL - }); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Check the icon URL - let notification = getHeartbeatNotification(flowId); - is(notification.image, iconURL, "The optional icon URL is not taken correctly"); - - // Close the heartbeat notification. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - cleanUpNotification(flowId); - - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received"); - checkTelemetry(data, flowId, ["offeredTS", "closedTS"]); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the heartbeat UI correctly works with null engagement URL. - */ -add_UITour_task(function* test_heartbeat_null_engagementURL() { - let flowId = "ui-ratefirefox-" + Math.random(); - let originalTabCount = gBrowser.tabs.length; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // The UI was just shown. We can simulate a click on a rating element (i.e., "star"). - simulateVote(flowId, 2); - data = yield votedPromise; - validateTimestamp('Heartbeat:Voted', data.timestamp); - - // Validate the closing timestamp. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened."); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]); - is(data.score, 2, "Checking Telemetry payload.score"); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the heartbeat UI correctly works with an invalid, but non null, engagement URL. - */ -add_UITour_task(function* test_heartbeat_invalid_engagement_URL() { - let flowId = "ui-ratefirefox-" + Math.random(); - let originalTabCount = gBrowser.tabs.length; - let invalidEngagementURL = "invalidEngagement"; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, invalidEngagementURL); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // The UI was just shown. We can simulate a click on a rating element (i.e., "star"). - simulateVote(flowId, 2); - data = yield votedPromise; - validateTimestamp('Heartbeat:Voted', data.timestamp); - - // Validate the closing timestamp. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened."); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]); - is(data.score, 2, "Checking Telemetry payload.score"); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the score is correctly reported. - */ -add_UITour_task(function* test_heartbeat_stars_vote() { - const expectedScore = 4; - let originalTabCount = gBrowser.tabs.length; - let flowId = "ui-ratefirefox-" + Math.random(); - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // The UI was just shown. We can simulate a click on a rating element (i.e., "star"). - simulateVote(flowId, expectedScore); - data = yield votedPromise; - validateTimestamp('Heartbeat:Voted', data.timestamp); - is(data.score, expectedScore, "Should report a score of " + expectedScore); - - // Validate the closing timestamp and vote. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened."); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]); - is(data.score, expectedScore, "Checking Telemetry payload.score"); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the engagement page is correctly opened when voting. - */ -add_UITour_task(function* test_heartbeat_engagement_tab() { - let engagementURL = "http://example.com"; - let flowId = "ui-ratefirefox-" + Math.random(); - let originalTabCount = gBrowser.tabs.length; - const expectedTabCount = originalTabCount + 1; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL); - - // Validate the returned timestamp. - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // The UI was just shown. We can simulate a click on a rating element (i.e., "star"). - simulateVote(flowId, 1); - data = yield votedPromise; - validateTimestamp('Heartbeat:Voted', data.timestamp); - - // Validate the closing timestamp, vote and make sure the engagement page was opened. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab."); - gBrowser.removeCurrentTab(); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]); - is(data.score, 1, "Checking Telemetry payload.score"); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the engagement button opens the engagement URL. - */ -add_UITour_task(function* test_heartbeat_engagement_button() { - let engagementURL = "http://example.com"; - let flowId = "ui-engagewithfirefox-" + Math.random(); - let originalTabCount = gBrowser.tabs.length; - const expectedTabCount = originalTabCount + 1; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:Engaged", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, null, null, { - engagementButtonLabel: "Engage Me", - }); - - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the Engaged, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let engagedPromise = promiseWaitHeartbeatNotification("Heartbeat:Engaged"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // Simulate user engagement. - let notification = getHeartbeatNotification(flowId); - is(notification.querySelectorAll(".star-x").length, 0, "No stars should be present"); - // The UI was just shown. We can simulate a click on the engagement button. - let engagementButton = notification.querySelector(".notification-button"); - is(engagementButton.label, "Engage Me", "Check engagement button text"); - engagementButton.doCommand(); - - data = yield engagedPromise; - validateTimestamp('Heartbeat:Engaged', data.timestamp); - - // Validate the closing timestamp, vote and make sure the engagement page was opened. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab."); - gBrowser.removeCurrentTab(); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "engagedTS", "closedTS"]); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Test that the learn more link is displayed and that the page is correctly opened when - * clicking on it. - */ -add_UITour_task(function* test_heartbeat_learnmore() { - let dummyURL = "http://example.com"; - let flowId = "ui-ratefirefox-" + Math.random(); - let originalTabCount = gBrowser.tabs.length; - const expectedTabCount = originalTabCount + 1; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:LearnMore", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, dummyURL, - "What is this?", dummyURL); - - let data = yield shownPromise; - validateTimestamp('Heartbeat:Offered', data.timestamp); - - // Wait an the LearnMore, Closed and Telemetry Sent events. They are fired together, so - // wait for them here. - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let learnMorePromise = promiseWaitHeartbeatNotification("Heartbeat:LearnMore"); - let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - // The UI was just shown. Simulate a click on the learn more link. - clickLearnMore(flowId); - - data = yield learnMorePromise; - validateTimestamp('Heartbeat:LearnMore', data.timestamp); - cleanUpNotification(flowId); - - // The notification was closed. - data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - is(gBrowser.tabs.length, expectedTabCount, "Learn more URL should open in a new tab."); - gBrowser.removeCurrentTab(); - - // Validate the data we send out. - data = yield pingSentPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "learnMoreTS", "closedTS"]); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -add_UITour_task(function* test_invalidEngagementButtonLabel() { - let engagementURL = "http://example.com"; - let flowId = "invalidEngagementButtonLabel-" + Math.random(); - - let eventPromise = promisePageEvent(); - - gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, - null, null, { - engagementButtonLabel: 42, - }); - - yield eventPromise; - ok(!isTourBrowser(gBrowser.selectedBrowser), - "Invalid engagementButtonLabel should prevent init"); - -}) - -add_UITour_task(function* test_privateWindowsOnly_noneOpen() { - let engagementURL = "http://example.com"; - let flowId = "privateWindowsOnly_noneOpen-" + Math.random(); - - let eventPromise = promisePageEvent(); - - gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, - null, null, { - engagementButtonLabel: "Yes!", - privateWindowsOnly: true, - }); - - yield eventPromise; - ok(!isTourBrowser(gBrowser.selectedBrowser), - "If there are no private windows opened, tour init should be prevented"); -}) - -add_UITour_task(function* test_privateWindowsOnly_notMostRecent() { - let engagementURL = "http://example.com"; - let flowId = "notMostRecent-" + Math.random(); - - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - let mostRecentWin = yield BrowserTestUtils.openNewBrowserWindow(); - - let eventPromise = promisePageEvent(); - - gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, - null, null, { - engagementButtonLabel: "Yes!", - privateWindowsOnly: true, - }); - - yield eventPromise; - is(getHeartbeatNotification(flowId, window), null, - "Heartbeat shouldn't appear in the default window"); - is(!!getHeartbeatNotification(flowId, privateWin), true, - "Heartbeat should appear in the most recent private window"); - is(getHeartbeatNotification(flowId, mostRecentWin), null, - "Heartbeat shouldn't appear in the most recent non-private window"); - - yield BrowserTestUtils.closeWindow(mostRecentWin); - yield BrowserTestUtils.closeWindow(privateWin); -}) - -add_UITour_task(function* test_privateWindowsOnly() { - let engagementURL = "http://example.com"; - let learnMoreURL = "http://example.org/learnmore/"; - let flowId = "ui-privateWindowsOnly-" + Math.random(); - - let privateWin = yield BrowserTestUtils.openNewBrowserWindow({ private: true }); - - yield new Promise((resolve) => { - gContentAPI.observe(function(aEventName, aData) { - info(aEventName + " notification received: " + JSON.stringify(aData, null, 2)); - ok(false, "No heartbeat notifications should arrive for privateWindowsOnly"); - }, resolve); - }); - - gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, - "Learn More", learnMoreURL, { - engagementButtonLabel: "Yes!", - privateWindowsOnly: true, - }); - - yield promisePageEvent(); - - ok(isTourBrowser(gBrowser.selectedBrowser), "UITour should have been init for the browser"); - - let notification = getHeartbeatNotification(flowId, privateWin); - - is(notification.querySelectorAll(".star-x").length, 0, "No stars should be present"); - - info("Test the learn more link."); - let learnMoreLink = notification.querySelector(".text-link"); - is(learnMoreLink.value, "Learn More", "Check learn more label"); - let learnMoreTabPromise = BrowserTestUtils.waitForNewTab(privateWin.gBrowser, null); - learnMoreLink.click(); - let learnMoreTab = yield learnMoreTabPromise; - is(learnMoreTab.linkedBrowser.currentURI.host, "example.org", "Check learn more site opened"); - ok(PrivateBrowsingUtils.isBrowserPrivate(learnMoreTab.linkedBrowser), "Ensure the learn more tab is private"); - yield BrowserTestUtils.removeTab(learnMoreTab); - - info("Test the engagement button's new tab."); - let engagementButton = notification.querySelector(".notification-button"); - is(engagementButton.label, "Yes!", "Check engagement button text"); - let engagementTabPromise = BrowserTestUtils.waitForNewTab(privateWin.gBrowser, null); - engagementButton.doCommand(); - let engagementTab = yield engagementTabPromise; - is(engagementTab.linkedBrowser.currentURI.host, "example.com", "Check enagement site opened"); - ok(PrivateBrowsingUtils.isBrowserPrivate(engagementTab.linkedBrowser), "Ensure the engagement tab is private"); - yield BrowserTestUtils.removeTab(engagementTab); - - yield BrowserTestUtils.closeWindow(privateWin); -}) - -/** - * Test that the survey closes itself after a while and submits Telemetry - */ -add_UITour_task(function* test_telemetry_surveyExpired() { - let flowId = "survey-expired-" + Math.random(); - let engagementURL = "http://example.com"; - let surveyDuration = 1; // 1 second (pref is in seconds) - Services.prefs.setIntPref("browser.uitour.surveyDuration", surveyDuration); - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications(["Heartbeat:NotificationOffered", - "Heartbeat:NotificationClosed", "Heartbeat:SurveyExpired", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL); - - let expiredPromise = promiseWaitHeartbeatNotification("Heartbeat:SurveyExpired"); - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let pingPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - - yield Promise.all([shownPromise, expiredPromise, closedPromise]); - // Validate the ping data. - let data = yield pingPromise; - checkTelemetry(data, flowId, ["offeredTS", "expiredTS", "closedTS"]); - - Services.prefs.clearUserPref("browser.uitour.surveyDuration"); - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) - -/** - * Check that certain whitelisted experiment parameters get reflected in the - * Telemetry ping - */ -add_UITour_task(function* test_telemetry_params() { - let flowId = "telemetry-params-" + Math.random(); - let engagementURL = "http://example.com"; - let extraParams = { - "surveyId": "foo", - "surveyVersion": 1.5, - "testing": true, - "notWhitelisted": 123, - }; - let expectedFields = ["surveyId", "surveyVersion", "testing"]; - - // We need to call |gContentAPI.observe| at least once to set a valid |notificationListener| - // in UITour-lib.js, otherwise no message will get propagated. - gContentAPI.observe(() => {}); - - let receivedExpectedPromise = promiseWaitExpectedNotifications( - ["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]); - - // Show the Heartbeat notification and wait for it to be displayed. - let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered"); - gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", - flowId, engagementURL, null, null, extraParams); - yield shownPromise; - - let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed"); - let pingPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent"); - cleanUpNotification(flowId); - - // The notification was closed. - let data = yield closedPromise; - validateTimestamp('Heartbeat:NotificationClosed', data.timestamp); - - // Validate the data we send out. - data = yield pingPromise; - info("'Heartbeat:TelemetrySent' notification received."); - checkTelemetry(data, flowId, ["offeredTS", "closedTS"].concat(expectedFields)); - for (let param of expectedFields) { - is(data[param], extraParams[param], - "Whitelisted experiment configs should be copied into Telemetry pings"); - } - - // This rejects whenever an unexpected notification is received. - yield receivedExpectedPromise; -}) diff --git a/browser/components/uitour/test/browser_UITour_modalDialog.js b/browser/components/uitour/test/browser_UITour_modalDialog.js deleted file mode 100644 index 1890739c4..000000000 --- a/browser/components/uitour/test/browser_UITour_modalDialog.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var handleDialog; - -// Modified from toolkit/components/passwordmgr/test/prompt_common.js -var didDialog; - -var timer; // keep in outer scope so it's not GC'd before firing -function startCallbackTimer() { - didDialog = false; - - // Delay before the callback twiddles the prompt. - const dialogDelay = 10; - - // Use a timer to invoke a callback to twiddle the authentication dialog - timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - timer.init(observer, dialogDelay, Ci.nsITimer.TYPE_ONE_SHOT); -} - - -var observer = SpecialPowers.wrapCallbackObject({ - QueryInterface : function (iid) { - const interfaces = [Ci.nsIObserver, - Ci.nsISupports, Ci.nsISupportsWeakReference]; - - if (!interfaces.some( function(v) { return iid.equals(v) } )) - throw SpecialPowers.Components.results.NS_ERROR_NO_INTERFACE; - return this; - }, - - observe : function (subject, topic, data) { - var doc = getDialogDoc(); - if (doc) - handleDialog(doc); - else - startCallbackTimer(); // try again in a bit - } -}); - -function getDialogDoc() { - // Find the <browser> which contains notifyWindow, by looking - // through all the open windows and all the <browsers> in each. - var wm = Cc["@mozilla.org/appshell/window-mediator;1"]. - getService(Ci.nsIWindowMediator); - // var enumerator = wm.getEnumerator("navigator:browser"); - var enumerator = wm.getXULWindowEnumerator(null); - - while (enumerator.hasMoreElements()) { - var win = enumerator.getNext(); - var windowDocShell = win.QueryInterface(Ci.nsIXULWindow).docShell; - - var containedDocShells = windowDocShell.getDocShellEnumerator( - Ci.nsIDocShellTreeItem.typeChrome, - Ci.nsIDocShell.ENUMERATE_FORWARDS); - while (containedDocShells.hasMoreElements()) { - // Get the corresponding document for this docshell - var childDocShell = containedDocShells.getNext(); - // We don't want it if it's not done loading. - if (childDocShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE) - continue; - var childDoc = childDocShell.QueryInterface(Ci.nsIDocShell) - .contentViewer - .DOMDocument; - - // ok(true, "Got window: " + childDoc.location.href); - if (childDoc.location.href == "chrome://global/content/commonDialog.xul") - return childDoc; - } - } - - return null; -} - -function test() { - UITourTest(); -} - - -var tests = [ - taskify(function* test_modal_dialog_while_opening_tooltip() { - let panelShown; - let popup; - - handleDialog = (doc) => { - popup = document.getElementById("UITourTooltip"); - gContentAPI.showInfo("appMenu", "test title", "test text"); - doc.defaultView.setTimeout(function() { - is(popup.state, "closed", "Popup shouldn't be shown while dialog is up"); - panelShown = promisePanelElementShown(window, popup); - let dialog = doc.getElementById("commonDialog"); - dialog.acceptDialog(); - }, 1000); - }; - startCallbackTimer(); - executeSoon(() => alert("test")); - yield waitForConditionPromise(() => panelShown, "Timed out waiting for panel promise to be assigned", 100); - yield panelShown; - - yield hideInfoPromise(); - }) -]; diff --git a/browser/components/uitour/test/browser_UITour_observe.js b/browser/components/uitour/test/browser_UITour_observe.js deleted file mode 100644 index b4b435659..000000000 --- a/browser/components/uitour/test/browser_UITour_observe.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -function test() { - requestLongerTimeout(2); - UITourTest(); -} - -var tests = [ - function test_no_params(done) { - function listener(event, params) { - is(event, "test-event-1", "Correct event name"); - is(params, null, "No param object"); - gContentAPI.observe(null); - done(); - } - - gContentAPI.observe(listener, () => { - UITour.notify("test-event-1"); - }); - }, - function test_param_string(done) { - function listener(event, params) { - is(event, "test-event-2", "Correct event name"); - is(params, "a param", "Correct param string"); - gContentAPI.observe(null); - done(); - } - - gContentAPI.observe(listener, () => { - UITour.notify("test-event-2", "a param"); - }); - }, - function test_param_object(done) { - function listener(event, params) { - is(event, "test-event-3", "Correct event name"); - is(JSON.stringify(params), JSON.stringify({key: "something"}), "Correct param object"); - gContentAPI.observe(null); - done(); - } - - gContentAPI.observe(listener, () => { - UITour.notify("test-event-3", {key: "something"}); - }); - }, - function test_background_tab(done) { - function listener(event, params) { - is(event, "test-event-background-1", "Correct event name"); - is(params, null, "No param object"); - gContentAPI.observe(null); - gBrowser.removeCurrentTab(); - done(); - } - - gContentAPI.observe(listener, () => { - gBrowser.selectedTab = gBrowser.addTab("about:blank"); - isnot(gBrowser.selectedTab, gTestTab, "Make sure the selected tab changed"); - - UITour.notify("test-event-background-1"); - }); - }, - // Make sure the tab isn't torn down when switching back to the tour one. - function test_background_then_foreground_tab(done) { - let blankTab = null; - function listener(event, params) { - is(event, "test-event-4", "Correct event name"); - is(params, null, "No param object"); - gContentAPI.observe(null); - gBrowser.removeTab(blankTab); - done(); - } - - gContentAPI.observe(listener, () => { - blankTab = gBrowser.selectedTab = gBrowser.addTab("about:blank"); - isnot(gBrowser.selectedTab, gTestTab, "Make sure the selected tab changed"); - gBrowser.selectedTab = gTestTab; - is(gBrowser.selectedTab, gTestTab, "Switch back to the test tab"); - - UITour.notify("test-event-4"); - }); - }, -]; diff --git a/browser/components/uitour/test/browser_UITour_panel_close_annotation.js b/browser/components/uitour/test/browser_UITour_panel_close_annotation.js deleted file mode 100644 index cff446573..000000000 --- a/browser/components/uitour/test/browser_UITour_panel_close_annotation.js +++ /dev/null @@ -1,153 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -/** - * Tests that annotations disappear when their target is hidden. - */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var highlight = document.getElementById("UITourHighlight"); -var tooltip = document.getElementById("UITourTooltip"); - -function test() { - registerCleanupFunction(() => { - // Close the find bar in case it's open in the remaining tab - gBrowser.getFindBar(gBrowser.selectedTab).close(); - }); - UITourTest(); -} - -var tests = [ - function test_highlight_move_outside_panel(done) { - gContentAPI.showInfo("urlbar", "test title", "test text"); - gContentAPI.showHighlight("customize"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Move the highlight outside which should close the app menu. - gContentAPI.showHighlight("appMenu"); - waitForPopupAtAnchor(highlight.parentElement, document.getElementById("PanelUI-button"), () => { - isnot(PanelUI.panel.state, "open", - "Panel should have closed after the highlight moved elsewhere."); - ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open"); - done(); - }, "Highlight should move to the appMenu button and still be visible"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_highlight_panel_hideMenu(done) { - gContentAPI.showHighlight("customize"); - gContentAPI.showInfo("search", "test title", "test text"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Close the app menu and make sure the highlight also disappeared. - gContentAPI.hideMenu("appMenu"); - waitForElementToBeHidden(highlight, function checkPanelIsClosed() { - isnot(PanelUI.panel.state, "open", - "Panel still should have closed"); - ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open"); - done(); - }, "Highlight should have disappeared when panel closed"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_highlight_panel_click_find(done) { - gContentAPI.showHighlight("help"); - gContentAPI.showInfo("searchIcon", "test title", "test text"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Click the find button which should close the panel. - let findButton = document.getElementById("find-button"); - EventUtils.synthesizeMouseAtCenter(findButton, {}); - waitForElementToBeHidden(highlight, function checkPanelIsClosed() { - isnot(PanelUI.panel.state, "open", - "Panel should have closed when the find bar opened"); - ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open"); - done(); - }, "Highlight should have disappeared when panel closed"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_highlight_info_panel_click_find(done) { - gContentAPI.showHighlight("help"); - gContentAPI.showInfo("customize", "customize me!", "awesome!"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Click the find button which should close the panel. - let findButton = document.getElementById("find-button"); - EventUtils.synthesizeMouseAtCenter(findButton, {}); - waitForElementToBeHidden(highlight, function checkPanelIsClosed() { - isnot(PanelUI.panel.state, "open", - "Panel should have closed when the find bar opened"); - waitForElementToBeHidden(tooltip, function checkTooltipIsClosed() { - isnot(tooltip.state, "open", "The info panel should have closed too"); - done(); - }, "Tooltip should hide with the menu"); - }, "Highlight should have disappeared when panel closed"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_highlight_panel_open_subview(done) { - gContentAPI.showHighlight("customize"); - gContentAPI.showInfo("backForward", "test title", "test text"); - waitForElementToBeVisible(highlight, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Click the help button which should open the subview in the panel menu. - let helpButton = document.getElementById("PanelUI-help"); - EventUtils.synthesizeMouseAtCenter(helpButton, {}); - waitForElementToBeHidden(highlight, function highlightHidden() { - is(PanelUI.panel.state, "open", - "Panel should have stayed open when the subview opened"); - ok(tooltip.state == "showing" || tooltip.state == "open", "The info panel should have remained open"); - PanelUI.hide(); - done(); - }, "Highlight should have disappeared when the subview opened"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_info_panel_open_subview(done) { - gContentAPI.showHighlight("urlbar"); - gContentAPI.showInfo("customize", "customize me!", "Open a subview"); - waitForElementToBeVisible(tooltip, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Click the help button which should open the subview in the panel menu. - let helpButton = document.getElementById("PanelUI-help"); - EventUtils.synthesizeMouseAtCenter(helpButton, {}); - waitForElementToBeHidden(tooltip, function tooltipHidden() { - is(PanelUI.panel.state, "open", - "Panel should have stayed open when the subview opened"); - is(highlight.parentElement.state, "open", "The highlight should have remained open"); - PanelUI.hide(); - done(); - }, "Tooltip should have disappeared when the subview opened"); - }, "Highlight should be shown after showHighlight() for fixed panel items"); - }, - - function test_info_move_outside_panel(done) { - gContentAPI.showInfo("addons", "test title", "test text"); - gContentAPI.showHighlight("urlbar"); - let addonsButton = document.getElementById("add-ons-button"); - waitForPopupAtAnchor(tooltip, addonsButton, function checkPanelIsOpen() { - isnot(PanelUI.panel.state, "closed", "Panel should have opened"); - - // Move the info panel outside which should close the app menu. - gContentAPI.showInfo("appMenu", "Cool menu button", "It's three lines"); - waitForPopupAtAnchor(tooltip, document.getElementById("PanelUI-button"), () => { - isnot(PanelUI.panel.state, "open", - "Menu should have closed after the highlight moved elsewhere."); - is(highlight.parentElement.state, "open", "The highlight should have remained visible"); - done(); - }, "Tooltip should move to the appMenu button and still be visible"); - }, "Tooltip should be shown after showInfo() for a panel item"); - }, - -]; diff --git a/browser/components/uitour/test/browser_UITour_pocket.js b/browser/components/uitour/test/browser_UITour_pocket.js deleted file mode 100644 index 29548a475..000000000 --- a/browser/components/uitour/test/browser_UITour_pocket.js +++ /dev/null @@ -1,82 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; -var button; - -function test() { - UITourTest(); -} - -var tests = [ - taskify(function* test_menu_show_navbar() { - is(button.open, false, "Menu should initially be closed"); - gContentAPI.showMenu("pocket"); - - // The panel gets created dynamically. - let widgetPanel = null; - yield waitForConditionPromise(() => { - widgetPanel = document.getElementById("customizationui-widget-panel"); - return widgetPanel && widgetPanel.state == "open"; - }, "Menu should be visible after showMenu()"); - - ok(button.open, "Button should know its view is open"); - ok(!widgetPanel.hasAttribute("noautohide"), "@noautohide shouldn't be on the pocket panel"); - ok(button.hasAttribute("open"), "Pocket button should know that the menu is open"); - - widgetPanel.hidePopup(); - checkPanelIsHidden(widgetPanel); - }), - taskify(function* test_menu_show_appMenu() { - CustomizableUI.addWidgetToArea("pocket-button", CustomizableUI.AREA_PANEL); - - is(PanelUI.multiView.hasAttribute("panelopen"), false, "Multiview should initially be closed"); - gContentAPI.showMenu("pocket"); - - yield waitForConditionPromise(() => { - return PanelUI.panel.state == "open"; - }, "Menu should be visible after showMenu()"); - - ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide shouldn't be on the pocket panel"); - ok(PanelUI.multiView.showingSubView, "Subview should be open"); - ok(PanelUI.multiView.hasAttribute("panelopen"), "Multiview should know it's open"); - - PanelUI.showMainView(); - PanelUI.panel.hidePopup(); - checkPanelIsHidden(PanelUI.panel); - }), -]; - -// End tests - -function checkPanelIsHidden(aPanel) { - if (aPanel.parentElement) { - is_hidden(aPanel); - } else { - ok(!aPanel.parentElement, "Widget panel should have been removed"); - } - is(button.hasAttribute("open"), false, "Pocket button should know that the panel is closed"); -} - -if (Services.prefs.getBoolPref("extensions.pocket.enabled")) { - let placement = CustomizableUI.getPlacementOfWidget("pocket-button"); - - // Add the button to the nav-bar by default. - if (!placement || placement.area != CustomizableUI.AREA_NAVBAR) { - CustomizableUI.addWidgetToArea("pocket-button", CustomizableUI.AREA_NAVBAR); - } - registerCleanupFunction(() => { - CustomizableUI.reset(); - }); - - let widgetGroupWrapper = CustomizableUI.getWidget("pocket-button"); - button = widgetGroupWrapper.forWindow(window).node; - ok(button, "Got button node"); -} else { - todo(false, "Pocket is disabled so skip its UITour tests"); - tests = []; -} diff --git a/browser/components/uitour/test/browser_UITour_registerPageID.js b/browser/components/uitour/test/browser_UITour_registerPageID.js deleted file mode 100644 index 369abb1ed..000000000 --- a/browser/components/uitour/test/browser_UITour_registerPageID.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -Components.utils.import("resource://gre/modules/UITelemetry.jsm"); -Components.utils.import("resource:///modules/BrowserUITelemetry.jsm"); - -add_task(function* setup_telemetry() { - UITelemetry._enabled = true; - - registerCleanupFunction(function() { - Services.prefs.clearUserPref("browser.uitour.seenPageIDs"); - resetSeenPageIDsLazyGetter(); - UITelemetry._enabled = undefined; - BrowserUITelemetry.setBucket(null); - delete window.UITelemetry; - delete window.BrowserUITelemetry; - }); -}); - -add_task(setup_UITourTest); - -function resetSeenPageIDsLazyGetter() { - delete UITour.seenPageIDs; - // This should be kept in sync with how UITour.init() sets this. - Object.defineProperty(UITour, "seenPageIDs", { - get: UITour.restoreSeenPageIDs.bind(UITour), - configurable: true, - }); -} - -function checkExpectedSeenPageIDs(expected) { - is(UITour.seenPageIDs.size, expected.length, "Should be " + expected.length + " total seen page IDs"); - - for (let id of expected) - ok(UITour.seenPageIDs.has(id), "Should have seen '" + id + "' page ID"); - - let prefData = Services.prefs.getCharPref("browser.uitour.seenPageIDs"); - prefData = new Map(JSON.parse(prefData)); - - is(prefData.size, expected.length, "Should be " + expected.length + " total seen page IDs persisted"); - - for (let id of expected) - ok(prefData.has(id), "Should have seen '" + id + "' page ID persisted"); -} - - -add_UITour_task(function test_seenPageIDs_restore() { - info("Setting up seenPageIDs to be restored from pref"); - let data = JSON.stringify([ - ["savedID1", { lastSeen: Date.now() }], - ["savedID2", { lastSeen: Date.now() }], - // 9 weeks ago, should auto expire. - ["savedID3", { lastSeen: Date.now() - 9 * 7 * 24 * 60 * 60 * 1000 }], - ]); - Services.prefs.setCharPref("browser.uitour.seenPageIDs", - data); - - resetSeenPageIDsLazyGetter(); - checkExpectedSeenPageIDs(["savedID1", "savedID2"]); -}); - -add_UITour_task(function* test_seenPageIDs_set_1() { - yield gContentAPI.registerPageID("testpage1"); - - yield waitForConditionPromise(() => UITour.seenPageIDs.size == 3, "Waiting for page to be registered."); - - checkExpectedSeenPageIDs(["savedID1", "savedID2", "testpage1"]); - - const PREFIX = BrowserUITelemetry.BUCKET_PREFIX; - const SEP = BrowserUITelemetry.BUCKET_SEPARATOR; - - let bucket = PREFIX + "UITour" + SEP + "testpage1"; - is(BrowserUITelemetry.currentBucket, bucket, "Bucket should have correct name"); - - gBrowser.selectedTab = gBrowser.addTab("about:blank"); - bucket = PREFIX + "UITour" + SEP + "testpage1" + SEP + "inactive" + SEP + "1m"; - is(BrowserUITelemetry.currentBucket, bucket, - "After switching tabs, bucket should be expiring"); - - gBrowser.removeTab(gBrowser.selectedTab); - gBrowser.selectedTab = gTestTab; - BrowserUITelemetry.setBucket(null); -}); - -add_UITour_task(function* test_seenPageIDs_set_2() { - yield gContentAPI.registerPageID("testpage2"); - - yield waitForConditionPromise(() => UITour.seenPageIDs.size == 4, "Waiting for page to be registered."); - - checkExpectedSeenPageIDs(["savedID1", "savedID2", "testpage1", "testpage2"]); - - const PREFIX = BrowserUITelemetry.BUCKET_PREFIX; - const SEP = BrowserUITelemetry.BUCKET_SEPARATOR; - - let bucket = PREFIX + "UITour" + SEP + "testpage2"; - is(BrowserUITelemetry.currentBucket, bucket, "Bucket should have correct name"); - - gBrowser.removeTab(gTestTab); - gTestTab = null; - bucket = PREFIX + "UITour" + SEP + "testpage2" + SEP + "closed" + SEP + "1m"; - is(BrowserUITelemetry.currentBucket, bucket, - "After closing tab, bucket should be expiring"); - - BrowserUITelemetry.setBucket(null); -}); diff --git a/browser/components/uitour/test/browser_UITour_resetProfile.js b/browser/components/uitour/test/browser_UITour_resetProfile.js deleted file mode 100644 index c91d0a4f2..000000000 --- a/browser/components/uitour/test/browser_UITour_resetProfile.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -// Test that a reset profile dialog appears when "resetFirefox" event is triggered -add_UITour_task(function* test_resetFirefox() { - let canReset = yield getConfigurationPromise("canReset"); - ok(!canReset, "Shouldn't be able to reset from mochitest's temporary profile."); - let dialogPromise = new Promise((resolve) => { - let winWatcher = Cc["@mozilla.org/embedcomp/window-watcher;1"]. - getService(Ci.nsIWindowWatcher); - winWatcher.registerNotification(function onOpen(subj, topic, data) { - if (topic == "domwindowopened" && subj instanceof Ci.nsIDOMWindow) { - subj.addEventListener("load", function onLoad() { - subj.removeEventListener("load", onLoad); - if (subj.document.documentURI == - "chrome://global/content/resetProfile.xul") { - winWatcher.unregisterNotification(onOpen); - ok(true, "Observed search manager window open"); - is(subj.opener, window, - "Reset Firefox event opened a reset profile window."); - subj.close(); - resolve(); - } - }); - } - }); - }); - - // make reset possible. - let profileService = Cc["@mozilla.org/toolkit/profile-service;1"]. - getService(Ci.nsIToolkitProfileService); - let currentProfileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); - let profileName = "mochitest-test-profile-temp-" + Date.now(); - let tempProfile = profileService.createProfile(currentProfileDir, profileName); - canReset = yield getConfigurationPromise("canReset"); - ok(canReset, "Should be able to reset from mochitest's temporary profile once it's in the profile manager."); - yield gContentAPI.resetFirefox(); - yield dialogPromise; - tempProfile.remove(false); - canReset = yield getConfigurationPromise("canReset"); - ok(!canReset, "Shouldn't be able to reset from mochitest's temporary profile once removed from the profile manager."); -}); - diff --git a/browser/components/uitour/test/browser_UITour_showNewTab.js b/browser/components/uitour/test/browser_UITour_showNewTab.js deleted file mode 100644 index 2deb08148..000000000 --- a/browser/components/uitour/test/browser_UITour_showNewTab.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -// Test that we can switch to about:newtab -add_UITour_task(function* test_aboutNewTab() { - let newTabLoaded = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser, false, "about:newtab"); - info("Showing about:newtab"); - yield gContentAPI.showNewTab(); - info("Waiting for about:newtab to load"); - yield newTabLoaded; - is(gBrowser.selectedBrowser.currentURI.spec, "about:newtab", "Loaded about:newtab"); -}); diff --git a/browser/components/uitour/test/browser_UITour_sync.js b/browser/components/uitour/test/browser_UITour_sync.js deleted file mode 100644 index 14ac0c1f6..000000000 --- a/browser/components/uitour/test/browser_UITour_sync.js +++ /dev/null @@ -1,105 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -registerCleanupFunction(function() { - Services.prefs.clearUserPref("services.sync.username"); -}); - -add_task(setup_UITourTest); - -add_UITour_task(function* test_checkSyncSetup_disabled() { - let result = yield getConfigurationPromise("sync"); - is(result.setup, false, "Sync shouldn't be setup by default"); -}); - -add_UITour_task(function* test_checkSyncSetup_enabled() { - Services.prefs.setCharPref("services.sync.username", "uitour@tests.mozilla.org"); - let result = yield getConfigurationPromise("sync"); - is(result.setup, true, "Sync should be setup"); -}); - -add_UITour_task(function* test_checkSyncCounts() { - Services.prefs.setIntPref("services.sync.clients.devices.desktop", 4); - Services.prefs.setIntPref("services.sync.clients.devices.mobile", 5); - Services.prefs.setIntPref("services.sync.numClients", 9); - let result = yield getConfigurationPromise("sync"); - is(result.mobileDevices, 5, "mobileDevices should be set"); - is(result.desktopDevices, 4, "desktopDevices should be set"); - is(result.totalDevices, 9, "totalDevices should be set"); - - Services.prefs.clearUserPref("services.sync.clients.devices.desktop"); - result = yield getConfigurationPromise("sync"); - is(result.mobileDevices, 5, "mobileDevices should be set"); - is(result.desktopDevices, 0, "desktopDevices should be 0"); - is(result.totalDevices, 9, "totalDevices should be set"); - - Services.prefs.clearUserPref("services.sync.clients.devices.mobile"); - result = yield getConfigurationPromise("sync"); - is(result.mobileDevices, 0, "mobileDevices should be 0"); - is(result.desktopDevices, 0, "desktopDevices should be 0"); - is(result.totalDevices, 9, "totalDevices should be set"); - - Services.prefs.clearUserPref("services.sync.numClients"); - result = yield getConfigurationPromise("sync"); - is(result.mobileDevices, 0, "mobileDevices should be 0"); - is(result.desktopDevices, 0, "desktopDevices should be 0"); - is(result.totalDevices, 0, "totalDevices should be 0"); -}); - -// The showFirefoxAccounts API is sync related, so we test that here too... -add_UITour_task(function* test_firefoxAccountsNoParams() { - yield gContentAPI.showFirefoxAccounts(); - yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false, - "about:accounts?action=signup&entrypoint=uitour"); -}); - -add_UITour_task(function* test_firefoxAccountsValidParams() { - yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", utm_bar: "bar" }); - yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false, - "about:accounts?action=signup&entrypoint=uitour&utm_foo=foo&utm_bar=bar"); -}); - -add_UITour_task(function* test_firefoxAccountsNonAlphaValue() { - // All characters in the value are allowed, but they must be automatically escaped. - // (we throw a unicode character in there too - it's not auto-utf8 encoded, - // but that's ok, so long as it is escaped correctly.) - let value = "foo& /=?:\\\xa9"; - // encodeURIComponent encodes spaces to %20 but we want "+" - let expected = encodeURIComponent(value).replace(/%20/g, "+"); - yield gContentAPI.showFirefoxAccounts({ utm_foo: value }); - yield BrowserTestUtils.browserLoaded(gTestTab.linkedBrowser, false, - "about:accounts?action=signup&entrypoint=uitour&utm_foo=" + expected); -}); - -// A helper to check the request was ignored due to invalid params. -function* checkAboutAccountsNotLoaded() { - try { - yield waitForConditionPromise(() => { - return gBrowser.selectedBrowser.currentURI.spec.startsWith("about:accounts"); - }, "Check if about:accounts opened"); - ok(false, "No about:accounts tab should have opened"); - } catch (ex) { - ok(true, "No about:accounts tab opened"); - } -} - -add_UITour_task(function* test_firefoxAccountsNonObject() { - // non-string should be rejected. - yield gContentAPI.showFirefoxAccounts(99); - yield checkAboutAccountsNotLoaded(); -}); - -add_UITour_task(function* test_firefoxAccountsNonUtmPrefix() { - // Any non "utm_" name should should be rejected. - yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", bar: "bar" }); - yield checkAboutAccountsNotLoaded(); -}); - -add_UITour_task(function* test_firefoxAccountsNonAlphaName() { - // Any "utm_" name which includes non-alpha chars should be rejected. - yield gContentAPI.showFirefoxAccounts({ utm_foo: "foo", "utm_bar=": "bar" }); - yield checkAboutAccountsNotLoaded(); -}); diff --git a/browser/components/uitour/test/browser_UITour_toggleReaderMode.js b/browser/components/uitour/test/browser_UITour_toggleReaderMode.js deleted file mode 100644 index 58313e74b..000000000 --- a/browser/components/uitour/test/browser_UITour_toggleReaderMode.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -add_UITour_task(function*() { - ok(!gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader"), - "Should not be in reader mode at start of test."); - yield gContentAPI.toggleReaderMode(); - yield waitForConditionPromise(() => gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader")); - ok(gBrowser.selectedBrowser.currentURI.spec.startsWith("about:reader"), - "Should be in reader mode now."); -}); diff --git a/browser/components/uitour/test/browser_backgroundTab.js b/browser/components/uitour/test/browser_backgroundTab.js deleted file mode 100644 index c4117c698..000000000 --- a/browser/components/uitour/test/browser_backgroundTab.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -requestLongerTimeout(2); -add_task(setup_UITourTest); - -add_UITour_task(function* test_bg_getConfiguration() { - info("getConfiguration is on the allowed list so should work"); - yield* loadForegroundTab(); - let data = yield getConfigurationPromise("availableTargets"); - ok(data, "Got data from getConfiguration"); - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); -}); - -add_UITour_task(function* test_bg_showInfo() { - info("showInfo isn't on the allowed action list so should be denied"); - yield* loadForegroundTab(); - - yield showInfoPromise("appMenu", "Hello from the background", "Surprise!").then( - () => ok(false, "panel shouldn't have shown from a background tab"), - () => ok(true, "panel wasn't shown from a background tab")); - - yield BrowserTestUtils.removeTab(gBrowser.selectedTab); -}); - - -function* loadForegroundTab() { - // Spawn a content task that resolves once we're sure the visibilityState was - // changed. This state is what the tests in this file rely on. - let promise = ContentTask.spawn(gBrowser.selectedTab.linkedBrowser, null, function* () { - return new Promise(resolve => { - let document = content.document; - document.addEventListener("visibilitychange", function onStateChange() { - Assert.equal(document.visibilityState, "hidden", "UITour page should be hidden now."); - document.removeEventListener("visibilitychange", onStateChange); - resolve(); - }); - }); - }); - yield BrowserTestUtils.openNewForegroundTab(gBrowser); - yield promise; - isnot(gBrowser.selectedTab, gTestTab, "Make sure tour tab isn't selected"); -} diff --git a/browser/components/uitour/test/browser_closeTab.js b/browser/components/uitour/test/browser_closeTab.js deleted file mode 100644 index 2b998347a..000000000 --- a/browser/components/uitour/test/browser_closeTab.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -add_UITour_task(function* test_closeTab() { - // Setting gTestTab to null indicates that the tab has already been closed, - // and if this does not happen the test run will fail. - let closePromise = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "TabClose"); - yield gContentAPI.closeTab(); - yield closePromise; - gTestTab = null; -}); diff --git a/browser/components/uitour/test/browser_fxa.js b/browser/components/uitour/test/browser_fxa.js deleted file mode 100644 index 36ac45a62..000000000 --- a/browser/components/uitour/test/browser_fxa.js +++ /dev/null @@ -1,68 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts", - "resource://gre/modules/FxAccounts.jsm"); - -var gTestTab; -var gContentAPI; -var gContentWindow; - -function test() { - UITourTest(); -} - -registerCleanupFunction(function*() { - yield signOut(); - gFxAccounts.updateAppMenuItem(); -}); - -var tests = [ - taskify(function* test_highlight_accountStatus_loggedOut() { - let userData = yield fxAccounts.getSignedInUser(); - is(userData, null, "Not logged in initially"); - yield showMenuPromise("appMenu"); - yield showHighlightPromise("accountStatus"); - let highlight = document.getElementById("UITourHighlightContainer"); - is(highlight.getAttribute("targetName"), "accountStatus", "Correct highlight target"); - }), - - taskify(function* test_highlight_accountStatus_loggedIn() { - yield setSignedInUser(); - let userData = yield fxAccounts.getSignedInUser(); - isnot(userData, null, "Logged in now"); - gFxAccounts.updateAppMenuItem(); // Causes a leak - yield showMenuPromise("appMenu"); - yield showHighlightPromise("accountStatus"); - let highlight = document.getElementById("UITourHighlightContainer"); - is(highlight.popupBoxObject.anchorNode.id, "PanelUI-fxa-avatar", "Anchored on avatar"); - is(highlight.getAttribute("targetName"), "accountStatus", "Correct highlight target"); - }), -]; - -// Helpers copied from browser_aboutAccounts.js -// 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); -} diff --git a/browser/components/uitour/test/browser_no_tabs.js b/browser/components/uitour/test/browser_no_tabs.js deleted file mode 100644 index 62048b156..000000000 --- a/browser/components/uitour/test/browser_no_tabs.js +++ /dev/null @@ -1,102 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var HiddenFrame = Cu.import("resource:///modules/HiddenFrame.jsm", {}).HiddenFrame; - -const HTML_NS = "http://www.w3.org/1999/xhtml"; -const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; - -/** - * Create a frame in the |hiddenDOMWindow| to host a |browser|, then load the URL in the - * latter. - * - * @param aURL - * The URL to open in the browser. - **/ -function createHiddenBrowser(aURL) { - let frame = new HiddenFrame(); - return new Promise(resolve => - frame.get().then(aFrame => { - let doc = aFrame.document; - let browser = doc.createElementNS(XUL_NS, "browser"); - browser.setAttribute("type", "content"); - browser.setAttribute("disableglobalhistory", "true"); - browser.setAttribute("src", aURL); - - doc.documentElement.appendChild(browser); - resolve({frame: frame, browser: browser}); - })); -} - -/** - * Remove the browser and the HiddenFrame. - * - * @param aFrame - * The HiddenFrame to dismiss. - * @param aBrowser - * The browser to dismiss. - */ -function destroyHiddenBrowser(aFrame, aBrowser) { - // Dispose of the hidden browser. - aBrowser.remove(); - - // Take care of the frame holding our invisible browser. - aFrame.destroy(); -} - -/** - * Test that UITour works when called when no tabs are available (e.g., when using windowless - * browsers). - */ -add_task(function* test_windowless_UITour() { - // Get the URL for the test page. - let pageURL = getRootDirectory(gTestPath) + "uitour.html"; - - // Allow the URL to use the UITour. - info("Adding UITour permission to the test page."); - let pageURI = Services.io.newURI(pageURL, null, null); - Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION); - - // UITour's ping will resolve this promise. - let deferredPing = Promise.defer(); - - // Create a windowless browser and test that UITour works in it. - let browserPromise = createHiddenBrowser(pageURL); - browserPromise.then(frameInfo => { - isnot(frameInfo.browser, null, "The browser must exist and not be null."); - - // Load UITour frame script. - frameInfo.browser.messageManager.loadFrameScript( - "chrome://browser/content/content-UITour.js", false); - - // When the page loads, try to use UITour API. - frameInfo.browser.addEventListener("load", function loadListener() { - info("The test page was correctly loaded."); - - frameInfo.browser.removeEventListener("load", loadListener, true); - - // Get a reference to the UITour API. - info("Testing access to the UITour API."); - let contentWindow = Cu.waiveXrays(frameInfo.browser.contentDocument.defaultView); - isnot(contentWindow, null, "The content window must exist and not be null."); - - let uitourAPI = contentWindow.Mozilla.UITour; - - // Test the UITour API with a ping. - uitourAPI.ping(function() { - info("Ping response received from the UITour API."); - - // Make sure to clean up. - destroyHiddenBrowser(frameInfo.frame, frameInfo.browser); - - // Resolve our promise. - deferredPing.resolve(); - }); - }, true); - }); - - // Wait for the UITour ping to complete. - yield deferredPing.promise; -}); diff --git a/browser/components/uitour/test/browser_openPreferences.js b/browser/components/uitour/test/browser_openPreferences.js deleted file mode 100644 index c41865120..000000000 --- a/browser/components/uitour/test/browser_openPreferences.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -add_UITour_task(function* test_openPreferences() { - let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences"); - yield gContentAPI.openPreferences(); - let tab = yield promiseTabOpened; - yield BrowserTestUtils.removeTab(tab); -}); - -add_UITour_task(function* test_openInvalidPreferences() { - yield gContentAPI.openPreferences(999); - - try { - yield waitForConditionPromise(() => { - return gBrowser.selectedBrowser.currentURI.spec.startsWith("about:preferences"); - }, "Check if about:preferences opened"); - ok(false, "No about:preferences tab should have opened"); - } catch (ex) { - ok(true, "No about:preferences tab opened: " + ex); - } -}); - -add_UITour_task(function* test_openPrivacyPreferences() { - let promiseTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "about:preferences#privacy"); - yield gContentAPI.openPreferences("privacy"); - let tab = yield promiseTabOpened; - yield BrowserTestUtils.removeTab(tab); -}); diff --git a/browser/components/uitour/test/browser_openSearchPanel.js b/browser/components/uitour/test/browser_openSearchPanel.js deleted file mode 100644 index 5faa9db02..000000000 --- a/browser/components/uitour/test/browser_openSearchPanel.js +++ /dev/null @@ -1,33 +0,0 @@ -/* Any copyright is dedicated to the Public Domain. - * http://creativecommons.org/publicdomain/zero/1.0/ */ - -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -function test() { - UITourTest(); -} - -var tests = [ - function test_openSearchPanel(done) { - let searchbar = document.getElementById("searchbar"); - - // If suggestions are enabled, the panel will attempt to use the network to connect - // to the suggestions provider, causing the test suite to fail. - Services.prefs.setBoolPref("browser.search.suggest.enabled", false); - registerCleanupFunction(() => { - Services.prefs.clearUserPref("browser.search.suggest.enabled"); - }); - - ok(!searchbar.textbox.open, "Popup starts as closed"); - gContentAPI.openSearchPanel(() => { - ok(searchbar.textbox.open, "Popup was opened"); - searchbar.textbox.closePopup(); - ok(!searchbar.textbox.open, "Popup was closed"); - done(); - }); - }, -]; diff --git a/browser/components/uitour/test/browser_showMenu_controlCenter.js b/browser/components/uitour/test/browser_showMenu_controlCenter.js deleted file mode 100644 index 0faa5f862..000000000 --- a/browser/components/uitour/test/browser_showMenu_controlCenter.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; -const CONTROL_CENTER_PANEL = gIdentityHandler._identityPopup; -const CONTROL_CENTER_MENU_NAME = "controlCenter"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -add_task(setup_UITourTest); - -add_UITour_task(function* test_showMenu() { - is_element_hidden(CONTROL_CENTER_PANEL, "Panel should initially be hidden"); - yield showMenuPromise(CONTROL_CENTER_MENU_NAME); - is_element_visible(CONTROL_CENTER_PANEL, "Panel should be visible after showMenu"); - - yield gURLBar.focus(); - is_element_visible(CONTROL_CENTER_PANEL, "Panel should remain visible after focus outside"); - - yield showMenuPromise(CONTROL_CENTER_MENU_NAME); - is_element_visible(CONTROL_CENTER_PANEL, - "Panel should remain visible and callback called after a 2nd showMenu"); - - yield BrowserTestUtils.withNewTab({ - gBrowser, - url: "about:blank" - }, function*() { - ok(true, "Tab opened"); - }); - - is_element_hidden(CONTROL_CENTER_PANEL, "Panel should hide upon tab switch"); -}); - -add_UITour_task(function* test_hideMenu() { - is_element_hidden(CONTROL_CENTER_PANEL, "Panel should initially be hidden"); - yield showMenuPromise(CONTROL_CENTER_MENU_NAME); - is_element_visible(CONTROL_CENTER_PANEL, "Panel should be visible after showMenu"); - let hidePromise = promisePanelElementHidden(window, CONTROL_CENTER_PANEL); - yield gContentAPI.hideMenu(CONTROL_CENTER_MENU_NAME); - yield hidePromise; - - is_element_hidden(CONTROL_CENTER_PANEL, "Panel should hide after hideMenu"); -}); diff --git a/browser/components/uitour/test/browser_trackingProtection.js b/browser/components/uitour/test/browser_trackingProtection.js deleted file mode 100644 index 32a9920ec..000000000 --- a/browser/components/uitour/test/browser_trackingProtection.js +++ /dev/null @@ -1,90 +0,0 @@ -"use strict"; - -var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; -const PREF_INTRO_COUNT = "privacy.trackingprotection.introCount"; -const PREF_TP_ENABLED = "privacy.trackingprotection.enabled"; -const BENIGN_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/benignPage.html"; -const TRACKING_PAGE = "http://tracking.example.org/browser/browser/base/content/test/general/trackingPage.html"; -const TOOLTIP_PANEL = document.getElementById("UITourTooltip"); -const TOOLTIP_ANCHOR = document.getElementById("tracking-protection-icon"); - -var {UrlClassifierTestUtils} = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {}); - -registerCleanupFunction(function() { - UrlClassifierTestUtils.cleanupTestTrackers(); - Services.prefs.clearUserPref(PREF_TP_ENABLED); - Services.prefs.clearUserPref(PREF_INTRO_COUNT); -}); - -function allowOneIntro() { - Services.prefs.setIntPref(PREF_INTRO_COUNT, TrackingProtection.MAX_INTROS - 1); -} - -add_task(function* setup_test() { - Services.prefs.setBoolPref(PREF_TP_ENABLED, true); - yield UrlClassifierTestUtils.addTestTrackers(); -}); - -add_task(function* test_benignPage() { - info("Load a test page not containing tracking elements"); - allowOneIntro(); - yield BrowserTestUtils.withNewTab({gBrowser, url: BENIGN_PAGE}, function*() { - yield waitForConditionPromise(() => { - return is_visible(TOOLTIP_PANEL); - }, "Info panel shouldn't appear on a benign page"). - then(() => ok(false, "Info panel shouldn't appear"), - () => { - ok(true, "Info panel didn't appear on a benign page"); - }); - - }); -}); - -add_task(function* test_trackingPages() { - info("Load a test page containing tracking elements"); - allowOneIntro(); - yield BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, function*() { - yield new Promise((resolve, reject) => { - waitForPopupAtAnchor(TOOLTIP_PANEL, TOOLTIP_ANCHOR, resolve, - "Intro panel should appear"); - }); - - is(Services.prefs.getIntPref(PREF_INTRO_COUNT), TrackingProtection.MAX_INTROS, "Check intro count increased"); - - let step2URL = Services.urlFormatter.formatURLPref("privacy.trackingprotection.introURL") + - "?step=2&newtab=true"; - let buttons = document.getElementById("UITourTooltipButtons"); - - info("Click the step text and nothing should happen"); - let tabCount = gBrowser.tabs.length; - yield EventUtils.synthesizeMouseAtCenter(buttons.children[0], {}); - is(gBrowser.tabs.length, tabCount, "Same number of tabs should be open"); - - info("Resetting count to test that viewing the tour prevents future panels"); - allowOneIntro(); - - let panelHiddenPromise = promisePanelElementHidden(window, TOOLTIP_PANEL); - let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, step2URL); - info("Clicking the main button"); - EventUtils.synthesizeMouseAtCenter(buttons.children[1], {}); - let tab = yield tabPromise; - is(Services.prefs.getIntPref(PREF_INTRO_COUNT), TrackingProtection.MAX_INTROS, - "Check intro count is at the max after opening step 2"); - is(gBrowser.tabs.length, tabCount + 1, "Tour step 2 tab opened"); - yield panelHiddenPromise; - ok(true, "Panel hid when the button was clicked"); - yield BrowserTestUtils.removeTab(tab); - }); - - info("Open another tracking page and make sure we don't show the panel again"); - yield BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, function*() { - yield waitForConditionPromise(() => { - return is_visible(TOOLTIP_PANEL); - }, "Info panel shouldn't appear more than MAX_INTROS"). - then(() => ok(false, "Info panel shouldn't appear again"), - () => { - ok(true, "Info panel didn't appear more than MAX_INTROS on tracking pages"); - }); - - }); -}); diff --git a/browser/components/uitour/test/browser_trackingProtection_tour.js b/browser/components/uitour/test/browser_trackingProtection_tour.js deleted file mode 100644 index 0ee0e1686..000000000 --- a/browser/components/uitour/test/browser_trackingProtection_tour.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; - -var gTestTab; -var gContentAPI; -var gContentWindow; - -const { UrlClassifierTestUtils } = Cu.import("resource://testing-common/UrlClassifierTestUtils.jsm", {}); - -const TP_ENABLED_PREF = "privacy.trackingprotection.enabled"; - -add_task(setup_UITourTest); - -add_task(function* test_setup() { - Services.prefs.setBoolPref("privacy.trackingprotection.enabled", true); - yield UrlClassifierTestUtils.addTestTrackers(); - - registerCleanupFunction(function() { - UrlClassifierTestUtils.cleanupTestTrackers(); - Services.prefs.clearUserPref("privacy.trackingprotection.enabled"); - }); -}); - -add_UITour_task(function* test_unblock_target() { - yield* checkToggleTarget("controlCenter-trackingUnblock"); -}); - -add_UITour_task(function* setup_block_target() { - // Preparation for test_block_target. These are separate since the reload - // interferes with UITour as it does a teardown. All we really care about - // is the permission manager entry but UITour tests shouldn't rely on that - // implementation detail. - TrackingProtection.disableForCurrentPage(); -}); - -add_UITour_task(function* test_block_target() { - yield* checkToggleTarget("controlCenter-trackingBlock"); - TrackingProtection.enableForCurrentPage(); -}); - - -function* checkToggleTarget(targetID) { - let popup = document.getElementById("UITourTooltip"); - - yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function () { - let doc = content.document; - let iframe = doc.createElement("iframe"); - iframe.setAttribute("id", "tracking-element"); - iframe.setAttribute("src", "https://tracking.example.com/"); - doc.body.insertBefore(iframe, doc.body.firstChild); - }); - - let testTargetAvailability = function* (expectedAvailable) { - let data = yield getConfigurationPromise("availableTargets"); - let available = (data.targets.indexOf(targetID) != -1); - is(available, expectedAvailable, "Target has expected availability."); - }; - yield testTargetAvailability(false); - yield showMenuPromise("controlCenter"); - yield testTargetAvailability(true); - - yield showInfoPromise(targetID, "This is " + targetID, - "My arrow should be on the side"); - is(popup.popupBoxObject.alignmentPosition, "end_before", - "Check " + targetID + " position"); - - let hideMenuPromise = - promisePanelElementHidden(window, gIdentityHandler._identityPopup); - yield gContentAPI.hideMenu("controlCenter"); - yield hideMenuPromise; - - ok(!is_visible(popup), "The tooltip should now be hidden."); - yield testTargetAvailability(false); - - yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function () { - content.document.getElementById("tracking-element").remove(); - }); -} diff --git a/browser/components/uitour/test/head.js b/browser/components/uitour/test/head.js deleted file mode 100644 index 2b5b994ae..000000000 --- a/browser/components/uitour/test/head.js +++ /dev/null @@ -1,449 +0,0 @@ -"use strict"; - -Cu.import("resource://gre/modules/Promise.jsm"); -Cu.import("resource://gre/modules/Task.jsm"); -XPCOMUtils.defineLazyModuleGetter(this, "UITour", - "resource:///modules/UITour.jsm"); - - -const SINGLE_TRY_TIMEOUT = 100; -const NUMBER_OF_TRIES = 30; - -function waitForConditionPromise(condition, timeoutMsg, tryCount=NUMBER_OF_TRIES) { - let defer = Promise.defer(); - let tries = 0; - function checkCondition() { - if (tries >= tryCount) { - defer.reject(timeoutMsg); - } - var conditionPassed; - try { - conditionPassed = condition(); - } catch (e) { - return defer.reject(e); - } - if (conditionPassed) { - return defer.resolve(); - } - tries++; - setTimeout(checkCondition, SINGLE_TRY_TIMEOUT); - return undefined; - } - setTimeout(checkCondition, SINGLE_TRY_TIMEOUT); - return defer.promise; -} - -function waitForCondition(condition, nextTest, errorMsg) { - waitForConditionPromise(condition, errorMsg).then(nextTest, (reason) => { - ok(false, reason + (reason.stack ? "\n" + reason.stack : "")); - }); -} - -/** - * Wrapper to partially transition tests to Task. Use `add_UITour_task` instead for new tests. - */ -function taskify(fun) { - return (done) => { - // Output the inner function name otherwise no name will be output. - info("\t" + fun.name); - return Task.spawn(fun).then(done, (reason) => { - ok(false, reason); - done(); - }); - }; -} - -function is_hidden(element) { - var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") - return true; - if (style.visibility != "visible") - return true; - if (style.display == "-moz-popup") - return ["hiding", "closed"].indexOf(element.state) != -1; - - // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) - return is_hidden(element.parentNode); - - return false; -} - -function is_visible(element) { - var style = element.ownerGlobal.getComputedStyle(element); - if (style.display == "none") - return false; - if (style.visibility != "visible") - return false; - if (style.display == "-moz-popup" && element.state != "open") - return false; - - // Hiding a parent element will hide all its children - if (element.parentNode != element.ownerDocument) - return is_visible(element.parentNode); - - return true; -} - -function is_element_visible(element, msg) { - isnot(element, null, "Element should not be null, when checking visibility"); - ok(is_visible(element), msg); -} - -function waitForElementToBeVisible(element, nextTest, msg) { - waitForCondition(() => is_visible(element), - () => { - ok(true, msg); - nextTest(); - }, - "Timeout waiting for visibility: " + msg); -} - -function waitForElementToBeHidden(element, nextTest, msg) { - waitForCondition(() => is_hidden(element), - () => { - ok(true, msg); - nextTest(); - }, - "Timeout waiting for invisibility: " + msg); -} - -function elementVisiblePromise(element, msg) { - return waitForConditionPromise(() => is_visible(element), "Timeout waiting for visibility: " + msg); -} - -function elementHiddenPromise(element, msg) { - return waitForConditionPromise(() => is_hidden(element), "Timeout waiting for invisibility: " + msg); -} - -function waitForPopupAtAnchor(popup, anchorNode, nextTest, msg) { - waitForCondition(() => is_visible(popup) && popup.popupBoxObject.anchorNode == anchorNode, - () => { - ok(true, msg); - is_element_visible(popup, "Popup should be visible"); - nextTest(); - }, - "Timeout waiting for popup at anchor: " + msg); -} - -function getConfigurationPromise(configName) { - return ContentTask.spawn(gTestTab.linkedBrowser, configName, configName => { - return new Promise((resolve) => { - let contentWin = Components.utils.waiveXrays(content); - contentWin.Mozilla.UITour.getConfiguration(configName, resolve); - }); - }); -} - -function hideInfoPromise(...args) { - let popup = document.getElementById("UITourTooltip"); - gContentAPI.hideInfo.apply(gContentAPI, args); - return promisePanelElementHidden(window, popup); -} - -/** - * `buttons` and `options` require functions from the content scope so we take a - * function name to call to generate the buttons/options instead of the - * buttons/options themselves. This makes the signature differ from the content one. - */ -function showInfoPromise(target, title, text, icon, buttonsFunctionName, optionsFunctionName) { - let popup = document.getElementById("UITourTooltip"); - let shownPromise = promisePanelElementShown(window, popup); - return ContentTask.spawn(gTestTab.linkedBrowser, [...arguments], args => { - let contentWin = Components.utils.waiveXrays(content); - let [target, title, text, icon, buttonsFunctionName, optionsFunctionName] = args; - let buttons = buttonsFunctionName ? contentWin[buttonsFunctionName]() : null; - let options = optionsFunctionName ? contentWin[optionsFunctionName]() : null; - contentWin.Mozilla.UITour.showInfo(target, title, text, icon, buttons, options); - }).then(() => shownPromise); -} - -function showHighlightPromise(...args) { - let popup = document.getElementById("UITourHighlightContainer"); - gContentAPI.showHighlight.apply(gContentAPI, args); - return promisePanelElementShown(window, popup); -} - -function showMenuPromise(name) { - return ContentTask.spawn(gTestTab.linkedBrowser, name, name => { - return new Promise((resolve) => { - let contentWin = Components.utils.waiveXrays(content); - contentWin.Mozilla.UITour.showMenu(name, resolve); - }); - }); -} - -function waitForCallbackResultPromise() { - return ContentTask.spawn(gTestTab.linkedBrowser, null, function*() { - let contentWin = Components.utils.waiveXrays(content); - yield ContentTaskUtils.waitForCondition(() => { - return contentWin.callbackResult; - }, "callback should be called"); - return { - data: contentWin.callbackData, - result: contentWin.callbackResult, - }; - }); -} - -function promisePanelShown(win) { - let panelEl = win.PanelUI.panel; - return promisePanelElementShown(win, panelEl); -} - -function promisePanelElementEvent(win, aPanel, aEvent) { - return new Promise((resolve, reject) => { - let timeoutId = win.setTimeout(() => { - aPanel.removeEventListener(aEvent, onPanelEvent); - reject(aEvent + " event did not happen within 5 seconds."); - }, 5000); - - function onPanelEvent(e) { - aPanel.removeEventListener(aEvent, onPanelEvent); - win.clearTimeout(timeoutId); - // Wait one tick to let UITour.jsm process the event as well. - executeSoon(resolve); - } - - aPanel.addEventListener(aEvent, onPanelEvent); - }); -} - -function promisePanelElementShown(win, aPanel) { - return promisePanelElementEvent(win, aPanel, "popupshown"); -} - -function promisePanelElementHidden(win, aPanel) { - return promisePanelElementEvent(win, aPanel, "popuphidden"); -} - -function is_element_hidden(element, msg) { - isnot(element, null, "Element should not be null, when checking visibility"); - ok(is_hidden(element), msg); -} - -function isTourBrowser(aBrowser) { - let chromeWindow = aBrowser.ownerGlobal; - return UITour.tourBrowsersByWindow.has(chromeWindow) && - UITour.tourBrowsersByWindow.get(chromeWindow).has(aBrowser); -} - -function promisePageEvent() { - return new Promise((resolve) => { - Services.mm.addMessageListener("UITour:onPageEvent", function onPageEvent(aMessage) { - Services.mm.removeMessageListener("UITour:onPageEvent", onPageEvent); - SimpleTest.executeSoon(resolve); - }); - }); -} - -function loadUITourTestPage(callback, host = "https://example.org/") { - if (gTestTab) - gBrowser.removeTab(gTestTab); - - let url = getRootDirectory(gTestPath) + "uitour.html"; - url = url.replace("chrome://mochitests/content/", host); - - gTestTab = gBrowser.addTab(url); - gBrowser.selectedTab = gTestTab; - - gTestTab.linkedBrowser.addEventListener("load", function onLoad() { - gTestTab.linkedBrowser.removeEventListener("load", onLoad, true); - - if (gMultiProcessBrowser) { - // When e10s is enabled, make gContentAPI and gContentWindow proxies which has every property - // return a function which calls the method of the same name on - // contentWin.Mozilla.UITour/contentWin in a ContentTask. - let contentWinHandler = { - get(target, prop, receiver) { - return (...args) => { - let taskArgs = { - methodName: prop, - args, - }; - return ContentTask.spawn(gTestTab.linkedBrowser, taskArgs, args => { - let contentWin = Components.utils.waiveXrays(content); - return contentWin[args.methodName].apply(contentWin, args.args); - }); - }; - }, - }; - gContentWindow = new Proxy({}, contentWinHandler); - - let UITourHandler = { - get(target, prop, receiver) { - return (...args) => { - let browser = gTestTab.linkedBrowser; - const proxyFunctionName = "UITourHandler:proxiedfunction-"; - // We need to proxy any callback functions using messages: - let callbackMap = new Map(); - let fnIndices = []; - args = args.map((arg, index) => { - // Replace function arguments with "", and add them to the list of - // forwarded functions. We'll construct a function on the content-side - // that forwards all its arguments to a message, and we'll listen for - // those messages on our side and call the corresponding function with - // the arguments we got from the content side. - if (typeof arg == "function") { - callbackMap.set(index, arg); - fnIndices.push(index); - let handler = function(msg) { - // Please note that this handler assumes that the callback is used only once. - // That means that a single gContentAPI.observer() call can't be used to observe - // multiple events. - browser.messageManager.removeMessageListener(proxyFunctionName + index, handler); - callbackMap.get(index).apply(null, msg.data); - }; - browser.messageManager.addMessageListener(proxyFunctionName + index, handler); - return ""; - } - return arg; - }); - let taskArgs = { - methodName: prop, - args, - fnIndices, - }; - return ContentTask.spawn(browser, taskArgs, function*(args) { - let contentWin = Components.utils.waiveXrays(content); - let callbacksCalled = 0; - let resolveCallbackPromise; - let allCallbacksCalledPromise = new Promise(resolve => resolveCallbackPromise = resolve); - let argumentsWithFunctions = args.args.map((arg, index) => { - if (arg === "" && args.fnIndices.includes(index)) { - return function() { - callbacksCalled++; - sendAsyncMessage("UITourHandler:proxiedfunction-" + index, Array.from(arguments)); - if (callbacksCalled >= args.fnIndices.length) { - resolveCallbackPromise(); - } - }; - } - return arg; - }); - let rv = contentWin.Mozilla.UITour[args.methodName].apply(contentWin.Mozilla.UITour, - argumentsWithFunctions); - if (args.fnIndices.length) { - yield allCallbacksCalledPromise; - } - return rv; - }); - }; - }, - }; - gContentAPI = new Proxy({}, UITourHandler); - } else { - gContentWindow = Components.utils.waiveXrays(gTestTab.linkedBrowser.contentDocument.defaultView); - gContentAPI = gContentWindow.Mozilla.UITour; - } - - waitForFocus(callback, gTestTab.linkedBrowser); - }, true); -} - -// Wrapper for UITourTest to be used by add_task tests. -function* setup_UITourTest() { - return UITourTest(true); -} - -// Use `add_task(setup_UITourTest);` instead as we will fold this into `setup_UITourTest` once all tests are using `add_UITour_task`. -function UITourTest(usingAddTask = false) { - Services.prefs.setBoolPref("browser.uitour.enabled", true); - let testHttpsUri = Services.io.newURI("https://example.org", null, null); - let testHttpUri = Services.io.newURI("http://example.org", null, null); - Services.perms.add(testHttpsUri, "uitour", Services.perms.ALLOW_ACTION); - Services.perms.add(testHttpUri, "uitour", Services.perms.ALLOW_ACTION); - - // If a test file is using add_task, we don't need to have a test function or - // call `waitForExplicitFinish`. - if (!usingAddTask) { - waitForExplicitFinish(); - } - - registerCleanupFunction(function() { - delete window.gContentWindow; - delete window.gContentAPI; - if (gTestTab) - gBrowser.removeTab(gTestTab); - delete window.gTestTab; - Services.prefs.clearUserPref("browser.uitour.enabled"); - Services.perms.remove(testHttpsUri, "uitour"); - Services.perms.remove(testHttpUri, "uitour"); - }); - - // When using tasks, the harness will call the next added task for us. - if (!usingAddTask) { - nextTest(); - } -} - -function done(usingAddTask = false) { - info("== Done test, doing shared checks before teardown =="); - return new Promise((resolve) => { - executeSoon(() => { - if (gTestTab) - gBrowser.removeTab(gTestTab); - gTestTab = null; - - let highlight = document.getElementById("UITourHighlightContainer"); - is_element_hidden(highlight, "Highlight should be closed/hidden after UITour tab is closed"); - - let tooltip = document.getElementById("UITourTooltip"); - is_element_hidden(tooltip, "Tooltip should be closed/hidden after UITour tab is closed"); - - ok(!PanelUI.panel.hasAttribute("noautohide"), "@noautohide on the menu panel should have been cleaned up"); - ok(!PanelUI.panel.hasAttribute("panelopen"), "The panel shouldn't have @panelopen"); - isnot(PanelUI.panel.state, "open", "The panel shouldn't be open"); - is(document.getElementById("PanelUI-menu-button").hasAttribute("open"), false, "Menu button should know that the menu is closed"); - - info("Done shared checks"); - if (usingAddTask) { - executeSoon(resolve); - } else { - executeSoon(nextTest); - } - }); - }); -} - -function nextTest() { - if (tests.length == 0) { - info("finished tests in this file"); - finish(); - return; - } - let test = tests.shift(); - info("Starting " + test.name); - waitForFocus(function() { - loadUITourTestPage(function() { - test(done); - }); - }); -} - -/** - * All new tests that need the help of `loadUITourTestPage` should use this - * wrapper around their test's generator function to reduce boilerplate. - */ -function add_UITour_task(func) { - let genFun = function*() { - yield new Promise((resolve) => { - waitForFocus(function() { - loadUITourTestPage(function() { - let funcPromise = Task.spawn(func) - .then(() => done(true), - (reason) => { - ok(false, reason); - return done(true); - }); - resolve(funcPromise); - }); - }); - }); - }; - Object.defineProperty(genFun, "name", { - configurable: true, - value: func.name, - }); - add_task(genFun); -} diff --git a/browser/components/uitour/test/image.png b/browser/components/uitour/test/image.png Binary files differdeleted file mode 100644 index 597c7fd2c..000000000 --- a/browser/components/uitour/test/image.png +++ /dev/null diff --git a/browser/components/uitour/test/uitour.html b/browser/components/uitour/test/uitour.html deleted file mode 100644 index 6c42ac7f8..000000000 --- a/browser/components/uitour/test/uitour.html +++ /dev/null @@ -1,42 +0,0 @@ -<!DOCTYPE html> -<html> - <head> - <meta charset="utf-8" /> - <title>UITour test</title> - <script type="application/javascript" src="UITour-lib.js"> - </script> - <script type="application/javascript"> - var callbackResult, callbackData; - function makeCallback(name) { - return (function(data) { - callbackResult = name; - callbackData = data; - }); - } - - // Defined in content to avoid weird issues when crossing between chrome/content. - function makeButtons() { - return [ - {label: "Regular text", style: "text"}, - {label: "Link", callback: makeCallback("link"), style: "link"}, - {label: "Button 1", callback: makeCallback("button1")}, - {label: "Button 2", callback: makeCallback("button2"), icon: "image.png", - style: "primary"} - ]; - } - - function makeInfoOptions() { - return { - closeButtonCallback: makeCallback("closeButton"), - targetCallback: makeCallback("target"), - }; - } - </script> - </head> - <body> - <h1>UITour tests</h1> - <p>Because Firefox is...</p> - <p>Never gonna let you down</p> - <p>Never gonna give you up</p> - </body> -</html> |