I get loaded to do permission testing.
\ 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 5df9998ca3..0000000000
--- 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 63c74d1fe8..0000000000
--- a/browser/components/originattributes/test/mochitest/test_permissions_api.html
+++ /dev/null
@@ -1,207 +0,0 @@
-
-
-
-
-
- _) 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 7a0eec22f1..0000000000
--- 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 735d6b1687..0000000000
--- 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 5a54fe353b..0000000000
--- a/browser/components/places/tests/browser/frameLeft.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
- Left frame
-
-
- Open page in the right frame.
-
-
diff --git a/browser/components/places/tests/browser/frameRight.html b/browser/components/places/tests/browser/frameRight.html
deleted file mode 100644
index 226accc349..0000000000
--- a/browser/components/places/tests/browser/frameRight.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
- Right Frame
-
-
- This is the right frame.
-
-
diff --git a/browser/components/places/tests/browser/framedPage.html b/browser/components/places/tests/browser/framedPage.html
deleted file mode 100644
index d388562e6e..0000000000
--- a/browser/components/places/tests/browser/framedPage.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
- Framed page
-
-
-
-
-
-
diff --git a/browser/components/places/tests/browser/head.js b/browser/components/places/tests/browser/head.js
deleted file mode 100644
index aaf78332e1..0000000000
--- 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 a881c0d5ad..0000000000
--- a/browser/components/places/tests/browser/keyword_form.html
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
diff --git a/browser/components/places/tests/browser/pageopeningwindow.html b/browser/components/places/tests/browser/pageopeningwindow.html
deleted file mode 100644
index 282f9c5930..0000000000
--- a/browser/components/places/tests/browser/pageopeningwindow.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-Hi, I was opened via a
-
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 c73eaa5403..0000000000
--- a/browser/components/places/tests/browser/sidebarpanels_click_test_page.html
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
- browser_sidebarpanels_click.js test page
-
-
-
-
diff --git a/browser/components/places/tests/chrome/.eslintrc.js b/browser/components/places/tests/chrome/.eslintrc.js
deleted file mode 100644
index 8c0f4f574c..0000000000
--- 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 d7b4a55c8e..0000000000
--- 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 26b97f6d76..0000000000
--- 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 86e102180a..0000000000
--- a/browser/components/places/tests/chrome/test_0_bug510634.xul
+++ /dev/null
@@ -1,99 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 09a4d20549..0000000000
--- a/browser/components/places/tests/chrome/test_0_multiple_left_pane.xul
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 8e3a995339..0000000000
--- a/browser/components/places/tests/chrome/test_bug1163447_selectItems_through_shortcut.xul
+++ /dev/null
@@ -1,89 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 b659b2b468..0000000000
--- a/browser/components/places/tests/chrome/test_bug427633_no_newfolder_if_noip.xul
+++ /dev/null
@@ -1,91 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- %editBookmarkOverlayDTD;
-]>
-
-
-
-
-
-
-
-
-
-
-
-
-
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 afad950cb4..0000000000
--- a/browser/components/places/tests/chrome/test_bug485100-change-case-loses-tag.xul
+++ /dev/null
@@ -1,83 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- %editBookmarkOverlayDTD;
-]>
-
-
-
-
-
-
-
-
-
-
-
-
-
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 4e6a89bb14..0000000000
--- a/browser/components/places/tests/chrome/test_bug549192.xul
+++ /dev/null
@@ -1,120 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 5ec7a765a7..0000000000
--- a/browser/components/places/tests/chrome/test_bug549491.xul
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 b1d73017f6..0000000000
--- a/browser/components/places/tests/chrome/test_bug631374_tags_selector_scroll.xul
+++ /dev/null
@@ -1,170 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- %editBookmarkOverlayDTD;
-]>
-
-
-
-
-
-
-
-
-
-
-
-
-
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 f553d018bf..0000000000
--- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_keywords.xul
+++ /dev/null
@@ -1,99 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- %editBookmarkOverlayDTD;
-]>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 1b1cc6473c..0000000000
--- a/browser/components/places/tests/chrome/test_editBookmarkOverlay_tags_liveUpdate.xul
+++ /dev/null
@@ -1,204 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- %editBookmarkOverlayDTD;
-]>
-
-
-
-
-
-
-
-
-
-
-
-
-
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 032c7a258e..0000000000
--- a/browser/components/places/tests/chrome/test_selectItems_on_nested_tree.xul
+++ /dev/null
@@ -1,86 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 5592326110..0000000000
--- a/browser/components/places/tests/chrome/test_treeview_date.xul
+++ /dev/null
@@ -1,159 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/browser/components/places/tests/unit/.eslintrc.js b/browser/components/places/tests/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2c..0000000000
--- 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 07b22e9b3f..0000000000
--- a/browser/components/places/tests/unit/bookmarks.glue.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-Bookmarks
-Bookmarks Menu
-
-
-
example
- Bookmarks Toolbar
-Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
-
-
example
-
-
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 95900e176e..0000000000
--- 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
deleted file mode 100644
index b234246cac..0000000000
Binary files a/browser/components/places/tests/unit/corruptDB.sqlite and /dev/null differ
diff --git a/browser/components/places/tests/unit/distribution.ini b/browser/components/places/tests/unit/distribution.ini
deleted file mode 100644
index 93e73cb5c2..0000000000
--- 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 460295f96c..0000000000
--- 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 a0d1383728..0000000000
--- 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 c0626f53bd..0000000000
--- 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 4db21555fe..0000000000
--- 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 5b2a090688..0000000000
--- 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 7cb4e5e4cb..0000000000
--- 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 4804200915..0000000000
--- 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 c3d6e1d9ee..0000000000
--- 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 817f10c81a..0000000000
--- 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 9f35046363..0000000000
--- 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 9d7ac5ac13..0000000000
--- 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 6ecaec4fec..0000000000
--- 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 072056b3fb..0000000000
--- 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 0c1d788013..0000000000
--- 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 0af6f4e95d..0000000000
--- 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 1c40e1c53e..0000000000
--- 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 7c80211924..0000000000
--- 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 6cba02599b..0000000000
--- 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 e9d0e86521..0000000000
--- 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 32c1bd7263..0000000000
--- 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 9d938fdd40..0000000000
--- 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 bc2c6d8002..0000000000
--- 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 0972b2de4f..0000000000
--- 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 59b644c8fa..0000000000
--- a/browser/components/preferences/in-content/tests/browser_bug1184989_prevent_scrolling_when_preferences_flipped.xul
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
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 5b100966df..0000000000
--- 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 24732083b8..0000000000
--- 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 c1031d4128..0000000000
--- 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 21f92db8d0..0000000000
--- 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 f66cdfd37b..0000000000
--- 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 50438aed1b..0000000000
--- 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 5a348876e6..0000000000
--- 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 89313d7366..0000000000
--- 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 b30b6d9e29..0000000000
--- 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 bbfae9707c..0000000000
--- 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 366454fccf..0000000000
--- 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 68f9653f6c..0000000000
--- 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 d9253735ad..0000000000
--- 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 0df60c6ac2..0000000000
--- 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 8fe6f0825e..0000000000
--- 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 b7ef3deda7..0000000000
--- 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 a075300106..0000000000
--- 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 756b19a2f1..0000000000
--- 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 3ad24c7ec9..0000000000
--- 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 6b587e0366..0000000000
--- 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 0185a23b9e..0000000000
--- 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 e6eb2a91d7..0000000000
--- 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 ff0c1f8ae8..0000000000
--- 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 d8139d87af..0000000000
--- 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 0ed811e943..0000000000
--- 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 53c6d7d8a5..0000000000
--- 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 48d297b737..0000000000
--- a/browser/components/preferences/in-content/tests/subdialog.xul
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
- A sample sub-dialog for testing
-
-
-
-
-
-
-
-
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 89803c2503..0000000000
--- a/browser/components/preferences/in-content/tests/subdialog2.xul
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
- A sample sub-dialog for testing
-
-
-
-
-
-
-
-
diff --git a/browser/components/privatebrowsing/test/browser/.eslintrc.js b/browser/components/privatebrowsing/test/browser/.eslintrc.js
deleted file mode 100644
index 7c80211924..0000000000
--- 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 5efca4c0ec..0000000000
--- 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 bcd19b1923..0000000000
--- 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 e00f3f67a9..0000000000
--- 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 6f52f77197..0000000000
--- 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 5f6a918362..0000000000
--- 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 2ceb1032bd..0000000000
--- 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 4990f6d3ba..0000000000
--- 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 519f43475e..0000000000
--- 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 b73bbf2193..0000000000
--- 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 db35b114da..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_concurrent_page.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
-
-
-
-
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 30f7ee0259..0000000000
--- 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 cd316d1fbc..0000000000
--- 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 81b2943eeb..0000000000
--- 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 5a04d1999d..0000000000
--- 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 b192c08f74..0000000000
--- 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 86f714082b..0000000000
--- 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 3a078ffc15..0000000000
--- 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 36d5e3cecc..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_geoprompt_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
- Geolocation invoker
-
-
-
-
-
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 dbe8ed0603..0000000000
--- 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 acccb5e2d4..0000000000
--- 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 3bcb6e5c9d..0000000000
--- 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 143fea4e72..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
-
-
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 9a7e2da630..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_before_after_page2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
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 3e79a01bf8..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page1.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
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 8c9b28fd80..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_localStorage_page2.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
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 b09ec03684..0000000000
--- 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(`
- Now click this
- `);
-const POPUP_LINK = `data:text/html;charset=utf-8;base64,${POPUP_BODY_BASE64}`;
-const WINDOW_BODY = `data:text/html,
-
- First click this.
- `;
-
-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 ae6e8a6a3a..0000000000
--- 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 d2a69dd4e1..0000000000
--- 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 0b1369b115..0000000000
--- 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 f5bb3212f8..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_placesTitleNoUpdate.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- Title 1
-
-
-
-
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 32436b3cc7..0000000000
--- 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 a70019976e..0000000000
--- 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 71d85f296c..0000000000
--- 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 fe69a2234b..0000000000
--- 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 74f846d54a..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_protocolhandler_page.html
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
- Protocol registrar page
-
-
-
-
-
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 dbd74029d8..0000000000
--- 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 e2b8593d66..0000000000
--- 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 cbd2c60f88..0000000000
--- 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 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 2be701bcda..0000000000
--- 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 aca8d0c7b4..0000000000
--- 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 760bde7d14..0000000000
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_windowtitle_page.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- Test title
-
-
- Test page for the window title test
-
-
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 f5afcbd61c..0000000000
--- 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 b67bfc2295..0000000000
--- 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 42682b4746..0000000000
--- a/browser/components/privatebrowsing/test/browser/empty_file.html
+++ /dev/null
@@ -1 +0,0 @@
-
\ 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 b571134e1b..0000000000
--- a/browser/components/privatebrowsing/test/browser/file_favicon.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
- Favicon Test for originAttributes
-
-
-
- Favicon!!
-
-
\ 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
deleted file mode 100644
index 5535363c94..0000000000
Binary files a/browser/components/privatebrowsing/test/browser/file_favicon.png and /dev/null differ
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 9e23c73b7f..0000000000
--- 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 c822ba8d1a..0000000000
--- 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 68bbbfa260..0000000000
--- a/browser/components/privatebrowsing/test/browser/popup.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
- Page creating a popup
-
-
-
-
-
diff --git a/browser/components/privatebrowsing/test/browser/title.sjs b/browser/components/privatebrowsing/test/browser/title.sjs
deleted file mode 100644
index 568e235be1..0000000000
--- 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("");
- response.write(title);
- response.write(" test page");
-}
diff --git a/browser/components/safebrowsing/content/test/.eslintrc.js b/browser/components/safebrowsing/content/test/.eslintrc.js
deleted file mode 100644
index 7c80211924..0000000000
--- 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 1ce19118e6..0000000000
--- 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 fac187753a..0000000000
--- 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 fc2e3472ff..0000000000
--- 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 afb647a812..0000000000
--- 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 90eef0a3f1..0000000000
--- 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 c764b133dc..0000000000
--- 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 e4545cc771..0000000000
--- a/browser/components/search/test/426329.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-
- Bug 426329
- 426329 Search
- utf-8
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- http://mochi.test:8888/browser/browser/components/search/test/test.html
-
diff --git a/browser/components/search/test/483086-1.xml b/browser/components/search/test/483086-1.xml
deleted file mode 100644
index 9dbba4886d..0000000000
--- a/browser/components/search/test/483086-1.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
- 483086a
- Bug 483086 Test 1
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- foo://example.com
-
diff --git a/browser/components/search/test/483086-2.xml b/browser/components/search/test/483086-2.xml
deleted file mode 100644
index f130b90689..0000000000
--- a/browser/components/search/test/483086-2.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
- 483086b
- Bug 483086 Test 2
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- http://example.com
-
diff --git a/browser/components/search/test/browser.ini b/browser/components/search/test/browser.ini
deleted file mode 100644
index f1070264db..0000000000
--- 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 d9cbd3f7a9..0000000000
--- 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 208add867c..0000000000
--- 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 64376d6da0..0000000000
--- 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 3291b41f4d..0000000000
--- 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 b971ea5f78..0000000000
--- 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 965a3dcf87..0000000000
--- 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 22d16581a0..0000000000
--- 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 3a41ae0ac7..0000000000
--- 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 bc9b187ec0..0000000000
--- 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 21a8c11308..0000000000
--- 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 c485242b43..0000000000
--- 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 2b0cabea7f..0000000000
--- 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 55405bb297..0000000000
--- 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 e166b68689..0000000000
--- 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 c68ad174c7..0000000000
--- 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 9a584feb6f..0000000000
--- 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 db24c7192b..0000000000
--- 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 69207923bb..0000000000
--- 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 ff49cb0c62..0000000000
--- 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 3a209bf562..0000000000
--- 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 c0410371b1..0000000000
--- 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 d395dfdc22..0000000000
--- 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 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 befc8f142d..0000000000
--- 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 37ca32cf28..0000000000
--- 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 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 d8161ffbe5..0000000000
--- 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 f45b47d0cc..0000000000
--- 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 5b2d61422d..0000000000
--- 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 de27b5e1ed..0000000000
--- 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 f4c0cc98e5..0000000000
--- a/browser/components/search/test/opensearch.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/browser/components/search/test/test.html b/browser/components/search/test/test.html
deleted file mode 100644
index a39bece4ff..0000000000
--- a/browser/components/search/test/test.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- Bug 426329
-
-
-
diff --git a/browser/components/search/test/testEngine.xml b/browser/components/search/test/testEngine.xml
deleted file mode 100644
index 21ddc4b9a9..0000000000
--- a/browser/components/search/test/testEngine.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
- Foo
- Foo Search
- utf-8
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- http://mochi.test:8888/browser/browser/components/search/test/
- fooalias
-
diff --git a/browser/components/search/test/testEngine_diacritics.xml b/browser/components/search/test/testEngine_diacritics.xml
deleted file mode 100644
index 0744921eba..0000000000
--- a/browser/components/search/test/testEngine_diacritics.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
- Foo ♡
- Engine whose ShortName contains non-BMP Unicode characters
- utf-8
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- http://mochi.test:8888/browser/browser/components/search/test/
- diacriticalias
-
diff --git a/browser/components/search/test/testEngine_dupe.xml b/browser/components/search/test/testEngine_dupe.xml
deleted file mode 100644
index d2db580c4b..0000000000
--- a/browser/components/search/test/testEngine_dupe.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-
- FooDupe
- Second Engine Search
- utf-8
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
- http://mochi.test:8888/browser/browser/components/search/test/
- secondalias
-
diff --git a/browser/components/search/test/testEngine_mozsearch.xml b/browser/components/search/test/testEngine_mozsearch.xml
deleted file mode 100644
index 9b4c02a0c8..0000000000
--- a/browser/components/search/test/testEngine_mozsearch.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-
- Foo
- Foo Search
- utf-8
- data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC
-
-
-
-
-
-
-
- http://mochi.test:8888/browser/browser/components/search/test/
-
diff --git a/browser/components/search/test/webapi.html b/browser/components/search/test/webapi.html
deleted file mode 100644
index 1ef38b8951..0000000000
--- a/browser/components/search/test/webapi.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
diff --git a/browser/components/selfsupport/test/.eslintrc.js b/browser/components/selfsupport/test/.eslintrc.js
deleted file mode 100644
index c764b133dc..0000000000
--- 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 ba56857b3a..0000000000
--- 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 2a54d4ae65..0000000000
--- 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 c764b133dc..0000000000
--- 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 37154a0cc2..0000000000
--- 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 a307d1e01f..0000000000
--- 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 4a74fbc021..0000000000
--- a/browser/components/sessionstore/test/browser_1234021_page.html
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
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 f5775cd5b3..0000000000
--- 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 76c3ae1aa0..0000000000
--- a/browser/components/sessionstore/test/browser_248970_b_sample.html
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-Test for bug 248970
-
-Text Fields
-
-
-
-
-Checkboxes and Radio buttons
- Check 1
- Check 2
-
- Radio 1
- Radio 2
- Radio 3
-
-
Selects
-
- Select 1
- Select 2
- Select 3
-
-
- Multi-select 1
- Multi-select 2
- Multi-select 3
- Multi-select 4
-
-
-Text Areas
-
-
-
-
-File Selector
-
diff --git a/browser/components/sessionstore/test/browser_339445.js b/browser/components/sessionstore/test/browser_339445.js
deleted file mode 100644
index c38a6cb184..0000000000
--- 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 32656a8d9d..0000000000
--- a/browser/components/sessionstore/test/browser_339445_sample.html
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-Test for bug 339445
-
-storageTestItem = FAIL
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_345898.js b/browser/components/sessionstore/test/browser_345898.js
deleted file mode 100644
index bd4a46e693..0000000000
--- 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 1d87b37542..0000000000
--- 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 bf80cd7107..0000000000
--- 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 3cc89a66c6..0000000000
--- 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 c59bdcc8b7..0000000000
--- 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 1b1650e277..0000000000
--- 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, " +
- " ";
-
-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 aa74dc0616..0000000000
--- 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 83eec30702..0000000000
--- 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 75144aba11..0000000000
--- 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 584002cff8..0000000000
--- 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 6ff7e7aa3e..0000000000
--- a/browser/components/sessionstore/test/browser_423132_sample.html
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_447951.js b/browser/components/sessionstore/test/browser_447951.js
deleted file mode 100644
index a7b6a5ee84..0000000000
--- 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 00282f25ef..0000000000
--- a/browser/components/sessionstore/test/browser_447951_sample.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-Testcase for bug 447951
-
-click me
diff --git a/browser/components/sessionstore/test/browser_454908.js b/browser/components/sessionstore/test/browser_454908.js
deleted file mode 100644
index fb8206e2ff..0000000000
--- 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 02f40bf20b..0000000000
--- a/browser/components/sessionstore/test/browser_454908_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-Test for bug 454908
-
-Dummy Login
-
diff --git a/browser/components/sessionstore/test/browser_456342.js b/browser/components/sessionstore/test/browser_456342.js
deleted file mode 100644
index d7ed33ee52..0000000000
--- 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 a08777a8dc..0000000000
--- a/browser/components/sessionstore/test/browser_456342_sample.xhtml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-Test for bug 456342
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_459906.js b/browser/components/sessionstore/test/browser_459906.js
deleted file mode 100644
index cadab3e5cc..0000000000
--- 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 = "Unique: " + 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 e01aaa3394..0000000000
--- a/browser/components/sessionstore/test/browser_459906_empty.html
+++ /dev/null
@@ -1,3 +0,0 @@
-Cross Domain File for bug 459906
-
-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 39b7897766..0000000000
--- a/browser/components/sessionstore/test/browser_459906_sample.html
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
-Test for bug 459906
-
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_461634.js b/browser/components/sessionstore/test/browser_461634.js
deleted file mode 100644
index 01d3a4b0da..0000000000
--- 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 263fff5f26..0000000000
--- 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 80c9e612af..0000000000
--- a/browser/components/sessionstore/test/browser_461743_sample.html
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-
-Test for bug 461743
-
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_463205.js b/browser/components/sessionstore/test/browser_463205.js
deleted file mode 100644
index ad3f227944..0000000000
--- 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 6591401b69..0000000000
--- a/browser/components/sessionstore/test/browser_463205_sample.html
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-bug 463205
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_463206.js b/browser/components/sessionstore/test/browser_463206.js
deleted file mode 100644
index 99ee8373ee..0000000000
--- 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 0d31f29066..0000000000
--- a/browser/components/sessionstore/test/browser_463206_sample.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-Test for bug 463206
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_464199.js b/browser/components/sessionstore/test/browser_464199.js
deleted file mode 100644
index 36f07832c0..0000000000
--- 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 1f03c92c74..0000000000
--- a/browser/components/sessionstore/test/browser_464620_a.html
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
-Test for bug 464620 (injection on input)
-
-
-
-
-
-
-pending
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 9756fa7031..0000000000
--- 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 8c86d21520..0000000000
--- a/browser/components/sessionstore/test/browser_464620_b.html
+++ /dev/null
@@ -1,58 +0,0 @@
-
-
-Test for bug 464620 (injection on DOM node insertion)
-
-
-
-
-
-
-
-pending
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 cf23aa4600..0000000000
--- 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 9ec51c4c7b..0000000000
--- a/browser/components/sessionstore/test/browser_464620_xd.html
+++ /dev/null
@@ -1,5 +0,0 @@
-Cross Document File for bug 464620
-
-
- This document is editable.
-
diff --git a/browser/components/sessionstore/test/browser_465215.js b/browser/components/sessionstore/test/browser_465215.js
deleted file mode 100644
index 3a0a7b9c54..0000000000
--- 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 04f888b30e..0000000000
--- 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 0a07caa0cf..0000000000
--- 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 1d46c649a2..0000000000
--- a/browser/components/sessionstore/test/browser_466937_sample.html
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
-
-
-Test for bug 466937
-
-
-
-
-
-
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 0e990c6142..0000000000
--- 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 1a8ee3412b..0000000000
--- 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 e3ddb39b71..0000000000
--- 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 68ec9941b3..0000000000
--- 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 c2097b5930..0000000000
--- a/browser/components/sessionstore/test/browser_485482_sample.html
+++ /dev/null
@@ -1,12 +0,0 @@
-
-Test for bug 485482
-
-
-
-
-
-
-
- Check
-
-
diff --git a/browser/components/sessionstore/test/browser_485563.js b/browser/components/sessionstore/test/browser_485563.js
deleted file mode 100644
index f4e6b31cc4..0000000000
--- 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 bc680c32f8..0000000000
--- 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 ae66afe77d..0000000000
--- 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 0e088d7028..0000000000
--- 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 658f81c20a..0000000000
--- 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 44650ef8b9..0000000000
--- 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 6e5bd83bdb..0000000000
--- 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,"
- + "top
"
-
- // 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 ff80245c4b..0000000000
--- 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 50b74d6cde..0000000000
--- 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 f4d3731665..0000000000
--- 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 de53f6c92d..0000000000
--- 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 7e7fe8059c..0000000000
--- 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 d799c97401..0000000000
--- 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 d6c6245d00..0000000000
--- 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 6886be0389..0000000000
--- 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 ef048cd377..0000000000
--- 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 74ddaa9d26..0000000000
--- 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 f8727c04f8..0000000000
--- 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 b58aa649b2..0000000000
--- 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 de8f1aba00..0000000000
--- 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 041aea85ca..0000000000
--- 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 03337568e1..0000000000
--- 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 630c91f2d4..0000000000
--- 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 433e1754c5..0000000000
--- 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 6097a70db1..0000000000
--- 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 731e033071..0000000000
--- 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 fbfec53c7b..0000000000
--- 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 d2462f2bd9..0000000000
--- 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 d1f539073c..0000000000
--- 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 2b0c2f32d4..0000000000
--- 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 5d1d8f866c..0000000000
--- 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 4c2b2d24ac..0000000000
--- 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 f8ddaaf542..0000000000
--- 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 1d2c411fe0..0000000000
--- 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 6852357c2c..0000000000
--- 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 797d5d7ccb..0000000000
--- 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 ed4b03b9c8..0000000000
--- 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 0b6b8faa61..0000000000
--- 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 bdc268e6c8..0000000000
--- 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 267bccb2d0..0000000000
--- 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 85d6ff0423..0000000000
--- 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 b551fcbb3e..0000000000
--- 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 f552cbfdac..0000000000
--- 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 3b21c5b0f2..0000000000
--- 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 2509956062..0000000000
--- 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 1c1f357d76..0000000000
--- 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 41da3c2ad9..0000000000
--- 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 56826801ae..0000000000
--- 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 124a7aea9a..0000000000
--- 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 60b1dcd2e6..0000000000
--- 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 212180213e..0000000000
--- 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 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 de48fa0c9f..0000000000
--- a/browser/components/sessionstore/test/browser_662743_sample.html
+++ /dev/null
@@ -1,15 +0,0 @@
-
-Test 662743
-
-
-Select options
-
- Zero
- One
- Two
- Three
- Four
- Five
- Six
- Seven
-
\ 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 1bbaf67dc3..0000000000
--- 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 524b4969fc..0000000000
--- 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 52b95341b4..0000000000
--- 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 372ecf7ae5..0000000000
--- 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 c22e737503..0000000000
--- 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 8578428d8f..0000000000
--- 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 1bf2625ef9..0000000000
--- 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 efadcfe888..0000000000
--- 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 e12c44af4e..0000000000
--- 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 e5927caf65..0000000000
--- 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 ad317ab0c3..0000000000
--- a/browser/components/sessionstore/test/browser_739531_sample.html
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_739805.js b/browser/components/sessionstore/test/browser_739805.js
deleted file mode 100644
index f00871661a..0000000000
--- 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, ";
-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 21f916f0da..0000000000
--- 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 58b2e9ef18..0000000000
--- 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 ccc2011593..0000000000
--- a/browser/components/sessionstore/test/browser_911547_sample.html
+++ /dev/null
@@ -1,19 +0,0 @@
-
-
-
-
- Test 911547
-
-
-
-
-
-
- Test Link
-
-
-
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 4623dec303..0000000000
--- 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 3050bd4c10..0000000000
--- 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 8ab91e4dfe..0000000000
--- 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 8696a284fd..0000000000
--- 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,clickme ";
-
-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 a4cbbfbc78..0000000000
--- 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,clickme ";
-
-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 20f3463d04..0000000000
--- 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 418c055c2a..0000000000
--- 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 40c7b4e021..0000000000
--- 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 e804b177ee..0000000000
--- 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())
- * 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 81f6788560..0000000000
--- 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, "");
- 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 95984d6d0c..0000000000
--- 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 456e418829..0000000000
--- 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 921d7d3e46..0000000000
--- 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 cc5b41e4b4..0000000000
--- 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 bffbd66d97..0000000000
--- 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(" hi");
-}
diff --git a/browser/components/sessionstore/test/browser_crashedTabs.js b/browser/components/sessionstore/test/browser_crashedTabs.js
deleted file mode 100644
index 5841d536a6..0000000000
--- 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,A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,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 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 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 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 c573aa5d44..0000000000
--- 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 e4355fee3f..0000000000
--- 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," +
- " " +
- " " +
- "";
-
- // 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," +
- "" +
- "clickme " +
- "";
-
- // 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 c130ec5adb..0000000000
--- 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 3fc2e0fd4f..0000000000
--- 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 1d46d40400..0000000000
--- a/browser/components/sessionstore/test/browser_form_restore_events_sample.html
+++ /dev/null
@@ -1,99 +0,0 @@
-
-
-Test for form restore events (originally bug 476161)
-
-
-
-
-Text fields with changed text
-
-
-
-
-
-Text fields with unchanged text
-
-
-
-
-
-Textarea with changed text
-
-preset value
-
-Textarea with unchanged text
-
-preset value
-
-file field with changed value
-
-
-file field with unchanged value
-
-
-
-
-Select menu with changed selection
-
- one
- two
- three
-
-
-Select menu with unchanged selection (change event still fires)
-
- one
- two
- three
-
-
-Multiple Select menu with changed selection
-
- one
- two
- three
-
-
-Select menu with unchanged selection
-
- one
- two
- three
-
-
-checkbox with changed value
-
-
-
-checkbox with unchanged value
-
-
-
-radio with changed value
- Radio 1
- Radio 2
- Radio 3
-
-radio with unchanged value
- Radio 4
- Radio 5
- Radio 6
-
-Changed field IDs
-
-
-
diff --git a/browser/components/sessionstore/test/browser_formdata.js b/browser/components/sessionstore/test/browser_formdata.js
deleted file mode 100644
index ce12728880..0000000000
--- 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, ";
- 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," +
- "";
-
- const FORM_DATA = {
- children: [{
- xpath: {"/xhtml:html/xhtml:body/xhtml:input": "M"},
- url: "data:text/html;charset=utf-8, "
- }]
- };
-
- // 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,mozilla " +
- "";
-
- // 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 = "Mmozilla ";
- 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 = "Mmozilla ";
- 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 6e27ca970e..0000000000
--- 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 6a1b5975d0..0000000000
--- 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 f991e36575..0000000000
--- a/browser/components/sessionstore/test/browser_formdata_format_sample.html
+++ /dev/null
@@ -1,7 +0,0 @@
-
-Test formdata format
-
-
-Input fields
-
-
\ 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 6cbb54fb5b..0000000000
--- a/browser/components/sessionstore/test/browser_formdata_sample.html
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
- browser_formdata_sample.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 d69feb546d..0000000000
--- 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 682162d6a3..0000000000
--- a/browser/components/sessionstore/test/browser_formdata_xpath_sample.html
+++ /dev/null
@@ -1,37 +0,0 @@
-
-Test for bug 346337
-
-Text Fields
-
-
-
-
-Checkboxes and Radio buttons
- Check 1
- Check 2
-
- Radio 1
- Radio 2
- Radio 3
-
-
Selects
-
- Select 1
- Select 2
- Select 3
-
-
- Multi-select 1
- Multi-select 2
- Multi-select 3
- Multi-select 4
-
-
-Text Areas
-
-
-
-
-File Selector
-
-
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 e0d152f772..0000000000
--- 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 100644
index 8e7b35d7a1..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_a.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- I'm A!
-
-
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 100644
index 38b43da211..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_b.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- I'm B!
- click me first
- then click me
- Close this tab.
- Restore this tab.
- Click back.
-
-
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 100644
index 0efd7d9026..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- I'm C!
-
-
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 100644
index b55c1d45a9..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c1.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- I'm C1!
-
-
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 100644
index aec504141b..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_c2.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
- I'm C2!
-
-
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 76eeb4c4d0..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
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 e4dfb40831..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index2.html
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
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 30fd1f58ca..0000000000
--- a/browser/components/sessionstore/test/browser_frame_history_index_blank.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_frametree.js b/browser/components/sessionstore/test/browser_frametree.js
deleted file mode 100644
index a342f8c66d..0000000000
--- 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 dda129448c..0000000000
--- a/browser/components/sessionstore/test/browser_frametree_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- browser_frametree_sample.html
-
- top
-
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 e1cd087357..0000000000
--- a/browser/components/sessionstore/test/browser_frametree_sample_frameset.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
- browser_frametree_sample_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 7921548307..0000000000
--- 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 6b9e62abcd..0000000000
--- 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 db68eb0429..0000000000
--- 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 b26e86f22b..0000000000
--- 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 fc958b2934..0000000000
--- a/browser/components/sessionstore/test/browser_multiple_navigateAndRestore.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-const PAGE_1 = "data:text/html,A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,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 66dc933803..0000000000
--- 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 7abee5d9da..0000000000
--- 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 810054049b..0000000000
--- a/browser/components/sessionstore/test/browser_pageStyle_sample.html
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
- pageStyle sample
-
-
-
-
-
-
-
-
-
-
-
-
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 157609fa6c..0000000000
--- a/browser/components/sessionstore/test/browser_pageStyle_sample_nested.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- pageStyle sample (nested)
-
-
-
-
-
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 9bbb1ca762..0000000000
--- a/browser/components/sessionstore/test/browser_page_title.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-const URL = "data:text/html,initial 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 1deb461c8f..0000000000
--- 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 e734e55c9a..0000000000
--- 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 cc02e56cfa..0000000000
--- 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 28c6f6f24d..0000000000
--- 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 7dbee03fd5..0000000000
--- 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 5464a0874f..0000000000
--- 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 5767c6c0f5..0000000000
--- 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 bea6e9f472..0000000000
--- 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 e29cd5e49d..0000000000
--- 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,A%20regular,%20everyday,%20normal%20page.";
-const PAGE_2 = "data:text/html,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 865520772f..0000000000
--- 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 735a876341..0000000000
--- 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 55452e0439..0000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_readerModeArticle.html
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
-Article title
-
-
-
-
-
-
Article title
-
by Jane Doe
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
-
-
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 0182783dbb..0000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_sample.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
- browser_scrollPositions_sample.html
-
- top
-
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 c7e363fa1d..0000000000
--- a/browser/components/sessionstore/test/browser_scrollPositions_sample_frameset.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
- browser_scrollPositions_sample_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 6afd771db3..0000000000
--- 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 f4523e06a2..0000000000
--- 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,clickme ";
-
- // 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,first ";
- const URL2 = "data:text/html;charset=utf-8,second ";
-
- // 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," +
- "" +
- "clickme " +
- "clickme ";
-
- // 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," +
- "" +
- " " +
- " ";
-
- // 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 41da3c2ad9..0000000000
--- 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 7e2dccf4a9..0000000000
--- a/browser/components/sessionstore/test/browser_sessionStorage.html
+++ /dev/null
@@ -1,27 +0,0 @@
-
-
-
-
- browser_sessionStorage.html
-
-
-
-
-
diff --git a/browser/components/sessionstore/test/browser_sessionStorage.js b/browser/components/sessionstore/test/browser_sessionStorage.js
deleted file mode 100644
index b580c5cc2e..0000000000
--- 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 d1d8946119..0000000000
--- 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 1bc9537e2e..0000000000
--- 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 839f060e73..0000000000
--- 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 9eb8c260a3..0000000000
--- 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 f2f0f919cc..0000000000
--- 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 e46348e59c..0000000000
--- 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,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 768671051e..0000000000
--- 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 781692909a..0000000000
--- 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 beb8380887..0000000000
--- 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 da7bc9c08d..0000000000
--- 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 e815a6783f..0000000000
--- 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 5a8c5dbfce..0000000000
--- 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 e69de29bb2..0000000000
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 533bda36f3..0000000000
--- 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 1f5f0e54ca..0000000000
--- a/browser/components/sessionstore/test/restore_redirect_js.html
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
\ 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 6c8b3aae56..0000000000
--- a/browser/components/sessionstore/test/restore_redirect_target.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-Test page
-
-Test page
-
diff --git a/browser/components/sessionstore/test/unit/.eslintrc.js b/browser/components/sessionstore/test/unit/.eslintrc.js
deleted file mode 100644
index d35787cd2c..0000000000
--- 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 928de6a39b..0000000000
--- 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 a8c3ff2ff9..0000000000
--- 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 f9511f29f6..0000000000
--- 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 b628560124..0000000000
--- 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 fff34ad580..0000000000
--- 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 c7d8b03edc..0000000000
--- 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 b99e566e94..0000000000
--- 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 9f6df85858..0000000000
--- 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 5185b02d68..0000000000
--- 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 459acf885a..0000000000
--- 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 09980f8776..0000000000
--- 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 c764b133dc..0000000000
--- 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 8f18415c07..0000000000
--- 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 ae45218905..0000000000
--- 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 7929e80984..0000000000
--- 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 d35787cd2c..0000000000
--- 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 637db4b912..0000000000
--- 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 be00037e09..0000000000
--- 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 7c80211924..0000000000
--- 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 02fa364f10..0000000000
--- 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 afbc00282d..0000000000
--- 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 40e36123e9..0000000000
--- 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 d35787cd2c..0000000000
--- 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 00055231cf..0000000000
--- 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 bc73ac6217..0000000000
--- 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 3d748b33c1..0000000000
--- 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 69abb40245..0000000000
--- 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 51580235fa..0000000000
--- 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 0b0665a1b3..0000000000
--- 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 1cb8dcb7af..0000000000
--- 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 c764b133dc..0000000000
--- 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 6d00b69faa..0000000000
--- 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 fce3790a05..0000000000
--- 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 = " ";
-
-const XML_PREFIX = " ";
-
-// 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 054aa22e83..0000000000
--- 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} 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 fee088c179..0000000000
--- 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 b9fa0a4644..0000000000
--- a/browser/components/tests/unit/data/engine-de-DE.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-Google
-override-de-DE
-UTF-8
-
-
-
-
diff --git a/browser/components/tests/unit/distribution.ini b/browser/components/tests/unit/distribution.ini
deleted file mode 100644
index d7d2988083..0000000000
--- 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 3d4e23452b..0000000000
--- 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 a68503db30..0000000000
--- 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 183ab85d63..0000000000
--- 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 c2f461966a..0000000000
--- 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 c764b133dc..0000000000
--- 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 ce3b968559..0000000000
--- 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 = "TranslateApiException Method: TranslateArray()
Message: The Azure Market Place Translator Subscription associated with the request credentials is not in an active state.
message id=5641.V2_Rest.TranslateArray.48CC6470
";
- 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 59e4818554..0000000000
--- 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 399a67022d..0000000000
--- 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 bf68757680..0000000000
--- 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 ' 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 c16b3939c0..0000000000
--- 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 e60bc17ef7..0000000000
--- 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("Привет, мир! ", "ru");
-
- // Translate another page.
- yield translate("Hallo Welt! Bratwurst! ", "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("Hallo Welt! ", "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("Hallo Welt! ", "de", false);
- yield MetricsChecker.checkAdditions({ deniedOffers: 0 });
- gBrowser.removeTab(tab);
-});
-
-add_task(function* test_show_original() {
- let tab =
- yield translate("Hallo Welt! Bratwurst! ", "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("Hallo Welt! ", "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("Hallo Welt! ", "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 6e0af18e6c..0000000000
--- 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 f30edf52eb..0000000000
--- a/browser/components/translation/test/fixtures/bug1022725-fr.html
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
-
-
- test
-
-
- Coupe du monde de football de 2014
- 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.
-
-
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 d2d14c7885..0000000000
--- a/browser/components/translation/test/fixtures/result-da39a3ee5e.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-
-
- fr
-
- 34
-
- Football's 2014 World Cup
-
- 25
-
-
-
- fr
-
- 508
-
- 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.
-
- 475
-
-
-
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 de2f5650ef..0000000000
--- 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 d35787cd2c..0000000000
--- 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 9ebc4d7668..0000000000
--- 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 8431a8c4ef..0000000000
--- 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 ed515beab9..0000000000
--- 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 c764b133dc..0000000000
--- 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 ae027a738a..0000000000
--- 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 964be0215f..0000000000
--- 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 e74a71afa8..0000000000
--- 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 b852339f1d..0000000000
--- 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 ");
- 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 ");
- 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 ");
- 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 ");
- 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 dbdeb95895..0000000000
--- 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 a6e96e31fa..0000000000
--- 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 5ebf553b05..0000000000
--- 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 b8edf6dc44..0000000000
--- 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 5b5e883c39..0000000000
--- 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 61be1d44b1..0000000000
--- 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 1890739c46..0000000000
--- 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 which contains notifyWindow, by looking
- // through all the open windows and all the 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 b4b4356599..0000000000
--- 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 cff446573e..0000000000
--- 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 29548a4759..0000000000
--- 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 369abb1edf..0000000000
--- 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 c91d0a4f27..0000000000
--- 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 2deb08148a..0000000000
--- 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 14ac0c1f68..0000000000
--- 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 58313e74b3..0000000000
--- 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 c4117c698a..0000000000
--- 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 2b998347a4..0000000000
--- 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 36ac45a624..0000000000
--- 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 62048b1568..0000000000
--- 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 c418651201..0000000000
--- 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 5faa9db02a..0000000000
--- 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 0faa5f8629..0000000000
--- 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 32a9920ecb..0000000000
--- 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 0ee0e16863..0000000000
--- 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 2b5b994ae0..0000000000
--- 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
deleted file mode 100644
index 597c7fd2cb..0000000000
Binary files a/browser/components/uitour/test/image.png and /dev/null differ
diff --git a/browser/components/uitour/test/uitour.html b/browser/components/uitour/test/uitour.html
deleted file mode 100644
index 6c42ac7f8c..0000000000
--- a/browser/components/uitour/test/uitour.html
+++ /dev/null
@@ -1,42 +0,0 @@
-
-
-
-
- UITour test
-
-
-
-
- UITour tests
- Because Firefox is...
- Never gonna let you down
- Never gonna give you up
-
-
diff --git a/browser/extensions/formautofill/test/browser/.eslintrc.js b/browser/extensions/formautofill/test/browser/.eslintrc.js
deleted file mode 100644
index 52a2004c9d..0000000000
--- a/browser/extensions/formautofill/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = { // eslint-disable-line no-undef
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js",
- ],
-};
diff --git a/browser/extensions/formautofill/test/browser/browser.ini b/browser/extensions/formautofill/test/browser/browser.ini
deleted file mode 100644
index 5002246367..0000000000
--- a/browser/extensions/formautofill/test/browser/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[browser_check_installed.js]
diff --git a/browser/extensions/formautofill/test/browser/browser_check_installed.js b/browser/extensions/formautofill/test/browser/browser_check_installed.js
deleted file mode 100644
index b018c0f71f..0000000000
--- a/browser/extensions/formautofill/test/browser/browser_check_installed.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-
-add_task(function* test_enabled() {
- let addon = yield new Promise(
- resolve => AddonManager.getAddonByID("formautofill@mozilla.org", resolve)
- );
- isnot(addon, null, "Check addon exists");
- is(addon.version, "1.0", "Check version");
- is(addon.name, "Form Autofill", "Check name");
- ok(addon.isCompatible, "Check application compatibility");
- ok(!addon.appDisabled, "Check not app disabled");
- ok(addon.isActive, "Check addon is active");
- is(addon.type, "extension", "Check type is 'extension'");
-});
diff --git a/browser/extensions/formautofill/test/unit/.eslintrc b/browser/extensions/formautofill/test/unit/.eslintrc
deleted file mode 100644
index 8e33fb0c6c..0000000000
--- a/browser/extensions/formautofill/test/unit/.eslintrc
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ],
-}
diff --git a/browser/extensions/formautofill/test/unit/head.js b/browser/extensions/formautofill/test/unit/head.js
deleted file mode 100644
index 67e3bd60b7..0000000000
--- a/browser/extensions/formautofill/test/unit/head.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Provides infrastructure for automated login components tests.
- */
-
- /* exported importAutofillModule, getTempFile */
-
-"use strict";
-
-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://testing-common/MockDocument.jsm");
-
-// Redirect the path of the resouce in addon to the exact file path.
-let defineLazyModuleGetter = XPCOMUtils.defineLazyModuleGetter;
-XPCOMUtils.defineLazyModuleGetter = function() {
- let result = /^resource\:\/\/formautofill\/(.+)$/.exec(arguments[2]);
- if (result) {
- arguments[2] = Services.io.newFileURI(do_get_file(result[1])).spec;
- }
- return defineLazyModuleGetter.apply(this, arguments);
-};
-
-// Load the module by Service newFileURI API for running extension's XPCShell test
-function importAutofillModule(module) {
- return Cu.import(Services.io.newFileURI(do_get_file(module)).spec);
-}
-
-XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
- "resource://gre/modules/DownloadPaths.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
- "resource://gre/modules/FileUtils.jsm");
-
-// While the previous test file should have deleted all the temporary files it
-// used, on Windows these might still be pending deletion on the physical file
-// system. Thus, start from a new base number every time, to make a collision
-// with a file that is still pending deletion highly unlikely.
-let gFileCounter = Math.floor(Math.random() * 1000000);
-
-/**
- * Returns a reference to a temporary file, that is guaranteed not to exist, and
- * to have never been created before.
- *
- * @param {string} leafName
- * Suggested leaf name for the file to be created.
- *
- * @returns {nsIFile} pointing to a non-existent file in a temporary directory.
- *
- * @note It is not enough to delete the file if it exists, or to delete the file
- * after calling nsIFile.createUnique, because on Windows the delete
- * operation in the file system may still be pending, preventing a new
- * file with the same name to be created.
- */
-function getTempFile(leafName) {
- // Prepend a serial number to the extension in the suggested leaf name.
- let [base, ext] = DownloadPaths.splitBaseNameAndExtension(leafName);
- let finalLeafName = base + "-" + gFileCounter + ext;
- gFileCounter++;
-
- // Get a file reference under the temporary directory for this test file.
- let file = FileUtils.getFile("TmpD", [finalLeafName]);
- do_check_false(file.exists());
-
- do_register_cleanup(function() {
- if (file.exists()) {
- file.remove(false);
- }
- });
-
- return file;
-}
-
-add_task(function* test_common_initialize() {
- Services.prefs.setBoolPref("dom.forms.autocomplete.experimental", true);
-
- // Clean up after every test.
- do_register_cleanup(() => {
- Services.prefs.setBoolPref("dom.forms.autocomplete.experimental", false);
- });
-});
diff --git a/browser/extensions/formautofill/test/unit/test_autofillFormFields.js b/browser/extensions/formautofill/test/unit/test_autofillFormFields.js
deleted file mode 100644
index a842e84e81..0000000000
--- a/browser/extensions/formautofill/test/unit/test_autofillFormFields.js
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Test for form auto fill content helper fill all inputs function.
- */
-
-"use strict";
-
-let {FormAutofillHandler} = importAutofillModule("FormAutofillContent.jsm");
-
-const TESTCASES = [
- {
- description: "Form without autocomplete property",
- document: `
-
- `,
- fieldDetails: [],
- profileData: [],
- expectedResult: {
- "given-name": "",
- "family-name": "",
- "street-addr": "",
- "city": "",
- "country": "",
- "email": "",
- "tel": "",
- },
- },
- {
- description: "Form with autocomplete properties and 1 token",
- document: `
-
-
-
-
-
- `,
- fieldDetails: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
- {
- description: "Form with autocomplete properties and 2 tokens",
- document: `
-
-
-
-
-
- `,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
- {
- description: "Form with autocomplete properties and profile is partly matched",
- document: `
-
-
-
-
-
- `,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "2 Harrison St",
- "city": "San Francisco",
- "country": "US",
- "email": "",
- "tel": "",
- },
- },
- {
- description: "Form with autocomplete properties but mismatched",
- document: `
-
-
-
-
-
- `,
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- profileData: [
- {"section": "", "addressType": "shipping", "fieldName": "given-name", "contactType": "", "index": 0, "value": "foo"},
- {"section": "", "addressType": "shipping", "fieldName": "family-name", "contactType": "", "index": 1, "value": "bar"},
- {"section": "", "addressType": "shipping", "fieldName": "street-address", "contactType": "", "index": 2, "value": "2 Harrison St"},
- {"section": "", "addressType": "shipping", "fieldName": "address-level2", "contactType": "", "index": 3, "value": "San Francisco"},
- {"section": "", "addressType": "shipping", "fieldName": "country", "contactType": "", "index": 4, "value": "US"},
- {"section": "", "addressType": "shipping", "fieldName": "email", "contactType": "", "index": 5, "value": "foo@mozilla.com"},
- {"section": "", "addressType": "shipping", "fieldName": "tel", "contactType": "", "index": 6, "value": "1234567"},
- ],
- expectedResult: {
- "given-name": "foo",
- "family-name": "bar",
- "street-addr": "",
- "city": "",
- "country": "",
- "email": "foo@mozilla.com",
- "tel": "1234567",
- },
- },
-];
-
-for (let tc of TESTCASES) {
- (function() {
- let testcase = tc;
- add_task(function* () {
- do_print("Starting testcase: " + testcase.description);
-
- let doc = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
- let form = doc.querySelector("form");
- let handler = new FormAutofillHandler(form);
-
- handler.fieldDetails = testcase.fieldDetails;
- handler.fieldDetails.forEach((field, index) => {
- field.element = doc.querySelectorAll("input")[index];
- });
-
- handler.autofillFormFields(testcase.profileData);
- for (let id in testcase.expectedResult) {
- Assert.equal(doc.getElementById(id).value, testcase.expectedResult[id],
- "Check the " + id + " fields were filled with correct data");
- }
- });
- })();
-}
diff --git a/browser/extensions/formautofill/test/unit/test_collectFormFields.js b/browser/extensions/formautofill/test/unit/test_collectFormFields.js
deleted file mode 100644
index 52549b7464..0000000000
--- a/browser/extensions/formautofill/test/unit/test_collectFormFields.js
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Test for form auto fill content helper collectFormFields functions.
- */
-
-"use strict";
-
-let {FormAutofillHandler} = importAutofillModule("FormAutofillContent.jsm");
-
-const TESTCASES = [
- {
- description: "Form without autocomplete property",
- document: `
-
- `,
- returnedFormat: [],
- fieldDetails: [],
- },
- {
- description: "Form with autocomplete properties and 1 token",
- document: `
-
-
-
-
-
- `,
- returnedFormat: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
- {
- description: "Form with autocomplete properties and 2 tokens",
- document: `
-
-
-
-
-
- `,
- returnedFormat: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
- {
- description: "Form with autocomplete properties and profile is partly matched",
- document: `
-
-
-
-
-
- `,
- returnedFormat: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "index": 0},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "index": 1},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "index": 2},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "index": 3},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "index": 4},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "index": 5},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "index": 6},
- ],
- fieldDetails: [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "given-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "family-name", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email", "element": {}},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel", "element": {}},
- ],
- },
-];
-
-for (let tc of TESTCASES) {
- (function() {
- let testcase = tc;
- add_task(function* () {
- do_print("Starting testcase: " + testcase.description);
-
- let doc = MockDocument.createTestDocument("http://localhost:8080/test/",
- testcase.document);
- let form = doc.querySelector("form");
- let handler = new FormAutofillHandler(form);
-
- Assert.deepEqual(handler.collectFormFields(), testcase.returnedFormat,
- "Check the format of form autofill were returned correctly");
-
- Assert.deepEqual(handler.fieldDetails, testcase.fieldDetails,
- "Check the fieldDetails were set correctly");
- });
- })();
-}
diff --git a/browser/extensions/formautofill/test/unit/test_populateFieldValues.js b/browser/extensions/formautofill/test/unit/test_populateFieldValues.js
deleted file mode 100644
index 1215cbd16d..0000000000
--- a/browser/extensions/formautofill/test/unit/test_populateFieldValues.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Test for populating field values in Form Autofill Parent.
- */
-
-/* global FormAutofillParent */
-
-"use strict";
-
-importAutofillModule("FormAutofillParent.jsm");
-
-do_get_profile();
-
-const TEST_FIELDS = [
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "organization"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "street-address"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level2"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "address-level1"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "postal-code"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "country"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "tel"},
- {"section": "", "addressType": "shipping", "contactType": "", "fieldName": "email"},
-];
-
-const TEST_GUID = "test-guid";
-
-const TEST_PROFILE = {
- guid: TEST_GUID,
- organization: "World Wide Web Consortium",
- streetAddress: "32 Vassar Street\nMIT Room 32-G524",
- addressLevel2: "Cambridge",
- addressLevel1: "MA",
- postalCode: "02139",
- country: "US",
- tel: "+1 617 253 5702",
- email: "timbl@w3.org",
-};
-
-function camelCase(str) {
- return str.toLowerCase().replace(/-([a-z])/g, s => s[1].toUpperCase());
-}
-
-add_task(function* test_populateFieldValues() {
- FormAutofillParent.init();
-
- let store = FormAutofillParent.getProfileStore();
- do_check_neq(store, null);
-
- store.get = function(guid) {
- do_check_eq(guid, TEST_GUID);
- return store._clone(TEST_PROFILE);
- };
-
- let notifyUsedCalledCount = 0;
- store.notifyUsed = function(guid) {
- do_check_eq(guid, TEST_GUID);
- notifyUsedCalledCount++;
- };
-
- yield new Promise((resolve) => {
- FormAutofillParent.receiveMessage({
- name: "FormAutofill:PopulateFieldValues",
- data: {
- guid: TEST_GUID,
- fields: TEST_FIELDS,
- },
- target: {
- sendAsyncMessage: function(name, data) {
- do_check_eq(name, "FormAutofill:fillForm");
-
- let fields = data.fields;
- do_check_eq(fields.length, TEST_FIELDS.length);
-
- for (let i = 0; i < fields.length; i++) {
- do_check_eq(fields[i].fieldName, TEST_FIELDS[i].fieldName);
- do_check_eq(fields[i].value,
- TEST_PROFILE[camelCase(fields[i].fieldName)]);
- }
-
- resolve();
- },
- },
- });
- });
-
- do_check_eq(notifyUsedCalledCount, 1);
-
- FormAutofillParent._uninit();
- do_check_null(FormAutofillParent.getProfileStore());
-});
-
-add_task(function* test_populateFieldValues_with_invalid_guid() {
- FormAutofillParent.init();
-
- Assert.throws(() => {
- FormAutofillParent.receiveMessage({
- name: "FormAutofill:PopulateFieldValues",
- data: {
- guid: "invalid-guid",
- fields: TEST_FIELDS,
- },
- target: {},
- });
- }, /No matching profile\./);
-
- FormAutofillParent._uninit();
-});
diff --git a/browser/extensions/formautofill/test/unit/test_profileStorage.js b/browser/extensions/formautofill/test/unit/test_profileStorage.js
deleted file mode 100644
index 018adedb8d..0000000000
--- a/browser/extensions/formautofill/test/unit/test_profileStorage.js
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * Tests ProfileStorage object.
- */
-
-/* global ProfileStorage */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import(Services.io.newFileURI(do_get_file("ProfileStorage.jsm")).spec);
-
-const TEST_STORE_FILE_NAME = "test-profile.json";
-
-const TEST_PROFILE_1 = {
- organization: "World Wide Web Consortium",
- streetAddress: "32 Vassar Street\nMIT Room 32-G524",
- addressLevel2: "Cambridge",
- addressLevel1: "MA",
- postalCode: "02139",
- country: "US",
- tel: "+1 617 253 5702",
- email: "timbl@w3.org",
-};
-
-const TEST_PROFILE_2 = {
- streetAddress: "Some Address",
- country: "US",
-};
-
-const TEST_PROFILE_3 = {
- streetAddress: "Other Address",
- postalCode: "12345",
-};
-
-const TEST_PROFILE_WITH_INVALID_FIELD = {
- streetAddress: "Another Address",
- invalidField: "INVALID",
-};
-
-let prepareTestProfiles = Task.async(function* (path) {
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- profileStorage.add(TEST_PROFILE_1);
- profileStorage.add(TEST_PROFILE_2);
- yield profileStorage._saveImmediately();
-});
-
-let do_check_profile_matches = (profileWithMeta, profile) => {
- for (let key in profile) {
- do_check_eq(profileWithMeta[key], profile[key]);
- }
-};
-
-add_task(function* test_initialize() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- do_check_eq(profileStorage._store.data.version, 1);
- do_check_eq(profileStorage._store.data.profiles.length, 0);
-
- let data = profileStorage._store.data;
-
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- Assert.deepEqual(profileStorage._store.data, data);
-});
-
-add_task(function* test_getAll() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 2);
- do_check_profile_matches(profiles[0], TEST_PROFILE_1);
- do_check_profile_matches(profiles[1], TEST_PROFILE_2);
-
- // Modifying output shouldn't affect the storage.
- profiles[0].organization = "test";
- do_check_profile_matches(profileStorage.getAll()[0], TEST_PROFILE_1);
-});
-
-add_task(function* test_get() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[0].guid;
-
- let profile = profileStorage.get(guid);
- do_check_profile_matches(profile, TEST_PROFILE_1);
-
- // Modifying output shouldn't affect the storage.
- profile.organization = "test";
- do_check_profile_matches(profileStorage.get(guid), TEST_PROFILE_1);
-
- Assert.throws(() => profileStorage.get("INVALID_GUID"),
- /No matching profile\./);
-});
-
-add_task(function* test_add() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 2);
-
- do_check_profile_matches(profiles[0], TEST_PROFILE_1);
- do_check_profile_matches(profiles[1], TEST_PROFILE_2);
-
- do_check_neq(profiles[0].guid, undefined);
- do_check_neq(profiles[0].timeCreated, undefined);
- do_check_eq(profiles[0].timeLastModified, profiles[0].timeCreated);
- do_check_eq(profiles[0].timeLastUsed, 0);
- do_check_eq(profiles[0].timesUsed, 0);
-
- Assert.throws(() => profileStorage.add(TEST_PROFILE_WITH_INVALID_FIELD),
- /"invalidField" is not a valid field\./);
-});
-
-add_task(function* test_update() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
- let timeLastModified = profiles[1].timeLastModified;
-
- do_check_neq(profiles[1].country, undefined);
-
- profileStorage.update(guid, TEST_PROFILE_3);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profile = profileStorage.get(guid);
-
- do_check_eq(profile.country, undefined);
- do_check_neq(profile.timeLastModified, timeLastModified);
- do_check_profile_matches(profile, TEST_PROFILE_3);
-
- Assert.throws(
- () => profileStorage.update("INVALID_GUID", TEST_PROFILE_3),
- /No matching profile\./
- );
-
- Assert.throws(
- () => profileStorage.update(guid, TEST_PROFILE_WITH_INVALID_FIELD),
- /"invalidField" is not a valid field\./
- );
-});
-
-add_task(function* test_notifyUsed() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
- let timeLastUsed = profiles[1].timeLastUsed;
- let timesUsed = profiles[1].timesUsed;
-
- profileStorage.notifyUsed(guid);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profile = profileStorage.get(guid);
-
- do_check_eq(profile.timesUsed, timesUsed + 1);
- do_check_neq(profile.timeLastUsed, timeLastUsed);
-
- Assert.throws(() => profileStorage.notifyUsed("INVALID_GUID"),
- /No matching profile\./);
-});
-
-add_task(function* test_remove() {
- let path = getTempFile(TEST_STORE_FILE_NAME).path;
- yield prepareTestProfiles(path);
-
- let profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- let profiles = profileStorage.getAll();
- let guid = profiles[1].guid;
-
- do_check_eq(profiles.length, 2);
-
- profileStorage.remove(guid);
- yield profileStorage._saveImmediately();
-
- profileStorage = new ProfileStorage(path);
- yield profileStorage.initialize();
-
- profiles = profileStorage.getAll();
-
- do_check_eq(profiles.length, 1);
-
- Assert.throws(() => profileStorage.get(guid), /No matching profile\./);
-});
diff --git a/browser/extensions/formautofill/test/unit/xpcshell.ini b/browser/extensions/formautofill/test/unit/xpcshell.ini
deleted file mode 100644
index 2c57636816..0000000000
--- a/browser/extensions/formautofill/test/unit/xpcshell.ini
+++ /dev/null
@@ -1,12 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-support-files =
- ../../content/FormAutofillContent.jsm
- ../../content/FormAutofillParent.jsm
- ../../content/ProfileStorage.jsm
-
-[test_autofillFormFields.js]
-[test_collectFormFields.js]
-[test_populateFieldValues.js]
-[test_profileStorage.js]
diff --git a/browser/extensions/pdfjs/test/.eslintrc.js b/browser/extensions/pdfjs/test/.eslintrc.js
deleted file mode 100644
index c764b133dc..0000000000
--- a/browser/extensions/pdfjs/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/pdfjs/test/browser.ini b/browser/extensions/pdfjs/test/browser.ini
deleted file mode 100644
index fb4aa9afc2..0000000000
--- a/browser/extensions/pdfjs/test/browser.ini
+++ /dev/null
@@ -1,10 +0,0 @@
-[DEFAULT]
-support-files =
- file_pdfjs_test.pdf
- head.js
-
-[browser_pdfjs_main.js]
-[browser_pdfjs_navigation.js]
-[browser_pdfjs_savedialog.js]
-[browser_pdfjs_views.js]
-[browser_pdfjs_zoom.js]
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_main.js b/browser/extensions/pdfjs/test/browser_pdfjs_main.js
deleted file mode 100644
index 9660e92c17..0000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_main.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser: gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf");
-
- ok(gBrowser.isFindBarInitialized(), "Browser FindBar initialized!");
-
- yield ContentTask.spawn(newTabBrowser, null, function* () {
- //
- // Overall sanity tests
- //
- Assert.ok(content.document.querySelector('div#viewer'), "document content has viewer UI");
- Assert.ok('PDFJS' in content.wrappedJSObject, "window content has PDFJS object");
-
- //
- // Sidebar: open
- //
- var sidebar = content.document.querySelector('button#sidebarToggle'),
- outerContainer = content.document.querySelector('div#outerContainer');
-
- sidebar.click();
- Assert.ok(outerContainer.classList.contains('sidebarOpen'), "sidebar opens on click");
-
- //
- // Sidebar: close
- //
- sidebar.click();
- Assert.ok(!outerContainer.classList.contains('sidebarOpen'), "sidebar closes on click");
-
- //
- // Page change from prev/next buttons
- //
- var prevPage = content.document.querySelector('button#previous'),
- nextPage = content.document.querySelector('button#next');
-
- var pgNumber = content.document.querySelector('input#pageNumber').value;
- Assert.equal(parseInt(pgNumber, 10), 1, "initial page is 1");
-
- //
- // Bookmark button
- //
- var viewBookmark = content.document.querySelector('a#viewBookmark');
- viewBookmark.click();
-
- Assert.ok(viewBookmark.href.length > 0, "viewBookmark button has href");
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js b/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js
deleted file mode 100644
index b01a87ec81..0000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_navigation.js
+++ /dev/null
@@ -1,283 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-const PDF_OUTLINE_ITEMS = 17;
-const TESTS = [
- {
- action: {
- selector: "button#next",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to next page using NEXT button"
-
- },
- {
- action: {
- selector: "button#previous",
- event: "click"
- },
- expectedPage: 1,
- message: "navigated to previous page using PREV button"
- },
- {
- action: {
- selector: "button#next",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to next page using NEXT button"
- },
- {
- action: {
- selector: "input#pageNumber",
- value: 1,
- event: "change"
- },
- expectedPage: 1,
- message: "navigated to first page using pagenumber"
- },
- {
- action: {
- selector: "#thumbnailView a:nth-child(4)",
- event: "click"
- },
- expectedPage: 4,
- message: "navigated to 4th page using thumbnail view"
- },
- {
- action: {
- selector: "#thumbnailView a:nth-child(2)",
- event: "click"
- },
- expectedPage: 2,
- message: "navigated to 2nd page using thumbnail view"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 36
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'home' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 34
- },
- expectedPage: 2,
- message: "navigated to 2nd page using 'Page Down' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 33
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'Page Up' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 39
- },
- expectedPage: 2,
- message: "navigated to 2nd page using 'right' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 37
- },
- expectedPage: 1,
- message: "navigated to 1st page using 'left' key"
- },
- {
- action: {
- selector: "#viewer",
- event: "keydown",
- keyCode: 35
- },
- expectedPage: 5,
- message: "navigated to last page using 'home' key"
- },
- {
- action: {
- selector: ".outlineItem:nth-child(1) a",
- event: "click"
- },
- expectedPage: 1,
- message: "navigated to 1st page using outline view"
- },
- {
- action: {
- selector: ".outlineItem:nth-child(" + PDF_OUTLINE_ITEMS + ") a",
- event: "click"
- },
- expectedPage: 4,
- message: "navigated to 4th page using outline view"
- },
- {
- action: {
- selector: "input#pageNumber",
- value: 5,
- event: "change"
- },
- expectedPage: 5,
- message: "navigated to 5th page using pagenumber"
- }
-];
-
-add_task(function* test() {
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf");
-
- yield ContentTask.spawn(newTabBrowser, null, function* () {
- // Check if PDF is opened with internal viewer
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
- });
-
- yield ContentTask.spawn(newTabBrowser, null, contentSetUp);
-
- yield Task.spawn(runTests(newTabBrowser));
-
- yield ContentTask.spawn(newTabBrowser, null, function*() {
- let pageNumber = content.document.querySelector('input#pageNumber');
- Assert.equal(pageNumber.value, pageNumber.max, "Document is left on the last page");
- });
- });
-});
-
-function* contentSetUp() {
- /**
- * Outline Items gets appended to the document later on we have to
- * wait for them before we start to navigate though document
- *
- * @param document
- * @returns {deferred.promise|*}
- */
- function waitForOutlineItems(document) {
- return new Promise((resolve, reject) => {
- document.addEventListener("outlineloaded", function outlineLoaded(evt) {
- document.removeEventListener("outlineloaded", outlineLoaded);
- var outlineCount = evt.detail.outlineCount;
-
- if (document.querySelectorAll(".outlineItem").length === outlineCount) {
- resolve();
- } else {
- reject();
- }
- });
- });
- }
-
- /**
- * The key navigation has to happen in page-fit, otherwise it won't scroll
- * through a complete page
- *
- * @param document
- * @returns {deferred.promise|*}
- */
- function setZoomToPageFit(document) {
- return new Promise((resolve) => {
- document.addEventListener("pagerendered", function onZoom(e) {
- document.removeEventListener("pagerendered", onZoom);
- document.querySelector("#viewer").click();
- resolve();
- });
-
- var select = document.querySelector("select#scaleSelect");
- select.selectedIndex = 2;
- select.dispatchEvent(new Event("change"));
- });
- }
-
- yield waitForOutlineItems(content.document);
- yield setZoomToPageFit(content.document);
-}
-
-/**
- * As the page changes asynchronously, we have to wait for the event after
- * we trigger the action so we will be at the expected page number after each action
- *
- * @param document
- * @param window
- * @param test
- * @param callback
- */
-function* runTests(browser) {
- yield ContentTask.spawn(browser, TESTS, function* (TESTS) {
- let window = content;
- let document = window.document;
-
- for (let test of TESTS) {
- let deferred = {};
- deferred.promise = new Promise((resolve, reject) => {
- deferred.resolve = resolve;
- deferred.reject = reject;
- });
-
- let pageNumber = document.querySelector('input#pageNumber');
-
- // Add an event-listener to wait for page to change, afterwards resolve the promise
- let timeout = window.setTimeout(() => deferred.reject(), 5000);
- window.addEventListener('pagechange', function pageChange() {
- if (pageNumber.value == test.expectedPage) {
- window.removeEventListener('pagechange', pageChange);
- window.clearTimeout(timeout);
- deferred.resolve(+pageNumber.value);
- }
- });
-
- // Get the element and trigger the action for changing the page
- var el = document.querySelector(test.action.selector);
- Assert.ok(el, "Element '" + test.action.selector + "' has been found");
-
- // The value option is for input case
- if (test.action.value)
- el.value = test.action.value;
-
- // Dispatch the event for changing the page
- if (test.action.event == "keydown") {
- var ev = document.createEvent("KeyboardEvent");
- ev.initKeyEvent("keydown", true, true, null, false, false, false, false,
- test.action.keyCode, 0);
- el.dispatchEvent(ev);
- }
- else {
- var ev = new Event(test.action.event);
- }
- el.dispatchEvent(ev);
-
- let pgNumber = yield deferred.promise;
- Assert.equal(pgNumber, test.expectedPage, test.message);
- }
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
-}
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js b/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js
deleted file mode 100644
index a6564e5919..0000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_savedialog.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-function test() {
- var oldAction = changeMimeHandler(Ci.nsIHandlerInfo.useSystemDefault, true);
- var tab = gBrowser.addTab(TESTROOT + "file_pdfjs_test.pdf");
- //
- // Test: "Open with" dialog comes up when pdf.js is not selected as the default
- // handler.
- //
- addWindowListener('chrome://mozapps/content/downloads/unknownContentType.xul', finish);
-
- waitForExplicitFinish();
- registerCleanupFunction(function() {
- changeMimeHandler(oldAction[0], oldAction[1]);
- gBrowser.removeTab(tab);
- });
-}
-
-function changeMimeHandler(preferredAction, alwaysAskBeforeHandling) {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
- var oldAction = [handlerInfo.preferredAction, handlerInfo.alwaysAskBeforeHandling];
-
- // Change and save mime handler settings
- handlerInfo.alwaysAskBeforeHandling = alwaysAskBeforeHandling;
- handlerInfo.preferredAction = preferredAction;
- handlerService.store(handlerInfo);
-
- Services.obs.notifyObservers(null, 'pdfjs:handlerChanged', null);
-
- // Refresh data
- handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- //
- // Test: Mime handler was updated
- //
- is(handlerInfo.alwaysAskBeforeHandling, alwaysAskBeforeHandling, 'always-ask prompt change successful');
- is(handlerInfo.preferredAction, preferredAction, 'mime handler change successful');
-
- return oldAction;
-}
-
-function addWindowListener(aURL, aCallback) {
- Services.wm.addListener({
- onOpenWindow: function(aXULWindow) {
- info("window opened, waiting for focus");
- Services.wm.removeListener(this);
-
- var domwindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIDOMWindow);
- waitForFocus(function() {
- is(domwindow.document.location.href, aURL, "should have seen the right window open");
- domwindow.close();
- aCallback();
- }, domwindow);
- },
- onCloseWindow: function(aXULWindow) { },
- onWindowTitleChange: function(aXULWindow, aNewTitle) { }
- });
-}
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_views.js b/browser/extensions/pdfjs/test/browser_pdfjs_views.js
deleted file mode 100644
index d14503e415..0000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_views.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"].getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false, 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally, 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (browser) {
- // check that PDF is opened with internal viewer
- yield waitForPdfJS(browser, TESTROOT + "file_pdfjs_test.pdf");
-
- yield ContentTask.spawn(browser, null, function* () {
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
-
- //open sidebar
- var sidebar = content.document.querySelector('button#sidebarToggle');
- var outerContainer = content.document.querySelector('div#outerContainer');
-
- sidebar.click();
- Assert.ok(outerContainer.classList.contains("sidebarOpen"), "sidebar opens on click");
-
- // check that thumbnail view is open
- var thumbnailView = content.document.querySelector('div#thumbnailView');
- var outlineView = content.document.querySelector('div#outlineView');
-
- Assert.equal(thumbnailView.getAttribute("class"), null,
- "Initial view is thumbnail view");
- Assert.equal(outlineView.getAttribute("class"), "hidden",
- "Outline view is hidden initially");
-
- //switch to outline view
- var viewOutlineButton = content.document.querySelector('button#viewOutline');
- viewOutlineButton.click();
-
- Assert.equal(thumbnailView.getAttribute("class"), "hidden",
- "Thumbnail view is hidden when outline is selected");
- Assert.equal(outlineView.getAttribute("class"), "",
- "Outline view is visible when selected");
-
- //switch back to thumbnail view
- var viewThumbnailButton = content.document.querySelector('button#viewThumbnail');
- viewThumbnailButton.click();
-
- Assert.equal(thumbnailView.getAttribute("class"), "",
- "Thumbnail view is visible when selected");
- Assert.equal(outlineView.getAttribute("class"), "hidden",
- "Outline view is hidden when thumbnail is selected");
-
- sidebar.click();
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js b/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js
deleted file mode 100644
index f2b73fd994..0000000000
--- a/browser/extensions/pdfjs/test/browser_pdfjs_zoom.js
+++ /dev/null
@@ -1,154 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-requestLongerTimeout(2);
-
-Components.utils.import("resource://gre/modules/Promise.jsm", this);
-
-const RELATIVE_DIR = "browser/extensions/pdfjs/test/";
-const TESTROOT = "http://example.com/browser/" + RELATIVE_DIR;
-
-const TESTS = [
- {
- action: {
- selector: "button#zoomIn",
- event: "click"
- },
- expectedZoom: 1, // 1 - zoom in
- message: "Zoomed in using the '+' (zoom in) button"
- },
-
- {
- action: {
- selector: "button#zoomOut",
- event: "click"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed out using the '-' (zoom out) button"
- },
-
- {
- action: {
- keyboard: true,
- keyCode: 61,
- event: "+"
- },
- expectedZoom: 1, // 1 - zoom in
- message: "Zoomed in using the CTRL++ keys"
- },
-
- {
- action: {
- keyboard: true,
- keyCode: 109,
- event: "-"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed out using the CTRL+- keys"
- },
-
- {
- action: {
- selector: "select#scaleSelect",
- index: 5,
- event: "change"
- },
- expectedZoom: -1, // -1 - zoom out
- message: "Zoomed using the zoom picker"
- }
-];
-
-add_task(function* test() {
- let handlerService = Cc["@mozilla.org/uriloader/handler-service;1"]
- .getService(Ci.nsIHandlerService);
- let mimeService = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
- let handlerInfo = mimeService.getFromTypeAndExtension('application/pdf', 'pdf');
-
- // Make sure pdf.js is the default handler.
- is(handlerInfo.alwaysAskBeforeHandling, false,
- 'pdf handler defaults to always-ask is false');
- is(handlerInfo.preferredAction, Ci.nsIHandlerInfo.handleInternally,
- 'pdf handler defaults to internal');
-
- info('Pref action: ' + handlerInfo.preferredAction);
-
- yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" },
- function* (newTabBrowser) {
- yield waitForPdfJS(newTabBrowser, TESTROOT + "file_pdfjs_test.pdf" + "#zoom=100");
-
- yield ContentTask.spawn(newTabBrowser, TESTS, function* (TESTS) {
- let document = content.document;
-
- function waitForRender() {
- return new Promise((resolve) => {
- document.addEventListener("pagerendered", function onPageRendered(e) {
- if(e.detail.pageNumber !== 1) {
- return;
- }
-
- document.removeEventListener("pagerendered", onPageRendered, true);
- resolve();
- }, true);
- });
- }
-
- // check that PDF is opened with internal viewer
- Assert.ok(content.document.querySelector("div#viewer"), "document content has viewer UI");
- Assert.ok("PDFJS" in content.wrappedJSObject, "window content has PDFJS object");
-
- let initialWidth, previousWidth;
- initialWidth = previousWidth =
- parseInt(content.document.querySelector("div#pageContainer1").style.width);
-
- for (let test of TESTS) {
- // We zoom using an UI element
- var ev;
- if (test.action.selector) {
- // Get the element and trigger the action for changing the zoom
- var el = document.querySelector(test.action.selector);
- Assert.ok(el, "Element '" + test.action.selector + "' has been found");
-
- if (test.action.index){
- el.selectedIndex = test.action.index;
- }
-
- // Dispatch the event for changing the zoom
- ev = new Event(test.action.event);
- }
- // We zoom using keyboard
- else {
- // Simulate key press
- ev = new content.KeyboardEvent("keydown",
- { key: test.action.event,
- keyCode: test.action.keyCode,
- ctrlKey: true });
- el = content;
- }
-
- el.dispatchEvent(ev);
- yield waitForRender();
-
- var pageZoomScale = content.document.querySelector('select#scaleSelect');
-
- // The zoom value displayed in the zoom select
- var zoomValue = pageZoomScale.options[pageZoomScale.selectedIndex].innerHTML;
-
- let pageContainer = content.document.querySelector('div#pageContainer1');
- let actualWidth = parseInt(pageContainer.style.width);
-
- // the actual zoom of the PDF document
- let computedZoomValue = parseInt(((actualWidth/initialWidth).toFixed(2))*100) + "%";
- Assert.equal(computedZoomValue, zoomValue, "Content has correct zoom");
-
- // Check that document zooms in the expected way (in/out)
- let zoom = (actualWidth - previousWidth) * test.expectedZoom;
- Assert.ok(zoom > 0, test.message);
-
- previousWidth = actualWidth;
- }
-
- var viewer = content.wrappedJSObject.PDFViewerApplication;
- yield viewer.close();
- });
- });
-});
diff --git a/browser/extensions/pdfjs/test/file_pdfjs_test.pdf b/browser/extensions/pdfjs/test/file_pdfjs_test.pdf
deleted file mode 100644
index 7ad87e3c2e..0000000000
Binary files a/browser/extensions/pdfjs/test/file_pdfjs_test.pdf and /dev/null differ
diff --git a/browser/extensions/pdfjs/test/head.js b/browser/extensions/pdfjs/test/head.js
deleted file mode 100644
index d980bceb14..0000000000
--- a/browser/extensions/pdfjs/test/head.js
+++ /dev/null
@@ -1,15 +0,0 @@
-function waitForPdfJS(browser, url) {
- // Runs tests after all 'load' event handlers have fired off
- return ContentTask.spawn(browser, url, function* (url) {
- yield new Promise((resolve) => {
- // NB: Add the listener to the global object so that we receive the
- // event fired from the new window.
- addEventListener("documentload", function listener() {
- removeEventListener("documentload", listener, false);
- resolve();
- }, false, true);
-
- content.location = url;
- });
- });
-}
diff --git a/browser/extensions/pocket/test/.eslintrc.js b/browser/extensions/pocket/test/.eslintrc.js
deleted file mode 100644
index c764b133dc..0000000000
--- a/browser/extensions/pocket/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/pocket/test/browser.ini b/browser/extensions/pocket/test/browser.ini
deleted file mode 100644
index 1f2d8afccf..0000000000
--- a/browser/extensions/pocket/test/browser.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
- test.html
-
-[browser_pocket_ui_check.js]
diff --git a/browser/extensions/pocket/test/browser_pocket_ui_check.js b/browser/extensions/pocket/test/browser_pocket_ui_check.js
deleted file mode 100644
index 12aeaffd60..0000000000
--- a/browser/extensions/pocket/test/browser_pocket_ui_check.js
+++ /dev/null
@@ -1,61 +0,0 @@
-"use strict";
-
-function checkWindowProperties(expectPresent, l) {
- for (let name of l) {
- is(!!window.hasOwnProperty(name), expectPresent, "property " + name + (expectPresent ? " is" : " is not") + " present");
- }
-}
-function checkElements(expectPresent, l) {
- for (let id of l) {
- is(!!document.getElementById(id), expectPresent, "element " + id + (expectPresent ? " is" : " is not") + " present");
- }
-}
-
-add_task(function* test_setup() {
- let clearValue = Services.prefs.prefHasUserValue("extensions.pocket.enabled");
- let enabledOnStartup = Services.prefs.getBoolPref("extensions.pocket.enabled");
- registerCleanupFunction(() => {
- if (clearValue) {
- Services.prefs.clearUserPref("extensions.pocket.enabled");
- } else {
- Services.prefs.setBoolPref("extensions.pocket.enabled", enabledOnStartup);
- }
- });
-});
-
-add_task(function*() {
- yield promisePocketEnabled();
-
- checkWindowProperties(true, ["Pocket", "pktUI", "pktUIMessaging"]);
- checkElements(true, ["pocket-button", "panelMenu_pocket", "menu_pocket", "BMB_pocket",
- "panelMenu_pocketSeparator", "menu_pocketSeparator",
- "BMB_pocketSeparator"]);
-
- // check context menu exists
- info("checking content context menu");
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "https://example.com/browser/browser/extensions/pocket/test/test.html");
-
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let popupShown = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- let popupHidden = BrowserTestUtils.waitForEvent(contextMenu, "popuphidden");
- yield BrowserTestUtils.synthesizeMouseAtCenter("body", {
- type: "contextmenu",
- button: 2
- }, tab.linkedBrowser);
- yield popupShown;
-
- checkElements(true, ["context-pocket", "context-savelinktopocket"]);
-
- contextMenu.hidePopup();
- yield popupHidden;
- yield BrowserTestUtils.removeTab(tab);
-
- yield promisePocketDisabled();
-
- checkWindowProperties(false, ["Pocket", "pktUI", "pktUIMessaging"]);
- checkElements(false, ["pocket-button", "panelMenu_pocket", "menu_pocket", "BMB_pocket",
- "panelMenu_pocketSeparator", "menu_pocketSeparator",
- "BMB_pocketSeparator", "context-pocket", "context-savelinktopocket"]);
-
- yield promisePocketReset();
-});
diff --git a/browser/extensions/pocket/test/head.js b/browser/extensions/pocket/test/head.js
deleted file mode 100644
index e044a42c76..0000000000
--- a/browser/extensions/pocket/test/head.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Currently Pocket is disabled in tests. We want these tests to work under
-// either case that Pocket is disabled or enabled on startup of the browser,
-// and that at the end we're reset to the correct state.
-let enabledOnStartup = false;
-
-// PocketEnabled/Disabled promises return true if it was already
-// Enabled/Disabled, and false if it need to Enable/Disable.
-function promisePocketEnabled() {
- if (Services.prefs.getPrefType("extensions.pocket.enabled") != Services.prefs.PREF_INVALID &&
- Services.prefs.getBoolPref("extensions.pocket.enabled")) {
- info( "pocket was already enabled, assuming enabled by default for tests");
- enabledOnStartup = true;
- return Promise.resolve(true);
- }
- info( "pocket is not enabled");
- return new Promise((resolve, reject) => {
- let listener = {
- onWidgetAfterCreation(widgetid) {
- if (widgetid == "pocket-button") {
- info("pocket-button created");
- CustomizableUI.removeListener(listener);
- resolve(false);
- }
- }
- }
- CustomizableUI.addListener(listener);
- Services.prefs.setBoolPref("extensions.pocket.enabled", true);
- });
-}
-
-function promisePocketDisabled() {
- if (Services.prefs.getPrefType("extensions.pocket.enabled") == Services.prefs.PREF_INVALID ||
- !Services.prefs.getBoolPref("extensions.pocket.enabled")) {
- info("pocket-button already disabled");
- return Promise.resolve(true);
- }
- return new Promise((resolve, reject) => {
- let listener = {
- onWidgetDestroyed: function(widgetid) {
- if (widgetid == "pocket-button") {
- CustomizableUI.removeListener(listener);
- info( "pocket-button destroyed");
- // wait for a full unload of pocket
- BrowserTestUtils.waitForCondition(() => {
- return !window.hasOwnProperty("pktUI");
- }, "pocket properties removed from window").then(() => {
- resolve(false);
- })
- }
- }
- }
- CustomizableUI.addListener(listener);
- info("reset pocket enabled pref");
- // testing/profiles/prefs_general.js uses user_pref to disable pocket, set
- // back to false.
- Services.prefs.setBoolPref("extensions.pocket.enabled", false);
- });
-}
-
-function promisePocketReset() {
- if (enabledOnStartup) {
- info("reset is enabling pocket addon");
- return promisePocketEnabled();
- }
- info("reset is disabling pocket addon");
- return promisePocketDisabled();
-}
diff --git a/browser/extensions/pocket/test/test.html b/browser/extensions/pocket/test/test.html
deleted file mode 100644
index aa08cd566c..0000000000
--- a/browser/extensions/pocket/test/test.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
- Page Title
-
-
-
-
-
-
diff --git a/browser/extensions/webcompat/test/browser/.eslintrc.js b/browser/extensions/webcompat/test/browser/.eslintrc.js
deleted file mode 100644
index 7c80211924..0000000000
--- a/browser/extensions/webcompat/test/browser/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/extensions/webcompat/test/browser/browser.ini b/browser/extensions/webcompat/test/browser/browser.ini
deleted file mode 100644
index 5002246367..0000000000
--- a/browser/extensions/webcompat/test/browser/browser.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[browser_check_installed.js]
diff --git a/browser/extensions/webcompat/test/browser/browser_check_installed.js b/browser/extensions/webcompat/test/browser/browser_check_installed.js
deleted file mode 100644
index b774580544..0000000000
--- a/browser/extensions/webcompat/test/browser/browser_check_installed.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-add_task(function* test_enabled() {
- let addon = yield new Promise(
- resolve => AddonManager.getAddonByID("webcompat@mozilla.org", resolve)
- );
- isnot(addon, null, "Check addon exists");
- is(addon.version, "1.0", "Check version");
- is(addon.name, "Web Compat", "Check name");
- ok(addon.isCompatible, "Check application compatibility");
- ok(!addon.appDisabled, "Check not app disabled");
- ok(addon.isActive, "Check addon is active");
-});
diff --git a/browser/modules/test/.eslintrc.js b/browser/modules/test/.eslintrc.js
deleted file mode 100644
index e2d7896f8d..0000000000
--- a/browser/modules/test/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../testing/mochitest/browser.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/browser.ini b/browser/modules/test/browser.ini
deleted file mode 100644
index af624439cc..0000000000
--- a/browser/modules/test/browser.ini
+++ /dev/null
@@ -1,42 +0,0 @@
-[DEFAULT]
-support-files =
- head.js
-
-[browser_BrowserUITelemetry_buckets.js]
-[browser_BrowserUITelemetry_defaults.js]
-[browser_BrowserUITelemetry_sidebar.js]
-[browser_BrowserUITelemetry_syncedtabs.js]
-[browser_ContentSearch.js]
-skip-if = true # Bug 1308343
-support-files =
- contentSearch.js
- contentSearchBadImage.xml
- contentSearchSuggestions.sjs
- contentSearchSuggestions.xml
- !/browser/components/search/test/head.js
- !/browser/components/search/test/testEngine.xml
-[browser_NetworkPrioritizer.js]
-[browser_PermissionUI.js]
-[browser_ProcessHangNotifications.js]
-skip-if = !e10s
-[browser_SelfSupportBackend.js]
-support-files =
- ../../components/uitour/test/uitour.html
- ../../components/uitour/UITour-lib.js
-[browser_taskbar_preview.js]
-skip-if = os != "win"
-[browser_UnsubmittedCrashHandler.js]
-run-if = crashreporter
-[browser_UsageTelemetry.js]
-[browser_UsageTelemetry_private_and_restore.js]
-[browser_UsageTelemetry_urlbar.js]
-support-files =
- usageTelemetrySearchSuggestions.sjs
- usageTelemetrySearchSuggestions.xml
-[browser_UsageTelemetry_searchbar.js]
-support-files =
- usageTelemetrySearchSuggestions.sjs
- usageTelemetrySearchSuggestions.xml
-[browser_UsageTelemetry_content.js]
-[browser_UsageTelemetry_content_aboutHome.js]
-[browser_urlBar_zoom.js]
diff --git a/browser/modules/test/browser_BrowserUITelemetry_buckets.js b/browser/modules/test/browser_BrowserUITelemetry_buckets.js
deleted file mode 100644
index f557617050..0000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_buckets.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-/*
- WHERE'S MAH BUCKET?!
- \
- ___
- .-9 9 `\
- =(:(::)= ;
- |||| \
- |||| `-.
- ,\|\| `,
- / \
- ; `'---.,
- | `\
- ; / |
- \ | /
- ) \ __,.--\ /
- .-' \,..._\ \` .-' .-'
- `-=`` `: | /-/-/`
- `.__/
-*/
-
-"use strict";
-
-
-add_task(function* testBUIT() {
- let s = {};
- Components.utils.import("resource:///modules/BrowserUITelemetry.jsm", s);
- let BUIT = s.BrowserUITelemetry;
-
- registerCleanupFunction(function() {
- BUIT.setBucket(null);
- });
-
-
- // setBucket
- is(BUIT.currentBucket, BUIT.BUCKET_DEFAULT, "Bucket should be default bucket");
- BUIT.setBucket("mah-bucket");
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "mah-bucket", "Bucket should have correct name");
- BUIT.setBucket(null);
- is(BUIT.currentBucket, BUIT.BUCKET_DEFAULT, "Bucket should be reset to default");
-
-
- // _toTimeStr
- is(BUIT._toTimeStr(10), "10ms", "Checking time string reprentation, 10ms");
- is(BUIT._toTimeStr(1000 + 10), "1s10ms", "Checking time string reprentation, 1s10ms");
- is(BUIT._toTimeStr((20 * 1000) + 10), "20s10ms", "Checking time string reprentation, 20s10ms");
- is(BUIT._toTimeStr(60 * 1000), "1m", "Checking time string reprentation, 1m");
- is(BUIT._toTimeStr(3 * 60 * 1000), "3m", "Checking time string reprentation, 3m");
- is(BUIT._toTimeStr((3 * 60 * 1000) + 1), "3m1ms", "Checking time string reprentation, 3m1ms");
- is(BUIT._toTimeStr((60 * 60 * 1000) + (10 * 60 * 1000)), "1h10m", "Checking time string reprentation, 1h10m");
- is(BUIT._toTimeStr(100 * 60 * 60 * 1000), "100h", "Checking time string reprentation, 100h");
-
-
- // setExpiringBucket
- BUIT.setExpiringBucket("walrus", [1001, 2001, 3001, 10001]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "1s1ms",
- "Bucket should be expiring and have time step of 1s1ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "2s1ms");
- }, "Bucket should be expiring and have time step of 2s1ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus" + BUIT.BUCKET_SEPARATOR + "3s1ms");
- }, "Bucket should be expiring and have time step of 3s1ms");
-
-
- // Interupt previous expiring bucket
- BUIT.setExpiringBucket("walrus2", [1002, 2002]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus2" + BUIT.BUCKET_SEPARATOR + "1s2ms",
- "Should be new expiring bucket, with time step of 1s2ms");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "walrus2" + BUIT.BUCKET_SEPARATOR + "2s2ms");
- }, "Should be new expiring bucket, with time step of 2s2ms");
-
-
- // Let expiring bucket expire
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == BUIT.BUCKET_DEFAULT;
- }, "Bucket should have expired, default bucket should now be active");
-
-
- // Interupt expiring bucket with normal bucket
- BUIT.setExpiringBucket("walrus3", [1003, 2003]);
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "walrus3" + BUIT.BUCKET_SEPARATOR + "1s3ms",
- "Should be new expiring bucket, with time step of 1s3ms");
-
- BUIT.setBucket("mah-bucket");
- is(BUIT.currentBucket, BUIT.BUCKET_PREFIX + "mah-bucket", "Bucket should have correct name");
-
- yield waitForConditionPromise(function() {
- return BUIT.currentBucket == (BUIT.BUCKET_PREFIX + "mah-bucket");
- }, "Next step of old expiring bucket shouldn't have progressed");
-});
diff --git a/browser/modules/test/browser_BrowserUITelemetry_defaults.js b/browser/modules/test/browser_BrowserUITelemetry_defaults.js
deleted file mode 100644
index ced1bbce09..0000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_defaults.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// The purpose of this test is to ensure that by default, BrowserUITelemetry
-// isn't reporting any UI customizations. This is primarily so changes to
-// customizableUI (eg, new buttons, button location changes) also have a
-// corresponding BrowserUITelemetry change.
-
-function test() {
- let s = {};
- Cu.import("resource:///modules/CustomizableUI.jsm", s);
- Cu.import("resource:///modules/BrowserUITelemetry.jsm", s);
-
- let { CustomizableUI, BrowserUITelemetry } = s;
-
- // Bug 1278176 - DevEdition never has the UI in a default state by default.
- if (!AppConstants.MOZ_DEV_EDITION) {
- Assert.ok(CustomizableUI.inDefaultState,
- "No other test should have left CUI in a dirty state.");
- }
-
- let result = BrowserUITelemetry._getWindowMeasurements(window, 0);
-
- // Bug 1278176 - DevEdition always reports the developer-button is moved.
- if (!AppConstants.MOZ_DEV_EDITION) {
- Assert.deepEqual(result.defaultMoved, []);
- }
- Assert.deepEqual(result.nondefaultAdded, []);
- // This one is a bit weird - the "social-share-button" is dynamically added
- // to the toolbar as the feature is first used - but it's listed as being in
- // the toolbar by default so it doesn't end up in nondefaultAdded once it
- // is created. The end result is that it ends up in defaultRemoved before
- // the feature has been activated.
- // Bug 1273358 exists to fix this.
- Assert.deepEqual(result.defaultRemoved, ["social-share-button"]);
-
- // And mochi insists there's only a single window with a single tab when
- // starting a test, so check that for good measure.
- Assert.deepEqual(result.visibleTabs, [1]);
-}
diff --git a/browser/modules/test/browser_BrowserUITelemetry_sidebar.js b/browser/modules/test/browser_BrowserUITelemetry_sidebar.js
deleted file mode 100644
index 5f19eabd59..0000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_sidebar.js
+++ /dev/null
@@ -1,56 +0,0 @@
-// Test the sidebar counters in BrowserUITelemetry.
-"use strict";
-
-const { BrowserUITelemetry: BUIT } = Cu.import("resource:///modules/BrowserUITelemetry.jsm", {});
-
-add_task(function* testSidebarOpenClose() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- yield SidebarUI.show("viewTabsSidebar");
-
- let counts = BUIT._countableEvents[BUIT.currentBucket];
-
- Assert.deepEqual(counts, { sidebar: { viewTabsSidebar: { show: 1 } } });
- yield SidebarUI.hide();
- Assert.deepEqual(counts, { sidebar: { viewTabsSidebar: { show: 1, hide: 1 } } });
-
- yield SidebarUI.show("viewBookmarksSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 1, hide: 1 },
- viewBookmarksSidebar: { show: 1 },
- }
- });
- // Re-open the tabs sidebar while bookmarks is open - bookmarks should
- // record a close.
- yield SidebarUI.show("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 2, hide: 1 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- yield SidebarUI.hide();
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 2, hide: 2 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- // Toggle - this will re-open viewTabsSidebar
- yield SidebarUI.toggle("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 3, hide: 2 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
- yield SidebarUI.toggle("viewTabsSidebar");
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 3, hide: 3 },
- viewBookmarksSidebar: { show: 1, hide: 1 },
- }
- });
-});
diff --git a/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js b/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
deleted file mode 100644
index d3e1eac578..0000000000
--- a/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
+++ /dev/null
@@ -1,114 +0,0 @@
-// Test the SyncedTabs counters in BrowserUITelemetry.
-"use strict";
-
-const { BrowserUITelemetry: BUIT } = Cu.import("resource:///modules/BrowserUITelemetry.jsm", {});
-const {SyncedTabs} = Cu.import("resource://services-sync/SyncedTabs.jsm", {});
-
-function mockSyncedTabs() {
- // Mock SyncedTabs.jsm
- let mockedInternal = {
- get isConfiguredToSyncTabs() { return true; },
- getTabClients() {
- return Promise.resolve([
- {
- id: "guid_desktop",
- type: "client",
- name: "My Desktop",
- tabs: [
- {
- title: "http://example.com/10",
- lastUsed: 10, // the most recent
- },
- ],
- }
- ]);
- },
- syncTabs() {
- return Promise.resolve();
- },
- hasSyncedThisSession: true,
- };
-
- let oldInternal = SyncedTabs._internal;
- SyncedTabs._internal = mockedInternal;
-
- // 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;
-
- registerCleanupFunction(() => {
- SyncedTabs._internal = oldInternal;
-
- document.getElementById("sync-reauth-state").hidden = true;
- document.getElementById("sync-setup-state").hidden = false;
- document.getElementById("sync-syncnow-state").hidden = true;
- });
-}
-
-mockSyncedTabs();
-
-function promiseTabsUpdated() {
- return new Promise(resolve => {
- Services.obs.addObserver(function onNotification(aSubject, aTopic, aData) {
- Services.obs.removeObserver(onNotification, aTopic);
- resolve();
- }, "synced-tabs-menu:test:tabs-updated", false);
- });
-}
-
-add_task(function* test_menu() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- let tabsUpdated = promiseTabsUpdated();
-
- // check the button's functionality
- yield PanelUI.show();
-
- let syncButton = document.getElementById("sync-button");
- syncButton.click();
-
- yield tabsUpdated;
- // Get our 1 tab and click on it.
- let tabList = document.getElementById("PanelUI-remotetabs-tabslist");
- let tabEntry = tabList.firstChild.nextSibling;
- tabEntry.click();
-
- let counts = BUIT._countableEvents[BUIT.currentBucket];
- Assert.deepEqual(counts, {
- "click-builtin-item": { "sync-button": { left: 1 } },
- "synced-tabs": { open: { "toolbarbutton-subview": 1 } },
- });
-});
-
-add_task(function* test_sidebar() {
- // Reset BrowserUITelemetry's world.
- BUIT._countableEvents = {};
-
- yield SidebarUI.show('viewTabsSidebar');
-
- let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
-
- syncedTabsDeckComponent._accountStatus = () => Promise.resolve(true);
-
- // Once the tabs container has been selected (which here means "'selected'
- // added to the class list") we are ready to test.
- let container = SidebarUI.browser.contentDocument.querySelector(".tabs-container");
- let promiseUpdated = BrowserTestUtils.waitForAttribute("class", container);
-
- yield syncedTabsDeckComponent.updatePanel();
- yield promiseUpdated;
-
- let selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
- let tab = selectedPanel.querySelector(".tab");
- tab.click();
- let counts = BUIT._countableEvents[BUIT.currentBucket];
- Assert.deepEqual(counts, {
- sidebar: {
- viewTabsSidebar: { show: 1 },
- },
- "synced-tabs": { open: { sidebar: 1 } }
- });
- yield SidebarUI.hide();
-});
diff --git a/browser/modules/test/browser_ContentSearch.js b/browser/modules/test/browser_ContentSearch.js
deleted file mode 100644
index 97bd6ac516..0000000000
--- a/browser/modules/test/browser_ContentSearch.js
+++ /dev/null
@@ -1,425 +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_MSG = "ContentSearchTest";
-const CONTENT_SEARCH_MSG = "ContentSearch";
-const TEST_CONTENT_SCRIPT_BASENAME = "contentSearch.js";
-
-// This timeout is absurdly high to avoid random failures like bug 1087120.
-// That bug was reported when the timeout was 5 seconds, so let's try 10.
-const SUGGESTIONS_TIMEOUT = 10000;
-
-var gMsgMan;
-/* eslint no-undef:"error" */
-/* import-globals-from ../../components/search/test/head.js */
-Services.scriptloader.loadSubScript(
- "chrome://mochitests/content/browser/browser/components/search/test/head.js",
- this);
-
-let originalEngine = Services.search.currentEngine;
-
-add_task(function* setup() {
- yield promiseNewEngine("testEngine.xml", {
- setAsCurrent: true,
- testPath: "chrome://mochitests/content/browser/browser/components/search/test/",
- });
-
- registerCleanupFunction(() => {
- Services.search.currentEngine = originalEngine;
- });
-});
-
-add_task(function* GetState() {
- yield addTab();
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetState",
- });
- let msg = yield waitForTestMsg("State");
- checkMsg(msg, {
- type: "State",
- data: yield currentStateObj(),
- });
-});
-
-add_task(function* SetCurrentEngine() {
- yield addTab();
- let newCurrentEngine = null;
- let oldCurrentEngine = Services.search.currentEngine;
- let engines = Services.search.getVisibleEngines();
- for (let engine of engines) {
- if (engine != oldCurrentEngine) {
- newCurrentEngine = engine;
- break;
- }
- }
- if (!newCurrentEngine) {
- info("Couldn't find a non-selected search engine, " +
- "skipping this part of the test");
- return;
- }
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "SetCurrentEngine",
- data: newCurrentEngine.name,
- });
- let deferred = Promise.defer();
- Services.obs.addObserver(function obs(subj, topic, data) {
- info("Test observed " + data);
- if (data == "engine-current") {
- ok(true, "Test observed engine-current");
- Services.obs.removeObserver(obs, "browser-search-engine-modified");
- deferred.resolve();
- }
- }, "browser-search-engine-modified", false);
- let searchPromise = waitForTestMsg("CurrentEngine");
- info("Waiting for test to observe engine-current...");
- yield deferred.promise;
- let msg = yield searchPromise;
- checkMsg(msg, {
- type: "CurrentEngine",
- data: yield currentEngineObj(newCurrentEngine),
- });
-
- Services.search.currentEngine = oldCurrentEngine;
- msg = yield waitForTestMsg("CurrentEngine");
- checkMsg(msg, {
- type: "CurrentEngine",
- data: yield currentEngineObj(oldCurrentEngine),
- });
-});
-
-add_task(function* modifyEngine() {
- yield addTab();
- let engine = Services.search.currentEngine;
- let oldAlias = engine.alias;
- engine.alias = "ContentSearchTest";
- let msg = yield waitForTestMsg("CurrentState");
- checkMsg(msg, {
- type: "CurrentState",
- data: yield currentStateObj(),
- });
- engine.alias = oldAlias;
- msg = yield waitForTestMsg("CurrentState");
- checkMsg(msg, {
- type: "CurrentState",
- data: yield currentStateObj(),
- });
-});
-
-add_task(function* search() {
- yield addTab();
- let engine = Services.search.currentEngine;
- let data = {
- engineName: engine.name,
- searchString: "ContentSearchTest",
- healthReportKey: "ContentSearchTest",
- searchPurpose: "ContentSearchTest",
- };
- let submissionURL =
- engine.getSubmission(data.searchString, "", data.whence).uri.spec;
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "Search",
- data: data,
- expectedURL: submissionURL,
- });
- let msg = yield waitForTestMsg("loadStopped");
- Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
-});
-
-add_task(function* searchInBackgroundTab() {
- // This test is like search(), but it opens a new tab after starting a search
- // in another. In other words, it performs a search in a background tab. The
- // search page should be loaded in the same tab that performed the search, in
- // the background tab.
- yield addTab();
- let engine = Services.search.currentEngine;
- let data = {
- engineName: engine.name,
- searchString: "ContentSearchTest",
- healthReportKey: "ContentSearchTest",
- searchPurpose: "ContentSearchTest",
- };
- let submissionURL =
- engine.getSubmission(data.searchString, "", data.whence).uri.spec;
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "Search",
- data: data,
- expectedURL: submissionURL,
- });
-
- let newTab = gBrowser.addTab();
- gBrowser.selectedTab = newTab;
- registerCleanupFunction(() => gBrowser.removeTab(newTab));
-
- let msg = yield waitForTestMsg("loadStopped");
- Assert.equal(msg.data.url, submissionURL, "Correct search page loaded");
-});
-
-add_task(function* badImage() {
- yield addTab();
- // If the bad image URI caused an exception to be thrown within ContentSearch,
- // then we'll hang waiting for the CurrentState responses triggered by the new
- // engine. That's what we're testing, and obviously it shouldn't happen.
- let vals = yield waitForNewEngine("contentSearchBadImage.xml", 1);
- let engine = vals[0];
- let finalCurrentStateMsg = vals[vals.length - 1];
- let expectedCurrentState = yield currentStateObj();
- let expectedEngine =
- expectedCurrentState.engines.find(e => e.name == engine.name);
- ok(!!expectedEngine, "Sanity check: engine should be in expected state");
- ok(expectedEngine.iconBuffer === null,
- "Sanity check: icon array buffer of engine in expected state " +
- "should be null: " + expectedEngine.iconBuffer);
- checkMsg(finalCurrentStateMsg, {
- type: "CurrentState",
- data: expectedCurrentState,
- });
- // Removing the engine triggers a final CurrentState message. Wait for it so
- // it doesn't trip up subsequent tests.
- Services.search.removeEngine(engine);
- yield waitForTestMsg("CurrentState");
-});
-
-add_task(function* GetSuggestions_AddFormHistoryEntry_RemoveFormHistoryEntry() {
- yield addTab();
-
- // Add the test engine that provides suggestions.
- let vals = yield waitForNewEngine("contentSearchSuggestions.xml", 0);
- let engine = vals[0];
-
- let searchStr = "browser_ContentSearch.js-suggestions-";
-
- // Add a form history suggestion and wait for Satchel to notify about it.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "AddFormHistoryEntry",
- data: searchStr + "form",
- });
- let deferred = Promise.defer();
- Services.obs.addObserver(function onAdd(subj, topic, data) {
- if (data == "formhistory-add") {
- Services.obs.removeObserver(onAdd, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
- yield deferred.promise;
-
- // Send GetSuggestions using the test engine. Its suggestions should appear
- // in the remote suggestions in the Suggestions response below.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetSuggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- remoteTimeout: SUGGESTIONS_TIMEOUT,
- },
- });
-
- // Check the Suggestions response.
- let msg = yield waitForTestMsg("Suggestions");
- checkMsg(msg, {
- type: "Suggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- formHistory: [searchStr + "form"],
- remote: [searchStr + "foo", searchStr + "bar"],
- },
- });
-
- // Delete the form history suggestion and wait for Satchel to notify about it.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "RemoveFormHistoryEntry",
- data: searchStr + "form",
- });
- deferred = Promise.defer();
- Services.obs.addObserver(function onRemove(subj, topic, data) {
- if (data == "formhistory-remove") {
- Services.obs.removeObserver(onRemove, "satchel-storage-changed");
- executeSoon(() => deferred.resolve());
- }
- }, "satchel-storage-changed", false);
- yield deferred.promise;
-
- // Send GetSuggestions again.
- gMsgMan.sendAsyncMessage(TEST_MSG, {
- type: "GetSuggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- remoteTimeout: SUGGESTIONS_TIMEOUT,
- },
- });
-
- // The formHistory suggestions in the Suggestions response should be empty.
- msg = yield waitForTestMsg("Suggestions");
- checkMsg(msg, {
- type: "Suggestions",
- data: {
- engineName: engine.name,
- searchString: searchStr,
- formHistory: [],
- remote: [searchStr + "foo", searchStr + "bar"],
- },
- });
-
- // Finally, clean up by removing the test engine.
- Services.search.removeEngine(engine);
- yield waitForTestMsg("CurrentState");
-});
-
-function buffersEqual(actualArrayBuffer, expectedArrayBuffer) {
- let expectedView = new Int8Array(expectedArrayBuffer);
- let actualView = new Int8Array(actualArrayBuffer);
- for (let i = 0; i < expectedView.length; i++) {
- if (actualView[i] != expectedView[i]) {
- return false;
- }
- }
- return true;
-}
-
-function arrayBufferEqual(actualArrayBuffer, expectedArrayBuffer) {
- ok(actualArrayBuffer instanceof ArrayBuffer, "Actual value is ArrayBuffer.");
- ok(expectedArrayBuffer instanceof ArrayBuffer, "Expected value is ArrayBuffer.");
- Assert.equal(actualArrayBuffer.byteLength, expectedArrayBuffer.byteLength,
- "Array buffers have the same length.");
- ok(buffersEqual(actualArrayBuffer, expectedArrayBuffer), "Buffers are equal.");
-}
-
-function checkArrayBuffers(actual, expected) {
- if (actual instanceof ArrayBuffer) {
- arrayBufferEqual(actual, expected);
- }
- if (typeof actual == "object") {
- for (let i in actual) {
- checkArrayBuffers(actual[i], expected[i]);
- }
- }
-}
-
-function checkMsg(actualMsg, expectedMsgData) {
- let actualMsgData = actualMsg.data;
- SimpleTest.isDeeply(actualMsg.data, expectedMsgData, "Checking message");
-
- // Engines contain ArrayBuffers which we have to compare byte by byte and
- // not as Objects (like SimpleTest.isDeeply does).
- checkArrayBuffers(actualMsgData, expectedMsgData);
-}
-
-function waitForMsg(name, type) {
- let deferred = Promise.defer();
- info("Waiting for " + name + " message " + type + "...");
- gMsgMan.addMessageListener(name, function onMsg(msg) {
- info("Received " + name + " message " + msg.data.type + "\n");
- if (msg.data.type == type) {
- gMsgMan.removeMessageListener(name, onMsg);
- deferred.resolve(msg);
- }
- });
- return deferred.promise;
-}
-
-function waitForTestMsg(type) {
- return waitForMsg(TEST_MSG, type);
-}
-
-function waitForNewEngine(basename, numImages) {
- info("Waiting for engine to be added: " + basename);
-
- // Wait for the search events triggered by adding the new engine.
- // engine-added engine-loaded
- let expectedSearchEvents = ["CurrentState", "CurrentState"];
- // engine-changed for each of the images
- for (let i = 0; i < numImages; i++) {
- expectedSearchEvents.push("CurrentState");
- }
- let eventPromises = expectedSearchEvents.map(e => waitForTestMsg(e));
-
- // Wait for addEngine().
- let addDeferred = Promise.defer();
- let url = getRootDirectory(gTestPath) + basename;
- Services.search.addEngine(url, null, "", false, {
- onSuccess: function (engine) {
- info("Search engine added: " + basename);
- addDeferred.resolve(engine);
- },
- onError: function (errCode) {
- ok(false, "addEngine failed with error code " + errCode);
- addDeferred.reject();
- },
- });
-
- return Promise.all([addDeferred.promise].concat(eventPromises));
-}
-
-function addTab() {
- let deferred = Promise.defer();
- let tab = gBrowser.addTab();
- gBrowser.selectedTab = tab;
- tab.linkedBrowser.addEventListener("load", function load() {
- tab.linkedBrowser.removeEventListener("load", load, true);
- let url = getRootDirectory(gTestPath) + TEST_CONTENT_SCRIPT_BASENAME;
- gMsgMan = tab.linkedBrowser.messageManager;
- gMsgMan.sendAsyncMessage(CONTENT_SEARCH_MSG, {
- type: "AddToWhitelist",
- data: ["about:blank"],
- });
- waitForMsg(CONTENT_SEARCH_MSG, "AddToWhitelistAck").then(() => {
- gMsgMan.loadFrameScript(url, false);
- deferred.resolve();
- });
- }, true);
- registerCleanupFunction(() => gBrowser.removeTab(tab));
- return deferred.promise;
-}
-
-var currentStateObj = Task.async(function* () {
- let state = {
- engines: [],
- currentEngine: yield currentEngineObj(),
- };
- for (let engine of Services.search.getVisibleEngines()) {
- let uri = engine.getIconURLBySize(16, 16);
- state.engines.push({
- name: engine.name,
- iconBuffer: yield arrayBufferFromDataURI(uri),
- hidden: false,
- });
- }
- return state;
-});
-
-var currentEngineObj = Task.async(function* () {
- let engine = Services.search.currentEngine;
- let uriFavicon = engine.getIconURLBySize(16, 16);
- let bundle = Services.strings.createBundle("chrome://global/locale/autocomplete.properties");
- return {
- name: engine.name,
- placeholder: bundle.formatStringFromName("searchWithEngine", [engine.name], 1),
- iconBuffer: yield arrayBufferFromDataURI(uriFavicon),
- };
-});
-
-function arrayBufferFromDataURI(uri) {
- if (!uri) {
- return Promise.resolve(null);
- }
- let deferred = Promise.defer();
- let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].
- createInstance(Ci.nsIXMLHttpRequest);
- xhr.open("GET", uri, true);
- xhr.responseType = "arraybuffer";
- xhr.onerror = () => {
- deferred.resolve(null);
- };
- xhr.onload = () => {
- deferred.resolve(xhr.response);
- };
- try {
- xhr.send();
- }
- catch (err) {
- return Promise.resolve(null);
- }
- return deferred.promise;
-}
diff --git a/browser/modules/test/browser_NetworkPrioritizer.js b/browser/modules/test/browser_NetworkPrioritizer.js
deleted file mode 100644
index 91557b0fdb..0000000000
--- a/browser/modules/test/browser_NetworkPrioritizer.js
+++ /dev/null
@@ -1,165 +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 for NetworkPrioritizer.jsm (Bug 514490) **/
-
-const LOWEST = Ci.nsISupportsPriority.PRIORITY_LOWEST;
-const LOW = Ci.nsISupportsPriority.PRIORITY_LOW;
-const NORMAL = Ci.nsISupportsPriority.PRIORITY_NORMAL;
-const HIGH = Ci.nsISupportsPriority.PRIORITY_HIGH;
-const HIGHEST = Ci.nsISupportsPriority.PRIORITY_HIGHEST;
-
-const DELTA = NORMAL - LOW; // lower value means higher priority
-
-// Test helper functions.
-// getPriority and setPriority can take a tab or a Browser
-function* getPriority(aBrowser) {
- if (aBrowser.localName == "tab")
- aBrowser = aBrowser.linkedBrowser;
-
- return yield ContentTask.spawn(aBrowser, null, function* () {
- return docShell.QueryInterface(Components.interfaces.nsIWebNavigation)
- .QueryInterface(Components.interfaces.nsIDocumentLoader)
- .loadGroup
- .QueryInterface(Components.interfaces.nsISupportsPriority)
- .priority;
- });
-}
-
-function* setPriority(aBrowser, aPriority) {
- if (aBrowser.localName == "tab")
- aBrowser = aBrowser.linkedBrowser;
-
- yield ContentTask.spawn(aBrowser, aPriority, function* (aPriority) {
- docShell.QueryInterface(Components.interfaces.nsIWebNavigation)
- .QueryInterface(Components.interfaces.nsIDocumentLoader)
- .loadGroup
- .QueryInterface(Ci.nsISupportsPriority)
- .priority = aPriority;
- });
-}
-
-function* isWindowState(aWindow, aTabPriorities) {
- let browsers = aWindow.gBrowser.browsers;
- // Make sure we have the right number of tabs & priorities
- is(browsers.length, aTabPriorities.length,
- "Window has expected number of tabs");
- // aState should be in format [ priority, priority, priority ]
- for (let i = 0; i < browsers.length; i++) {
- is(yield getPriority(browsers[i]), aTabPriorities[i],
- "Tab " + i + " had expected priority");
- }
-}
-
-function promiseWaitForFocus(aWindow) {
- return new Promise((resolve) => {
- waitForFocus(resolve, aWindow);
- });
-}
-
-add_task(function*() {
- // This is the real test. It creates multiple tabs & windows, changes focus,
- // closes windows/tabs to make sure we behave correctly.
- // This test assumes that no priorities have been adjusted and the loadgroup
- // priority starts at 0.
-
- // Call window "window_A" to make the test easier to follow
- let window_A = window;
-
- // Test 1 window, 1 tab case.
- yield isWindowState(window_A, [HIGH]);
-
- // Exising tab is tab_A1
- let tab_A2 = window_A.gBrowser.addTab("http://example.com");
- let tab_A3 = window_A.gBrowser.addTab("about:config");
- yield BrowserTestUtils.browserLoaded(tab_A3.linkedBrowser);
-
- // tab_A2 isn't focused yet
- yield isWindowState(window_A, [HIGH, NORMAL, NORMAL]);
-
- // focus tab_A2 & make sure priority got updated
- window_A.gBrowser.selectedTab = tab_A2;
- yield isWindowState(window_A, [NORMAL, HIGH, NORMAL]);
-
- window_A.gBrowser.removeTab(tab_A2);
- // Next tab is auto selected synchronously as part of removeTab, and we
- // expect the priority to be updated immediately.
- yield isWindowState(window_A, [NORMAL, HIGH]);
-
- // Open another window then play with focus
- let window_B = yield BrowserTestUtils.openNewBrowserWindow();
-
- yield promiseWaitForFocus(window_B);
- yield isWindowState(window_A, [LOW, NORMAL]);
- yield isWindowState(window_B, [HIGH]);
-
- yield promiseWaitForFocus(window_A);
- yield isWindowState(window_A, [NORMAL, HIGH]);
- yield isWindowState(window_B, [NORMAL]);
-
- yield promiseWaitForFocus(window_B);
- yield isWindowState(window_A, [LOW, NORMAL]);
- yield isWindowState(window_B, [HIGH]);
-
- // Cleanup
- window_A.gBrowser.removeTab(tab_A3);
- yield BrowserTestUtils.closeWindow(window_B);
-});
-
-add_task(function*() {
- // This is more a test of nsLoadGroup and how it handles priorities. But since
- // we depend on its behavior, it's good to test it. This is testing that there
- // are no errors if we adjust beyond nsISupportsPriority's bounds.
-
- yield promiseWaitForFocus();
-
- let tab1 = gBrowser.tabs[0];
- let oldPriority = yield getPriority(tab1);
-
- // Set the priority of tab1 to the lowest possible. Selecting the other tab
- // will try to lower it
- yield setPriority(tab1, LOWEST);
-
- let tab2 = gBrowser.addTab("http://example.com");
- yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser);
- gBrowser.selectedTab = tab2;
- is(yield getPriority(tab1), LOWEST - DELTA, "Can adjust priority beyond 'lowest'");
-
- // Now set priority to "highest" and make sure that no errors occur.
- yield setPriority(tab1, HIGHEST);
- gBrowser.selectedTab = tab1;
-
- is(yield getPriority(tab1), HIGHEST + DELTA, "Can adjust priority beyond 'highest'");
-
- // Cleanup
- gBrowser.removeTab(tab2);
- yield setPriority(tab1, oldPriority);
-});
-
-add_task(function*() {
- // This tests that the priority doesn't get lost when switching the browser's remoteness
-
- if (!gMultiProcessBrowser) {
- return;
- }
-
- let browser = gBrowser.selectedBrowser;
-
- browser.loadURI("http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(browser.isRemoteBrowser, "web page should be loaded in remote browser");
- is(yield getPriority(browser), HIGH, "priority of selected tab should be 'high'");
-
- browser.loadURI("about:rights");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(!browser.isRemoteBrowser, "about:rights should switch browser to non-remote");
- is(yield getPriority(browser), HIGH,
- "priority of selected tab should be 'high' when going from remote to non-remote");
-
- browser.loadURI("http://example.com");
- yield BrowserTestUtils.browserLoaded(browser);
- ok(browser.isRemoteBrowser, "going from about:rights to web page should switch browser to remote");
- is(yield getPriority(browser), HIGH,
- "priority of selected tab should be 'high' when going from non-remote to remote");
-});
diff --git a/browser/modules/test/browser_PermissionUI.js b/browser/modules/test/browser_PermissionUI.js
deleted file mode 100644
index 006bc5e664..0000000000
--- a/browser/modules/test/browser_PermissionUI.js
+++ /dev/null
@@ -1,445 +0,0 @@
-/**
- * These tests test the ability for the PermissionUI module to open
- * permission prompts to the user. It also tests to ensure that
- * add-ons can introduce their own permission prompts.
- */
-
-"use strict";
-
-Cu.import("resource://gre/modules/Integration.jsm", this);
-Cu.import("resource:///modules/PermissionUI.jsm", this);
-
-/**
- * Given a at some non-internal web page,
- * return something that resembles an nsIContentPermissionRequest,
- * using the browsers currently loaded document to get a principal.
- *
- * @param browser ()
- * The browser that we'll create a nsIContentPermissionRequest
- * for.
- * @returns A nsIContentPermissionRequest-ish object.
- */
-function makeMockPermissionRequest(browser) {
- let result = {
- types: null,
- principal: browser.contentPrincipal,
- requester: null,
- _cancelled: false,
- cancel() {
- this._cancelled = true;
- },
- _allowed: false,
- allow() {
- this._allowed = true;
- },
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPermissionRequest]),
- };
-
- // In the e10s-case, nsIContentPermissionRequest will have
- // element defined. window is defined otherwise.
- if (browser.isRemoteBrowser) {
- result.element = browser;
- } else {
- result.window = browser.contentWindow;
- }
-
- return result;
-}
-
-/**
- * For an opened PopupNotification, clicks on the main action,
- * and waits for the panel to fully close.
- *
- * @return {Promise}
- * Resolves once the panel has fired the "popuphidden"
- * event.
- */
-function clickMainAction() {
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- let popupNotification = getPopupNotificationNode();
- popupNotification.button.click();
- return removePromise;
-}
-
-/**
- * For an opened PopupNotification, clicks on a secondary action,
- * and waits for the panel to fully close.
- *
- * @param {int} index
- * The 0-indexed index of the secondary menuitem to choose.
- * @return {Promise}
- * Resolves once the panel has fired the "popuphidden"
- * event.
- */
-function clickSecondaryAction(index) {
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- let popupNotification = getPopupNotificationNode();
- let menuitems = popupNotification.children;
- menuitems[index].click();
- return removePromise;
-}
-
-/**
- * Makes sure that 1 (and only 1) is being displayed
- * by PopupNotification, and then returns that .
- *
- * @return {}
- */
-function getPopupNotificationNode() {
- // PopupNotification is a bit overloaded here, so to be
- // clear, popupNotifications is a list of
- // nodes.
- let popupNotifications = PopupNotifications.panel.childNodes;
- Assert.equal(popupNotifications.length, 1,
- "Should be showing a ");
- return popupNotifications[0];
-}
-
-/**
- * Tests the PermissionPromptForRequest prototype to ensure that a prompt
- * can be displayed. Does not test permission handling.
- */
-add_task(function* test_permission_prompt_for_request() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- let mainAction = {
- label: "Main",
- accessKey: "M",
- };
- let secondaryAction = {
- label: "Secondary",
- accessKey: "S",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
- Assert.ok(notification, "Should have gotten the notification");
-
- Assert.equal(notification.message, kTestMessage,
- "Should be showing the right message");
- Assert.equal(notification.mainAction.label, mainAction.label,
- "The main action should have the right label");
- Assert.equal(notification.mainAction.accessKey, mainAction.accessKey,
- "The main action should have the right access key");
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- Assert.equal(notification.secondaryActions[0].label, secondaryAction.label,
- "The secondary action should have the right label");
- Assert.equal(notification.secondaryActions[0].accessKey,
- secondaryAction.accessKey,
- "The secondary action should have the right access key");
- Assert.ok(notification.options.displayURI.equals(mockRequest.principal.URI),
- "Should be showing the URI of the requesting page");
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that if the PermissionPrompt sets displayURI to false in popupOptions,
- * then there is no URI shown on the popupnotification.
- */
-add_task(function* test_permission_prompt_for_popupOptions() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com/",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- let mainAction = {
- label: "Main",
- accessKey: "M",
- };
- let secondaryAction = {
- label: "Secondary",
- accessKey: "S",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- popupOptions: {
- displayURI: false,
- },
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- Assert.ok(!notification.options.displayURI,
- "Should not show the URI of the requesting page");
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that if the PermissionPrompt has the permissionKey
- * set that permissions can be set properly by the user. Also
- * ensures that callbacks for promptActions are properly fired.
- */
-add_task(function* test_with_permission_key() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
- const kTestPermissionKey = "test-permission-key";
-
- let allowed = false;
- let mainAction = {
- label: "Allow",
- accessKey: "M",
- action: Ci.nsIPermissionManager.ALLOW_ACTION,
- expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION,
- callback: function() {
- allowed = true;
- }
- };
-
- let denied = false;
- let secondaryAction = {
- label: "Deny",
- accessKey: "D",
- action: Ci.nsIPermissionManager.DENY_ACTION,
- expiryType: Ci.nsIPermissionManager.EXPIRE_SESSION,
- callback: function() {
- denied = true;
- }
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let principal = mockRequest.principal;
- registerCleanupFunction(function() {
- Services.perms.removeFromPrincipal(principal, kTestPermissionKey);
- });
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- permissionKey: kTestPermissionKey,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
- Assert.ok(notification, "Should have gotten the notification");
-
- let curPerm =
- Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.UNKNOWN_ACTION,
- "Should be no permission set to begin with.");
-
- // First test denying the permission request.
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- yield clickSecondaryAction(0);
- curPerm = Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.DENY_ACTION,
- "Should have denied the action");
- Assert.ok(denied, "The secondaryAction callback should have fired");
- Assert.ok(!allowed, "The mainAction callback should not have fired");
- Assert.ok(mockRequest._cancelled,
- "The request should have been cancelled");
- Assert.ok(!mockRequest._allowed,
- "The request should not have been allowed");
-
- // Clear the permission and pretend we never denied
- Services.perms.removeFromPrincipal(principal, kTestPermissionKey);
- denied = false;
- mockRequest._cancelled = false;
-
- // Bring the PopupNotification back up now...
- shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
-
- // Next test allowing the permission request.
- yield clickMainAction();
- curPerm = Services.perms.testPermissionFromPrincipal(principal,
- kTestPermissionKey);
- Assert.equal(curPerm, Ci.nsIPermissionManager.ALLOW_ACTION,
- "Should have allowed the action");
- Assert.ok(!denied, "The secondaryAction callback should not have fired");
- Assert.ok(allowed, "The mainAction callback should have fired");
- Assert.ok(!mockRequest._cancelled,
- "The request should not have been cancelled");
- Assert.ok(mockRequest._allowed,
- "The request should have been allowed");
- });
-});
-
-/**
- * Tests that the onBeforeShow method will be called before
- * the popup appears.
- */
-add_task(function* test_on_before_show() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- const kTestMessage = "Test message";
-
- let mainAction = {
- label: "Test action",
- accessKey: "T",
- };
-
- let mockRequest = makeMockPermissionRequest(browser);
- let beforeShown = false;
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptForRequestPrototype,
- request: mockRequest,
- notificationID: kTestNotificationID,
- message: kTestMessage,
- promptActions: [mainAction],
- onBeforeShow() {
- beforeShown = true;
- }
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- Assert.ok(beforeShown, "Should have called onBeforeShown");
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- let removePromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popuphidden");
- notification.remove();
- yield removePromise;
- });
-});
-
-/**
- * Tests that we can open a PermissionPrompt without wrapping a
- * nsIContentPermissionRequest.
- */
-add_task(function* test_no_request() {
- yield BrowserTestUtils.withNewTab({
- gBrowser,
- url: "http://example.com",
- }, function*(browser) {
- const kTestNotificationID = "test-notification";
- let allowed = false;
- let mainAction = {
- label: "Allow",
- accessKey: "M",
- callback: function() {
- allowed = true;
- }
- };
-
- let denied = false;
- let secondaryAction = {
- label: "Deny",
- accessKey: "D",
- callback: function() {
- denied = true;
- }
- };
-
- const kTestMessage = "Test message with no request";
- let principal = browser.contentPrincipal;
- let beforeShown = false;
-
- let TestPrompt = {
- __proto__: PermissionUI.PermissionPromptPrototype,
- notificationID: kTestNotificationID,
- principal,
- browser,
- message: kTestMessage,
- promptActions: [mainAction, secondaryAction],
- onBeforeShow() {
- beforeShown = true;
- }
- };
-
- let shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- Assert.ok(beforeShown, "Should have called onBeforeShown");
- yield shownPromise;
- let notification =
- PopupNotifications.getNotification(kTestNotificationID, browser);
-
- Assert.equal(notification.message, kTestMessage,
- "Should be showing the right message");
- Assert.equal(notification.mainAction.label, mainAction.label,
- "The main action should have the right label");
- Assert.equal(notification.mainAction.accessKey, mainAction.accessKey,
- "The main action should have the right access key");
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- Assert.equal(notification.secondaryActions[0].label, secondaryAction.label,
- "The secondary action should have the right label");
- Assert.equal(notification.secondaryActions[0].accessKey,
- secondaryAction.accessKey,
- "The secondary action should have the right access key");
- Assert.ok(notification.options.displayURI.equals(principal.URI),
- "Should be showing the URI of the requesting page");
-
- // First test denying the permission request.
- Assert.equal(notification.secondaryActions.length, 1,
- "There should only be 1 secondary action");
- yield clickSecondaryAction(0);
- Assert.ok(denied, "The secondaryAction callback should have fired");
- Assert.ok(!allowed, "The mainAction callback should not have fired");
-
- shownPromise =
- BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
- TestPrompt.prompt();
- yield shownPromise;
-
- // Next test allowing the permission request.
- yield clickMainAction();
- Assert.ok(allowed, "The mainAction callback should have fired");
- });
-});
diff --git a/browser/modules/test/browser_ProcessHangNotifications.js b/browser/modules/test/browser_ProcessHangNotifications.js
deleted file mode 100644
index 597be611a7..0000000000
--- a/browser/modules/test/browser_ProcessHangNotifications.js
+++ /dev/null
@@ -1,189 +0,0 @@
-
-Cu.import("resource://gre/modules/UpdateUtils.jsm");
-
-function getNotificationBox(aWindow) {
- return aWindow.document.getElementById("high-priority-global-notificationbox");
-}
-
-function promiseNotificationShown(aWindow, aName) {
- return new Promise((resolve) => {
- let notification = getNotificationBox(aWindow);
- notification.addEventListener("AlertActive", function active() {
- notification.removeEventListener("AlertActive", active, true);
- is(notification.allNotifications.length, 1, "Notification Displayed.");
- resolve(notification);
- });
- });
-}
-
-function promiseReportCallMade(aValue) {
- return new Promise((resolve) => {
- let old = gTestHangReport.testCallback;
- gTestHangReport.testCallback = function (val) {
- gTestHangReport.testCallback = old;
- is(aValue, val, "was the correct method call made on the hang report object?");
- resolve();
- };
- });
-}
-
-function pushPrefs(...aPrefs) {
- return new Promise((resolve) => {
- SpecialPowers.pushPrefEnv({"set": aPrefs}, resolve);
- resolve();
- });
-}
-
-function popPrefs() {
- return new Promise((resolve) => {
- SpecialPowers.popPrefEnv(resolve);
- resolve();
- });
-}
-
-let gTestHangReport = {
- SLOW_SCRIPT: 1,
- PLUGIN_HANG: 2,
-
- TEST_CALLBACK_CANCELED: 1,
- TEST_CALLBACK_TERMSCRIPT: 2,
- TEST_CALLBACK_TERMPLUGIN: 3,
-
- _hangType: 1,
- _tcb: function (aCallbackType) {},
-
- get hangType() {
- return this._hangType;
- },
-
- set hangType(aValue) {
- this._hangType = aValue;
- },
-
- set testCallback(aValue) {
- this._tcb = aValue;
- },
-
- QueryInterface: function (aIID) {
- if (aIID.equals(Components.interfaces.nsIHangReport) ||
- aIID.equals(Components.interfaces.nsISupports))
- return this;
- throw Components.results.NS_NOINTERFACE;
- },
-
- userCanceled: function () {
- this._tcb(this.TEST_CALLBACK_CANCELED);
- },
-
- terminateScript: function () {
- this._tcb(this.TEST_CALLBACK_TERMSCRIPT);
- },
-
- terminatePlugin: function () {
- this._tcb(this.TEST_CALLBACK_TERMPLUGIN);
- },
-
- isReportForBrowser: function(aFrameLoader) {
- return true;
- }
-};
-
-// on dev edition we add a button for js debugging of hung scripts.
-let buttonCount = (UpdateUtils.UpdateChannel == "aurora" ? 3 : 2);
-
-/**
- * Test if hang reports receive a terminate script callback when the user selects
- * stop in response to a script hang.
- */
-
-add_task(function* terminateScriptTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- // Click the "Stop It" button, we should get a terminate script callback
- gTestHangReport.hangType = gTestHangReport.SLOW_SCRIPT;
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_TERMSCRIPT);
- buttons[0].click();
- yield promise;
-});
-
-/**
- * Test if hang reports receive user canceled callbacks after a user selects wait
- * and the browser frees up from a script hang on its own.
- */
-
-add_task(function* waitForScriptTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- yield pushPrefs(["browser.hangNotification.waitPeriod", 1000]);
-
- function nocbcheck() {
- ok(false, "received a callback?");
- }
- let oldcb = gTestHangReport.testCallback;
- gTestHangReport.testCallback = nocbcheck;
- // Click the "Wait" button this time, we shouldn't get a callback at all.
- buttons[1].click();
- gTestHangReport.testCallback = oldcb;
-
- // send another hang pulse, we should not get a notification here
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- is(notification.currentNotification, null, "no notification should be visible");
-
- gTestHangReport.testCallback = function() {};
- Services.obs.notifyObservers(gTestHangReport, "clear-hang-report", null);
- gTestHangReport.testCallback = oldcb;
-
- yield popPrefs();
-});
-
-/**
- * Test if hang reports receive user canceled callbacks after the content
- * process stops sending hang notifications.
- */
-
-add_task(function* hangGoesAwayTest() {
- yield pushPrefs(["browser.hangNotification.expiration", 1000]);
-
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- yield promise;
-
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_CANCELED);
- Services.obs.notifyObservers(gTestHangReport, "clear-hang-report", null);
- yield promise;
-
- yield popPrefs();
-});
-
-/**
- * Tests if hang reports receive a terminate plugin callback when the user selects
- * stop in response to a plugin hang.
- */
-
-add_task(function* terminatePluginTest() {
- let promise = promiseNotificationShown(window, "process-hang");
- Services.obs.notifyObservers(gTestHangReport, "process-hang-report", null);
- let notification = yield promise;
-
- let buttons = notification.currentNotification.getElementsByTagName("button");
- // Fails on aurora on-push builds, bug 1232204
- // is(buttons.length, buttonCount, "proper number of buttons");
-
- // Click the "Stop It" button, we should get a terminate script callback
- gTestHangReport.hangType = gTestHangReport.PLUGIN_HANG;
- promise = promiseReportCallMade(gTestHangReport.TEST_CALLBACK_TERMPLUGIN);
- buttons[0].click();
- yield promise;
-});
diff --git a/browser/modules/test/browser_SelfSupportBackend.js b/browser/modules/test/browser_SelfSupportBackend.js
deleted file mode 100644
index 9e2c1d1813..0000000000
--- a/browser/modules/test/browser_SelfSupportBackend.js
+++ /dev/null
@@ -1,214 +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";
-
-// Pass an empty scope object to the import to prevent "leaked window property"
-// errors in tests.
-var Preferences = Cu.import("resource://gre/modules/Preferences.jsm", {}).Preferences;
-var PromiseUtils = Cu.import("resource://gre/modules/PromiseUtils.jsm", {}).PromiseUtils;
-var SelfSupportBackend =
- Cu.import("resource:///modules/SelfSupportBackend.jsm", {}).SelfSupportBackend;
-
-const PREF_SELFSUPPORT_ENABLED = "browser.selfsupport.enabled";
-const PREF_SELFSUPPORT_URL = "browser.selfsupport.url";
-const PREF_UITOUR_ENABLED = "browser.uitour.enabled";
-
-const TEST_WAIT_RETRIES = 60;
-
-const TEST_PAGE_URL = getRootDirectory(gTestPath) + "uitour.html";
-const TEST_PAGE_URL_HTTPS = TEST_PAGE_URL.replace("chrome://mochitests/content/", "https://example.com/");
-
-function sendSessionRestoredNotification() {
- let selfSupportBackendImpl =
- Cu.import("resource:///modules/SelfSupportBackend.jsm", {}).SelfSupportBackendInternal;
- selfSupportBackendImpl.observe(null, "sessionstore-windows-restored", null);
-}
-
-/**
- * Find a browser, with an IFRAME as parent, who has aURL as the source attribute.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Object} The browser element or null on failure.
- */
-function findSelfSupportBrowser(aURL) {
- let frames = Services.appShell.hiddenDOMWindow.document.querySelectorAll('iframe');
- for (let frame of frames) {
- try {
- let browser = frame.contentDocument.getElementById("win").querySelectorAll('browser')[0];
- let url = browser.getAttribute("src");
- if (url == aURL) {
- return browser;
- }
- } catch (e) {
- continue;
- }
- }
- return null;
-}
-
-/**
- * Wait for self support page to load.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Promise} Return a promise which is resolved when SelfSupport page is fully
- * loaded.
- */
-function promiseSelfSupportLoad(aURL) {
- return new Promise((resolve, reject) => {
- // Find the SelfSupport browser.
- let browserPromise = waitForConditionPromise(() => !!findSelfSupportBrowser(aURL),
- "SelfSupport browser not found.",
- TEST_WAIT_RETRIES);
-
- // Once found, append a "load" listener to catch page loads.
- browserPromise.then(() => {
- let browser = findSelfSupportBrowser(aURL);
- if (browser.contentDocument.readyState === "complete") {
- resolve(browser);
- } else {
- let handler = () => {
- browser.removeEventListener("load", handler, true);
- resolve(browser);
- };
- browser.addEventListener("load", handler, true);
- }
- }, reject);
- });
-}
-
-/**
- * Wait for self support to close.
- *
- * @param aURL The URL to look for to identify the browser.
- *
- * @returns {Promise} Return a promise which is resolved when SelfSupport browser cannot
- * be found anymore.
- */
-function promiseSelfSupportClose(aURL) {
- return waitForConditionPromise(() => !findSelfSupportBrowser(aURL),
- "SelfSupport browser is still open.", TEST_WAIT_RETRIES);
-}
-
-/**
- * Prepare the test environment.
- */
-add_task(function* setupEnvironment() {
- // We always run the SelfSupportBackend in tests to check for weird behaviours.
- // Disable it to test its start-up.
- SelfSupportBackend.uninit();
-
- // Testing prefs are set via |user_pref|, so we need to get their value in order
- // to restore them.
- let selfSupportEnabled = Preferences.get(PREF_SELFSUPPORT_ENABLED, true);
- let uitourEnabled = Preferences.get(PREF_UITOUR_ENABLED, false);
- let selfSupportURL = Preferences.get(PREF_SELFSUPPORT_URL, "");
-
- // Enable the SelfSupport backend and set the page URL. We also make sure UITour
- // is enabled.
- Preferences.set(PREF_SELFSUPPORT_ENABLED, true);
- Preferences.set(PREF_UITOUR_ENABLED, true);
- Preferences.set(PREF_SELFSUPPORT_URL, TEST_PAGE_URL_HTTPS);
-
- // Whitelist the HTTPS page to use UITour.
- let pageURI = Services.io.newURI(TEST_PAGE_URL_HTTPS, null, null);
- Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION);
-
- registerCleanupFunction(() => {
- Services.perms.remove(pageURI, "uitour");
- Preferences.set(PREF_SELFSUPPORT_ENABLED, selfSupportEnabled);
- Preferences.set(PREF_UITOUR_ENABLED, uitourEnabled);
- Preferences.set(PREF_SELFSUPPORT_URL, selfSupportURL);
- });
-});
-
-/**
- * Test that the self support page can use the UITour API and close itself.
- */
-add_task(function* test_selfSupport() {
- // Initialise the SelfSupport backend and trigger the load.
- SelfSupportBackend.init();
-
- // SelfSupportBackend waits for "sessionstore-windows-restored" to start loading. Send it.
- info("Sending sessionstore-windows-restored");
- sendSessionRestoredNotification();
-
- // Wait for the SelfSupport page to load.
- info("Waiting for the SelfSupport local page to load.");
- let selfSupportBrowser = yield promiseSelfSupportLoad(TEST_PAGE_URL_HTTPS);
- Assert.ok(!!selfSupportBrowser, "SelfSupport browser must exist.");
-
- // Get a reference to the UITour API.
- info("Testing access to the UITour API.");
- let contentWindow =
- Cu.waiveXrays(selfSupportBrowser.contentDocument.defaultView);
- let uitourAPI = contentWindow.Mozilla.UITour;
-
- // Test the UITour API with a ping.
- let pingPromise = new Promise((resolve) => {
- uitourAPI.ping(resolve);
- });
- yield pingPromise;
- info("Ping succeeded");
-
- let observePromise = ContentTask.spawn(selfSupportBrowser, null, function* checkObserve() {
- yield new Promise(resolve => {
- let win = Cu.waiveXrays(content);
- win.Mozilla.UITour.observe((event, data) => {
- if (event != "Heartbeat:Engaged") {
- return;
- }
- Assert.equal(data.flowId, "myFlowID", "Check flowId");
- Assert.ok(!!data.timestamp, "Check timestamp");
- resolve(data);
- }, () => {});
- });
- });
-
- info("Notifying Heartbeat:Engaged");
- UITour.notify("Heartbeat:Engaged", {
- flowId: "myFlowID",
- timestamp: Date.now(),
- });
- yield observePromise;
- info("Observed in the hidden frame");
-
- // Close SelfSupport from content.
- contentWindow.close();
-
- // Wait until SelfSupport closes.
- info("Waiting for the SelfSupport to close.");
- yield promiseSelfSupportClose(TEST_PAGE_URL_HTTPS);
-
- // Find the SelfSupport browser, again. We don't expect to find it.
- selfSupportBrowser = findSelfSupportBrowser(TEST_PAGE_URL_HTTPS);
- Assert.ok(!selfSupportBrowser, "SelfSupport browser must not exist.");
-
- // We shouldn't need this, but let's keep it to make sure closing SelfSupport twice
- // doesn't create any problem.
- SelfSupportBackend.uninit();
-});
-
-/**
- * Test that SelfSupportBackend only allows HTTPS.
- */
-add_task(function* test_selfSupport_noHTTPS() {
- Preferences.set(PREF_SELFSUPPORT_URL, TEST_PAGE_URL);
-
- SelfSupportBackend.init();
-
- // SelfSupportBackend waits for "sessionstore-windows-restored" to start loading. Send it.
- info("Sending sessionstore-windows-restored");
- sendSessionRestoredNotification();
-
- // Find the SelfSupport browser. We don't expect to find it since we are not using https.
- let selfSupportBrowser = findSelfSupportBrowser(TEST_PAGE_URL);
- Assert.ok(!selfSupportBrowser, "SelfSupport browser must not exist.");
-
- // We shouldn't need this, but let's keep it to make sure closing SelfSupport twice
- // doesn't create any problem.
- SelfSupportBackend.uninit();
-})
diff --git a/browser/modules/test/browser_UnsubmittedCrashHandler.js b/browser/modules/test/browser_UnsubmittedCrashHandler.js
deleted file mode 100644
index 2d78c746b2..0000000000
--- a/browser/modules/test/browser_UnsubmittedCrashHandler.js
+++ /dev/null
@@ -1,680 +0,0 @@
-"use strict";
-
-/**
- * This suite tests the "unsubmitted crash report" notification
- * that is seen when we detect pending crash reports on startup.
- */
-
-const { UnsubmittedCrashHandler } =
- Cu.import("resource:///modules/ContentCrashHandlers.jsm", this);
-const { FileUtils } =
- Cu.import("resource://gre/modules/FileUtils.jsm", this);
-const { makeFakeAppDir } =
- Cu.import("resource://testing-common/AppData.jsm", this);
-const { OS } =
- Cu.import("resource://gre/modules/osfile.jsm", this);
-
-const DAY = 24 * 60 * 60 * 1000; // milliseconds
-const SERVER_URL = "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs";
-
-/**
- * Returns the directly where the browsing is storing the
- * pending crash reports.
- *
- * @returns nsIFile
- */
-function getPendingCrashReportDir() {
- // The fake UAppData directory that makeFakeAppDir provides
- // is just UAppData under the profile directory.
- return FileUtils.getDir("ProfD", [
- "UAppData",
- "Crash Reports",
- "pending",
- ], false);
-}
-
-/**
- * Synchronously deletes all entries inside the pending
- * crash report directory.
- */
-function clearPendingCrashReports() {
- let dir = getPendingCrashReportDir();
- let entries = dir.directoryEntries;
-
- while (entries.hasMoreElements()) {
- let entry = entries.getNext().QueryInterface(Ci.nsIFile);
- if (entry.isFile()) {
- entry.remove(false);
- }
- }
-}
-
-/**
- * Randomly generates howMany crash report .dmp and .extra files
- * to put into the pending crash report directory. We're not
- * actually creating real crash reports here, just stubbing
- * out enough of the files to satisfy our notification and
- * submission code.
- *
- * @param howMany (int)
- * How many pending crash reports to put in the pending
- * crash report directory.
- * @param accessDate (Date, optional)
- * What date to set as the last accessed time on the created
- * crash reports. This defaults to the current date and time.
- * @returns Promise
- */
-function* createPendingCrashReports(howMany, accessDate) {
- let dir = getPendingCrashReportDir();
- if (!accessDate) {
- accessDate = new Date();
- }
-
- /**
- * Helper function for creating a file in the pending crash report
- * directory.
- *
- * @param fileName (string)
- * The filename for the crash report, not including the
- * extension. This is usually a UUID.
- * @param extension (string)
- * The file extension for the created file.
- * @param accessDate (Date)
- * The date to set lastAccessed to.
- * @param contents (string, optional)
- * Set this to whatever the file needs to contain, if anything.
- * @returns Promise
- */
- let createFile = (fileName, extension, accessDate, contents) => {
- let file = dir.clone();
- file.append(fileName + "." + extension);
- file.create(Ci.nsILocalFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
- let promises = [OS.File.setDates(file.path, accessDate)];
-
- if (contents) {
- let encoder = new TextEncoder();
- let array = encoder.encode(contents);
- promises.push(OS.File.writeAtomic(file.path, array, {
- tmpPath: file.path + ".tmp",
- }));
- }
- return Promise.all(promises);
- }
-
- let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
- .getService(Ci.nsIUUIDGenerator);
- // CrashSubmit expects there to be a ServerURL key-value
- // pair in the .extra file, so we'll satisfy it.
- let extraFileContents = "ServerURL=" + SERVER_URL;
-
- return Task.spawn(function*() {
- let uuids = [];
- for (let i = 0; i < howMany; ++i) {
- let uuid = uuidGenerator.generateUUID().toString();
- // Strip the {}...
- uuid = uuid.substring(1, uuid.length - 1);
- yield createFile(uuid, "dmp", accessDate);
- yield createFile(uuid, "extra", accessDate, extraFileContents);
- uuids.push(uuid);
- }
- return uuids;
- });
-}
-
-/**
- * Returns a Promise that resolves once CrashSubmit starts sending
- * success notifications for crash submission matching the reportIDs
- * being passed in.
- *
- * @param reportIDs (Array)
- * The IDs for the reports that we expect CrashSubmit to have sent.
- * @returns Promise
- */
-function waitForSubmittedReports(reportIDs) {
- let promises = [];
- for (let reportID of reportIDs) {
- let promise = TestUtils.topicObserved("crash-report-status", (subject, data) => {
- if (data == "success") {
- let propBag = subject.QueryInterface(Ci.nsIPropertyBag2);
- let dumpID = propBag.getPropertyAsAString("minidumpID");
- if (dumpID == reportID) {
- return true;
- }
- }
- return false;
- });
- promises.push(promise);
- }
- return Promise.all(promises);
-}
-
-/**
- * Returns a Promise that resolves once a .dmp.ignore file is created for
- * the crashes in the pending directory matching the reportIDs being
- * passed in.
- *
- * @param reportIDs (Array)
- * The IDs for the reports that we expect CrashSubmit to have been
- * marked for ignoring.
- * @returns Promise
- */
-function waitForIgnoredReports(reportIDs) {
- let dir = getPendingCrashReportDir();
- let promises = [];
- for (let reportID of reportIDs) {
- let file = dir.clone();
- file.append(reportID + ".dmp.ignore");
- promises.push(OS.File.exists(file.path));
- }
- return Promise.all(promises);
-}
-
-let gNotificationBox;
-
-add_task(function* setup() {
- // Pending crash reports are stored in the UAppData folder,
- // which exists outside of the profile folder. In order to
- // not overwrite / clear pending crash reports for the poor
- // soul who runs this test, we use AppData.jsm to point to
- // a special made-up directory inside the profile
- // directory.
- yield makeFakeAppDir();
- // We'll assume that the notifications will be shown in the current
- // browser window's global notification box.
- gNotificationBox = document.getElementById("global-notificationbox");
-
- // If we happen to already be seeing the unsent crash report
- // notification, it's because the developer running this test
- // happened to have some unsent reports in their UAppDir.
- // We'll remove the notification without touching those reports.
- let notification =
- gNotificationBox.getNotificationWithValue("pending-crash-reports");
- if (notification) {
- notification.close();
- }
-
- let env = Cc["@mozilla.org/process/environment;1"]
- .getService(Components.interfaces.nsIEnvironment);
- let oldServerURL = env.get("MOZ_CRASHREPORTER_URL");
- env.set("MOZ_CRASHREPORTER_URL", SERVER_URL);
-
- // nsBrowserGlue starts up UnsubmittedCrashHandler automatically
- // so at this point, it is initialized. It's possible that it
- // was initialized, but is preffed off, so it's inert, so we
- // shut it down, make sure it's preffed on, and then restart it.
- // Note that making the component initialize even when it's
- // disabled is an intentional choice, as this allows for easier
- // simulation of startup and shutdown.
- UnsubmittedCrashHandler.uninit();
- yield SpecialPowers.pushPrefEnv({
- set: [
- ["browser.crashReports.unsubmittedCheck.enabled", true],
- ],
- });
- UnsubmittedCrashHandler.init();
-
- registerCleanupFunction(function() {
- gNotificationBox = null;
- clearPendingCrashReports();
- env.set("MOZ_CRASHREPORTER_URL", oldServerURL);
- });
-});
-
-/**
- * Tests that if there are no pending crash reports, then the
- * notification will not show up.
- */
-add_task(function* test_no_pending_no_notification() {
- // Make absolutely sure there are no pending crash reports first...
- clearPendingCrashReports();
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should not be a notification if there are no " +
- "pending crash reports");
-});
-
-/**
- * Tests that there is a notification if there is one pending
- * crash report.
- */
-add_task(function* test_one_pending() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that there is a notification if there is more than one
- * pending crash report.
- */
-add_task(function* test_several_pending() {
- yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that there is no notification if the only pending crash
- * reports are over 28 days old. Also checks that if we put a newer
- * crash with that older set, that we can still get a notification.
- */
-add_task(function* test_several_pending() {
- // Let's create some crash reports from 30 days ago.
- let oldDate = new Date(Date.now() - (30 * DAY));
- yield createPendingCrashReports(3, oldDate);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should not be a notification if there are only " +
- "old pending crash reports");
- // Now let's create a new one and check again
- yield createPendingCrashReports(1);
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that the notification can submit a report.
- */
-add_task(function* test_can_submit() {
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the submit
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the first button.
- let submit = buttons[0];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash report");
- submit.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that the notification can submit multiple reports.
- */
-add_task(function* test_can_submit_several() {
- let reportIDs = yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the submit
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the first button.
- let submit = buttons[0];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash reports");
- submit.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that choosing "Send Always" flips the autoSubmit pref
- * and sends the pending crash reports.
- */
-add_task(function* test_can_submit_always() {
- let pref = "browser.crashReports.unsubmittedCheck.autoSubmit2";
- Assert.equal(Services.prefs.getBoolPref(pref), false,
- "We should not be auto-submitting by default");
-
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Attempt to submit the notification by clicking on the send all
- // button
- let buttons = notification.querySelectorAll(".notification-button");
- // ...which should be the second button.
- let sendAll = buttons[1];
-
- let promiseReports = waitForSubmittedReports(reportIDs);
- info("Sending crash reports");
- sendAll.click();
- info("Sent!");
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
-
- // Make sure the pref was set
- Assert.equal(Services.prefs.getBoolPref(pref), true,
- "The autoSubmit pref should have been set");
-
- // And revert back to default now.
- Services.prefs.clearUserPref(pref);
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if the user has chosen to automatically send
- * crash reports that no notification is displayed to the
- * user.
- */
-add_task(function* test_can_auto_submit() {
- yield SpecialPowers.pushPrefEnv({ set: [
- ["browser.crashReports.unsubmittedCheck.autoSubmit2", true],
- ]});
-
- let reportIDs = yield createPendingCrashReports(3);
- let promiseReports = waitForSubmittedReports(reportIDs);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null, "There should be no notification");
- info("Waiting on reports to be received.");
- yield promiseReports;
- info("Received!");
-
- clearPendingCrashReports();
- yield SpecialPowers.popPrefEnv();
-});
-
-/**
- * Tests that if the user chooses to dismiss the notification,
- * then the current pending requests won't cause the notification
- * to appear again in the future.
- */
-add_task(function* test_can_ignore() {
- let reportIDs = yield createPendingCrashReports(3);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Dismiss the notification by clicking on the "X" button.
- let anonyNodes = document.getAnonymousNodes(notification)[0];
- let closeButton = anonyNodes.querySelector(".close-icon");
- closeButton.click();
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
- yield waitForIgnoredReports(reportIDs);
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null, "There should be no notification");
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if the notification is shown, then the
- * lastShownDate is set for today.
- */
-add_task(function* test_last_shown_date() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- let lastShownDate =
- UnsubmittedCrashHandler.prefs.getCharPref("lastShownDate");
- Assert.equal(today, lastShownDate,
- "Last shown date should be today.");
-
- UnsubmittedCrashHandler.prefs.clearUserPref("lastShownDate");
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if UnsubmittedCrashHandler is uninit with a
- * notification still being shown, that
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set to true.
- */
-add_task(function* test_shutdown_while_showing() {
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
- UnsubmittedCrashHandler.prefs.clearUserPref("shutdownWhileShowing");
- UnsubmittedCrashHandler.init();
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if UnsubmittedCrashHandler is uninit after
- * the notification has been closed, that
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * not set in prefs.
- */
-add_task(function* test_shutdown_while_not_showing() {
- let reportIDs = yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- // Dismiss the notification by clicking on the "X" button.
- let anonyNodes = document.getAnonymousNodes(notification)[0];
- let closeButton = anonyNodes.querySelector(".close-icon");
- closeButton.click();
- // We'll not wait for the notification to finish its transition -
- // we'll just remove it right away.
- gNotificationBox.removeNotification(notification, true);
-
- yield waitForIgnoredReports(reportIDs);
-
- UnsubmittedCrashHandler.uninit();
- Assert.throws(() => {
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- }, "We should have noticed that the notification had closed before " +
- "uninitting.");
- UnsubmittedCrashHandler.init();
-
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set and the lastShownDate is today, then we don't decrement
- * browser.crashReports.unsubmittedCheck.chancesUntilSuppress.
- */
-add_task(function* test_dont_decrement_chances_on_same_day() {
- let initChances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
- Assert.ok(initChances > 1, "We should start with at least 1 chance.");
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
-
- gNotificationBox.removeNotification(notification, true);
-
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- let lastShownDate =
- UnsubmittedCrashHandler.prefs.getCharPref("lastShownDate");
- Assert.equal(today, lastShownDate,
- "Last shown date should be today.");
-
- UnsubmittedCrashHandler.init();
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should still be a notification");
-
- let chances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
-
- Assert.equal(initChances, chances,
- "We should not have decremented chances.");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if
- * browser.crashReports.unsubmittedCheck.shutdownWhileShowing is
- * set and the lastShownDate is before today, then we decrement
- * browser.crashReports.unsubmittedCheck.chancesUntilSuppress.
- */
-add_task(function* test_decrement_chances_on_other_day() {
- let initChances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
- Assert.ok(initChances > 1, "We should start with at least 1 chance.");
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should be a notification");
-
- UnsubmittedCrashHandler.uninit();
-
- gNotificationBox.removeNotification(notification, true);
-
- let shutdownWhileShowing =
- UnsubmittedCrashHandler.prefs.getBoolPref("shutdownWhileShowing");
- Assert.ok(shutdownWhileShowing,
- "We should have noticed that we uninitted while showing " +
- "the notification.");
-
- // Now pretend that the notification was shown yesterday.
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("lastShownDate", yesterday);
-
- UnsubmittedCrashHandler.init();
-
- notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.ok(notification, "There should still be a notification");
-
- let chances =
- UnsubmittedCrashHandler.prefs.getIntPref("chancesUntilSuppress");
-
- Assert.equal(initChances - 1, chances,
- "We should have decremented our chances.");
- UnsubmittedCrashHandler.prefs.clearUserPref("chancesUntilSuppress");
-
- gNotificationBox.removeNotification(notification, true);
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if we've shutdown too many times showing the
- * notification, and we've run out of chances, then
- * browser.crashReports.unsubmittedCheck.suppressUntilDate is
- * set for some days into the future.
- */
-add_task(function* test_can_suppress_after_chances() {
- // Pretend that a notification was shown yesterday.
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("lastShownDate", yesterday);
- UnsubmittedCrashHandler.prefs.setBoolPref("shutdownWhileShowing", true);
- UnsubmittedCrashHandler.prefs.setIntPref("chancesUntilSuppress", 0);
-
- yield createPendingCrashReports(1);
- let notification =
- yield UnsubmittedCrashHandler.checkForUnsubmittedCrashReports();
- Assert.equal(notification, null,
- "There should be no notification if we've run out of chances");
-
- // We should have set suppressUntilDate into the future
- let suppressUntilDate =
- UnsubmittedCrashHandler.prefs.getCharPref("suppressUntilDate");
-
- let today = UnsubmittedCrashHandler.dateString(new Date());
- Assert.ok(suppressUntilDate > today,
- "We should be suppressing until some days into the future.");
-
- UnsubmittedCrashHandler.prefs.clearUserPref("chancesUntilSuppress");
- UnsubmittedCrashHandler.prefs.clearUserPref("suppressUntilDate");
- UnsubmittedCrashHandler.prefs.clearUserPref("lastShownDate");
- clearPendingCrashReports();
-});
-
-/**
- * Tests that if there's a suppression date set, then no notification
- * will be shown even if there are pending crash reports.
- */
-add_task(function* test_suppression() {
- let future = UnsubmittedCrashHandler.dateString(new Date(Date.now() + (DAY * 5)));
- UnsubmittedCrashHandler.prefs.setCharPref("suppressUntilDate", future);
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-
- Assert.ok(UnsubmittedCrashHandler.suppressed,
- "The UnsubmittedCrashHandler should be suppressed.");
- UnsubmittedCrashHandler.prefs.clearUserPref("suppressUntilDate");
-
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-});
-
-/**
- * Tests that if there's a suppression date set, but we've exceeded
- * it, then we can show the notification again.
- */
-add_task(function* test_end_suppression() {
- let yesterday = UnsubmittedCrashHandler.dateString(new Date(Date.now() - DAY));
- UnsubmittedCrashHandler.prefs.setCharPref("suppressUntilDate", yesterday);
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-
- Assert.ok(!UnsubmittedCrashHandler.suppressed,
- "The UnsubmittedCrashHandler should not be suppressed.");
- Assert.ok(!UnsubmittedCrashHandler.prefs.prefHasUserValue("suppressUntilDate"),
- "The suppression date should been cleared from preferences.");
-
- UnsubmittedCrashHandler.uninit();
- UnsubmittedCrashHandler.init();
-});
diff --git a/browser/modules/test/browser_UsageTelemetry.js b/browser/modules/test/browser_UsageTelemetry.js
deleted file mode 100644
index a84f33a975..0000000000
--- a/browser/modules/test/browser_UsageTelemetry.js
+++ /dev/null
@@ -1,268 +0,0 @@
-"use strict";
-
-const MAX_CONCURRENT_TABS = "browser.engagement.max_concurrent_tab_count";
-const TAB_EVENT_COUNT = "browser.engagement.tab_open_event_count";
-const MAX_CONCURRENT_WINDOWS = "browser.engagement.max_concurrent_window_count";
-const WINDOW_OPEN_COUNT = "browser.engagement.window_open_event_count";
-const TOTAL_URI_COUNT = "browser.engagement.total_uri_count";
-const UNIQUE_DOMAINS_COUNT = "browser.engagement.unique_domains_count";
-const UNFILTERED_URI_COUNT = "browser.engagement.unfiltered_uri_count";
-
-const TELEMETRY_SUBSESSION_TOPIC = "internal-telemetry-after-subsession-split";
-
-/**
- * Waits for the web progress listener associated with this tab to fire an
- * onLocationChange for a non-error page.
- *
- * @param {xul:browser} browser
- * A xul:browser.
- *
- * @return {Promise}
- * @resolves When navigating to a non-error page.
- */
-function browserLocationChanged(browser) {
- return new Promise(resolve => {
- let wpl = {
- onStateChange() {},
- onSecurityChange() {},
- onStatusChange() {},
- onLocationChange(aWebProgress, aRequest, aURI, aFlags) {
- if (!(aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE)) {
- browser.webProgress.removeProgressListener(filter);
- filter.removeProgressListener(wpl);
- resolve();
- }
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIWebProgressListener,
- Ci.nsIWebProgressListener2,
- ]),
- };
- const filter = Cc["@mozilla.org/appshell/component/browser-status-filter;1"]
- .createInstance(Ci.nsIWebProgress);
- filter.addProgressListener(wpl, Ci.nsIWebProgress.NOTIFY_ALL);
- browser.webProgress.addProgressListener(filter, Ci.nsIWebProgress.NOTIFY_ALL);
- });
-}
-
-/**
- * An helper that checks the value of a scalar if it's expected to be > 0,
- * otherwise makes sure that the scalar it's not reported.
- */
-let checkScalar = (scalars, scalarName, value, msg) => {
- if (value > 0) {
- is(scalars[scalarName], value, msg);
- return;
- }
- ok(!(scalarName in scalars), scalarName + " must not be reported.");
-};
-
-/**
- * Get a snapshot of the scalars and check them against the provided values.
- */
-let checkScalars = (countsObject) => {
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- // Check the expected values. Scalars that are never set must not be reported.
- checkScalar(scalars, MAX_CONCURRENT_TABS, countsObject.maxTabs,
- "The maximum tab count must match the expected value.");
- checkScalar(scalars, TAB_EVENT_COUNT, countsObject.tabOpenCount,
- "The number of open tab event count must match the expected value.");
- checkScalar(scalars, MAX_CONCURRENT_WINDOWS, countsObject.maxWindows,
- "The maximum window count must match the expected value.");
- checkScalar(scalars, WINDOW_OPEN_COUNT, countsObject.windowsOpenCount,
- "The number of window open event count must match the expected value.");
- checkScalar(scalars, TOTAL_URI_COUNT, countsObject.totalURIs,
- "The total URI count must match the expected value.");
- checkScalar(scalars, UNIQUE_DOMAINS_COUNT, countsObject.domainCount,
- "The unique domains count must match the expected value.");
- checkScalar(scalars, UNFILTERED_URI_COUNT, countsObject.totalUnfilteredURIs,
- "The unfiltered URI count must match the expected value.");
-};
-
-add_task(function* test_tabsAndWindows() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- let openedTabs = [];
- let expectedTabOpenCount = 0;
- let expectedWinOpenCount = 0;
- let expectedMaxTabs = 0;
- let expectedMaxWins = 0;
-
- // Add a new tab and check that the count is right.
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- expectedTabOpenCount = 1;
- expectedMaxTabs = 2;
- // This, and all the checks below, also check that initial pages (about:newtab, about:blank, ..)
- // are not counted by the total_uri_count and the unfiltered_uri_count probes.
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Add two new tabs in the same window.
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- expectedTabOpenCount += 2;
- expectedMaxTabs += 2;
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Add a new window and then some tabs in it. An empty new windows counts as a tab.
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank"));
- // The new window started with a new tab, so account for it.
- expectedTabOpenCount += 4;
- expectedWinOpenCount += 1;
- expectedMaxWins = 2;
- expectedMaxTabs += 4;
-
- // Remove a tab from the first window, the max shouldn't change.
- yield BrowserTestUtils.removeTab(openedTabs.pop());
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-
- // Remove all the extra windows and tabs.
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(win);
-
- // Make sure all the scalars still have the expected values.
- checkScalars({maxTabs: expectedMaxTabs, tabOpenCount: expectedTabOpenCount, maxWindows: expectedMaxWins,
- windowsOpenCount: expectedWinOpenCount, totalURIs: 0, domainCount: 0,
- totalUnfilteredURIs: 0});
-});
-
-add_task(function* test_subsessionSplit() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // Add a new window (that will have 4 tabs).
- let win = yield BrowserTestUtils.openNewBrowserWindow();
- let openedTabs = [];
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:blank"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "about:mozilla"));
- openedTabs.push(yield BrowserTestUtils.openNewForegroundTab(win.gBrowser, "http://www.example.com"));
-
- // Check that the scalars have the right values. We expect 2 unfiltered URI loads
- // (about:mozilla and www.example.com, but no about:blank) and 1 URI totalURIs
- // (only www.example.com).
- checkScalars({maxTabs: 5, tabOpenCount: 4, maxWindows: 2, windowsOpenCount: 1,
- totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 2});
-
- // Remove a tab.
- yield BrowserTestUtils.removeTab(openedTabs.pop());
-
- // Simulate a subsession split by clearing the scalars (via |snapshotScalars|) and
- // notifying the subsession split topic.
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN,
- true /* clearScalars */);
- Services.obs.notifyObservers(null, TELEMETRY_SUBSESSION_TOPIC, "");
-
- // After a subsession split, only the MAX_CONCURRENT_* scalars must be available
- // and have the correct value. No tabs, windows or URIs were opened so other scalars
- // must not be reported.
- checkScalars({maxTabs: 4, tabOpenCount: 0, maxWindows: 2, windowsOpenCount: 0,
- totalURIs: 0, domainCount: 0, totalUnfilteredURIs: 0});
-
- // Remove all the extra windows and tabs.
- for (let tab of openedTabs) {
- yield BrowserTestUtils.removeTab(tab);
- }
- yield BrowserTestUtils.closeWindow(win);
-});
-
-add_task(function* test_URIAndDomainCounts() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- let checkCounts = (countsObject) => {
- // Get a snapshot of the scalars and then clear them.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
- checkScalar(scalars, TOTAL_URI_COUNT, countsObject.totalURIs,
- "The URI scalar must contain the expected value.");
- checkScalar(scalars, UNIQUE_DOMAINS_COUNT, countsObject.domainCount,
- "The unique domains scalar must contain the expected value.");
- checkScalar(scalars, UNFILTERED_URI_COUNT, countsObject.totalUnfilteredURIs,
- "The unfiltered URI scalar must contain the expected value.");
- };
-
- // Check that about:blank doesn't get counted in the URI total.
- let firstTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- checkCounts({totalURIs: 0, domainCount: 0, totalUnfilteredURIs: 0});
-
- // Open a different page and check the counts.
- yield BrowserTestUtils.loadURI(firstTab.linkedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(firstTab.linkedBrowser);
- checkCounts({totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 1});
-
- // Activating a different tab must not increase the URI count.
- let secondTab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
- yield BrowserTestUtils.switchTab(gBrowser, firstTab);
- checkCounts({totalURIs: 1, domainCount: 1, totalUnfilteredURIs: 1});
- yield BrowserTestUtils.removeTab(secondTab);
-
- // Open a new window and set the tab to a new address.
- let newWin = yield BrowserTestUtils.openNewBrowserWindow();
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 2, domainCount: 1, totalUnfilteredURIs: 2});
-
- // We should not count AJAX requests.
- const XHR_URL = "http://example.com/r";
- yield ContentTask.spawn(newWin.gBrowser.selectedBrowser, XHR_URL, function(url) {
- return new Promise(resolve => {
- var xhr = new content.window.XMLHttpRequest();
- xhr.open("GET", url);
- xhr.onload = () => resolve();
- xhr.send();
- });
- });
- checkCounts({totalURIs: 2, domainCount: 1, totalUnfilteredURIs: 2});
-
- // Check that we're counting page fragments.
- let loadingStopped = browserLocationChanged(newWin.gBrowser.selectedBrowser);
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://example.com/#2");
- yield loadingStopped;
- checkCounts({totalURIs: 3, domainCount: 1, totalUnfilteredURIs: 3});
-
- // Check that a different URI from the example.com domain doesn't increment the unique count.
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "http://test1.example.com/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 4, domainCount: 1, totalUnfilteredURIs: 4});
-
- // Make sure that the unique domains counter is incrementing for a different domain.
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, "https://example.org/");
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 5});
-
- // Check that we only account for top level loads (e.g. we don't count URIs from
- // embedded iframes).
- yield ContentTask.spawn(newWin.gBrowser.selectedBrowser, null, function* () {
- let doc = content.document;
- let iframe = doc.createElement("iframe");
- let promiseIframeLoaded = ContentTaskUtils.waitForEvent(iframe, "load", false);
- iframe.src = "https://example.org/test";
- doc.body.insertBefore(iframe, doc.body.firstChild);
- yield promiseIframeLoaded;
- });
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 5});
-
- // Check that uncommon protocols get counted in the unfiltered URI probe.
- const TEST_PAGE =
- "data:text/html,Click me The paragraph. ";
- yield BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, TEST_PAGE);
- yield BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
- checkCounts({totalURIs: 5, domainCount: 2, totalUnfilteredURIs: 6});
-
- // Clean up.
- yield BrowserTestUtils.removeTab(firstTab);
- yield BrowserTestUtils.closeWindow(newWin);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_content.js b/browser/modules/test/browser_UsageTelemetry_content.js
deleted file mode 100644
index 35c6b5a6dd..0000000000
--- a/browser/modules/test/browser_UsageTelemetry_content.js
+++ /dev/null
@@ -1,121 +0,0 @@
-"use strict";
-
-const BASE_PROBE_NAME = "browser.engagement.navigation.";
-const SCALAR_CONTEXT_MENU = BASE_PROBE_NAME + "contextmenu";
-const SCALAR_ABOUT_NEWTAB = BASE_PROBE_NAME + "about_newtab";
-
-add_task(function* setup() {
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // in content doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- yield SpecialPowers.pushPrefEnv({"set": [
- ["dom.select_events.enabled", true], // We want select events to be fired.
- ["toolkit.telemetry.enabled", true] // And Extended Telemetry to be enabled.
- ]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_context_menu() {
- // Let's reset the Telemetry data.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Open a new tab with a page containing some text.
- let tab =
- yield BrowserTestUtils.openNewForegroundTab(gBrowser, "data:text/plain;charset=utf8,test%20search");
-
- info("Select all the text in the page.");
- yield ContentTask.spawn(tab.linkedBrowser, "", function*() {
- return new Promise(resolve => {
- content.document.addEventListener("selectionchange", () => resolve(), { once: true });
- content.document.getSelection().selectAllChildren(content.document.body);
- });
- });
-
- info("Open the context menu.");
- let contextMenu = document.getElementById("contentAreaContextMenu");
- let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
- BrowserTestUtils.synthesizeMouseAtCenter("body", { type: "contextmenu", button: 2 },
- gBrowser.selectedBrowser);
- yield popupPromise;
-
- info("Click on search.");
- let searchItem = contextMenu.getElementsByAttribute("id", "context-searchselect")[0];
- searchItem.click();
-
- info("Validate the search metrics.");
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_CONTEXT_MENU, "search", 1);
- Assert.equal(Object.keys(scalars[SCALAR_CONTEXT_MENU]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.contextmenu', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "contextmenu", null, {engine: "other-MozSearch"}]]);
-
- contextMenu.hidePopup();
- yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_about_newtab() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:newtab", false);
- yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
- yield ContentTaskUtils.waitForCondition(() => !content.document.hidden);
- });
-
- info("Trigger a simple serch, just text + enter.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield typeInSearchField(tab.linkedBrowser, "test query", "newtab-search-text");
- yield BrowserTestUtils.synthesizeKey("VK_RETURN", {}, tab.linkedBrowser);
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_ABOUT_NEWTAB, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_ABOUT_NEWTAB]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.newtab', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "about_newtab", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js b/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
deleted file mode 100644
index 1818ae5fd9..0000000000
--- a/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
+++ /dev/null
@@ -1,84 +0,0 @@
-"use strict";
-
-const SCALAR_ABOUT_HOME = "browser.engagement.navigation.about_home";
-
-add_task(function* setup() {
- // about:home uses IndexedDB. However, the test finishes too quickly and doesn't
- // allow it enougth time to save. So it throws. This disables all the uncaught
- // exception in this file and that's the reason why we split about:home tests
- // out of the other UsageTelemetry files.
- ignoreAllUncaughtExceptions();
-
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // in content doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_abouthome_simpleQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser);
-
- info("Setup waiting for AboutHomeLoadSnippetsCompleted.");
- let promiseAboutHomeLoaded = new Promise(resolve => {
- tab.linkedBrowser.addEventListener("AboutHomeLoadSnippetsCompleted", function loadListener(event) {
- tab.linkedBrowser.removeEventListener("AboutHomeLoadSnippetsCompleted", loadListener, true);
- resolve();
- }, true, true);
- });
-
- info("Load about:home.");
- tab.linkedBrowser.loadURI("about:home");
- info("Wait for AboutHomeLoadSnippetsCompleted.");
- yield promiseAboutHomeLoaded;
-
- info("Trigger a simple serch, just test + enter.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield typeInSearchField(tab.linkedBrowser, "test query", "searchText");
- yield BrowserTestUtils.synthesizeKey("VK_RETURN", {}, tab.linkedBrowser);
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_ABOUT_HOME, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_ABOUT_HOME]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.abouthome', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "about_home", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_private_and_restore.js b/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
deleted file mode 100644
index 144a4a03fb..0000000000
--- a/browser/modules/test/browser_UsageTelemetry_private_and_restore.js
+++ /dev/null
@@ -1,90 +0,0 @@
-"use strict";
-
-const MAX_CONCURRENT_TABS = "browser.engagement.max_concurrent_tab_count";
-const TAB_EVENT_COUNT = "browser.engagement.tab_open_event_count";
-const MAX_CONCURRENT_WINDOWS = "browser.engagement.max_concurrent_window_count";
-const WINDOW_OPEN_COUNT = "browser.engagement.window_open_event_count";
-const TOTAL_URI_COUNT = "browser.engagement.total_uri_count";
-const UNFILTERED_URI_COUNT = "browser.engagement.unfiltered_uri_count";
-const UNIQUE_DOMAINS_COUNT = "browser.engagement.unique_domains_count";
-
-function promiseBrowserStateRestored() {
- return new Promise(resolve => {
- Services.obs.addObserver(function observer(aSubject, aTopic) {
- Services.obs.removeObserver(observer, "sessionstore-browser-state-restored");
- resolve();
- }, "sessionstore-browser-state-restored", false);
- });
-}
-
-add_task(function* test_privateMode() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // Open a private window and load a website in it.
- let privateWin = yield BrowserTestUtils.openNewBrowserWindow({private: true});
- yield BrowserTestUtils.loadURI(privateWin.gBrowser.selectedBrowser, "http://example.com/");
- yield BrowserTestUtils.browserLoaded(privateWin.gBrowser.selectedBrowser);
-
- // Check that tab and window count is recorded.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- ok(!(TOTAL_URI_COUNT in scalars), "We should not track URIs in private mode.");
- ok(!(UNFILTERED_URI_COUNT in scalars), "We should not track URIs in private mode.");
- ok(!(UNIQUE_DOMAINS_COUNT in scalars), "We should not track unique domains in private mode.");
- is(scalars[TAB_EVENT_COUNT], 1, "The number of open tab event count must match the expected value.");
- is(scalars[MAX_CONCURRENT_TABS], 2, "The maximum tab count must match the expected value.");
- is(scalars[WINDOW_OPEN_COUNT], 1, "The number of window open event count must match the expected value.");
- is(scalars[MAX_CONCURRENT_WINDOWS], 2, "The maximum window count must match the expected value.");
-
- // Clean up.
- yield BrowserTestUtils.closeWindow(privateWin);
-});
-
-add_task(function* test_sessionRestore() {
- const PREF_RESTORE_ON_DEMAND = "browser.sessionstore.restore_on_demand";
- Services.prefs.setBoolPref(PREF_RESTORE_ON_DEMAND, false);
- registerCleanupFunction(() => {
- Services.prefs.clearUserPref(PREF_RESTORE_ON_DEMAND);
- });
-
- // Let's reset the counts.
- Services.telemetry.clearScalars();
-
- // 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.
- const state = {
- windows: [
- {
- tabs: [
- { entries: [{ url: "http://example.org" }], extData: { "uniq": 3785 } }
- ],
- selected: 1
- }
- ]
- };
-
- // Save the current session.
- let SessionStore =
- Cu.import("resource:///modules/sessionstore/SessionStore.jsm", {}).SessionStore;
-
- // Load the custom state and wait for SSTabRestored, as we want to make sure
- // that the URI counting code was hit.
- let tabRestored = BrowserTestUtils.waitForEvent(gBrowser.tabContainer, "SSTabRestored");
- SessionStore.setBrowserState(JSON.stringify(state));
- yield tabRestored;
-
- // Check that the URI is not recorded.
- const scalars =
- Services.telemetry.snapshotScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN);
-
- ok(!(TOTAL_URI_COUNT in scalars), "We should not track URIs from restored sessions.");
- ok(!(UNFILTERED_URI_COUNT in scalars), "We should not track URIs from restored sessions.");
- ok(!(UNIQUE_DOMAINS_COUNT in scalars), "We should not track unique domains from restored sessions.");
-
- // Restore the original session and cleanup.
- let sessionRestored = promiseBrowserStateRestored();
- SessionStore.setBrowserState(JSON.stringify(state));
- yield sessionRestored;
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_searchbar.js b/browser/modules/test/browser_UsageTelemetry_searchbar.js
deleted file mode 100644
index 8aa3ceaeea..0000000000
--- a/browser/modules/test/browser_UsageTelemetry_searchbar.js
+++ /dev/null
@@ -1,195 +0,0 @@
-"use strict";
-
-const SCALAR_SEARCHBAR = "browser.engagement.navigation.searchbar";
-
-let searchInSearchbar = Task.async(function* (inputText) {
- let win = window;
- yield new Promise(r => waitForFocus(r, win));
- let sb = BrowserSearch.searchBar;
- // Write the search query in the searchbar.
- sb.focus();
- sb.value = inputText;
- sb.textbox.controller.startSearch(inputText);
- // Wait for the popup to show.
- yield BrowserTestUtils.waitForEvent(sb.textbox.popup, "popupshown");
- // And then for the search to complete.
- yield BrowserTestUtils.waitForCondition(() => sb.textbox.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH,
- "The search in the searchbar must complete.");
-});
-
-/**
- * Click one of the entries in the search suggestion popup.
- *
- * @param {String} entryName
- * The name of the elemet to click on.
- */
-function clickSearchbarSuggestion(entryName) {
- let popup = BrowserSearch.searchBar.textbox.popup;
- let column = popup.tree.columns[0];
-
- for (let rowID = 0; rowID < popup.tree.view.rowCount; rowID++) {
- const suggestion = popup.tree.view.getValueAt(rowID, column);
- if (suggestion !== entryName) {
- continue;
- }
-
- // Make sure the suggestion is visible, just in case.
- let tbo = popup.tree.treeBoxObject;
- tbo.ensureRowIsVisible(rowID);
- // Calculate the click coordinates.
- let rect = tbo.getCoordsForCellItem(rowID, column, "text");
- let x = rect.x + rect.width / 2;
- let y = rect.y + rect.height / 2;
- // Simulate the click.
- EventUtils.synthesizeMouse(popup.tree.body, x, y, {},
- popup.tree.ownerGlobal);
- break;
- }
-}
-
-add_task(function* setup() {
- // Create two new search engines. Mark one as the default engine, so
- // the test don't crash. We need to engines for this test as the searchbar
- // doesn't display the default search engine among the one-off engines.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- Services.search.addEngineWithDetails("MozSearch2", "", "mozalias2", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make the first engine the default search engine.
- let engineDefault = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engineDefault;
-
- // Move the second engine at the beginning of the one-off list.
- let engineOneOff = Services.search.getEngineByName("MozSearch2");
- Services.search.moveEngine(engineOneOff, 0);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engineDefault);
- Services.search.removeEngine(engineOneOff);
- });
-});
-
-add_task(function* test_plainQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Simulate entering a simple search.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("simple query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_oneOff() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("query");
-
- info("Pressing Alt+Down to highlight the first one off engine.");
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true });
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_oneoff", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch2.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "oneoff", {engine: "other-MozSearch2"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_suggestion() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Create an engine to generate search suggestions and add it as default
- // for this test.
- const url = getRootDirectory(gTestPath) + "usageTelemetrySearchSuggestions.xml";
- let suggestionEngine = yield new Promise((resolve, reject) => {
- Services.search.addEngine(url, null, "", false, {
- onSuccess(engine) { resolve(engine) },
- onError() { reject() }
- });
- });
-
- let previousEngine = Services.search.currentEngine;
- Services.search.currentEngine = suggestionEngine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInSearchbar("query");
- info("Clicking the searchbar suggestion.");
- clickSearchbarSuggestion("queryfoo");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_suggestion", 1);
- Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.searchbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "searchbar", "suggestion", {engine: searchEngineId}]]);
-
- Services.search.currentEngine = previousEngine;
- Services.search.removeEngine(suggestionEngine);
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_UsageTelemetry_urlbar.js b/browser/modules/test/browser_UsageTelemetry_urlbar.js
deleted file mode 100644
index 81d3e28bae..0000000000
--- a/browser/modules/test/browser_UsageTelemetry_urlbar.js
+++ /dev/null
@@ -1,220 +0,0 @@
-"use strict";
-
-const SCALAR_URLBAR = "browser.engagement.navigation.urlbar";
-
-// The preference to enable suggestions in the urlbar.
-const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches";
-// The name of the search engine used to generate suggestions.
-const SUGGESTION_ENGINE_NAME = "browser_UsageTelemetry usageTelemetrySearchSuggestions.xml";
-const ONEOFF_URLBAR_PREF = "browser.urlbar.oneOffSearches";
-
-let searchInAwesomebar = Task.async(function* (inputText, win=window) {
- yield new Promise(r => waitForFocus(r, win));
- // Write the search query in the urlbar.
- win.gURLBar.focus();
- win.gURLBar.value = inputText;
- win.gURLBar.controller.startSearch(inputText);
- // Wait for the popup to show.
- yield BrowserTestUtils.waitForEvent(win.gURLBar.popup, "popupshown");
- // And then for the search to complete.
- yield BrowserTestUtils.waitForCondition(() => win.gURLBar.controller.searchStatus >=
- Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH);
-});
-
-/**
- * Click one of the entries in the urlbar suggestion popup.
- *
- * @param {String} entryName
- * The name of the elemet to click on.
- */
-function clickURLBarSuggestion(entryName) {
- // The entry in the suggestion list should follow the format:
- // " Search"
- const expectedSuggestionName = entryName + " " + SUGGESTION_ENGINE_NAME + " Search";
- for (let child of gURLBar.popup.richlistbox.children) {
- if (child.label === expectedSuggestionName) {
- // This entry is the search suggestion we're looking for.
- child.click();
- return;
- }
- }
-}
-
-add_task(function* setup() {
- // Create a new search engine.
- Services.search.addEngineWithDetails("MozSearch", "", "mozalias", "", "GET",
- "http://example.com/?q={searchTerms}");
-
- // Make it the default search engine.
- let engine = Services.search.getEngineByName("MozSearch");
- let originalEngine = Services.search.currentEngine;
- Services.search.currentEngine = engine;
-
- // And the first one-off engine.
- Services.search.moveEngine(engine, 0);
-
- // Enable search suggestions in the urlbar.
- Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true);
-
- // Enable the urlbar one-off buttons.
- Services.prefs.setBoolPref(ONEOFF_URLBAR_PREF, true);
-
- // Enable Extended Telemetry.
- yield SpecialPowers.pushPrefEnv({"set": [["toolkit.telemetry.enabled", true]]});
-
- // Make sure to restore the engine once we're done.
- registerCleanupFunction(function* () {
- Services.search.currentEngine = originalEngine;
- Services.search.removeEngine(engine);
- Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF, true);
- Services.prefs.clearUserPref(ONEOFF_URLBAR_PREF);
- });
-});
-
-add_task(function* test_simpleQuery() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Simulate entering a simple search.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("simple query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_enter", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "enter", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_searchAlias() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Search using a search alias.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("mozalias query");
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_alias", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "alias", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_oneOff() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("query");
-
- info("Pressing Alt+Down to take us to the first one-off engine.");
- EventUtils.synthesizeKey("VK_DOWN", { altKey: true });
- EventUtils.sendKey("return");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_oneoff", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "oneoff", {engine: "other-MozSearch"}]]);
-
- yield BrowserTestUtils.removeTab(tab);
-});
-
-add_task(function* test_suggestion() {
- // Let's reset the counts.
- Services.telemetry.clearScalars();
- Services.telemetry.clearEvents();
- let search_hist = getSearchCountsHistogram();
-
- // Create an engine to generate search suggestions and add it as default
- // for this test.
- const url = getRootDirectory(gTestPath) + "usageTelemetrySearchSuggestions.xml";
- let suggestionEngine = yield new Promise((resolve, reject) => {
- Services.search.addEngine(url, null, "", false, {
- onSuccess(engine) { resolve(engine) },
- onError() { reject() }
- });
- });
-
- let previousEngine = Services.search.currentEngine;
- Services.search.currentEngine = suggestionEngine;
-
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "about:blank");
-
- info("Perform a one-off search using the first engine.");
- let p = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
- yield searchInAwesomebar("query");
- info("Clicking the urlbar suggestion.");
- clickURLBarSuggestion("queryfoo");
- yield p;
-
- // Check if the scalars contain the expected values.
- const scalars =
- Services.telemetry.snapshotKeyedScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- checkKeyedScalar(scalars, SCALAR_URLBAR, "search_suggestion", 1);
- Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
- "This search must only increment one entry in the scalar.");
-
- // Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.urlbar', 1);
-
- // Also check events.
- let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
- events = events.filter(e => e[1] == "navigation" && e[2] == "search");
- checkEvents(events, [["navigation", "search", "urlbar", "suggestion", {engine: searchEngineId}]]);
-
- Services.search.currentEngine = previousEngine;
- Services.search.removeEngine(suggestionEngine);
- yield BrowserTestUtils.removeTab(tab);
-});
diff --git a/browser/modules/test/browser_taskbar_preview.js b/browser/modules/test/browser_taskbar_preview.js
deleted file mode 100644
index 89295b9e0e..0000000000
--- a/browser/modules/test/browser_taskbar_preview.js
+++ /dev/null
@@ -1,100 +0,0 @@
-function test() {
- var isWin7OrHigher = false;
- try {
- let version = Cc["@mozilla.org/system-info;1"]
- .getService(Ci.nsIPropertyBag2)
- .getProperty("version");
- isWin7OrHigher = (parseFloat(version) >= 6.1);
- } catch (ex) { }
-
- is(!!Win7Features, isWin7OrHigher, "Win7Features available when it should be");
- if (!isWin7OrHigher)
- return;
-
- const ENABLE_PREF_NAME = "browser.taskbar.previews.enable";
-
- let temp = {};
- Cu.import("resource:///modules/WindowsPreviewPerTab.jsm", temp);
- let AeroPeek = temp.AeroPeek;
-
- waitForExplicitFinish();
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, true);
-
- is(1, AeroPeek.windows.length, "Got the expected number of windows");
-
- checkPreviews(1, "Browser starts with one preview");
-
- gBrowser.addTab();
- gBrowser.addTab();
- gBrowser.addTab();
-
- checkPreviews(4, "Correct number of previews after adding");
-
- for (let preview of AeroPeek.previews)
- ok(preview.visible, "Preview is shown as expected");
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, false);
- is(0, AeroPeek.previews.length, "Should have 0 previews when disabled");
-
- gPrefService.setBoolPref(ENABLE_PREF_NAME, true);
- checkPreviews(4, "Previews are back when re-enabling");
- for (let preview of AeroPeek.previews)
- ok(preview.visible, "Preview is shown as expected after re-enabling");
-
- [1, 2, 3, 4].forEach(function (idx) {
- gBrowser.selectedTab = gBrowser.tabs[idx];
- ok(checkSelectedTab(), "Current tab is correctly selected");
- });
-
- // Close #4
- getPreviewForTab(gBrowser.selectedTab).controller.onClose();
- checkPreviews(3, "Expected number of previews after closing selected tab via controller");
- ok(gBrowser.tabs.length == 3, "Successfully closed a tab");
-
- // Select #1
- ok(getPreviewForTab(gBrowser.tabs[0]).controller.onActivate(), "Activation was accepted");
- ok(gBrowser.tabs[0].selected, "Correct tab was selected");
- checkSelectedTab();
-
- // Remove #3 (non active)
- gBrowser.removeTab(gBrowser.tabContainer.lastChild);
- checkPreviews(2, "Expected number of previews after closing unselected via browser");
-
- // Remove #1 (active)
- gBrowser.removeTab(gBrowser.tabContainer.firstChild);
- checkPreviews(1, "Expected number of previews after closing selected tab via browser");
-
- // Add a new tab
- gBrowser.addTab();
- checkPreviews(2);
- // Check default selection
- checkSelectedTab();
-
- // Change selection
- gBrowser.selectedTab = gBrowser.tabs[0];
- checkSelectedTab();
- // Close nonselected tab via controller
- getPreviewForTab(gBrowser.tabs[1]).controller.onClose();
- checkPreviews(1);
-
- if (gPrefService.prefHasUserValue(ENABLE_PREF_NAME))
- gPrefService.setBoolPref(ENABLE_PREF_NAME, !gPrefService.getBoolPref(ENABLE_PREF_NAME));
-
- finish();
-
- function checkPreviews(aPreviews, msg) {
- let nPreviews = AeroPeek.previews.length;
- is(aPreviews, gBrowser.tabs.length, "Browser has expected number of tabs - " + msg);
- is(nPreviews, gBrowser.tabs.length, "Browser has one preview per tab - " + msg);
- is(nPreviews, aPreviews, msg || "Got expected number of previews");
- }
-
- function getPreviewForTab(tab) {
- return window.gTaskbarTabGroup.previewFromTab(tab);
- }
-
- function checkSelectedTab() {
- return getPreviewForTab(gBrowser.selectedTab).active;
- }
-}
diff --git a/browser/modules/test/browser_urlBar_zoom.js b/browser/modules/test/browser_urlBar_zoom.js
deleted file mode 100644
index 9cb5c96c67..0000000000
--- a/browser/modules/test/browser_urlBar_zoom.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 initialPageZoom = ZoomManager.zoom;
-const kTimeoutInMS = 20000;
-
-add_task(function* () {
- info("Confirm whether the browser zoom is set to the default level");
- is(initialPageZoom, 1, "Page zoom is set to default (100%)");
- let zoomResetButton = document.getElementById("urlbar-zoom-button");
- is(zoomResetButton.hidden, true, "Zoom reset button is currently hidden");
-
- info("Change zoom and confirm zoom button appears");
- let labelUpdatePromise = BrowserTestUtils.waitForAttribute("label", zoomResetButton);
- FullZoom.enlarge();
- yield labelUpdatePromise;
- info("Zoom increased to " + Math.floor(ZoomManager.zoom * 100) + "%");
- is(zoomResetButton.hidden, false, "Zoom reset button is now visible");
- let pageZoomLevel = Math.floor(ZoomManager.zoom * 100);
- let expectedZoomLevel = 110;
- let buttonZoomLevel = parseInt(zoomResetButton.getAttribute("label"), 10);
- is(buttonZoomLevel, expectedZoomLevel, ("Button label updated successfully to " + Math.floor(ZoomManager.zoom * 100) + "%"));
-
- let zoomResetPromise = promiseObserverNotification("browser-fullZoom:zoomReset");
- zoomResetButton.click();
- yield zoomResetPromise;
- pageZoomLevel = Math.floor(ZoomManager.zoom * 100);
- expectedZoomLevel = 100;
- is(pageZoomLevel, expectedZoomLevel, "Clicking zoom button successfully resets browser zoom to 100%");
- is(zoomResetButton.hidden, true, "Zoom reset button returns to being hidden");
-
-});
-
-add_task(function* () {
- info("Confirm that URL bar zoom button doesn't appear when customizable zoom widget is added to toolbar");
- CustomizableUI.addWidgetToArea("zoom-controls", CustomizableUI.AREA_NAVBAR);
- let zoomCustomizableWidget = document.getElementById("zoom-reset-button");
- let zoomResetButton = document.getElementById("urlbar-zoom-button");
- let zoomChangePromise = promiseObserverNotification("browser-fullZoom:zoomChange");
- FullZoom.enlarge();
- yield zoomChangePromise;
- is(zoomResetButton.hidden, true, "URL zoom button remains hidden despite zoom increase");
- is(parseInt(zoomCustomizableWidget.label, 10), 110, "Customizable zoom widget's label has updated to " + zoomCustomizableWidget.label);
-});
-
-add_task(function* asyncCleanup() {
- // reset zoom level and customizable widget
- ZoomManager.zoom = initialPageZoom;
- is(ZoomManager.zoom, 1, "Zoom level was restored");
- if (document.getElementById("zoom-controls")) {
- CustomizableUI.removeWidgetFromArea("zoom-controls", CustomizableUI.AREA_NAVBAR);
- ok(!document.getElementById("zoom-controls"), "Customizable zoom widget removed from toolbar");
- }
-
-});
-
-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;
-}
diff --git a/browser/modules/test/contentSearch.js b/browser/modules/test/contentSearch.js
deleted file mode 100644
index b5dddfe455..0000000000
--- a/browser/modules/test/contentSearch.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/. */
-
-const TEST_MSG = "ContentSearchTest";
-const SERVICE_EVENT_TYPE = "ContentSearchService";
-const CLIENT_EVENT_TYPE = "ContentSearchClient";
-
-// Forward events from the in-content service to the test.
-content.addEventListener(SERVICE_EVENT_TYPE, event => {
- // The event dispatch code in content.js clones the event detail into the
- // content scope. That's generally the right thing, but causes us to end
- // up with an XrayWrapper to it here, which will screw us up when trying to
- // serialize the object in sendAsyncMessage. Waive Xrays for the benefit of
- // the test machinery.
- sendAsyncMessage(TEST_MSG, Components.utils.waiveXrays(event.detail));
-});
-
-// Forward messages from the test to the in-content service.
-addMessageListener(TEST_MSG, msg => {
- // If the message is a search, stop the page from loading and then tell the
- // test that it loaded.
- if (msg.data.type == "Search") {
- waitForLoadAndStopIt(msg.data.expectedURL, url => {
- sendAsyncMessage(TEST_MSG, {
- type: "loadStopped",
- url: url,
- });
- });
- }
-
- content.dispatchEvent(
- new content.CustomEvent(CLIENT_EVENT_TYPE, {
- detail: msg.data,
- })
- );
-});
-
-function waitForLoadAndStopIt(expectedURL, callback) {
- let Ci = Components.interfaces;
- let webProgress = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
- .getInterface(Ci.nsIWebProgress);
- let listener = {
- onStateChange: function (webProg, req, flags, status) {
- if (req instanceof Ci.nsIChannel) {
- let url = req.originalURI.spec;
- dump("waitForLoadAndStopIt: onStateChange " + url + "\n");
- let docStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT |
- Ci.nsIWebProgressListener.STATE_START;
- if ((flags & docStart) && webProg.isTopLevel && url == expectedURL) {
- webProgress.removeProgressListener(listener);
- req.cancel(Components.results.NS_ERROR_FAILURE);
- callback(url);
- }
- }
- },
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIWebProgressListener,
- Ci.nsISupportsWeakReference,
- ]),
- };
- webProgress.addProgressListener(listener, Ci.nsIWebProgress.NOTIFY_ALL);
- dump("waitForLoadAndStopIt: Waiting for URL to load: " + expectedURL + "\n");
-}
diff --git a/browser/modules/test/contentSearchBadImage.xml b/browser/modules/test/contentSearchBadImage.xml
deleted file mode 100644
index 6e4cb60a58..0000000000
--- a/browser/modules/test/contentSearchBadImage.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-browser_ContentSearch contentSearchBadImage.xml
-
-data:image/x-icon;base64,notbase64
-
diff --git a/browser/modules/test/contentSearchSuggestions.sjs b/browser/modules/test/contentSearchSuggestions.sjs
deleted file mode 100644
index 1978b4f665..0000000000
--- a/browser/modules/test/contentSearchSuggestions.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/modules/test/contentSearchSuggestions.xml b/browser/modules/test/contentSearchSuggestions.xml
deleted file mode 100644
index 81c23379ca..0000000000
--- a/browser/modules/test/contentSearchSuggestions.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-browser_ContentSearch contentSearchSuggestions.xml
-
-
-
diff --git a/browser/modules/test/head.js b/browser/modules/test/head.js
deleted file mode 100644
index be02151567..0000000000
--- a/browser/modules/test/head.js
+++ /dev/null
@@ -1,113 +0,0 @@
-Cu.import("resource://gre/modules/Promise.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 : ""));
- });
-}
-
-/**
- * Checks if the snapshotted keyed scalars contain the expected
- * data.
- *
- * @param {Object} scalars
- * The snapshot of the keyed scalars.
- * @param {String} scalarName
- * The name of the keyed scalar to check.
- * @param {String} key
- * The key that must be within the keyed scalar.
- * @param {String|Boolean|Number} expectedValue
- * The expected value for the provided key in the scalar.
- */
-function checkKeyedScalar(scalars, scalarName, key, expectedValue) {
- Assert.ok(scalarName in scalars,
- scalarName + " must be recorded.");
- Assert.ok(key in scalars[scalarName],
- scalarName + " must contain the '" + key + "' key.");
- Assert.ok(scalars[scalarName][key], expectedValue,
- scalarName + "['" + key + "'] must contain the expected value");
-}
-
-/**
- * An utility function to write some text in the search input box
- * in a content page.
- * @param {Object} browser
- * The browser that contains the content.
- * @param {String} text
- * The string to write in the search field.
- * @param {String} fieldName
- * The name of the field to write to.
- */
-let typeInSearchField = Task.async(function* (browser, text, fieldName) {
- yield ContentTask.spawn(browser, { fieldName, text }, function* ({fieldName, text}) {
- // Avoid intermittent failures.
- if (fieldName === "searchText") {
- content.wrappedJSObject.gContentSearchController.remoteTimeout = 5000;
- }
- // Put the focus on the search box.
- let searchInput = content.document.getElementById(fieldName);
- searchInput.focus();
- searchInput.value = text;
- });
-});
-
-/**
- * Clear and get the SEARCH_COUNTS histogram.
- */
-function getSearchCountsHistogram() {
- let search_hist = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS");
- search_hist.clear();
- return search_hist;
-}
-
-/**
- * Check that the keyed histogram contains the right value.
- */
-function checkKeyedHistogram(h, key, expectedValue) {
- const snapshot = h.snapshot();
- Assert.ok(key in snapshot, `The histogram must contain ${key}.`);
- Assert.equal(snapshot[key].sum, expectedValue, `The key ${key} must contain ${expectedValue}.`);
-}
-
-function checkEvents(events, expectedEvents) {
- if (!Services.telemetry.canRecordExtended) {
- // Currently we only collect the tested events when extended Telemetry is enabled.
- return;
- }
-
- Assert.equal(events.length, expectedEvents.length, "Should have matching amount of events.");
-
- // Strip timestamps from the events for easier comparison.
- events = events.map(e => e.slice(1));
-
- for (let i = 0; i < events.length; ++i) {
- Assert.deepEqual(events[i], expectedEvents[i], "Events should match.");
- }
-}
diff --git a/browser/modules/test/unit/social/.eslintrc.js b/browser/modules/test/unit/social/.eslintrc.js
deleted file mode 100644
index d35787cd2c..0000000000
--- a/browser/modules/test/unit/social/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/unit/social/blocklist.xml b/browser/modules/test/unit/social/blocklist.xml
deleted file mode 100644
index c8d72d6242..0000000000
--- a/browser/modules/test/unit/social/blocklist.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/browser/modules/test/unit/social/head.js b/browser/modules/test/unit/social/head.js
deleted file mode 100644
index 0beabb6858..0000000000
--- a/browser/modules/test/unit/social/head.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/. */
-
-var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var Social, SocialService;
-
-var manifests = [
- {
- name: "provider 1",
- origin: "https://example1.com",
- sidebarURL: "https://example1.com/sidebar/",
- },
- {
- name: "provider 2",
- origin: "https://example2.com",
- sidebarURL: "https://example1.com/sidebar/",
- }
-];
-
-const MANIFEST_PREFS = Services.prefs.getBranch("social.manifest.");
-
-// SocialProvider class relies on blocklisting being enabled. To enable
-// blocklisting, we have to setup an app and initialize the blocklist (see
-// initApp below).
-const gProfD = do_get_profile();
-
-function createAppInfo(ID, name, version, platformVersion="1.0") {
- let tmp = {};
- Cu.import("resource://testing-common/AppInfo.jsm", tmp);
- tmp.updateAppInfo({
- ID, name, version, platformVersion,
- crashReporter: true,
- });
- gAppInfo = tmp.getAppInfo();
-}
-
-function initApp() {
- createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9");
- // prepare a blocklist file for the blocklist service
- var blocklistFile = gProfD.clone();
- blocklistFile.append("blocklist.xml");
- if (blocklistFile.exists())
- blocklistFile.remove(false);
- var source = do_get_file("blocklist.xml");
- source.copyTo(gProfD, "blocklist.xml");
- blocklistFile.lastModifiedTime = Date.now();
-
-
- let internalManager = Cc["@mozilla.org/addons/integration;1"].
- getService(Ci.nsIObserver).
- QueryInterface(Ci.nsITimerCallback);
-
- internalManager.observe(null, "addons-startup", null);
-}
-
-function setManifestPref(manifest) {
- let string = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- string.data = JSON.stringify(manifest);
- Services.prefs.setComplexValue("social.manifest." + manifest.origin, Ci.nsISupportsString, string);
-}
-
-function do_wait_observer(obsTopic, cb) {
- function observer(subject, topic, data) {
- Services.obs.removeObserver(observer, topic);
- cb();
- }
- Services.obs.addObserver(observer, obsTopic, false);
-}
-
-function do_add_providers(cb) {
- // run only after social is already initialized
- SocialService.addProvider(manifests[0], function() {
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.providers.length, 2, "2 providers installed");
- do_execute_soon(cb);
- });
- SocialService.addProvider(manifests[1]);
- });
-}
-
-function do_initialize_social(enabledOnStartup, cb) {
- initApp();
-
- if (enabledOnStartup) {
- // set prefs before initializing social
- manifests.forEach(function (manifest) {
- setManifestPref(manifest);
- });
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- for (let m of manifests)
- active[m.origin] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- do_register_cleanup(function() {
- manifests.forEach(function (manifest) {
- Services.prefs.clearUserPref("social.manifest." + manifest.origin);
- });
- Services.prefs.clearUserPref("social.activeProviders");
- });
-
- // expecting 2 providers installed
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.providers.length, 2, "2 providers installed");
- do_execute_soon(cb);
- });
- }
-
- // import and initialize everything
- SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
- do_check_eq(enabledOnStartup, SocialService.hasEnabledProviders, "Service has enabled providers");
- Social = Cu.import("resource:///modules/Social.jsm", {}).Social;
- do_check_false(Social.initialized, "Social is not initialized");
- Social.init();
- do_check_true(Social.initialized, "Social is initialized");
- if (!enabledOnStartup)
- do_execute_soon(cb);
-}
-
-function AsyncRunner() {
- do_test_pending();
- do_register_cleanup(() => this.destroy());
-
- this._callbacks = {
- done: do_test_finished,
- error: function (err) {
- // xpcshell test functions like do_check_eq throw NS_ERROR_ABORT on
- // failure. Ignore those so they aren't rethrown here.
- if (err !== Cr.NS_ERROR_ABORT) {
- if (err.stack) {
- err = err + " - See following stack:\n" + err.stack +
- "\nUseless do_throw stack";
- }
- do_throw(err);
- }
- },
- consoleError: function (scriptErr) {
- // Try to ensure the error is related to the test.
- let filename = scriptErr.sourceName || scriptErr.toString() || "";
- if (filename.indexOf("/toolkit/components/social/") >= 0)
- do_throw(scriptErr);
- },
- };
- this._iteratorQueue = [];
-
- // This catches errors reported to the console, e.g., via Cu.reportError, but
- // not on the runner's stack.
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- registerListener(this);
-}
-
-AsyncRunner.prototype = {
-
- appendIterator: function appendIterator(iter) {
- this._iteratorQueue.push(iter);
- },
-
- next: function next(arg) {
- if (!this._iteratorQueue.length) {
- this.destroy();
- this._callbacks.done();
- return;
- }
-
- try {
- var { done, value: val } = this._iteratorQueue[0].next(arg);
- if (done) {
- this._iteratorQueue.shift();
- this.next();
- return;
- }
- }
- catch (err) {
- this._callbacks.error(err);
- }
-
- // val is an iterator => prepend it to the queue and start on it
- // val is otherwise truthy => call next
- if (val) {
- if (typeof(val) != "boolean")
- this._iteratorQueue.unshift(val);
- this.next();
- }
- },
-
- destroy: function destroy() {
- Cc["@mozilla.org/consoleservice;1"].
- getService(Ci.nsIConsoleService).
- unregisterListener(this);
- this.destroy = function alreadyDestroyed() {};
- },
-
- observe: function observe(msg) {
- if (msg instanceof Ci.nsIScriptError &&
- !(msg.flags & Ci.nsIScriptError.warningFlag))
- {
- this._callbacks.consoleError(msg);
- }
- },
-};
diff --git a/browser/modules/test/unit/social/test_SocialService.js b/browser/modules/test/unit/social/test_SocialService.js
deleted file mode 100644
index e6f354fed3..0000000000
--- a/browser/modules/test/unit/social/test_SocialService.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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-function run_test() {
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifests = [
- { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- shareURL: "https://example1.com/share/",
- },
- { // provider without workerURL
- name: "provider 2",
- origin: "https://example2.com",
- shareURL: "https://example2.com/share/",
- }
- ];
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testAddProviders(manifests, next));
- runner.appendIterator(testGetProvider(manifests, next));
- runner.appendIterator(testGetProviderList(manifests, next));
- runner.appendIterator(testAddRemoveProvider(manifests, next));
- runner.appendIterator(testIsSameOrigin(manifests, next));
- runner.appendIterator(testResolveUri (manifests, next));
- runner.appendIterator(testOrderedProviders(manifests, next));
- runner.appendIterator(testRemoveProviders(manifests, next));
- runner.next();
-}
-
-function* testAddProviders(manifests, next) {
- do_check_false(SocialService.enabled);
- let provider = yield SocialService.addProvider(manifests[0], next);
- do_check_true(SocialService.enabled);
- do_check_false(provider.enabled);
- provider = yield SocialService.addProvider(manifests[1], next);
- do_check_false(provider.enabled);
-}
-
-function* testRemoveProviders(manifests, next) {
- do_check_true(SocialService.enabled);
- yield SocialService.disableProvider(manifests[0].origin, next);
- yield SocialService.disableProvider(manifests[1].origin, next);
- do_check_false(SocialService.enabled);
-}
-
-function* testGetProvider(manifests, next) {
- for (let i = 0; i < manifests.length; i++) {
- let manifest = manifests[i];
- let provider = yield SocialService.getProvider(manifest.origin, next);
- do_check_neq(provider, null);
- do_check_eq(provider.name, manifest.name);
- do_check_eq(provider.workerURL, manifest.workerURL);
- do_check_eq(provider.origin, manifest.origin);
- }
- do_check_eq((yield SocialService.getProvider("bogus", next)), null);
-}
-
-function* testGetProviderList(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- do_check_true(providers.length >= manifests.length);
- for (let i = 0; i < manifests.length; i++) {
- let providerIdx = providers.map(p => p.origin).indexOf(manifests[i].origin);
- let provider = providers[providerIdx];
- do_check_true(!!provider);
- do_check_false(provider.enabled);
- do_check_eq(provider.workerURL, manifests[i].workerURL);
- do_check_eq(provider.name, manifests[i].name);
- }
-}
-
-function* testAddRemoveProvider(manifests, next) {
- var threw;
- try {
- // Adding a provider whose origin already exists should fail
- SocialService.addProvider(manifests[0]);
- } catch (ex) {
- threw = ex;
- }
- do_check_neq(threw.toString().indexOf("SocialService.addProvider: provider with this origin already exists"), -1);
-
- let originalProviders = yield SocialService.getProviderList(next);
-
- // Check that provider installation succeeds
- let newProvider = yield SocialService.addProvider({
- name: "foo",
- origin: "http://example3.com"
- }, next);
- let retrievedNewProvider = yield SocialService.getProvider(newProvider.origin, next);
- do_check_eq(newProvider, retrievedNewProvider);
-
- let providersAfter = yield SocialService.getProviderList(next);
- do_check_eq(providersAfter.length, originalProviders.length + 1);
- do_check_neq(providersAfter.indexOf(newProvider), -1);
-
- // Now remove the provider
- yield SocialService.disableProvider(newProvider.origin, next);
- providersAfter = yield SocialService.getProviderList(next);
- do_check_eq(providersAfter.length, originalProviders.length);
- do_check_eq(providersAfter.indexOf(newProvider), -1);
- newProvider = yield SocialService.getProvider(newProvider.origin, next);
- do_check_true(!newProvider);
-}
-
-function* testIsSameOrigin(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- let provider = providers[0];
- // provider.origin is a string.
- do_check_true(provider.isSameOrigin(provider.origin));
- do_check_true(provider.isSameOrigin(Services.io.newURI(provider.origin, null, null)));
- do_check_true(provider.isSameOrigin(provider.origin + "/some-sub-page"));
- do_check_true(provider.isSameOrigin(Services.io.newURI(provider.origin + "/some-sub-page", null, null)));
- do_check_false(provider.isSameOrigin("http://something.com"));
- do_check_false(provider.isSameOrigin(Services.io.newURI("http://something.com", null, null)));
- do_check_false(provider.isSameOrigin("data:text/html,hi"));
- do_check_true(provider.isSameOrigin("data:text/html,
hi", true));
- do_check_false(provider.isSameOrigin(Services.io.newURI("data:text/html,
hi", null, null)));
- do_check_true(provider.isSameOrigin(Services.io.newURI("data:text/html,
hi", null, null), true));
- // we explicitly handle null and return false
- do_check_false(provider.isSameOrigin(null));
-}
-
-function* testResolveUri(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
- let provider = providers[0];
- do_check_eq(provider.resolveUri(provider.origin).spec, provider.origin + "/");
- do_check_eq(provider.resolveUri("foo.html").spec, provider.origin + "/foo.html");
- do_check_eq(provider.resolveUri("/foo.html").spec, provider.origin + "/foo.html");
- do_check_eq(provider.resolveUri("http://somewhereelse.com/foo.html").spec, "http://somewhereelse.com/foo.html");
- do_check_eq(provider.resolveUri("data:text/html,
hi").spec, "data:text/html,
hi");
-}
-
-function* testOrderedProviders(manifests, next) {
- let providers = yield SocialService.getProviderList(next);
-
- // add visits for only one of the providers
- let visits = [];
- let startDate = Date.now() * 1000;
- for (let i = 0; i < 10; i++) {
- visits.push({
- uri: Services.io.newURI(providers[1].shareURL + i, null, null),
- visitDate: startDate + i
- });
- }
-
- PlacesTestUtils.addVisits(visits).then(next);
- yield;
- let orderedProviders = yield SocialService.getOrderedProviderList(next);
- do_check_eq(orderedProviders[0], providers[1]);
- do_check_eq(orderedProviders[1], providers[0]);
- do_check_true(orderedProviders[0].frecency > orderedProviders[1].frecency);
- PlacesTestUtils.clearHistory().then(next);
- yield;
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration21.js b/browser/modules/test/unit/social/test_SocialServiceMigration21.js
deleted file mode 100644
index dfe6183bf2..0000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration21.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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-const DEFAULT_PREFS = Services.prefs.getDefaultBranch("social.manifest.");
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- builtin: true // as of fx22 this should be true for default prefs
- };
-
- DEFAULT_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
- Services.prefs.setBoolPref("social.active", true);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_false(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_true(SocialService.enabled);
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString);
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin]);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- do_check_true(JSON.parse(DEFAULT_PREFS.getCharPref(manifest.origin)).builtin);
-
- let userPref = JSON.parse(MANIFEST_PREFS.getCharPref(manifest.origin));
- do_check_true(parseInt(userPref.updateDate) > 0);
- // migrated providers wont have an installDate
- do_check_true(userPref.installDate === 0);
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration22.js b/browser/modules/test/unit/social/test_SocialServiceMigration22.js
deleted file mode 100644
index 1a39531756..0000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration22.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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-const DEFAULT_PREFS = Services.prefs.getDefaultBranch("social.manifest.");
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- builtin: true // as of fx22 this should be true for default prefs
- };
-
- DEFAULT_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
-
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- active[manifest.origin] = 1;
- // bad.origin tests that a missing manifest does not break migration, bug 859715
- active["bad.origin"] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_false(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_true(SocialService.enabled);
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString);
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin]);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- do_check_true(JSON.parse(DEFAULT_PREFS.getCharPref(manifest.origin)).builtin);
-
- let userPref = JSON.parse(MANIFEST_PREFS.getCharPref(manifest.origin));
- do_check_true(parseInt(userPref.updateDate) > 0);
- // migrated providers wont have an installDate
- do_check_true(userPref.installDate === 0);
-
- // bug 859715, this should have been removed during migration
- do_check_false(!!activeProviders["bad.origin"]);
-}
diff --git a/browser/modules/test/unit/social/test_SocialServiceMigration29.js b/browser/modules/test/unit/social/test_SocialServiceMigration29.js
deleted file mode 100644
index 824673ddfd..0000000000
--- a/browser/modules/test/unit/social/test_SocialServiceMigration29.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/. */
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-
-function run_test() {
- // Test must run at startup for migration to occur, so we can only test
- // one migration per test file
- initApp();
-
- // NOTE: none of the manifests here can have a workerURL set, or we attempt
- // to create a FrameWorker and that fails under xpcshell...
- let manifest = { // normal provider
- name: "provider 1",
- origin: "https://example1.com",
- };
-
- MANIFEST_PREFS.setCharPref(manifest.origin, JSON.stringify(manifest));
-
- // Set both providers active and flag the first one as "current"
- let activeVal = Cc["@mozilla.org/supports-string;1"].
- createInstance(Ci.nsISupportsString);
- let active = {};
- active[manifest.origin] = 1;
- activeVal.data = JSON.stringify(active);
- Services.prefs.setComplexValue("social.activeProviders",
- Ci.nsISupportsString, activeVal);
-
- // social.enabled pref is the key focus of this test. We set the user pref,
- // and then migration should a) remove the provider from activeProviders and
- // b) unset social.enabled
- Services.prefs.setBoolPref("social.enabled", false);
-
- Cu.import("resource:///modules/SocialService.jsm");
-
- let runner = new AsyncRunner();
- let next = runner.next.bind(runner);
- runner.appendIterator(testMigration(manifest, next));
- runner.next();
-}
-
-function* testMigration(manifest, next) {
- // look at social.activeProviders, we should have migrated into that, and
- // we should be set as a user level pref after migration
- do_check_true(Services.prefs.prefHasUserValue("social.enabled"));
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
- // we need to access the providers for everything to initialize
- yield SocialService.getProviderList(next);
- do_check_false(SocialService.enabled);
- do_check_false(Services.prefs.prefHasUserValue("social.enabled"));
- do_check_true(Services.prefs.prefHasUserValue("social.activeProviders"));
-
- let activeProviders;
- let pref = Services.prefs.getComplexValue("social.activeProviders",
- Ci.nsISupportsString).data;
- activeProviders = JSON.parse(pref);
- do_check_true(activeProviders[manifest.origin] == undefined);
- do_check_true(MANIFEST_PREFS.prefHasUserValue(manifest.origin));
-}
diff --git a/browser/modules/test/unit/social/test_social.js b/browser/modules/test/unit/social/test_social.js
deleted file mode 100644
index 3117306c1d..0000000000
--- a/browser/modules/test/unit/social/test_social.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/. */
-
-function run_test() {
- // we are testing worker startup specifically
- do_test_pending();
- add_test(testStartupEnabled);
- add_test(testDisableAfterStartup);
- do_initialize_social(true, run_next_test);
-}
-
-function testStartupEnabled() {
- // wait on startup before continuing
- do_check_eq(Social.providers.length, 2, "two social providers enabled");
- do_check_true(Social.providers[0].enabled, "provider 0 is enabled");
- do_check_true(Social.providers[1].enabled, "provider 1 is enabled");
- run_next_test();
-}
-
-function testDisableAfterStartup() {
- let SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
- SocialService.disableProvider(Social.providers[0].origin, function() {
- do_wait_observer("social:providers-changed", function() {
- do_check_eq(Social.enabled, false, "Social is disabled");
- do_check_eq(Social.providers.length, 0, "no social providers available");
- do_test_finished();
- run_next_test();
- });
- SocialService.disableProvider(Social.providers[0].origin)
- });
-}
diff --git a/browser/modules/test/unit/social/test_socialDisabledStartup.js b/browser/modules/test/unit/social/test_socialDisabledStartup.js
deleted file mode 100644
index a2f7a1d5af..0000000000
--- a/browser/modules/test/unit/social/test_socialDisabledStartup.js
+++ /dev/null
@@ -1,29 +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 run_test() {
- // we are testing worker startup specifically
- do_test_pending();
- add_test(testStartupDisabled);
- add_test(testEnableAfterStartup);
- do_initialize_social(false, run_next_test);
-}
-
-function testStartupDisabled() {
- // wait on startup before continuing
- do_check_false(Social.enabled, "Social is disabled");
- do_check_eq(Social.providers.length, 0, "zero social providers available");
- run_next_test();
-}
-
-function testEnableAfterStartup() {
- do_add_providers(function () {
- do_check_true(Social.enabled, "Social is enabled");
- do_check_eq(Social.providers.length, 2, "two social providers available");
- do_check_true(Social.providers[0].enabled, "provider 0 is enabled");
- do_check_true(Social.providers[1].enabled, "provider 1 is enabled");
- do_test_finished();
- run_next_test();
- });
-}
diff --git a/browser/modules/test/unit/social/xpcshell.ini b/browser/modules/test/unit/social/xpcshell.ini
deleted file mode 100644
index 277dd4f494..0000000000
--- a/browser/modules/test/unit/social/xpcshell.ini
+++ /dev/null
@@ -1,13 +0,0 @@
-[DEFAULT]
-head = head.js
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-support-files = blocklist.xml
-
-[test_social.js]
-[test_socialDisabledStartup.js]
-[test_SocialService.js]
-[test_SocialServiceMigration21.js]
-[test_SocialServiceMigration22.js]
-[test_SocialServiceMigration29.js]
diff --git a/browser/modules/test/usageTelemetrySearchSuggestions.sjs b/browser/modules/test/usageTelemetrySearchSuggestions.sjs
deleted file mode 100644
index 1978b4f665..0000000000
--- a/browser/modules/test/usageTelemetrySearchSuggestions.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/modules/test/usageTelemetrySearchSuggestions.xml b/browser/modules/test/usageTelemetrySearchSuggestions.xml
deleted file mode 100644
index 76276045df..0000000000
--- a/browser/modules/test/usageTelemetrySearchSuggestions.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-browser_UsageTelemetry usageTelemetrySearchSuggestions.xml
-
-
-
diff --git a/browser/modules/test/xpcshell/.eslintrc.js b/browser/modules/test/xpcshell/.eslintrc.js
deleted file mode 100644
index fee088c179..0000000000
--- a/browser/modules/test/xpcshell/.eslintrc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-module.exports = {
- "extends": [
- "../../../../testing/xpcshell/xpcshell.eslintrc.js"
- ]
-};
diff --git a/browser/modules/test/xpcshell/test_AttributionCode.js b/browser/modules/test/xpcshell/test_AttributionCode.js
deleted file mode 100644
index d979ae8459..0000000000
--- a/browser/modules/test/xpcshell/test_AttributionCode.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-const {interfaces: Ci, utils: Cu} = Components;
-
-Cu.import("resource://gre/modules/AppConstants.jsm");
-Cu.import("resource:///modules/AttributionCode.jsm");
-Cu.import('resource://gre/modules/osfile.jsm');
-Cu.import("resource://gre/modules/Services.jsm");
-
-let validAttrCodes = [
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D(not%20set)%26content%3D(not%20set)",
- parsed: {"source": "google.com", "medium": "organic",
- "campaign": "(not%20set)", "content": "(not%20set)"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D%26content%3D",
- parsed: {"source": "google.com", "medium": "organic"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D(not%20set)",
- parsed: {"source": "google.com", "medium": "organic", "campaign": "(not%20set)"}},
- {code: "source%3Dgoogle.com%26medium%3Dorganic",
- parsed: {"source": "google.com", "medium": "organic"}},
- {code: "source%3Dgoogle.com",
- parsed: {"source": "google.com"}},
- {code: "medium%3Dgoogle.com",
- parsed: {"medium": "google.com"}},
- {code: "campaign%3Dgoogle.com",
- parsed: {"campaign": "google.com"}},
- {code: "content%3Dgoogle.com",
- parsed: {"content": "google.com"}}
-];
-
-let invalidAttrCodes = [
- // Empty string
- "",
- // Not escaped
- "source=google.com&medium=organic&campaign=(not set)&content=(not set)",
- // Too long
- "source%3Dreallyreallyreallyreallyreallyreallyreallyreallyreallylongdomain.com%26medium%3Dorganic%26campaign%3D(not%20set)%26content%3Dalmostexactlyenoughcontenttomakethisstringlongerthanthe200characterlimit",
- // Unknown key name
- "source%3Dgoogle.com%26medium%3Dorganic%26large%3Dgeneticallymodified",
- // Empty key name
- "source%3Dgoogle.com%26medium%3Dorganic%26%3Dgeneticallymodified"
-];
-
-function* writeAttributionFile(data) {
- let appDir = Services.dirsvc.get("LocalAppData", Ci.nsIFile);
- let file = appDir.clone();
- file.append(Services.appinfo.vendor || "mozilla");
- file.append(AppConstants.MOZ_APP_NAME);
-
- yield OS.File.makeDir(file.path,
- {from: appDir.path, ignoreExisting: true});
-
- file.append("postSigningData");
- yield OS.File.writeAtomic(file.path, data);
-}
-
-/**
- * Test validation of attribution codes,
- * to make sure we reject bad ones and accept good ones.
- */
-add_task(function* testValidAttrCodes() {
- for (let entry of validAttrCodes) {
- AttributionCode._clearCache();
- yield writeAttributionFile(entry.code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, entry.parsed,
- "Parsed code should match expected value, code was: " + entry.code);
- }
- AttributionCode._clearCache();
-});
-
-/**
- * Make sure codes with various formatting errors are not seen as valid.
- */
-add_task(function* testInvalidAttrCodes() {
- for (let code of invalidAttrCodes) {
- AttributionCode._clearCache();
- yield writeAttributionFile(code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, {},
- "Code should have failed to parse: " + code);
- }
- AttributionCode._clearCache();
-});
-
-/**
- * Test the cache by deleting the attribution data file
- * and making sure we still get the expected code.
- */
-add_task(function* testDeletedFile() {
- // Set up the test by clearing the cache and writing a valid file.
- yield writeAttributionFile(validAttrCodes[0].code);
- let result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, validAttrCodes[0].parsed,
- "The code should be readable directly from the file");
-
- // Delete the file and make sure we can still read the value back from cache.
- yield AttributionCode.deleteFileAsync();
- result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, validAttrCodes[0].parsed,
- "The code should be readable from the cache");
-
- // Clear the cache and check we can't read anything.
- AttributionCode._clearCache();
- result = yield AttributionCode.getAttrDataAsync();
- Assert.deepEqual(result, {},
- "Shouldn't be able to get a code after file is deleted and cache is cleared");
-});
diff --git a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
deleted file mode 100644
index 712f52fa65..0000000000
--- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
+++ /dev/null
@@ -1,1854 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-/**
- * This file tests the DirectoryLinksProvider singleton in the DirectoryLinksProvider.jsm module.
- */
-
-var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu, Constructor: CC } = Components;
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource:///modules/DirectoryLinksProvider.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Http.jsm");
-Cu.import("resource://testing-common/httpd.js");
-Cu.import("resource://gre/modules/osfile.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/PlacesUtils.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
- "resource://gre/modules/NetUtil.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
- "resource://gre/modules/NewTabUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
- "resource://testing-common/PlacesTestUtils.jsm");
-
-do_get_profile();
-
-const DIRECTORY_LINKS_FILE = "directoryLinks.json";
-const DIRECTORY_FRECENCY = 1000;
-const SUGGESTED_FRECENCY = Infinity;
-const kURLData = {"directory": [{"url":"http://example.com", "title":"LocalSource"}]};
-const kTestURL = 'data:application/json,' + JSON.stringify(kURLData);
-
-// DirectoryLinksProvider preferences
-const kLocalePref = DirectoryLinksProvider._observedPrefs.prefSelectedLocale;
-const kSourceUrlPref = DirectoryLinksProvider._observedPrefs.linksURL;
-const kPingUrlPref = "browser.newtabpage.directory.ping";
-const kNewtabEnhancedPref = "browser.newtabpage.enhanced";
-
-// httpd settings
-var server;
-const kDefaultServerPort = 9000;
-const kBaseUrl = "http://localhost:" + kDefaultServerPort;
-const kExamplePath = "/exampleTest/";
-const kFailPath = "/fail/";
-const kPingPath = "/ping/";
-const kExampleURL = kBaseUrl + kExamplePath;
-const kFailURL = kBaseUrl + kFailPath;
-const kPingUrl = kBaseUrl + kPingPath;
-
-// app/profile/firefox.js are not avaialble in xpcshell: hence, preset them
-Services.prefs.setCharPref(kLocalePref, "en-US");
-Services.prefs.setCharPref(kSourceUrlPref, kTestURL);
-Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-Services.prefs.setBoolPref(kNewtabEnhancedPref, true);
-
-const kHttpHandlerData = {};
-kHttpHandlerData[kExamplePath] = {"directory": [{"url":"http://example.com", "title":"RemoteSource"}]};
-
-const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
- "nsIBinaryInputStream",
- "setInputStream");
-
-var gLastRequestPath;
-
-var suggestedTile1 = {
- url: "http://turbotax.com",
- type: "affiliate",
- lastVisitDate: 4,
- adgroup_name: "Adgroup1",
- frecent_sites: [
- "taxact.com",
- "hrblock.com",
- "1040.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile2 = {
- url: "http://irs.gov",
- type: "affiliate",
- lastVisitDate: 3,
- adgroup_name: "Adgroup2",
- frecent_sites: [
- "taxact.com",
- "hrblock.com",
- "freetaxusa.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile3 = {
- url: "http://hrblock.com",
- type: "affiliate",
- lastVisitDate: 2,
- adgroup_name: "Adgroup3",
- frecent_sites: [
- "taxact.com",
- "freetaxusa.com",
- "1040.com",
- "taxslayer.com"
- ]
-};
-var suggestedTile4 = {
- url: "http://sponsoredtile.com",
- type: "sponsored",
- lastVisitDate: 1,
- adgroup_name: "Adgroup4",
- frecent_sites: [
- "sponsoredtarget.com"
- ]
-}
-var suggestedTile5 = {
- url: "http://eviltile.com",
- type: "affiliate",
- lastVisitDate: 5,
- explanation: "This is an evil tile
X muhahaha",
- adgroup_name: "WE ARE EVIL ",
- frecent_sites: [
- "eviltarget.com"
- ]
-}
-var someOtherSite = {url: "http://someothersite.com", title: "Not_A_Suggested_Site"};
-
-function getHttpHandler(path) {
- let code = 200;
- let body = JSON.stringify(kHttpHandlerData[path]);
- if (path == kFailPath) {
- code = 204;
- }
- return function(aRequest, aResponse) {
- gLastRequestPath = aRequest.path;
- aResponse.setStatusLine(null, code);
- aResponse.setHeader("Content-Type", "application/json");
- aResponse.write(body);
- };
-}
-
-function isIdentical(actual, expected) {
- if (expected == null) {
- do_check_eq(actual, expected);
- }
- else if (typeof expected == "object") {
- // Make sure all the keys match up
- do_check_eq(Object.keys(actual).sort() + "", Object.keys(expected).sort());
-
- // Recursively check each value individually
- Object.keys(expected).forEach(key => {
- isIdentical(actual[key], expected[key]);
- });
- }
- else {
- do_check_eq(actual, expected);
- }
-}
-
-function fetchData() {
- let deferred = Promise.defer();
-
- DirectoryLinksProvider.getLinks(linkData => {
- deferred.resolve(linkData);
- });
- return deferred.promise;
-}
-
-function readJsonFile(jsonFile = DIRECTORY_LINKS_FILE) {
- let decoder = new TextDecoder();
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.localProfileDir, jsonFile);
- return OS.File.read(directoryLinksFilePath).then(array => {
- let json = decoder.decode(array);
- return JSON.parse(json);
- }, () => { return "" });
-}
-
-function cleanJsonFile(jsonFile = DIRECTORY_LINKS_FILE) {
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.localProfileDir, jsonFile);
- return OS.File.remove(directoryLinksFilePath);
-}
-
-function LinksChangeObserver() {
- this.deferred = Promise.defer();
- this.onManyLinksChanged = () => this.deferred.resolve();
- this.onDownloadFail = this.onManyLinksChanged;
-}
-
-function promiseDirectoryDownloadOnPrefChange(pref, newValue) {
- let oldValue = Services.prefs.getCharPref(pref);
- if (oldValue != newValue) {
- // if the preference value is already equal to newValue
- // the pref service will not call our observer and we
- // deadlock. Hence only setup observer if values differ
- let observer = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(observer);
- Services.prefs.setCharPref(pref, newValue);
- return observer.deferred.promise.then(() => {
- DirectoryLinksProvider.removeObserver(observer);
- });
- }
- return Promise.resolve();
-}
-
-function promiseSetupDirectoryLinksProvider(options = {}) {
- return Task.spawn(function*() {
- let linksURL = options.linksURL || kTestURL;
- yield DirectoryLinksProvider.init();
- yield promiseDirectoryDownloadOnPrefChange(kLocalePref, options.locale || "en-US");
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, linksURL);
- do_check_eq(DirectoryLinksProvider._linksURL, linksURL);
- DirectoryLinksProvider._lastDownloadMS = options.lastDownloadMS || 0;
- });
-}
-
-function promiseCleanDirectoryLinksProvider() {
- return Task.spawn(function*() {
- yield promiseDirectoryDownloadOnPrefChange(kLocalePref, "en-US");
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kTestURL);
- yield DirectoryLinksProvider._clearFrequencyCap();
- yield DirectoryLinksProvider._loadInadjacentSites();
- DirectoryLinksProvider._lastDownloadMS = 0;
- DirectoryLinksProvider.reset();
- });
-}
-
-function run_test() {
- // Set up a mock HTTP server to serve a directory page
- server = new HttpServer();
- server.registerPrefixHandler(kExamplePath, getHttpHandler(kExamplePath));
- server.registerPrefixHandler(kFailPath, getHttpHandler(kFailPath));
- server.start(kDefaultServerPort);
- NewTabUtils.init();
-
- run_next_test();
-
- // Teardown.
- do_register_cleanup(function() {
- server.stop(function() { });
- DirectoryLinksProvider.reset();
- Services.prefs.clearUserPref(kLocalePref);
- Services.prefs.clearUserPref(kSourceUrlPref);
- Services.prefs.clearUserPref(kPingUrlPref);
- Services.prefs.clearUserPref(kNewtabEnhancedPref);
- });
-}
-
-
-function setTimeout(fun, timeout) {
- let timer = Components.classes["@mozilla.org/timer;1"]
- .createInstance(Components.interfaces.nsITimer);
- var event = {
- notify: function () {
- fun();
- }
- };
- timer.initWithCallback(event, timeout,
- Components.interfaces.nsITimer.TYPE_ONE_SHOT);
- return timer;
-}
-
-add_task(function test_shouldUpdateSuggestedTile() {
- let suggestedLink = {
- targetedSite: "somesite.com"
- };
-
- // DirectoryLinksProvider has no suggested tile and no top sites => no need to update
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 0);
- isIdentical(NewTabUtils.getProviderLinks(), []);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), false);
-
- // DirectoryLinksProvider has a suggested tile and no top sites => need to update
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = (provider) => [suggestedLink];
-
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 0);
- isIdentical(NewTabUtils.getProviderLinks(), [suggestedLink]);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), true);
-
- // DirectoryLinksProvider has a suggested tile and 8 top sites => no need to update
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 8);
- isIdentical(NewTabUtils.getProviderLinks(), [suggestedLink]);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), false);
-
- // DirectoryLinksProvider has no suggested tile and 8 top sites => need to update
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- do_check_eq(DirectoryLinksProvider._getCurrentTopSiteCount(), 8);
- isIdentical(NewTabUtils.getProviderLinks(), []);
- do_check_eq(DirectoryLinksProvider._shouldUpdateSuggestedTile(), true);
-
- // Cleanup
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function* test_updateSuggestedTile() {
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
-
- // Initial setup
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestFirstRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- function TestFirstRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- links.unshift(link);
- let possibleLinks = [suggestedTile1.url, suggestedTile2.url, suggestedTile3.url];
-
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "1040.com", "freetaxusa.com"]);
- do_check_true(possibleLinks.indexOf(link.url) > -1);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.type, "affiliate");
- resolve();
- };
- });
- }
-
- function TestChangingSuggestedTile() {
- this.count = 0;
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- this.count++;
- let possibleLinks = [suggestedTile1.url, suggestedTile2.url, suggestedTile3.url];
-
- do_check_true(possibleLinks.indexOf(link.url) > -1);
- do_check_eq(link.type, "affiliate");
- do_check_true(this.count <= 2);
-
- if (this.count == 1) {
- // The removed suggested link is the one we added initially.
- do_check_eq(link.url, links.shift().url);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- } else {
- links.unshift(link);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- }
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "freetaxusa.com"]);
- resolve();
- }
- });
- }
-
- function TestRemovingSuggestedTile() {
- this.count = 0;
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- this.count++;
-
- do_check_eq(link.type, "affiliate");
- do_check_eq(this.count, 1);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.url, links.shift().url);
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], []);
- resolve();
- }
- });
- }
-
- // Test first call to '_updateSuggestedTile()', called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // Removing a top site that doesn't have a suggested link should
- // not change the current suggested tile.
- let removedTopsite = topSites.shift();
- do_check_eq(removedTopsite, "site0.com");
- do_check_false(NewTabUtils.isTopPlacesSite(removedTopsite));
- let updateSuggestedTile = DirectoryLinksProvider._handleLinkChanged({
- url: "http://" + removedTopsite,
- type: "history",
- });
- do_check_false(updateSuggestedTile);
-
- // Removing a top site that has a suggested link should
- // remove any current suggested tile and add a new one.
- testObserver = new TestChangingSuggestedTile();
- DirectoryLinksProvider.addObserver(testObserver);
- removedTopsite = topSites.shift();
- do_check_eq(removedTopsite, "1040.com");
- do_check_false(NewTabUtils.isTopPlacesSite(removedTopsite));
- DirectoryLinksProvider.onLinkChanged(DirectoryLinksProvider, {
- url: "http://" + removedTopsite,
- type: "history",
- });
- yield testObserver.promise;
- do_check_eq(testObserver.count, 2);
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // Removing all top sites with suggested links should remove
- // the current suggested link and not replace it.
- topSites = [];
- testObserver = new TestRemovingSuggestedTile();
- DirectoryLinksProvider.addObserver(testObserver);
- DirectoryLinksProvider.onManyLinksChanged();
- yield testObserver.promise;
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function* test_suggestedLinksMap() {
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3, suggestedTile4], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- // Ensure the suggested tiles were not considered directory tiles.
- do_check_eq(links.length, 1);
- let expected_data = [{url: "http://someothersite.com", title: "Not_A_Suggested_Site", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
- isIdentical(links, expected_data);
-
- // Check for correctly saved suggested tiles data.
- expected_data = {
- "taxact.com": [suggestedTile1, suggestedTile2, suggestedTile3],
- "hrblock.com": [suggestedTile1, suggestedTile2],
- "1040.com": [suggestedTile1, suggestedTile3],
- "taxslayer.com": [suggestedTile1, suggestedTile2, suggestedTile3],
- "freetaxusa.com": [suggestedTile2, suggestedTile3],
- "sponsoredtarget.com": [suggestedTile4],
- };
-
- let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
- do_check_eq(suggestedSites.indexOf("sponsoredtarget.com"), 5);
- do_check_eq(suggestedSites.length, Object.keys(expected_data).length);
-
- DirectoryLinksProvider._suggestedLinks.forEach((suggestedLinks, site) => {
- let suggestedLinksItr = suggestedLinks.values();
- for (let link of expected_data[site]) {
- let linkCopy = JSON.parse(JSON.stringify(link));
- linkCopy.targetedName = link.adgroup_name;
- linkCopy.explanation = "";
- isIdentical(suggestedLinksItr.next().value, linkCopy);
- }
- })
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_topSitesWithSuggestedLinks() {
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- // Mock out getProviderLinks() so we don't have to populate cache in NewTabUtils
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return [];
- }
-
- // We start off with no top sites with suggested links.
- do_check_eq(DirectoryLinksProvider._topSitesWithSuggestedLinks.size, 0);
-
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- yield fetchData();
-
- // Check we've populated suggested links as expected.
- do_check_eq(DirectoryLinksProvider._suggestedLinks.size, 5);
-
- // When many sites change, we update _topSitesWithSuggestedLinks as expected.
- let expectedTopSitesWithSuggestedLinks = ["hrblock.com", "1040.com", "freetaxusa.com"];
- DirectoryLinksProvider._handleManyLinksChanged();
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Removing site6.com as a topsite has no impact on _topSitesWithSuggestedLinks.
- let popped = topSites.pop();
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Removing freetaxusa.com as a topsite will remove it from _topSitesWithSuggestedLinks.
- popped = topSites.pop();
- expectedTopSitesWithSuggestedLinks.pop();
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Re-adding freetaxusa.com as a topsite will add it to _topSitesWithSuggestedLinks.
- topSites.push(popped);
- expectedTopSitesWithSuggestedLinks.push(popped);
- DirectoryLinksProvider._handleLinkChanged({url: "http://" + popped});
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], expectedTopSitesWithSuggestedLinks);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
-});
-
-add_task(function* test_suggestedAttributes() {
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let frecent_sites = "addons.mozilla.org,air.mozilla.org,blog.mozilla.org,bugzilla.mozilla.org,developer.mozilla.org,etherpad.mozilla.org,forums.mozillazine.org,hacks.mozilla.org,hg.mozilla.org,mozilla.org,planet.mozilla.org,quality.mozilla.org,support.mozilla.org,treeherder.mozilla.org,wiki.mozilla.org".split(",");
- let imageURI = "https://image/";
- let title = "the title";
- let type = "affiliate";
- let url = "http://test.url/";
- let adgroup_name = "Mozilla";
- let data = {
- suggested: [{
- frecent_sites,
- imageURI,
- title,
- type,
- url,
- adgroup_name
- }]
- };
- let dataURI = "data:application/json," + escape(JSON.stringify(data));
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- // Make sure we get the expected attributes on the suggested tile
- let link = gLinks.getLinks()[0];
- do_check_eq(link.imageURI, imageURI);
- do_check_eq(link.targetedName, "Mozilla");
- do_check_eq(link.targetedSite, frecent_sites[0]);
- do_check_eq(link.title, title);
- do_check_eq(link.type, type);
- do_check_eq(link.url, url);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
-});
-
-add_task(function* test_frequencyCappedSites_views() {
- Services.prefs.setCharPref(kPingUrlPref, "");
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let testUrl = "http://frequency.capped/link";
- let targets = ["top.site.com"];
- let data = {
- suggested: [{
- type: "affiliate",
- frecent_sites: targets,
- url: testUrl,
- frequency_caps: {daily: 5},
- adgroup_name: "Test"
- }],
- directory: [{
- type: "organic",
- url: "http://directory.site/"
- }]
- };
- let dataURI = "data:application/json," + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- function synthesizeAction(action) {
- DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: targets[0],
- url: testUrl
- }
- }], action, 0);
- }
-
- function checkFirstTypeAndLength(type, length) {
- let links = gLinks.getLinks();
- do_check_eq(links[0].type, type);
- do_check_eq(links.length, length);
- }
-
- // Make sure we get 5 views of the link before it is removed
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("organic", 1);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
- Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-});
-
-add_task(function* test_frequencyCappedSites_click() {
- Services.prefs.setCharPref(kPingUrlPref, "");
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let testUrl = "http://frequency.capped/link";
- let targets = ["top.site.com"];
- let data = {
- suggested: [{
- type: "affiliate",
- frecent_sites: targets,
- url: testUrl,
- adgroup_name: "Test"
- }],
- directory: [{
- type: "organic",
- url: "http://directory.site/"
- }]
- };
- let dataURI = "data:application/json," + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- function synthesizeAction(action) {
- DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: targets[0],
- url: testUrl
- }
- }], action, 0);
- }
-
- function checkFirstTypeAndLength(type, length) {
- let links = gLinks.getLinks();
- do_check_eq(links[0].type, type);
- do_check_eq(links.length, length);
- }
-
- // Make sure the link disappears after the first click
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("view");
- checkFirstTypeAndLength("affiliate", 2);
- synthesizeAction("click");
- checkFirstTypeAndLength("organic", 1);
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider.removeObserver(gLinks);
- Services.prefs.setCharPref(kPingUrlPref, kPingUrl);
-});
-
-add_task(function* test_fetchAndCacheLinks_local() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // Trigger cache of data or chrome uri files in profD
- yield DirectoryLinksProvider._fetchAndCacheLinks(kTestURL);
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-});
-
-add_task(function* test_fetchAndCacheLinks_remote() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // this must trigger directory links json download and save it to cache file
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kExampleURL + "%LOCALE%");
- do_check_eq(gLastRequestPath, kExamplePath + "en-US");
- let data = yield readJsonFile();
- isIdentical(data, kHttpHandlerData[kExamplePath]);
-});
-
-add_task(function* test_fetchAndCacheLinks_malformedURI() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- let someJunk = "some junk";
- try {
- yield DirectoryLinksProvider._fetchAndCacheLinks(someJunk);
- do_throw("Malformed URIs should fail")
- } catch (e) {
- do_check_eq(e, "Error fetching " + someJunk)
- }
-
- // File should be empty.
- let data = yield readJsonFile();
- isIdentical(data, "");
-});
-
-add_task(function* test_fetchAndCacheLinks_unknownHost() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- let nonExistentServer = "http://localhost:56789/";
- try {
- yield DirectoryLinksProvider._fetchAndCacheLinks(nonExistentServer);
- do_throw("BAD URIs should fail");
- } catch (e) {
- do_check_true(e.startsWith("Fetching " + nonExistentServer + " results in error code: "))
- }
-
- // File should be empty.
- let data = yield readJsonFile();
- isIdentical(data, "");
-});
-
-add_task(function* test_fetchAndCacheLinks_non200Status() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kFailURL);
- do_check_eq(gLastRequestPath, kFailPath);
- let data = yield readJsonFile();
- isIdentical(data, {});
-});
-
-// To test onManyLinksChanged observer, trigger a fetch
-add_task(function* test_DirectoryLinksProvider__linkObservers() {
- yield DirectoryLinksProvider.init();
-
- let testObserver = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(testObserver);
- do_check_eq(DirectoryLinksProvider._observers.size, 1);
- DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
-
- yield testObserver.deferred.promise;
- DirectoryLinksProvider._removeObservers();
- do_check_eq(DirectoryLinksProvider._observers.size, 0);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider__prefObserver_url() {
- yield promiseSetupDirectoryLinksProvider({linksURL: kTestURL});
-
- let links = yield fetchData();
- do_check_eq(links.length, 1);
- let expectedData = [{url: "http://example.com", title: "LocalSource", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
- isIdentical(links, expectedData);
-
- // tests these 2 things:
- // 1. _linksURL is properly set after the pref change
- // 2. invalid source url is correctly handled
- let exampleUrl = 'http://localhost:56789/bad';
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, exampleUrl);
- do_check_eq(DirectoryLinksProvider._linksURL, exampleUrl);
-
- // since the download fail, the directory file must remain the same
- let newLinks = yield fetchData();
- isIdentical(newLinks, expectedData);
-
- // now remove the file, and re-download
- yield cleanJsonFile();
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, exampleUrl + " ");
- // we now should see empty links
- newLinks = yield fetchData();
- isIdentical(newLinks, []);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinks_noDirectoryData() {
- let data = {
- "directory": [],
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 0);
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinks_badData() {
- let data = {
- "en-US": {
- "en-US": [{url: "http://example.com", title: "US"}],
- },
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Make sure we get nothing for incorrectly formatted data
- let links = yield fetchData();
- do_check_eq(links.length, 0);
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function test_DirectoryLinksProvider_needsDownload() {
- // test timestamping
- DirectoryLinksProvider._lastDownloadMS = 0;
- do_check_true(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = Date.now();
- do_check_false(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = Date.now() - (60*60*24 + 1)*1000;
- do_check_true(DirectoryLinksProvider._needsDownload);
- DirectoryLinksProvider._lastDownloadMS = 0;
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchAndCacheLinksIfNecessary() {
- yield DirectoryLinksProvider.init();
- yield cleanJsonFile();
- // explicitly change source url to cause the download during setup
- yield promiseSetupDirectoryLinksProvider({linksURL: kTestURL+" "});
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary();
-
- // inspect lastDownloadMS timestamp which should be 5 seconds less then now()
- let lastDownloadMS = DirectoryLinksProvider._lastDownloadMS;
- do_check_true((Date.now() - lastDownloadMS) < 5000);
-
- // we should have fetched a new file during setup
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- // attempt to download again - the timestamp should not change
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary();
- do_check_eq(DirectoryLinksProvider._lastDownloadMS, lastDownloadMS);
-
- // clean the file and force the download
- yield cleanJsonFile();
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- // make sure that failed download does not corrupt the file, nor changes lastDownloadMS
- lastDownloadMS = DirectoryLinksProvider._lastDownloadMS;
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, "http://");
- yield DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- data = yield readJsonFile();
- isIdentical(data, kURLData);
- do_check_eq(DirectoryLinksProvider._lastDownloadMS, lastDownloadMS);
-
- // _fetchAndCacheLinksIfNecessary must return same promise if download is in progress
- let downloadPromise = DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- let anotherPromise = DirectoryLinksProvider._fetchAndCacheLinksIfNecessary(true);
- do_check_true(downloadPromise === anotherPromise);
- yield downloadPromise;
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnPrefChange() {
- yield DirectoryLinksProvider.init();
-
- let testObserver = new LinksChangeObserver();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield cleanJsonFile();
- // ensure that provider does not think it needs to download
- do_check_false(DirectoryLinksProvider._needsDownload);
-
- // change the source URL, which should force directory download
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, kExampleURL);
- // then wait for testObserver to fire and test that json is downloaded
- yield testObserver.deferred.promise;
- do_check_eq(gLastRequestPath, kExamplePath);
- let data = yield readJsonFile();
- isIdentical(data, kHttpHandlerData[kExamplePath]);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnShow() {
- yield promiseSetupDirectoryLinksProvider();
-
- // set lastdownload to 0 to make DirectoryLinksProvider want to download
- DirectoryLinksProvider._lastDownloadMS = 0;
- do_check_true(DirectoryLinksProvider._needsDownload);
-
- // download should happen on view
- yield DirectoryLinksProvider.reportSitesAction([], "view");
- do_check_true(DirectoryLinksProvider._lastDownloadMS != 0);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_fetchDirectoryOnInit() {
- // ensure preferences are set to defaults
- yield promiseSetupDirectoryLinksProvider();
- // now clean to provider, so we can init it again
- yield promiseCleanDirectoryLinksProvider();
-
- yield cleanJsonFile();
- yield DirectoryLinksProvider.init();
- let data = yield readJsonFile();
- isIdentical(data, kURLData);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getLinksFromCorruptedFile() {
- yield promiseSetupDirectoryLinksProvider();
-
- // write bogus json to a file and attempt to fetch from it
- let directoryLinksFilePath = OS.Path.join(OS.Constants.Path.profileDir, DIRECTORY_LINKS_FILE);
- yield OS.File.writeAtomic(directoryLinksFilePath, '{"en-US":');
- let data = yield fetchData();
- isIdentical(data, []);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedLinks() {
- let data = {"directory": [
- {url: "ftp://example.com"},
- {url: "http://example.net"},
- {url: "javascript:5"},
- {url: "https://example.com"},
- {url: "httpJUNKjavascript:42"},
- {url: "data:text/plain,hi"},
- {url: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining url should be http and https
- do_check_eq(links[0].url, data["directory"][1].url);
- do_check_eq(links[1].url, data["directory"][3].url);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedImages() {
- let data = {"directory": [
- {url: "http://example.com", imageURI: "ftp://example.com"},
- {url: "http://example.com", imageURI: "http://example.net"},
- {url: "http://example.com", imageURI: "javascript:5"},
- {url: "http://example.com", imageURI: "https://example.com"},
- {url: "http://example.com", imageURI: "httpJUNKjavascript:42"},
- {url: "http://example.com", imageURI: "data:text/plain,hi"},
- {url: "http://example.com", imageURI: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining images should be https and data
- do_check_eq(links[0].imageURI, data["directory"][3].imageURI);
- do_check_eq(links[1].imageURI, data["directory"][5].imageURI);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedImages_base() {
- let data = {"directory": [
- {url: "http://example1.com", imageURI: "https://example.com"},
- {url: "http://example2.com", imageURI: "https://tiles.cdn.mozilla.net"},
- {url: "http://example3.com", imageURI: "https://tiles2.cdn.mozilla.net"},
- {url: "http://example4.com", enhancedImageURI: "https://mozilla.net"},
- {url: "http://example5.com", imageURI: "data:text/plain,hi"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Pretend we're using the default pref to trigger base matching
- DirectoryLinksProvider.__linksURLModified = false;
-
- let links = yield fetchData();
- do_check_eq(links.length, 4);
-
- // The only remaining images should be https with mozilla.net or data URI
- do_check_eq(links[0].url, data["directory"][1].url);
- do_check_eq(links[1].url, data["directory"][2].url);
- do_check_eq(links[2].url, data["directory"][3].url);
- do_check_eq(links[3].url, data["directory"][4].url);
-});
-
-add_task(function* test_DirectoryLinksProvider_getAllowedEnhancedImages() {
- let data = {"directory": [
- {url: "http://example.com", enhancedImageURI: "ftp://example.com"},
- {url: "http://example.com", enhancedImageURI: "http://example.net"},
- {url: "http://example.com", enhancedImageURI: "javascript:5"},
- {url: "http://example.com", enhancedImageURI: "https://example.com"},
- {url: "http://example.com", enhancedImageURI: "httpJUNKjavascript:42"},
- {url: "http://example.com", enhancedImageURI: "data:text/plain,hi"},
- {url: "http://example.com", enhancedImageURI: "http/bork:eh"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 2);
-
- // The only remaining enhancedImages should be http and https and data
- do_check_eq(links[0].enhancedImageURI, data["directory"][3].enhancedImageURI);
- do_check_eq(links[1].enhancedImageURI, data["directory"][5].enhancedImageURI);
-});
-
-add_task(function* test_DirectoryLinksProvider_getEnhancedLink() {
- let data = {"enhanced": [
- {url: "http://example.net", enhancedImageURI: "data:,net1"},
- {url: "http://example.com", enhancedImageURI: "data:,com1"},
- {url: "http://example.com", enhancedImageURI: "data:,com2"},
- ]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- let links = yield fetchData();
- do_check_eq(links.length, 0); // There are no directory links.
-
- function checkEnhanced(url, image) {
- let enhanced = DirectoryLinksProvider.getEnhancedLink({url: url});
- do_check_eq(enhanced && enhanced.enhancedImageURI, image);
- }
-
- // Get the expected image for the same site
- checkEnhanced("http://example.net/", "data:,net1");
- checkEnhanced("http://example.net/path", "data:,net1");
- checkEnhanced("https://www.example.net/", "data:,net1");
- checkEnhanced("https://www3.example.net/", "data:,net1");
-
- // Get the image of the last entry
- checkEnhanced("http://example.com", "data:,com2");
-
- // Get the inline enhanced image
- let inline = DirectoryLinksProvider.getEnhancedLink({
- url: "http://example.com/echo",
- enhancedImageURI: "data:,echo",
- });
- do_check_eq(inline.enhancedImageURI, "data:,echo");
- do_check_eq(inline.url, "http://example.com/echo");
-
- // Undefined for not enhanced
- checkEnhanced("http://sub.example.net/", undefined);
- checkEnhanced("http://example.org", undefined);
- checkEnhanced("http://localhost", undefined);
- checkEnhanced("http://127.0.0.1", undefined);
-
- // Make sure old data is not cached
- data = {"enhanced": [
- {url: "http://example.com", enhancedImageURI: "data:,fresh"},
- ]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- links = yield fetchData();
- do_check_eq(links.length, 0); // There are no directory links.
- checkEnhanced("http://example.net", undefined);
- checkEnhanced("http://example.com", "data:,fresh");
-});
-
-add_task(function* test_DirectoryLinksProvider_enhancedURIs() {
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = () => true;
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- let data = {
- "suggested": [
- {url: "http://example.net", enhancedImageURI: "data:,net1", title:"SuggestedTitle", adgroup_name: "Test", frecent_sites: ["test.com"]}
- ],
- "directory": [
- {url: "http://example.net", enhancedImageURI: "data:,net2", title:"DirectoryTitle"}
- ]
- };
- let dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
-
- // Wait for links to get loaded
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
- gLinks.populateCache();
- yield new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
-
- // Check that we've saved the directory tile.
- let links = yield fetchData();
- do_check_eq(links.length, 1);
- do_check_eq(links[0].title, "DirectoryTitle");
- do_check_eq(links[0].enhancedImageURI, "data:,net2");
-
- // Check that the suggested tile with the same URL replaces the directory tile.
- links = gLinks.getLinks();
- do_check_eq(links.length, 1);
- do_check_eq(links[0].title, "SuggestedTitle");
- do_check_eq(links[0].enhancedImageURI, "data:,net1");
-
- // Cleanup.
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- gLinks.removeProvider(DirectoryLinksProvider);
-});
-
-add_task(function test_DirectoryLinksProvider_setDefaultEnhanced() {
- function checkDefault(expected) {
- Services.prefs.clearUserPref(kNewtabEnhancedPref);
- do_check_eq(Services.prefs.getBoolPref(kNewtabEnhancedPref), expected);
- }
-
- // Use the default donottrack prefs (enabled = false)
- Services.prefs.clearUserPref("privacy.donottrackheader.enabled");
- checkDefault(true);
-
- // Turn on DNT - no track
- Services.prefs.setBoolPref("privacy.donottrackheader.enabled", true);
- checkDefault(false);
-
- // Turn off DNT header
- Services.prefs.clearUserPref("privacy.donottrackheader.enabled");
- checkDefault(true);
-
- // Clean up
- Services.prefs.clearUserPref("privacy.donottrackheader.value");
-});
-
-add_task(function* test_timeSensetiveSuggestedTiles() {
- // make tile json with start and end dates
- let testStartTime = Date.now();
- // start date is now + 1 seconds
- let startDate = new Date(testStartTime + 1000);
- // end date is now + 3 seconds
- let endDate = new Date(testStartTime + 3000);
- let suggestedTile = Object.assign({
- time_limits: {
- start: startDate.toISOString(),
- end: endDate.toISOString(),
- }
- }, suggestedTile1);
-
- // Initial setup
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestTimingRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // this tester will fire twice: when start limit is reached and when tile link
- // is removed upon end of the campaign, in which case deleteFlag will be set
- function TestTimingRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link, ignoreFlag, deleteFlag) => {
- // if we are not deleting, add link to links, so we can catch it's removal
- if (!deleteFlag) {
- links.unshift(link);
- }
-
- isIdentical([...DirectoryLinksProvider._topSitesWithSuggestedLinks], ["hrblock.com", "1040.com"]);
- do_check_eq(link.frecency, SUGGESTED_FRECENCY);
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- let timeDelta = Date.now() - testStartTime;
- if (!deleteFlag) {
- // this is start timeout corresponding to campaign start
- // a seconds must pass and targetedSite must be set
- do_print("TESTING START timeDelta: " + timeDelta);
- do_check_true(timeDelta >= 1000 / 2); // check for at least half time
- do_check_eq(link.targetedSite, "hrblock.com");
- do_check_true(DirectoryLinksProvider._campaignTimeoutID);
- }
- else {
- // this is the campaign end timeout, so 3 seconds must pass
- // and timeout should be cleared
- do_print("TESTING END timeDelta: " + timeDelta);
- do_check_true(timeDelta >= 3000 / 2); // check for at least half time
- do_check_false(link.targetedSite);
- do_check_false(DirectoryLinksProvider._campaignTimeoutID);
- resolve();
- }
- };
- });
- }
-
- // _updateSuggestedTile() is called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // shoudl suggest nothing
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // set links back to contain directory tile only
- links.shift();
-
- // drop the end time - we should pick up the tile
- suggestedTile.time_limits.end = null;
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
-
- // redownload json and getLinks to force time recomputation
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
-
- // ensure that there's a link returned by _updateSuggestedTile and no timeout
- let deferred = Promise.defer();
- DirectoryLinksProvider.getLinks(() => {
- let link = DirectoryLinksProvider._updateSuggestedTile();
- // we should have a suggested tile and no timeout
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- do_check_false(DirectoryLinksProvider._campaignTimeoutID);
- deferred.resolve();
- });
- yield deferred.promise;
-
- // repeat the test for end time only
- suggestedTile.time_limits.start = null;
- suggestedTile.time_limits.end = (new Date(Date.now() + 3000)).toISOString();
-
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
-
- // redownload json and call getLinks() to force time recomputation
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
-
- // ensure that there's a link returned by _updateSuggestedTile and timeout set
- deferred = Promise.defer();
- DirectoryLinksProvider.getLinks(() => {
- let link = DirectoryLinksProvider._updateSuggestedTile();
- // we should have a suggested tile and timeout set
- do_check_eq(link.type, "affiliate");
- do_check_eq(link.url, suggestedTile.url);
- do_check_true(DirectoryLinksProvider._campaignTimeoutID);
- DirectoryLinksProvider._clearCampaignTimeout();
- deferred.resolve();
- });
- yield deferred.promise;
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
-
-add_task(function test_setupStartEndTime() {
- let currentTime = Date.now();
- let dt = new Date(currentTime);
- let link = {
- time_limits: {
- start: dt.toISOString()
- }
- };
-
- // test ISO translation
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_eq(link.startTime, currentTime);
-
- // test localtime translation
- let shiftedDate = new Date(currentTime - dt.getTimezoneOffset()*60*1000);
- link.time_limits.start = shiftedDate.toISOString().replace(/Z$/, "");
-
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_eq(link.startTime, currentTime);
-
- // throw some garbage into date string
- delete link.startTime;
- link.time_limits.start = "no date"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-
- link.time_limits.start = "2015-99999-01T00:00:00"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-
- link.time_limits.start = "20150501T00:00:00"
- DirectoryLinksProvider._setupStartEndTime(link);
- do_check_false(link.startTime);
-});
-
-add_task(function* test_DirectoryLinksProvider_frequencyCapSetup() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- yield promiseCleanDirectoryLinksProvider();
- yield DirectoryLinksProvider._readFrequencyCapFile();
- isIdentical(DirectoryLinksProvider._frequencyCaps, {});
-
- // setup few links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "2",
- frequency_caps: {daily: 1, total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "3",
- frequency_caps: {total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "4",
- frequency_caps: {daily: 1}
- });
- let freqCapsObject = DirectoryLinksProvider._frequencyCaps;
- let capObject = freqCapsObject["1"];
- let defaultDaily = capObject.dailyCap;
- let defaultTotal = capObject.totalCap;
- // check if we have defaults set
- do_check_true(capObject.dailyCap > 0);
- do_check_true(capObject.totalCap > 0);
- // check if defaults are properly handled
- do_check_eq(freqCapsObject["2"].dailyCap, 1);
- do_check_eq(freqCapsObject["2"].totalCap, 2);
- do_check_eq(freqCapsObject["3"].dailyCap, defaultDaily);
- do_check_eq(freqCapsObject["3"].totalCap, 2);
- do_check_eq(freqCapsObject["4"].dailyCap, 1);
- do_check_eq(freqCapsObject["4"].totalCap, defaultTotal);
-
- // write object to file
- yield DirectoryLinksProvider._writeFrequencyCapFile();
- // empty out freqCapsObject and read file back
- DirectoryLinksProvider._frequencyCaps = {};
- yield DirectoryLinksProvider._readFrequencyCapFile();
- // re-ran tests - they should all pass
- do_check_eq(freqCapsObject["2"].dailyCap, 1);
- do_check_eq(freqCapsObject["2"].totalCap, 2);
- do_check_eq(freqCapsObject["3"].dailyCap, defaultDaily);
- do_check_eq(freqCapsObject["3"].totalCap, 2);
- do_check_eq(freqCapsObject["4"].dailyCap, 1);
- do_check_eq(freqCapsObject["4"].totalCap, defaultTotal);
-
- // wait a second and prune frequency caps
- yield new Promise(resolve => {
- setTimeout(resolve, 1100);
- });
-
- // update one link and create another
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "3",
- frequency_caps: {daily: 1, total: 2}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "7",
- frequency_caps: {daily: 1, total: 2}
- });
- // now prune the ones that have been in the object longer than 1 second
- DirectoryLinksProvider._pruneFrequencyCapUrls(1000);
- // make sure all keys but "3" and "7" are deleted
- Object.keys(DirectoryLinksProvider._frequencyCaps).forEach(key => {
- do_check_true(key == "3" || key == "7");
- });
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getFrequencyCapLogic() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- frequency_caps: {daily: 2, total: 4}
- });
-
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- // exhaust daily views
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // now step into the furture
- let _wasTodayOrig = DirectoryLinksProvider._wasToday;
- DirectoryLinksProvider._wasToday = function () { return false; }
- // exhaust total views
- DirectoryLinksProvider._addFrequencyCapView("1")
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
- DirectoryLinksProvider._addFrequencyCapView("1")
- // reached totalViews 4, should return false
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // add more views by updating configuration
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "1",
- frequency_caps: {daily: 5, total: 10}
- });
- // should be true, since we have more total views
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // set click flag
- DirectoryLinksProvider._setFrequencyCapClick("1");
- // always false after click
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("1"));
-
- // use unknown urls and ensure nothing breaks
- DirectoryLinksProvider._addFrequencyCapView("nosuch.url");
- DirectoryLinksProvider._setFrequencyCapClick("nosuch.url");
- // testing unknown url should always return false
- do_check_false(DirectoryLinksProvider._testFrequencyCapLimits("nosuch.url"));
-
- // reset _wasToday back to original function
- DirectoryLinksProvider._wasToday = _wasTodayOrig;
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_getFrequencyCapReportSiteAction() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "bar.com",
- frequency_caps: {daily: 2, total: 4}
- });
-
- do_check_true(DirectoryLinksProvider._testFrequencyCapLimits("bar.com"));
- // report site action
- yield DirectoryLinksProvider.reportSitesAction([{
- link: {
- targetedSite: "foo.com",
- url: "bar.com"
- },
- isPinned: function() { return false; },
- }], "view", 0);
-
- // read file content and ensure that view counters are updated
- let data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_eq(data["bar.com"].dailyViews, 1);
- do_check_eq(data["bar.com"].totalViews, 1);
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_DirectoryLinksProvider_ClickRemoval() {
- yield promiseSetupDirectoryLinksProvider();
- yield DirectoryLinksProvider.init();
- let landingUrl = "http://foo.com";
-
- // setup suggested links
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: landingUrl,
- frequency_caps: {daily: 2, total: 4}
- });
-
- // add views
- DirectoryLinksProvider._addFrequencyCapView(landingUrl)
- DirectoryLinksProvider._addFrequencyCapView(landingUrl)
- // make a click
- DirectoryLinksProvider._setFrequencyCapClick(landingUrl);
-
- // views must be 2 and click must be set
- do_check_eq(DirectoryLinksProvider._frequencyCaps[landingUrl].totalViews, 2);
- do_check_true(DirectoryLinksProvider._frequencyCaps[landingUrl].clicked);
-
- // now insert a visit into places
- yield new Promise(resolve => {
- PlacesUtils.asyncHistory.updatePlaces(
- {
- uri: NetUtil.newURI(landingUrl),
- title: "HELLO",
- visits: [{
- visitDate: Date.now()*1000,
- transitionType: Ci.nsINavHistoryService.TRANSITION_LINK
- }]
- },
- {
- handleError: function () { do_check_true(false); },
- handleResult: function () {},
- handleCompletion: function () { resolve(); }
- }
- );
- });
-
- function UrlDeletionTester() {
- this.promise = new Promise(resolve => {
- this.onDeleteURI = (directoryLinksProvider, link) => {
- resolve();
- };
- this.onClearHistory = (directoryLinksProvider) => {
- resolve();
- };
- });
- }
-
- let testObserver = new UrlDeletionTester();
- DirectoryLinksProvider.addObserver(testObserver);
-
- PlacesUtils.bhistory.removePage(NetUtil.newURI(landingUrl));
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
- // views must be 2 and click should not exist
- do_check_eq(DirectoryLinksProvider._frequencyCaps[landingUrl].totalViews, 2);
- do_check_false(DirectoryLinksProvider._frequencyCaps[landingUrl].hasOwnProperty("clicked"));
-
- // verify that disk written data is kosher
- let data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_eq(data[landingUrl].totalViews, 2);
- do_check_false(data[landingUrl].hasOwnProperty("clicked"));
-
- // now test clear history
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: landingUrl,
- frequency_caps: {daily: 2, total: 4}
- });
- DirectoryLinksProvider._updateFrequencyCapSettings({
- url: "http://bar.com",
- frequency_caps: {daily: 2, total: 4}
- });
-
- DirectoryLinksProvider._setFrequencyCapClick(landingUrl);
- DirectoryLinksProvider._setFrequencyCapClick("http://bar.com");
- // both tiles must have clicked
- do_check_true(DirectoryLinksProvider._frequencyCaps[landingUrl].clicked);
- do_check_true(DirectoryLinksProvider._frequencyCaps["http://bar.com"].clicked);
-
- testObserver = new UrlDeletionTester();
- DirectoryLinksProvider.addObserver(testObserver);
- yield PlacesTestUtils.clearHistory();
-
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
- // no clicks should remain in the cap object
- do_check_false(DirectoryLinksProvider._frequencyCaps[landingUrl].hasOwnProperty("clicked"));
- do_check_false(DirectoryLinksProvider._frequencyCaps["http://bar.com"].hasOwnProperty("clicked"));
-
- // verify that disk written data is kosher
- data = yield readJsonFile(DirectoryLinksProvider._frequencyCapFilePath);
- do_check_false(data[landingUrl].hasOwnProperty("clicked"));
- do_check_false(data["http://bar.com"].hasOwnProperty("clicked"));
-
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function test_DirectoryLinksProvider_anonymous() {
- do_check_true(DirectoryLinksProvider._newXHR().mozAnon);
-});
-
-add_task(function* test_sanitizeExplanation() {
- // Note: this is a basic test to ensure we applied sanitization to the link explanation.
- // Full testing for appropriate sanitization is done in parser/xml/test/unit/test_sanitizer.js.
- let data = {"suggested": [suggestedTile5]};
- let dataURI = 'data:application/json,' + encodeURIComponent(JSON.stringify(data));
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- yield fetchData();
-
- let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
- do_check_eq(suggestedSites.indexOf("eviltarget.com"), 0);
- do_check_eq(suggestedSites.length, 1);
-
- let suggestedLink = [...DirectoryLinksProvider._suggestedLinks.get(suggestedSites[0]).values()][0];
- do_check_eq(suggestedLink.explanation, "This is an evil tile X muhahaha");
- do_check_eq(suggestedLink.targetedName, "WE ARE EVIL ");
-});
-
-add_task(function* test_inadjecentSites() {
- let suggestedTile = Object.assign({
- check_inadjacency: true
- }, suggestedTile1);
-
- // Initial setup
- let topSites = ["1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- let testObserver = new TestFirstRun();
- DirectoryLinksProvider.addObserver(testObserver);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => {
- origCurrentTopSiteCount.apply(DirectoryLinksProvider);
- return 8;
- };
-
- // store oroginal inadjacent sites url
- let origInadjacentSitesUrl = DirectoryLinksProvider._inadjacentSitesUrl;
-
- // loading inadjacent sites list function
- function setInadjacentSites(sites) {
- let badSiteB64 = [];
- sites.forEach(site => {
- badSiteB64.push(DirectoryLinksProvider._generateHash(site));
- });
- let theList = {"domains": badSiteB64};
- let uri = 'data:application/json,' + JSON.stringify(theList);
- DirectoryLinksProvider._inadjacentSitesUrl = uri;
- return DirectoryLinksProvider._loadInadjacentSites();
- }
-
- // setup gLinks loader
- let gLinks = NewTabUtils.links;
- gLinks.addProvider(DirectoryLinksProvider);
-
- function updateNewTabCache() {
- gLinks.populateCache();
- return new Promise(resolve => {
- NewTabUtils.allPages.register({
- observe: _ => _,
- update() {
- NewTabUtils.allPages.unregister(this);
- resolve();
- }
- });
- });
- }
-
- // no suggested file
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
- // _avoidInadjacentSites should be set, since link.check_inadjacency is on
- do_check_true(DirectoryLinksProvider._avoidInadjacentSites);
- // make sure example.com is included in inadjacent sites list
- do_check_true(DirectoryLinksProvider._isInadjacentLink({baseDomain: "example.com"}));
-
- function TestFirstRun() {
- this.promise = new Promise(resolve => {
- this.onLinkChanged = (directoryLinksProvider, link) => {
- do_check_eq(link.url, suggestedTile.url);
- do_check_eq(link.type, "affiliate");
- resolve();
- };
- });
- }
-
- // Test first call to '_updateSuggestedTile()', called when fetching directory links.
- yield testObserver.promise;
- DirectoryLinksProvider.removeObserver(testObserver);
-
- // update newtab cache
- yield updateNewTabCache();
- // this should have set
- do_check_true(DirectoryLinksProvider._avoidInadjacentSites);
-
- // there should be siggested link
- let link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_eq(link.url, "http://turbotax.com");
- // and it should have avoidInadjacentSites flag
- do_check_true(link.check_inadjacency);
-
- // make someothersite.com inadjacent
- yield setInadjacentSites(["someothersite.com"]);
-
- // there should be no suggested link
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_false(link);
- do_check_true(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // _handleLinkChanged must return true on inadjacent site
- do_check_true(DirectoryLinksProvider._handleLinkChanged({
- url: "http://someothersite.com",
- type: "history",
- }));
- // _handleLinkChanged must return false on ok site
- do_check_false(DirectoryLinksProvider._handleLinkChanged({
- url: "http://foobar.com",
- type: "history",
- }));
-
- // change inadjacent list to sites not on newtab page
- yield setInadjacentSites(["foo.com", "bar.com"]);
-
- link = DirectoryLinksProvider._updateSuggestedTile();
- // we should now have a link
- do_check_true(link);
- do_check_eq(link.url, "http://turbotax.com");
-
- // make newtab offending again
- yield setInadjacentSites(["someothersite.com", "foo.com"]);
- // there should be no suggested link
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_false(link);
- do_check_true(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // remove avoidInadjacentSites flag from suggested tile and reload json
- delete suggestedTile.check_inadjacency;
- data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
- yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
- yield fetchData();
-
- // inadjacent checking should be disabled
- do_check_false(DirectoryLinksProvider._avoidInadjacentSites);
- link = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(link);
- do_check_eq(link.url, "http://turbotax.com");
- do_check_false(DirectoryLinksProvider._newTabHasInadjacentSite);
-
- // _handleLinkChanged should return false now, even if newtab has bad site
- do_check_false(DirectoryLinksProvider._handleLinkChanged({
- url: "http://someothersite.com",
- type: "history",
- }));
-
- // test _isInadjacentLink
- do_check_true(DirectoryLinksProvider._isInadjacentLink({baseDomain: "someothersite.com"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({baseDomain: "bar.com"}));
- do_check_true(DirectoryLinksProvider._isInadjacentLink({url: "http://www.someothersite.com"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "http://www.bar.com"}));
- // try to crash _isInadjacentLink
- do_check_false(DirectoryLinksProvider._isInadjacentLink({baseDomain: ""}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: ""}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "http://localhost:8081/"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({url: "abracodabra"}));
- do_check_false(DirectoryLinksProvider._isInadjacentLink({}));
-
- // test _checkForInadjacentSites
- do_check_true(DirectoryLinksProvider._checkForInadjacentSites());
-
- // Cleanup
- gLinks.removeProvider(DirectoryLinksProvider);
- DirectoryLinksProvider._inadjacentSitesUrl = origInadjacentSitesUrl;
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
- yield promiseCleanDirectoryLinksProvider();
-});
-
-add_task(function* test_blockSuggestedTiles() {
- // Initial setup
- let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
- let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
-
- yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
- let links = yield fetchData();
-
- let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
- NewTabUtils.isTopPlacesSite = function(site) {
- return topSites.indexOf(site) >= 0;
- }
-
- let origGetProviderLinks = NewTabUtils.getProviderLinks;
- NewTabUtils.getProviderLinks = function(provider) {
- return links;
- }
-
- let origCurrentTopSiteCount = DirectoryLinksProvider._getCurrentTopSiteCount;
- DirectoryLinksProvider._getCurrentTopSiteCount = () => 8;
-
- // load the links
- yield new Promise(resolve => {
- DirectoryLinksProvider.getLinks(resolve);
- });
-
- // ensure that tile is suggested
- let suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // block suggested tile in a regular way
- DirectoryLinksProvider.reportSitesAction([{
- isPinned: function() { return false; },
- link: Object.assign({frecency: 1000}, suggestedLink)
- }], "block", 0);
-
- // suggested tile still must be recommended
- suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // timestamp suggested_block in the frequency cap object
- DirectoryLinksProvider.handleSuggestedTileBlock();
- // no more recommendations should be seen
- do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
-
- // move lastUpdated for suggested tile into the past
- DirectoryLinksProvider._frequencyCaps["ignore://suggested_block"].lastUpdated = Date.now() - 25*60*60*1000;
- // ensure that suggested tile updates again
- suggestedLink = DirectoryLinksProvider._updateSuggestedTile();
- do_check_true(suggestedLink.frecent_sites);
-
- // Cleanup
- yield promiseCleanDirectoryLinksProvider();
- NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
- NewTabUtils.getProviderLinks = origGetProviderLinks;
- DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
-});
diff --git a/browser/modules/test/xpcshell/test_LaterRun.js b/browser/modules/test/xpcshell/test_LaterRun.js
deleted file mode 100644
index 7b45c7cd5f..0000000000
--- a/browser/modules/test/xpcshell/test_LaterRun.js
+++ /dev/null
@@ -1,138 +0,0 @@
-"use strict";
-
-const kEnabledPref = "browser.laterrun.enabled";
-const kPagePrefRoot = "browser.laterrun.pages.";
-const kSessionCountPref = "browser.laterrun.bookkeeping.sessionCount";
-const kProfileCreationTime = "browser.laterrun.bookkeeping.profileCreationTime";
-
-Components.utils.import("resource://gre/modules/Services.jsm");
-Components.utils.import("resource:///modules/LaterRun.jsm");
-
-Services.prefs.setBoolPref(kEnabledPref, true);
-Components.utils.import("resource://testing-common/AppInfo.jsm");
-updateAppInfo();
-
-add_task(function* test_page_applies() {
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "https://www.mozilla.org/%VENDOR%/%NAME%/%ID%/%VERSION%/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
-
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get included in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 1, "Got 1 page");
- let page = pages[0];
- Assert.equal(page.pref, kPagePrefRoot + "test_LaterRun_unittest.", "Should know its own pref");
- Assert.equal(page.minimumHoursSinceInstall, 10, "Needs to have 10 hours since install");
- Assert.equal(page.minimumSessionCount, 3, "Needs to have 3 sessions");
- Assert.equal(page.requireBoth, false, "Either requirement is enough");
- let expectedURL = "https://www.mozilla.org/" +
- Services.appinfo.vendor + "/" +
- Services.appinfo.name + "/" +
- Services.appinfo.ID + "/" +
- Services.appinfo.version + "/";
- Assert.equal(page.url, expectedURL, "URL is stored correctly");
-
- Assert.ok(page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Applies when session count has been met.");
- Assert.ok(page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Applies when session count has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Applies when total session time has been met.");
- Assert.ok(page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Applies when total session time has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Applies when both time and session count have been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when neither time and session count have been met.");
-
- page.requireBoth = true;
-
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Does not apply when only session count has been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Does not apply when only session count has been exceeded.");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Does not apply when only total session time has been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Does not apply when only total session time has been exceeded.");
- Assert.ok(page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Applies when both time and session count have been met.");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when neither time and session count have been met.");
-
- // Check that pages that have run never apply:
- Services.prefs.setBoolPref(kPagePrefRoot + "test_LaterRun_unittest.hasRun", true);
- page.requireBoth = false;
-
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 3}),
- "Does not apply when page has already run (sessionCount equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 4}),
- "Does not apply when page has already run (sessionCount exceeding).");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 2}),
- "Does not apply when page has already run (hoursSinceInstall equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 20, sessionCount: 2}),
- "Does not apply when page has already run (hoursSinceInstall exceeding).");
- Assert.ok(!page.applies({hoursSinceInstall: 10, sessionCount: 3}),
- "Does not apply when page has already run (both criteria equal).");
- Assert.ok(!page.applies({hoursSinceInstall: 1, sessionCount: 1}),
- "Does not apply when page has already run (both criteria insufficient anyway).");
-
- clearAllPagePrefs();
-});
-
-add_task(function* test_get_URL() {
- Services.prefs.setIntPref(kProfileCreationTime, Math.floor((Date.now() - 11 * 60 * 60 * 1000) / 1000));
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "https://www.mozilla.org/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get included in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 1, "Should only be 1 matching page");
- let page = pages[0];
- let url;
- do {
- url = LaterRun.getURL();
- // We have to loop because it's possible Firefox ships with other URLs that get triggered by
- // this test.
- } while (url && url != "https://www.mozilla.org/");
- Assert.equal(url, "https://www.mozilla.org/", "URL should be as expected when prefs are set.");
- Assert.ok(Services.prefs.prefHasUserValue(kPagePrefRoot + "test_LaterRun_unittest.hasRun"), "Should have set pref");
- Assert.ok(Services.prefs.getBoolPref(kPagePrefRoot + "test_LaterRun_unittest.hasRun"), "Should have set pref to true");
- Assert.ok(page.hasRun, "Other page objects should know it has run, too.");
-
- clearAllPagePrefs();
-});
-
-add_task(function* test_insecure_urls() {
- Services.prefs.setCharPref(kPagePrefRoot + "test_LaterRun_unittest.url", "http://www.mozilla.org/");
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumHoursSinceInstall", 10);
- Services.prefs.setIntPref(kPagePrefRoot + "test_LaterRun_unittest.minimumSessionCount", 3);
- let pages = LaterRun.readPages();
- // We have to filter the pages because it's possible Firefox ships with other URLs
- // that get triggered in this test.
- pages = pages.filter(page => page.pref == kPagePrefRoot + "test_LaterRun_unittest.");
- Assert.equal(pages.length, 0, "URL with non-https scheme should get ignored");
- clearAllPagePrefs();
-});
-
-add_task(function* test_dynamic_pref_getter_setter() {
- delete LaterRun._sessionCount;
- Services.prefs.setIntPref(kSessionCountPref, 0);
- Assert.equal(LaterRun.sessionCount, 0, "Should start at 0");
-
- LaterRun.sessionCount++;
- Assert.equal(LaterRun.sessionCount, 1, "Should increment.");
- Assert.equal(Services.prefs.getIntPref(kSessionCountPref), 1, "Should update pref");
-});
-
-function clearAllPagePrefs() {
- let allChangedPrefs = Services.prefs.getChildList(kPagePrefRoot);
- for (let pref of allChangedPrefs) {
- Services.prefs.clearUserPref(pref);
- }
-}
-
diff --git a/browser/modules/test/xpcshell/test_SitePermissions.js b/browser/modules/test/xpcshell/test_SitePermissions.js
deleted file mode 100644
index 808d965991..0000000000
--- a/browser/modules/test/xpcshell/test_SitePermissions.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-"use strict";
-
-Components.utils.import("resource:///modules/SitePermissions.jsm");
-Components.utils.import("resource://gre/modules/Services.jsm");
-
-add_task(function* testPermissionsListing() {
- Assert.deepEqual(SitePermissions.listPermissions().sort(),
- ["camera", "cookie", "desktop-notification", "geo", "image",
- "indexedDB", "install", "microphone", "popup", "screen"],
- "Correct list of all permissions");
-});
-
-add_task(function* testGetAllByURI() {
- // check that it returns an empty array on an invalid URI
- // like a file URI, which doesn't support site permissions
- let wrongURI = Services.io.newURI("file:///example.js", null, null)
- Assert.deepEqual(SitePermissions.getAllByURI(wrongURI), []);
-
- let uri = Services.io.newURI("https://example.com", null, null)
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
-
- SitePermissions.set(uri, "camera", SitePermissions.ALLOW);
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW }
- ]);
-
- SitePermissions.set(uri, "microphone", SitePermissions.SESSION);
- SitePermissions.set(uri, "desktop-notification", SitePermissions.BLOCK);
-
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW },
- { id: "microphone", state: SitePermissions.SESSION },
- { id: "desktop-notification", state: SitePermissions.BLOCK }
- ]);
-
- SitePermissions.remove(uri, "microphone");
- Assert.deepEqual(SitePermissions.getAllByURI(uri), [
- { id: "camera", state: SitePermissions.ALLOW },
- { id: "desktop-notification", state: SitePermissions.BLOCK }
- ]);
-
- SitePermissions.remove(uri, "camera");
- SitePermissions.remove(uri, "desktop-notification");
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
-
- // XXX Bug 1303108 - Control Center should only show non-default permissions
- SitePermissions.set(uri, "addon", SitePermissions.BLOCK);
- Assert.deepEqual(SitePermissions.getAllByURI(uri), []);
- SitePermissions.remove(uri, "addon");
-});
-
-add_task(function* testGetPermissionDetailsByURI() {
- // check that it returns an empty array on an invalid URI
- // like a file URI, which doesn't support site permissions
- let wrongURI = Services.io.newURI("file:///example.js", null, null)
- Assert.deepEqual(SitePermissions.getPermissionDetailsByURI(wrongURI), []);
-
- let uri = Services.io.newURI("https://example.com", null, null)
-
- SitePermissions.set(uri, "camera", SitePermissions.ALLOW);
- SitePermissions.set(uri, "cookie", SitePermissions.SESSION);
- SitePermissions.set(uri, "popup", SitePermissions.BLOCK);
-
- let permissions = SitePermissions.getPermissionDetailsByURI(uri);
-
- let camera = permissions.find(({id}) => id === "camera");
- Assert.deepEqual(camera, {
- id: "camera",
- label: "Use the Camera",
- state: SitePermissions.ALLOW,
- availableStates: [
- { id: SitePermissions.UNKNOWN, label: "Always Ask" },
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- // check that removed permissions (State.UNKNOWN) are skipped
- SitePermissions.remove(uri, "camera");
- permissions = SitePermissions.getPermissionDetailsByURI(uri);
-
- camera = permissions.find(({id}) => id === "camera");
- Assert.equal(camera, undefined);
-
- // check that different available state values are represented
-
- let cookie = permissions.find(({id}) => id === "cookie");
- Assert.deepEqual(cookie, {
- id: "cookie",
- label: "Set Cookies",
- state: SitePermissions.SESSION,
- availableStates: [
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.SESSION, label: "Allow for Session" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- let popup = permissions.find(({id}) => id === "popup");
- Assert.deepEqual(popup, {
- id: "popup",
- label: "Open Pop-up Windows",
- state: SitePermissions.BLOCK,
- availableStates: [
- { id: SitePermissions.ALLOW, label: "Allow" },
- { id: SitePermissions.BLOCK, label: "Block" },
- ]
- });
-
- SitePermissions.remove(uri, "cookie");
- SitePermissions.remove(uri, "popup");
-});
diff --git a/browser/modules/test/xpcshell/xpcshell.ini b/browser/modules/test/xpcshell/xpcshell.ini
deleted file mode 100644
index 28df9c4ed5..0000000000
--- a/browser/modules/test/xpcshell/xpcshell.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-[DEFAULT]
-head =
-tail =
-firefox-appdir = browser
-skip-if = toolkit == 'android'
-
-[test_AttributionCode.js]
-skip-if = os != 'win'
-[test_DirectoryLinksProvider.js]
-[test_SitePermissions.js]
-[test_LaterRun.js]
diff --git a/devtools/client/framework/test/browser.ini b/devtools/client/framework/test/browser.ini
index f34cd66f0e..2404490ce9 100644
--- a/devtools/client/framework/test/browser.ini
+++ b/devtools/client/framework/test/browser.ini
@@ -91,5 +91,3 @@ skip-if = os == "mac" && os_version == "10.8" || os == "win" && os_version == "5
[browser_toolbox_window_title_frame_select.js]
[browser_toolbox_zoom.js]
[browser_two_tabs.js]
-# We want this test to run for mochitest-dt as well, so we include it here:
-[../../../../browser/base/content/test/general/browser_parsable_css.js]
diff --git a/devtools/shared/webconsole/test/chrome.ini b/devtools/shared/webconsole/test/chrome.ini
index ae867b8218..fde5a79fd6 100644
--- a/devtools/shared/webconsole/test/chrome.ini
+++ b/devtools/shared/webconsole/test/chrome.ini
@@ -8,8 +8,6 @@ support-files =
network_requests_iframe.html
sandboxed_iframe.html
console-test-worker.js
- !/browser/base/content/test/general/browser_star_hsts.sjs
- !/browser/base/content/test/general/pinning_headers.sjs
[test_basics.html]
[test_bug819670_getter_throws.html]