| author | Myk Melez <myk@mykzilla.org> |
| Wed, 30 Jan 2019 17:26:25 +0000 | |
| changeset 456101 | 73a91e84dbec4fe4cd6881c0bdb377f7b0137e42 |
| parent 456100 | e793c88c1fd8f05495d4e032976af476aa76ce09 |
| child 456112 | 0a71d114c5e223542ca6687bbdf3ecb16c380677 |
| child 456113 | d8268f8ec7d271324c09e70cf23f40b18c584240 |
| push id | 35470 |
| push user | dvarga@mozilla.com |
| push date | Wed, 30 Jan 2019 21:53:29 +0000 |
| treeherder | mozilla-central@73a91e84dbec [default view] [failures only] |
| perfherder | [talos] [build metrics] [platform microbench] (compared to previous push) |
| reviewers | mossop, Standard8 |
| bugs | 1518283 |
| milestone | 67.0a1 |
| first release with | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
| last release without | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
--- a/accessible/jsat/Traversal.jsm +++ b/accessible/jsat/Traversal.jsm @@ -179,17 +179,16 @@ var TraversalRules = { // jshint ignore: Anchor: new BaseTraversalRule( [Roles.LINK], function Anchor_match(aAccessible) { // We want to ignore links, only focus named anchors. if (Utils.getState(aAccessible).contains(States.LINKED)) { return Filters.IGNORE; } return Filters.MATCH; - }), Button: new BaseTraversalRule( [Roles.PUSHBUTTON, Roles.SPINBUTTON, Roles.TOGGLE_BUTTON, Roles.BUTTONDROPDOWN, Roles.BUTTONDROPDOWNGRID]), @@ -268,17 +267,16 @@ var TraversalRules = { // jshint ignore: Link: new BaseTraversalRule( [Roles.LINK], function Link_match(aAccessible) { // We want to ignore anchors, only focus real links. if (Utils.getState(aAccessible).contains(States.LINKED)) { return Filters.MATCH; } return Filters.IGNORE; - }), /* For TalkBack's "Control" granularity. Form conrols and links */ Control: new BaseTraversalRule( [Roles.PUSHBUTTON, Roles.SPINBUTTON, Roles.TOGGLE_BUTTON, Roles.BUTTONDROPDOWN, @@ -387,12 +385,11 @@ var TraversalHelper = { // If we failed to step to another container, break and return false. break; } } return moved; } return aVirtualCursor[aMethod](rule); - }, };
--- a/accessible/jsat/Utils.jsm +++ b/accessible/jsat/Utils.jsm @@ -148,17 +148,16 @@ var Utils = { // jshint ignore:line return new State( aAccessibleOrEvent.isExtraState ? 0 : aAccessibleOrEvent.state, aAccessibleOrEvent.isExtraState ? aAccessibleOrEvent.state : 0); } let state = {}; let extState = {}; aAccessibleOrEvent.getState(state, extState); return new State(state.value, extState.value); - }, getAttributes: function getAttributes(aAccessible) { let attributes = {}; if (aAccessible && aAccessible.attributes) { // Populate |attributes| object with |aAccessible|'s attribute key-value // pairs.
--- a/accessible/tests/browser/.eslintrc.js +++ b/accessible/tests/browser/.eslintrc.js @@ -61,17 +61,16 @@ module.exports = { "no-underscore-dangle": "off", "no-undefined": "off", "no-unused-vars": ["error", {"vars": "all", "args": "none"}], "no-use-before-define": "off", "no-var": "off", "no-warning-comments": "off", "object-shorthand": "off", "one-var": ["error", "never"], - "padded-blocks": ["error", "never"], "quote-props": "off", "radix": "error", "semi-spacing": ["error", {"before": false, "after": true}], "sort-vars": "off", "space-in-parens": ["error", "never"], "strict": ["error", "global"], "valid-jsdoc": "off", "vars-on-top": "off",
--- a/accessible/tests/mochitest/actions.js +++ b/accessible/tests/mochitest/actions.js @@ -46,17 +46,16 @@ const XUL_EVENTS = CLICK_EVENTS | COMMAN * * * @param aArray [in] an array of action cheker objects */ function testActions(aArray) { gActionsQueue = new eventQueue(); for (var idx = 0; idx < aArray.length; idx++) { - var actionObj = aArray[idx]; var accOrElmOrID = actionObj.ID; var actionIndex = actionObj.actionIndex; var actionName = actionObj.actionName; var events = actionObj.events; var accOrElmOrIDOfTarget = actionObj.targetID ? actionObj.targetID : accOrElmOrID;
--- a/accessible/tests/mochitest/common.js +++ b/accessible/tests/mochitest/common.js @@ -251,20 +251,18 @@ const DONOTFAIL_IF_NO_INTERFACE = 2; function getAccessible(aAccOrElmOrID, aInterfaces, aElmObj, aDoNotFailIf) { if (!aAccOrElmOrID) return null; var elm = null; if (aAccOrElmOrID instanceof nsIAccessible) { try { elm = aAccOrElmOrID.DOMNode; } catch (e) { } - } else if (Node.isInstance(aAccOrElmOrID)) { elm = aAccOrElmOrID; - } else { elm = document.getElementById(aAccOrElmOrID); if (!elm) { ok(false, "Can't get DOM element for " + aAccOrElmOrID); return null; } } @@ -498,17 +496,16 @@ function testAccessibleTree(aAccOrElmOrI testChild = normalizeAccTreeObj(testChild); if (accChild.role !== testChild.role) { ok(false, prettyName(accTree) + " and " + prettyName(acc) + " have different children at index " + i + " : " + prettyName(testChild) + ", " + prettyName(accChild)); } info("Matching " + prettyName(accTree) + " and " + prettyName(acc) + " child at index " + i + " : " + prettyName(accChild)); - } catch (e) { ok(false, prettyName(accTree) + " is expected to have a child at index " + i + " : " + prettyName(testChild) + ", original tested: " + prettyName(aAccOrElmOrID) + ", " + e); } } } else { if (aFlags & kSkipTreeFullCheck) {
--- a/accessible/tests/mochitest/events.js +++ b/accessible/tests/mochitest/events.js @@ -84,17 +84,16 @@ function isXULElement(aNode) { * @param aContext [in, optional] object in which context the function is * called * @param aArg1 [in, optional] argument passed into the function * @param aArg2 [in, optional] argument passed into the function */ function waitForEvent(aEventType, aTargetOrFunc, aFunc, aContext, aArg1, aArg2) { var handler = { handleEvent: function handleEvent(aEvent) { - var target = aTargetOrFunc; if (typeof aTargetOrFunc == "function") target = aTargetOrFunc.call(); if (target) { if (target instanceof nsIAccessible && target != aEvent.accessible) return; @@ -591,17 +590,16 @@ function eventQueue(aEventType) { } } } // If we don't have more events to wait then schedule next invoker. if (this.hasMatchedScenario()) { if (this.mNextInvokerStatus == kInvokerNotScheduled) { this.processNextInvokerInTimeout(); - } else if (this.mNextInvokerStatus == kInvokerCanceled) { this.setInvokerStatus(kInvokerPending, "Full match. Void the cancelation of next invoker processing"); } return; } // If we have scheduled a next invoker then cancel in case of match. @@ -784,17 +782,16 @@ function eventQueue(aEventType) { // DOM event var target = eventQueue.getEventTarget(eventSeq[idx]); if (!target) { ok(false, "no target for DOM event!"); return false; } var phase = eventQueue.getEventPhase(eventSeq[idx]); target.addEventListener(eventType, this, phase); - } else { // A11y event addA11yEventListener(eventType, this); } } } return true; @@ -808,17 +805,16 @@ function eventQueue(aEventType) { var eventSeq = this.mScenarios[scnIdx]; for (var idx = 0; idx < eventSeq.length; idx++) { var eventType = eventSeq[idx].type; if (typeof eventType == "string") { // DOM event var target = eventQueue.getEventTarget(eventSeq[idx]); var phase = eventQueue.getEventPhase(eventSeq[idx]); target.removeEventListener(eventType, this, phase); - } else { // A11y event removeA11yEventListener(eventType, this); } } } this.mScenarios = null; }; @@ -1447,17 +1443,16 @@ function closeCombobox(aComboboxID) { */ function synthSelectAll(aNodeOrID, aCheckerOrEventSeq) { this.__proto__ = new synthAction(aNodeOrID, aCheckerOrEventSeq); this.invoke = function synthSelectAll_invoke() { if (ChromeUtils.getClassName(this.DOMNode) === "HTMLInputElement" || this.DOMNode.localName == "textbox") { this.DOMNode.select(); - } else { window.getSelection().selectAllChildren(this.DOMNode); } }; this.getID = function synthSelectAll_getID() { return aNodeOrID + " selectall"; }; @@ -1990,17 +1985,16 @@ var gA11yEventObserver = if (!dumpElm || parent != dumpElm) { var type = eventTypeToString(event.eventType); var info = "Event type: " + type; if (event instanceof nsIAccessibleStateChangeEvent) { var stateStr = statesToString(event.isExtraState ? 0 : event.state, event.isExtraState ? event.state : 0); info += ", state: " + stateStr + ", is enabled: " + event.isEnabled; - } else if (event instanceof nsIAccessibleTextChangeEvent) { info += ", start: " + event.start + ", length: " + event.length + ", " + (event.isInserted ? "inserted" : "removed") + " text: " + event.modifiedText; } info += ". Target: " + prettyName(event.accessible);
--- a/accessible/tests/mochitest/events/test_statechange.html +++ b/accessible/tests/mochitest/events/test_statechange.html @@ -26,17 +26,16 @@ this.DOMNode = aDocNode; this.invoke = function editabledoc_invoke() { // Note: this should fire an EVENT_STATE_CHANGE this.DOMNode.designMode = "on"; }; this.check = function editabledoc_check(aEvent) { - testStates(aDocNode, 0, EXT_STATE_EDITABLE); let event = null; try { event = aEvent.QueryInterface(nsIAccessibleStateChangeEvent); } catch (e) { ok(false, "State change event was expected"); } @@ -149,17 +148,16 @@ this.eventSeq = [ new stateChangeChecker(aState, aIsExtraState, aIsEnabled, getNode(aID)), ]; this.invoke = function echoingStateChange_invoke() { if (aValue == null) { getNode(aID).removeAttribute(aARIAAttr); getNode(aID).removeAttribute(aAttr); - } else { getNode(aID).setAttribute(aARIAAttr, aValue); getNode(aID).setAttribute(aAttr, aValue); } }; this.getID = function echoingStateChange_getID() { return "enchoing ARIA and native attributes change";
--- a/accessible/tests/mochitest/events/test_text.html +++ b/accessible/tests/mochitest/events/test_text.html @@ -68,17 +68,16 @@ let fSpan = document.createElement("span"); fSpan.textContent = "333"; topSpan.appendChild(fSpan); let sSpan = document.createElement("span"); sSpan.textContent = "22"; topSpan.appendChild(sSpan); this.DOMNode.insertBefore(topSpan, this.DOMNode.childNodes[0]); - } else { let topSpan = document.createElement("span"); this.DOMNode.insertBefore(topSpan, this.DOMNode.childNodes[0]); let fSpan = document.createElement("span"); fSpan.textContent = "333"; topSpan.appendChild(fSpan);
--- a/accessible/tests/mochitest/events/test_valuechange.html +++ b/accessible/tests/mochitest/events/test_valuechange.html @@ -29,17 +29,16 @@ function changeARIAValue(aNodeOrID, aValuenow, aValuetext) { this.DOMNode = getNode(aNodeOrID); this.eventSeq = [ new invokerChecker(aValuetext ? EVENT_TEXT_VALUE_CHANGE : EVENT_VALUE_CHANGE, this.DOMNode), ]; this.invoke = function changeARIAValue_invoke() { - // Note: this should not fire an EVENT_VALUE_CHANGE when aria-valuetext // is not empty if (aValuenow != undefined) this.DOMNode.setAttribute("aria-valuenow", aValuenow); // Note: this should always fire an EVENT_VALUE_CHANGE if (aValuetext != undefined) this.DOMNode.setAttribute("aria-valuetext", aValuetext);
--- a/accessible/tests/mochitest/name/markup.js +++ b/accessible/tests/mochitest/name/markup.js @@ -160,25 +160,23 @@ function testNamesForMarkupRules(aMarkup */ function testNameForRule(aElm, aRuleElm) { if (aRuleElm.hasAttribute("attr")) { if (gDumpToConsole) { dump("\nProcessing rule { attr: " + aRuleElm.getAttribute("attr") + " }\n"); } testNameForAttrRule(aElm, aRuleElm); - } else if (aRuleElm.hasAttribute("elm")) { if (gDumpToConsole) { dump("\nProcessing rule { elm: " + aRuleElm.getAttribute("elm") + ", elmattr: " + aRuleElm.getAttribute("elmattr") + " }\n"); } testNameForElmRule(aElm, aRuleElm); - } else if (aRuleElm.getAttribute("fromsubtree") == "true") { if (gDumpToConsole) { dump("\nProcessing rule { fromsubtree: " + aRuleElm.getAttribute("fromsubtree") + " }\n"); } testNameForSubtreeRule(aElm, aRuleElm); } @@ -188,17 +186,16 @@ function testNameForAttrRule(aElm, aRule var name = ""; var attr = aRule.getAttribute("attr"); var attrValue = aElm.getAttribute(attr); var type = aRule.getAttribute("type"); if (type == "string") { name = attrValue; - } else if (type == "ref" && attrValue) { var ids = attrValue.split(/\s+/); for (var idx = 0; idx < ids.length; idx++) { var labelElm = getNode(ids[idx]); if (name != "") name += " "; name += labelElm.getAttribute("textequiv"); @@ -215,27 +212,24 @@ function testNameForAttrRule(aElm, aRule // If @recreated attribute is used then this attribute change recreates an // accessible. Wait for reorder event in this case or otherwise proceed next // test immediately. if (aRule.hasAttribute("recreated")) { waitForEvent(EVENT_REORDER, aElm.parentNode, gTestIterator.iterateNext, gTestIterator); aElm.removeAttribute(attr); - } else if (aRule.hasAttribute("textchanged")) { waitForEvent(EVENT_TEXT_INSERTED, aElm, gTestIterator.iterateNext, gTestIterator); aElm.removeAttribute(attr); - } else if (aRule.hasAttribute("contentchanged")) { waitForEvent(EVENT_REORDER, aElm, gTestIterator.iterateNext, gTestIterator); aElm.removeAttribute(attr); - } else { aElm.removeAttribute(attr); gTestIterator.iterateNext(); } } function testNameForElmRule(aElm, aRule) { var labelElm; @@ -256,17 +250,16 @@ function testNameForElmRule(aElm, aRule) mAttrName: attrname, mAttrValue: aElm.getAttribute("id"), }; var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, filter); labelElm = treeWalker.nextNode(); - } else { // if attrname is empty then look for the element in subtree. labelElm = aElm.getElementsByTagName(tagname)[0]; if (!labelElm) labelElm = aElm.getElementsByTagName("html:" + tagname)[0]; } if (!labelElm) {
--- a/accessible/tests/mochitest/relations.js +++ b/accessible/tests/mochitest/relations.js @@ -50,17 +50,16 @@ function testRelation(aIdentifier, aRelT return; } var msg = relDescrStart + "has no expected targets: '" + prettyName(aRelatedIdentifiers) + "'"; ok(false, msg); return; - } else if (!aRelatedIdentifiers) { ok(false, "There are unexpected targets of " + relDescr); return; } var relatedIds = (aRelatedIdentifiers instanceof Array) ? aRelatedIdentifiers : [aRelatedIdentifiers];
--- a/accessible/tests/mochitest/relations/test_update.html +++ b/accessible/tests/mochitest/relations/test_update.html @@ -166,17 +166,16 @@ RELATION_FLOWS_TO, RELATION_FLOWS_FROM)); gQueue.push(new insertRelated("aria-flowto", "dependent12", false, RELATION_FLOWS_TO, RELATION_FLOWS_FROM)); // Update relations when accessibles are recreated gQueue.push(new recreateRelatives("container", "label", "input")); gQueue.invoke(); // will call SimpleTest.finish() - } SimpleTest.waitForExplicitFinish(); addA11yLoadEvent(doTest); </script> </head>
--- a/accessible/tests/mochitest/table.js +++ b/accessible/tests/mochitest/table.js @@ -162,17 +162,16 @@ function testTableStruct(aIdentifier, aC is(table.columnCount, colsCount, "Wrong columns count of " + prettyName(aIdentifier)); // rows and columns extents for (let rowIdx = 0; rowIdx < rowCount; rowIdx++) { for (let colIdx = 0; colIdx < colsCount; colIdx++) { let celltype = aCellsArray[rowIdx][colIdx]; if (celltype & kOrigin) { - // table getRowExtentAt var rowExtent = table.getRowExtentAt(rowIdx, colIdx); let idx; for (idx = rowIdx + 1; idx < rowCount && (aCellsArray[idx][colIdx] & kRowSpanned); idx++); var expectedRowExtent = idx - rowIdx; @@ -234,17 +233,16 @@ function testTableIndexes(aIdentifier, a cellAcc = null; cellAcc = tableAcc.getCellAt(rowIdx, colIdx); } catch (e) { } ok(idx != -1 && cellAcc || idx == -1 && !cellAcc, id + ": Can't get cell accessible at row = " + rowIdx + ", column = " + colIdx); if (idx != -1) { - // getRowIndexAt var origRowIdx = rowIdx; while (origRowIdx > 0 && aIdxes[rowIdx][colIdx] == aIdxes[origRowIdx - 1][colIdx]) origRowIdx--; try { obtainedRowIdx = tableAcc.getRowIndexAt(idx); @@ -280,17 +278,16 @@ function testTableIndexes(aIdentifier, a } is(obtainedRowIdxObj.value, origRowIdx, id + ": row for index " + idx + " is not correct (getRowAndColumnIndicesAt)"); is(obtainedColIdxObj.value, origColIdx, id + ": column for index " + idx + " is not correct (getRowAndColumnIndicesAt)"); if (cellAcc) { - var cellId = prettyName(cellAcc); cellAcc = getAccessible(cellAcc, [nsIAccessibleTableCell]); // cell: 'table-cell-index' attribute var attrs = cellAcc.attributes; var strIdx = ""; try { strIdx = attrs.getStringProperty("table-cell-index"); @@ -303,17 +300,16 @@ function testTableIndexes(aIdentifier, a is(parseInt(strIdx), idx, cellId + ": cell index from object attributes of cell accessible isn't corrent."); } // cell: table try { is(cellAcc.table, tableAcc, cellId + ": wrong table accessible for the cell."); - } catch (e) { ok(false, cellId + ": can't get table accessible from the cell."); } // cell: getRowIndex try { obtainedRowIdx = cellAcc.rowIndex; @@ -558,34 +554,30 @@ function testSelectTableColumn(aIdentifi for (var rowIdx = 0; rowIdx < rowCount; rowIdx++) { for (var colIdx = 0; colIdx < colsCount; colIdx++) { var cellState = aCellsArray[rowIdx][colIdx]; if (colIdx == aColIdx) { // select target column if (!(cellState & kSpanned)) { // Select the cell if it is origin. aCellsArray[rowIdx][colIdx] = true; - } else { // If the cell is spanned then search origin cell and select it. var [origRowIdx, origColIdx] = getOrigRowAndColumn(aCellsArray, rowIdx, colIdx); aCellsArray[origRowIdx][origColIdx] = true; } - } else if (!(cellState & kSpanned)) { // unselect other columns if (colIdx > aColIdx) { // Unselect the cell if traversed column index is greater than column // index of target cell. aCellsArray[rowIdx][colIdx] = false; - } else if (!(aCellsArray[rowIdx][aColIdx] & kColSpanned)) { // Unselect the cell if the target cell is not row spanned. aCellsArray[rowIdx][colIdx] = false; - } else { // Unselect the cell if it is not spanned to the target cell. for (var spannedColIdx = colIdx + 1; spannedColIdx < aColIdx; spannedColIdx++) { var spannedCellState = aCellsArray[rowIdx][spannedColIdx]; if (!(spannedCellState & kRowSpanned)) { aCellsArray[rowIdx][colIdx] = false; break; @@ -636,35 +628,31 @@ function testSelectTableRow(aIdentifier, for (var rowIdx = 0; rowIdx < rowCount; rowIdx++) { for (var colIdx = 0; colIdx < colsCount; colIdx++) { var cellState = aCellsArray[rowIdx][colIdx]; if (rowIdx == aRowIdx) { // select the given row if (!(cellState & kSpanned)) { // Select the cell if it is origin. aCellsArray[rowIdx][colIdx] = true; - } else { // If the cell is spanned then search origin cell and select it. var [origRowIdx, origColIdx] = getOrigRowAndColumn(aCellsArray, rowIdx, colIdx); aCellsArray[origRowIdx][origColIdx] = true; } - } else if (!(cellState & kSpanned)) { // unselect other rows if (rowIdx > aRowIdx) { // Unselect the cell if traversed row index is greater than row // index of target cell. aCellsArray[rowIdx][colIdx] = false; - } else if (!(aCellsArray[aRowIdx][colIdx] & kRowSpanned)) { // Unselect the cell if the target cell is not row spanned. aCellsArray[rowIdx][colIdx] = false; - } else { // Unselect the cell if it is not spanned to the target cell. for (var spannedRowIdx = rowIdx + 1; spannedRowIdx < aRowIdx; spannedRowIdx++) { var spannedCellState = aCellsArray[spannedRowIdx][colIdx]; if (!(spannedCellState & kRowSpanned)) { aCellsArray[rowIdx][colIdx] = false; break;
--- a/accessible/tests/mochitest/text.js +++ b/accessible/tests/mochitest/text.js @@ -582,17 +582,16 @@ function testTextHelper(aID, aOffset, aB isFunc2(startOffsetObj.value == aStartOffset, startMsg + "wrong start offset" + "(got '" + startOffsetObj.value + "', expected: '" + aStartOffset + "')" + ", offset: " + aOffset + endMsg); isFunc3(endOffsetObj.value == aEndOffset, startMsg + "wrong end offset" + "(got '" + endOffsetObj.value + "', expected: '" + aEndOffset + "')" + ", offset: " + aOffset + endMsg); - } catch (e) { var okFunc = exceptionFlag ? todo : ok; okFunc(false, startMsg + "failed at offset " + aOffset + endMsg + ", exception: " + e); } } function boundaryToString(aBoundaryType) {
--- a/accessible/tests/mochitest/text/test_atcaretoffset.html +++ b/accessible/tests/mochitest/text/test_atcaretoffset.html @@ -100,17 +100,16 @@ // The current word is a farthest word starting at or after the offset. if (this.mOffset >= nWord.start) { while (this.mOffset >= nWord.start && !this.mLine.isLastWord(cWord)) { cWord = nWord; nWord = nWord.nextWord; } pWord = cWord.prevWord; - } else if (this.mOffset < cWord.start) { while (this.mOffset < cWord.start) { cWord = pWord; pWord = pWord.prevWord; } nWord = cWord.nextWord; }
--- a/accessible/tests/mochitest/treeupdate/test_bug1100602.html +++ b/accessible/tests/mochitest/treeupdate/test_bug1100602.html @@ -64,17 +64,16 @@ this.getID = function showBullet_getID() { return "Show bullet by setting style to circle"; }; } var gQueue = null; function doTest() { - var list = getNode("list"); list.setAttribute("style", "list-style-type: circle;"); gQueue = new eventQueue(); gQueue.push(new hideBullet()); gQueue.push(new showBullet()); gQueue.invoke(); // SimpleTest.finish(); }
--- a/accessible/tests/mochitest/treeupdate/test_optgroup.html +++ b/accessible/tests/mochitest/treeupdate/test_optgroup.html @@ -98,17 +98,16 @@ function doTest() { gQueue = new eventQueue(); gQueue.push(new addOptGroup("select")); gQueue.push(new removeOptGroup("select")); gQueue.invoke(); // Will call SimpleTest.finish(); - } SimpleTest.waitForExplicitFinish(); addA11yLoadEvent(doTest); </script> </head> <body>
--- a/accessible/tests/mochitest/treeupdate/test_select.html +++ b/accessible/tests/mochitest/treeupdate/test_select.html @@ -114,17 +114,16 @@ function doTest() { gQueue = new eventQueue(); gQueue.push(new addOptions("select")); gQueue.push(new removeOptions("select")); gQueue.push(new setHrefOnOption()); gQueue.invoke(); // Will call SimpleTest.finish(); - } SimpleTest.waitForExplicitFinish(); addA11yLoadEvent(doTest); </script> </head> <body> <p id="display"></p>
--- a/accessible/tests/mochitest/treeupdate/test_table.html +++ b/accessible/tests/mochitest/treeupdate/test_table.html @@ -48,17 +48,16 @@ return "append caption"; }; } function doTest() { gQueue = new eventQueue(); gQueue.push(new appendCaption("table")); gQueue.invoke(); // Will call SimpleTest.finish(); - } SimpleTest.waitForExplicitFinish(); addA11yLoadEvent(doTest); </script> </head> <body> <p id="display"></p>
--- a/browser/actors/AboutReaderChild.jsm +++ b/browser/actors/AboutReaderChild.jsm @@ -88,17 +88,16 @@ class AboutReaderChild extends ActorChil // event, so we need to rely on "pageshow" in this case. if (aEvent.persisted) { this.updateReaderButton(); } break; case "DOMContentLoaded": this.updateReaderButton(); break; - } } /** * NB: this function will update the state of the reader button asynchronously * after the next mozAfterPaint call (assuming reader mode is enabled and * this is a suitable document). Calling it on things which won't be * painted is not going to work.
--- a/browser/actors/ContextMenuChild.jsm +++ b/browser/actors/ContextMenuChild.jsm @@ -930,17 +930,16 @@ class ContextMenuChild extends ActorChil // does in browser.js (this._isXULTextLinkLabel(elem) || (elem instanceof this.content.HTMLAnchorElement && elem.href) || (elem instanceof this.content.SVGAElement && (elem.href || elem.hasAttributeNS(XLINK_NS, "href"))) || (elem instanceof this.content.HTMLAreaElement && elem.href) || elem instanceof this.content.HTMLLinkElement || elem.getAttributeNS(XLINK_NS, "type") == "simple")) { - // Target is a link or a descendant of a link. context.onLink = true; // Remember corresponding element. context.link = elem; context.linkURL = this._getLinkURL(); context.linkURI = this._getLinkURI(); context.linkTextStr = this._getLinkText();
--- a/browser/actors/PageInfoChild.jsm +++ b/browser/actors/PageInfoChild.jsm @@ -287,17 +287,16 @@ class PageInfoChild extends ActorChild { return result; } // Other Misc Stuff // Modified from the Links Panel v2.3, http://segment7.net/mozilla/links/links.html // parse a node to extract the contents of the node getValueText(node) { - let valueText = ""; let content = node.ownerGlobal; // Form input elements don't generally contain information that is useful to our callers, so return nothing. if (node instanceof content.HTMLInputElement || node instanceof content.HTMLSelectElement || node instanceof content.HTMLTextAreaElement) { return valueText;
--- a/browser/actors/PluginChild.jsm +++ b/browser/actors/PluginChild.jsm @@ -781,17 +781,16 @@ class PluginChild extends ActorChild { * The DOM element that is currently full screen, or null. * @param domElement * The DOM element which contains the crashed plugin, or the crashed plugin * itself. * @returns bool * True if the plugin is a descendant of the full screen DOM element, false otherwise. **/ isWithinFullScreenElement(fullScreenElement, domElement) { - /** * Traverses down iframes until it find a non-iframe full screen DOM element. * @param fullScreenIframe * Target iframe to begin searching from. * @returns DOM element * The full screen DOM element contained within the iframe (could be inner iframe), or the original iframe if no inner DOM element is found. **/ let getTrueFullScreenElement = fullScreenIframe => {
--- a/browser/base/content/browser-compacttheme.js +++ b/browser/base/content/browser-compacttheme.js @@ -43,17 +43,16 @@ var CompactTheme = { theme.id == "firefox-compact-light@mozilla.org" || theme.id == "firefox-compact-dark@mozilla.org")) { // We are using the theme ID on this object instead of always referencing // LightweightThemeManager.currentTheme in case this is a preview this._toggleStyleSheet(true); } else { this._toggleStyleSheet(false); } - } }, _toggleStyleSheet(enabled) { let wasEnabled = this.isStyleSheetEnabled; if (enabled) { this.styleSheet.disabled = false; } else if (!enabled && wasEnabled) {
--- a/browser/base/content/browser-fullScreenAndPointerLock.js +++ b/browser/base/content/browser-fullScreenAndPointerLock.js @@ -52,17 +52,16 @@ var PointerlockFsWarning = { let timeout = Services.prefs.getIntPref("full-screen-api.warning.timeout"); let delay = Services.prefs.getIntPref("full-screen-api.warning.delay"); this.show(aOrigin, "fullscreen-warning", timeout, delay); }, // Shows a warning that the site has entered fullscreen or // pointer lock for a short duration. show(aOrigin, elementId, timeout, delay) { - if (!this._element) { this._element = document.getElementById(elementId); // Setup event listeners this._element.addEventListener("transitionend", this); window.addEventListener("mousemove", this, true); // The timeout to hide the warning box after a while. this._timeoutHide = new this.Timeout(() => { this._state = "hidden"; @@ -407,17 +406,16 @@ var FullScreen = { Services.obs.notifyObservers(window, "fullscreen-painted"); TelemetryStopwatch.finish("FULLSCREEN_CHANGE_MS"); break; } } }, enterDomFullscreen(aBrowser) { - if (!document.fullscreenElement) { return; } // If we have a current pointerlock warning shown then hide it // before transition. PointerlockFsWarning.close();
--- a/browser/base/content/browser-gestureSupport.js +++ b/browser/base/content/browser-gestureSupport.js @@ -336,17 +336,16 @@ var gGestureSupport = { if (node.getAttribute("disabled") != "true") { let cmdEvent = document.createEvent("xulcommandevent"); cmdEvent.initCommandEvent("command", true, true, window, 0, aEvent.ctrlKey, aEvent.altKey, aEvent.shiftKey, aEvent.metaKey, aEvent, aEvent.mozInputSource); node.dispatchEvent(cmdEvent); } - } else { goDoCommand(aCommand); } }, /** * Handle continual motion events. This function will be set by * _setupGesture or _setupSwipe.
--- a/browser/base/content/browser-siteIdentity.js +++ b/browser/base/content/browser-siteIdentity.js @@ -587,22 +587,20 @@ var gIdentityHandler = { // keeps track if we should show an indicator that there are active permissions let hasGrantedPermissions = false; // show permission icons let permissions = SitePermissions.getAllForBrowser(gBrowser.selectedBrowser); for (let permission of permissions) { if (permission.state == SitePermissions.BLOCK) { - let icon = permissionAnchors[permission.id]; if (icon) { icon.setAttribute("showing", "true"); } - } else if (permission.state != SitePermissions.UNKNOWN) { hasGrantedPermissions = true; } } if (hasGrantedPermissions) { this._identityBox.classList.add("grantedPermissions"); }
--- a/browser/base/content/browser-tabsintitlebar.js +++ b/browser/base/content/browser-tabsintitlebar.js @@ -1,17 +1,16 @@ /* -*- 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 TabsInTitlebar; { // start private TabsInTitlebar scope - TabsInTitlebar = { init() { this._readPref(); Services.prefs.addObserver(this._prefName, this); dragSpaceObserver.init(); this._initialized = true; this._update(); @@ -114,17 +113,16 @@ let dragSpaceObserver = { observe() { if (Services.prefs.getBoolPref(this.pref)) { document.documentElement.setAttribute("extradragspace", "true"); } else { document.documentElement.removeAttribute("extradragspace"); } }, }; - } // end private TabsInTitlebar scope function onTitlebarMaxClick() { if (window.windowState == window.STATE_MAXIMIZED) window.restore(); else window.maximize(); }
--- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -3036,17 +3036,16 @@ var BrowserOnClick = { case "copyToClipboard": const gClipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"] .getService(Ci.nsIClipboardHelper); securityInfo = getSecurityInfo(securityInfoAsString); let detailedInfo = getDetailedCertErrorInfo(location, securityInfo); gClipboardHelper.copyString(detailedInfo); break; - } }, onAboutBlocked(elementId, reason, isTopFrame, location, blockedInfo) { // Depending on what page we are displaying here (malware/phishing/unwanted) // use the right strings and links for each. let bucketName = ""; let sendTelemetry = false; @@ -4691,17 +4690,16 @@ var XULBrowserWindow = { // This function fires only for the currently selected tab. onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { const nsIWebProgressListener = Ci.nsIWebProgressListener; let browser = gBrowser.selectedBrowser; if (aStateFlags & nsIWebProgressListener.STATE_START && aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) { - if (aRequest && aWebProgress.isTopLevel) { // clear out search-engine data browser.engines = null; } this.isBusy = true; if (!(aStateFlags & nsIWebProgressListener.STATE_RESTORING)) {
--- a/browser/base/content/contentSearchUI.js +++ b/browser/base/content/contentSearchUI.js @@ -1,16 +1,15 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.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"; this.ContentSearchUIController = (function() { - const MAX_DISPLAYED_SUGGESTIONS = 6; const SUGGESTION_ID_PREFIX = "searchSuggestion"; const ONE_OFF_ID_PREFIX = "oneOff"; const DEFAULT_INPUT_ICON = "chrome://browser/skin/search-glass.svg"; const HTML_NS = "http://www.w3.org/1999/xhtml"; /**
--- a/browser/base/content/contentTheme.js +++ b/browser/base/content/contentTheme.js @@ -1,16 +1,15 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; { - function _isTextColorDark(r, g, b) { return (0.2125 * r + 0.7154 * g + 0.0721 * b) <= 110; } const inContentVariableMap = [ ["--newtab-background-color", { lwtProperty: "ntp_background", }], @@ -147,10 +146,9 @@ const ContentThemeController = { value = `rgba(${r}, ${g}, ${b}, ${a})`; } this._setProperty(elem, cssVarName, value); } }, }; ContentThemeController.init(); - }
--- a/browser/base/content/nsContextMenu.js +++ b/browser/base/content/nsContextMenu.js @@ -1100,17 +1100,16 @@ nsContextMenu.prototype = { // nsIExternalHelperAppService.doContent, which will wait for the // appropriate MIME-type headers and then prompt the user with a // file picker function saveAsListener() {} saveAsListener.prototype = { extListener: null, onStartRequest: function saveLinkAs_onStartRequest(aRequest, aContext) { - // if the timer fired, the error status will have been caused by that, // and we'll be restarting in onStopRequest, so no reason to notify // the user if (aRequest.status == NS_ERROR_SAVE_LINK_AS_TIMEOUT) return; timer.cancel();
--- a/browser/base/content/tabbrowser.js +++ b/browser/base/content/tabbrowser.js @@ -1,15 +1,14 @@ /* -*- 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/. */ { // start private scope for gBrowser - /** * A set of known icons to use for internal pages. These are hardcoded so we can * start loading them faster than ContentLinkHandler would normally find them. */ const FAVICON_DEFAULTS = { "about:newtab": "chrome://branding/content/icon32.png", "about:home": "chrome://branding/content/icon32.png", "about:welcome": "chrome://branding/content/icon32.png", @@ -2425,17 +2424,16 @@ window._gBrowser = { // Ensure we have an index if one was not provided. _insertTabAt // will do some additional validation. if (typeof index != "number") { // Move the new tab after another tab if needed. if (!bulkOrderedOpen && ((openerTab && Services.prefs.getBoolPref("browser.tabs.insertRelatedAfterCurrent")) || Services.prefs.getBoolPref("browser.tabs.insertAfterCurrent"))) { - let lastRelatedTab = openerTab && this._lastRelatedTabMap.get(openerTab); let previousTab = (lastRelatedTab || openerTab || this.selectedTab); if (previousTab.multiselected) { index = this.selectedTabs[this.selectedTabs.length - 1]._tPos + 1; } else { index = previousTab._tPos + 1; } @@ -5003,17 +5001,16 @@ class TabProgressListener { } if (this.mTab.selected) { gBrowser._isBusy = true; } } } else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP && aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) { - let modifiedAttrs = []; if (this.mTab.hasAttribute("busy")) { this.mTab.removeAttribute("busy"); modifiedAttrs.push("busy"); // Only animate the "burst" indicating the page has loaded if // the top-level page is the one that finished loading. if (aWebProgress.isTopLevel && !aWebProgress.isLoadingDocument && @@ -5243,17 +5240,16 @@ class TabProgressListener { return this._callProgressListeners("onRefreshAttempted", [aWebProgress, aURI, aDelay, aSameURI]); } } TabProgressListener.prototype.QueryInterface = ChromeUtils.generateQI( ["nsIWebProgressListener", "nsIWebProgressListener2", "nsISupportsWeakReference"]); - } // end private scope for gBrowser var StatusPanel = { get panel() { delete this.panel; return this.panel = document.getElementById("statuspanel"); },
--- a/browser/base/content/test/contextMenu/browser_utilityOverlayPrincipal.js +++ b/browser/base/content/test/contextMenu/browser_utilityOverlayPrincipal.js @@ -39,16 +39,15 @@ function test_openUILink_checkPrincipal( ok(content.document.nodePrincipal.isCodebasePrincipal, "sanity: correct doc.nodePrincipal"); is(content.document.nodePrincipal.URI.asciiSpec, "http://example.com/", "sanity: correct doc.nodePrincipal URL"); }); gBrowser.removeCurrentTab(); runNextTest(); - }); // Ensure we get the correct default of "allowInheritPrincipal: false" from openUILink openUILink("http://example.com", null, { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal({}), }); // defaults to "current" }
--- a/browser/base/content/test/general/browser_blockHPKP.js +++ b/browser/base/content/test/general/browser_blockHPKP.js @@ -42,17 +42,16 @@ function test() { let uri = Services.io.newURI("https://" + kPinningDomain); gSSService.removeState(Ci.nsISiteSecurityService.HEADER_HPKP, uri, 0); }); whenNewTabLoaded(window, loadPinningPage); } // Start by making a successful connection to a domain that will pin a site function loadPinningPage() { - BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "https://" + kPinningDomain + kURLPath + "valid").then(function() { BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(() => successfulPinningPageListener.handleEvent()); }); } // After the site is pinned try to load with a subdomain site that should // fail to validate var successfulPinningPageListener = {
--- a/browser/base/content/test/general/browser_bug427559.js +++ b/browser/base/content/test/general/browser_bug427559.js @@ -29,10 +29,9 @@ add_task(async function() { await BrowserTestUtils.switchTab(gBrowser, testTab); // Make sure focus is given to the window because the element is now gone. is((await getFocusedLocalName(browser)), "body", "body is focused"); // Cleanup. gBrowser.removeTab(blankTab); gBrowser.removeCurrentTab(); - });
--- a/browser/base/content/test/general/browser_bug435325.js +++ b/browser/base/content/test/general/browser_bug435325.js @@ -1,15 +1,14 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ /* Ensure that clicking the button in the Offline mode neterror page makes the browser go online. See bug 435325. */ add_task(async function checkSwitchPageToOnlineMode() { - // Go offline and disable the proxy and cache, then try to load the test URL. Services.io.offline = true; // Tests always connect to localhost, and per bug 87717, localhost is now // reachable in offline mode. To avoid this, disable any proxy. let proxyPrefValue = SpecialPowers.getIntPref("network.proxy.type"); await SpecialPowers.pushPrefEnv({"set": [ ["network.proxy.type", 0],
--- a/browser/base/content/test/general/browser_bug559991.js +++ b/browser/base/content/test/general/browser_bug559991.js @@ -1,12 +1,11 @@ var tab; function test() { - // ---------- // Test setup waitForExplicitFinish(); Services.prefs.setBoolPref("browser.zoom.updateBackgroundTabs", true); Services.prefs.setBoolPref("browser.zoom.siteSpecific", true);
--- a/browser/base/content/test/general/browser_bug734076.js +++ b/browser/base/content/test/general/browser_bug734076.js @@ -1,13 +1,12 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ add_task(async function() { - // allow top level data: URI navigations, otherwise loading data: URIs // in toplevel windows fail. await SpecialPowers.pushPrefEnv({ "set": [["security.data_uri.block_toplevel_data_uri_navigations", false]], }); let tab = await BrowserTestUtils.openNewForegroundTab(gBrowser, null, false);
--- a/browser/base/content/test/general/browser_e10s_switchbrowser.js +++ b/browser/base/content/test/general/browser_e10s_switchbrowser.js @@ -81,17 +81,16 @@ var waitForLoadWithFlags = async functio info("Loading " + uri + " flags = " + flags); gBrowser.selectedBrowser.loadURI(uri, { flags, triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), }); await BrowserTestUtils.browserStopped(gBrowser); if (!(flags & Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY)) { - if (flags & Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY) { gExpectedHistory.entries.pop(); } else { gExpectedHistory.index++; } gExpectedHistory.entries.push({ uri: gBrowser.currentURI.spec,
--- a/browser/base/content/test/general/browser_remoteWebNavigation_postdata.js +++ b/browser/base/content/test/general/browser_remoteWebNavigation_postdata.js @@ -13,17 +13,16 @@ add_task(async function test_remoteWebNa let obj = {}; ChromeUtils.import("resource://testing-common/httpd.js", obj); ChromeUtils.import("resource://services-common/utils.js", obj); let server = new obj.HttpServer(); server.start(-1); await new Promise(resolve => { - server.registerPathHandler("/test", (request, response) => { let body = obj.CommonUtils.readBytesFromInputStream(request.bodyInputStream); is(body, "success", "request body is correct"); is(request.method, "POST", "request was a post"); response.write("Received from POST: " + body); resolve(); });
--- a/browser/base/content/test/general/browser_save_private_link_perwindowpb.js +++ b/browser/base/content/test/general/browser_save_private_link_perwindowpb.js @@ -61,17 +61,16 @@ function promiseImageDownloaded() { mockTransferRegisterer.register(); registerCleanupFunction(function() { mockTransferCallback = null; mockTransferRegisterer.unregister(); MockFilePicker.cleanup(); destDir.remove(true); }); - }); } add_task(async function() { let testURI = "http://mochi.test:8888/browser/browser/base/content/test/general/bug792517.html"; let privateWindow = await BrowserTestUtils.openNewBrowserWindow({private: true}); let tab = await BrowserTestUtils.openNewForegroundTab(privateWindow.gBrowser, testURI);
--- a/browser/base/content/test/general/browser_tabfocus.js +++ b/browser/base/content/test/general/browser_tabfocus.js @@ -506,17 +506,16 @@ function expectFocusShift(callback, expe newElementIsFocused = false; } if (_lastfocus && _lastfocus != _expectedElement) expectedEvents.push("blur: " + _lastfocus); if (_lastfocuswindow && _lastfocuswindow != expectedWindow) { - if (!gMultiProcessBrowser || _lastfocuswindow != "main-window") { expectedEvents.push("blur: " + _lastfocuswindow + "-document"); expectedEvents.push("blur: " + _lastfocuswindow + "-window"); } } if (expectedWindow && _lastfocuswindow != expectedWindow) { if (gMultiProcessBrowser && expectedWindow != "main-window") {
--- a/browser/base/content/test/general/browser_tabkeynavigation.js +++ b/browser/base/content/test/general/browser_tabkeynavigation.js @@ -1,13 +1,12 @@ /* * This test checks that keyboard navigation for tabs isn't blocked by content */ add_task(async function test() { - let testPage1 = "data:text/html,<html id='tab1'><body><button id='button1'>Tab 1</button></body></html>"; let testPage2 = "data:text/html,<html id='tab2'><body><button id='button2'>Tab 2</button><script>function preventDefault(event) { event.preventDefault(); event.stopImmediatePropagation(); } window.addEventListener('keydown', preventDefault, true); window.addEventListener('keypress', preventDefault, true);</script></body></html>"; let testPage3 = "data:text/html,<html id='tab3'><body><button id='button3'>Tab 3</button></body></html>"; let tab1 = await BrowserTestUtils.openNewForegroundTab(gBrowser, testPage1); let browser1 = gBrowser.getBrowserForTab(tab1); let tab2 = await BrowserTestUtils.openNewForegroundTab(gBrowser, testPage2); let tab3 = await BrowserTestUtils.openNewForegroundTab(gBrowser, testPage3);
--- a/browser/base/content/test/general/browser_web_channel.js +++ b/browser/base/content/test/general/browser_web_channel.js @@ -143,17 +143,16 @@ var gTests = [ */ let preRedirectChannel = new WebChannel("pre_redirect", Services.io.newURI(HTTP_IFRAME_PATH)); let postRedirectChannel = new WebChannel("post_redirect", Services.io.newURI(HTTP_REDIRECTED_IFRAME_PATH)); let promiseTestDone = new Promise(function(resolve, reject) { preRedirectChannel.listen(function(id, message, preRedirectSender) { if (message.command === "redirecting") { - postRedirectChannel.listen(function(aId, aMessage, aPostRedirectSender) { is(aId, "post_redirect"); isnot(aMessage.command, "no_response_expected"); if (aMessage.command === "loaded") { // The message should not be received on the preRedirectChannel // because the target window has redirected. preRedirectChannel.send({ command: "no_response_expected" }, preRedirectSender); @@ -244,17 +243,16 @@ var gTests = [ resolve(); }); }); await BrowserTestUtils.withNewTab({ gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited", }, async function(targetBrowser) { - channel.send({ command: "unsolicited" }, { browser: targetBrowser, principal: Services.scriptSecurityManager.createCodebasePrincipal(targetURI, {}), }); await messagePromise; channel.stopListening(); }); @@ -281,17 +279,16 @@ var gTests = [ } }); }); await BrowserTestUtils.withNewTab({ gBrowser, url: HTTP_PATH + HTTP_ENDPOINT + "?unsolicited", }, async function(targetBrowser) { - let mismatchURI = Services.io.newURI(HTTP_MISMATCH_PATH); let mismatchPrincipal = Services.scriptSecurityManager.createCodebasePrincipal(mismatchURI, {}); // send a message to the wrong principal. It should not be delivered // to content, and should not be echoed back. channel.send({ command: "unsolicited_no_response_expected" }, { browser: targetBrowser, principal: mismatchPrincipal,
--- a/browser/base/content/test/general/browser_windowactivation.js +++ b/browser/base/content/test/general/browser_windowactivation.js @@ -8,17 +8,16 @@ const testPage = getRootDirectory(gTestP const testPage2 = getRootDirectory(gTestPath) + "file_window_activation2.html"; var colorChangeNotifications = 0; var otherWindow; var browser1, browser2; add_task(async function reallyRunTests() { - let tab1 = await BrowserTestUtils.openNewForegroundTab(gBrowser, testPage); browser1 = tab1.linkedBrowser; // This can't use openNewForegroundTab because if we focus tab2 now, we // won't send a focus event during test 6, further down in this file. let tab2 = BrowserTestUtils.addTab(gBrowser, testPage); browser2 = tab2.linkedBrowser; await BrowserTestUtils.browserLoaded(browser2);
--- a/browser/base/content/test/general/contentSearchUI.js +++ b/browser/base/content/test/general/contentSearchUI.js @@ -1,17 +1,16 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ /* eslint-env mozilla/frame-script */ "use strict"; (function() { - const TEST_MSG = "ContentSearchUIControllerTest"; const ENGINE_NAME = "browser_searchSuggestionEngine searchSuggestionEngine.xml"; var gController; addMessageListener(TEST_MSG, msg => { messageHandlers[msg.data.type](msg.data.data); }); @@ -197,10 +196,9 @@ function currentState() { state.suggestionAtIndex.push(gController.suggestionAtIndex(i)); state.isFormHistorySuggestionAtIndex.push( gController.isFormHistorySuggestionAtIndex(i)); } } return state; } - })();
--- a/browser/base/content/test/general/contextmenu_common.js +++ b/browser/base/content/test/general/contextmenu_common.js @@ -142,17 +142,16 @@ function checkContextMenu(expectedItems) } function checkMenuItem(actualItem, actualEnabled, expectedItem, expectedEnabled, index) { is(actualItem, expectedItem, "checking item #" + index / 2 + " (" + expectedItem + ") name"); if (typeof expectedEnabled == "object" && expectedEnabled != null || typeof actualEnabled == "object" && actualEnabled != null) { - ok(!(actualEnabled == null), "actualEnabled is not null"); ok(!(expectedEnabled == null), "expectedEnabled is not null"); is(typeof actualEnabled, typeof expectedEnabled, "checking types"); if (typeof actualEnabled != typeof expectedEnabled || actualEnabled == null || expectedEnabled == null) return;
--- a/browser/base/content/test/general/head.js +++ b/browser/base/content/test/general/head.js @@ -37,17 +37,16 @@ function closeAllNotifications() { for (let notification of gNotificationBox.allNotifications) { waitForNotificationClose(notification, function() { if (gNotificationBox.allNotifications.length === 0) { resolve(); } }); notification.close(); } - }); } function whenDelayedStartupFinished(aWindow, aCallback) { Services.obs.addObserver(function observer(aSubject, aTopic) { if (aWindow == aSubject) { Services.obs.removeObserver(observer, aTopic); executeSoon(aCallback); @@ -208,17 +207,16 @@ function promiseOpenAndLoadWindow(aOptio if (aWaitForDelayedStartup) { Services.obs.addObserver(function onDS(aSubject, aTopic, aData) { if (aSubject != win) { return; } Services.obs.removeObserver(onDS, "browser-delayed-startup-finished"); resolve(win); }, "browser-delayed-startup-finished"); - } else { win.addEventListener("load", function() { resolve(win); }, {once: true}); } }); }
--- a/browser/base/content/test/pageActions/browser_page_action_menu_share_win.js +++ b/browser/base/content/test/pageActions/browser_page_action_menu_share_win.js @@ -21,17 +21,16 @@ let stub = sinon.stub(BrowserPageActions }); registerCleanupFunction(async function() { stub.restore(); delete window.sinon; }); add_task(async function shareURL() { - if (!AppConstants.isPlatformAndVersionAtLeast("win", "6.4")) { Assert.ok(true, "We only expose share on windows 10 and above"); return; } await BrowserTestUtils.withNewTab(TEST_URL, async () => { // Open the panel. await promisePageActionPanelOpen();
--- a/browser/base/content/test/pageinfo/browser_pageinfo_firstPartyIsolation.js +++ b/browser/base/content/test/pageinfo/browser_pageinfo_firstPartyIsolation.js @@ -50,17 +50,16 @@ function testFirstPartyDomain(pageInfo) // Check the node has the attribute 'triggeringprincipal'. let serial = Cc["@mozilla.org/network/serialization-helper;1"] .getService(Ci.nsISerializationHelper); let loadingPrincipalStr = preview.getAttribute("triggeringprincipal"); let loadingPrincipal = serial.deserializeObject(loadingPrincipalStr); Assert.equal(loadingPrincipal.originAttributes.firstPartyDomain, EXPECTED_DOMAIN, "loadingPrincipal should have firstPartyDomain set to " + EXPECTED_DOMAIN); - } resolve(); }); }); } async function test() {
--- a/browser/base/content/test/pageinfo/browser_pageinfo_security.js +++ b/browser/base/content/test/pageinfo/browser_pageinfo_security.js @@ -7,17 +7,16 @@ const TEST_ORIGIN = "https://example.com const TEST_SUB_ORIGIN = "https://test1.example.com"; const REMOVE_DIALOG_URL = "chrome://browser/content/preferences/siteDataRemoveSelected.xul"; // Test displaying and removing quota managed data. add_task(async function test_SiteData() { await SiteDataTestUtils.addToIndexedDB(TEST_ORIGIN); await BrowserTestUtils.withNewTab(TEST_ORIGIN, async function(browser) { - let totalUsage = await SiteDataTestUtils.getQuotaUsage(TEST_ORIGIN); Assert.greater(totalUsage, 0, "The total usage should not be 0"); let pageInfo = BrowserPageInfo(TEST_ORIGIN, "securityTab"); await BrowserTestUtils.waitForEvent(pageInfo, "load"); let label = pageInfo.document.getElementById("security-privacy-sitedata-value"); let clearButton = pageInfo.document.getElementById("security-clear-sitedata");
--- a/browser/base/content/test/permissions/browser_autoplay_blocked.js +++ b/browser/base/content/test/permissions/browser_autoplay_blocked.js @@ -17,17 +17,16 @@ function closeIdentityPopup() { } function autoplayBlockedIcon() { return document.querySelector("#blocked-permissions-container " + ".blocked-permission-icon.autoplay-media-icon"); } add_task(async function testMainViewVisible() { - Services.prefs.setIntPref("media.autoplay.default", Ci.nsIAutoplay.ALLOWED); await BrowserTestUtils.withNewTab(AUTOPLAY_PAGE, async function() { let permissionsList = document.getElementById("identity-popup-permission-list"); let emptyLabel = permissionsList.nextElementSibling.nextElementSibling; ok(BrowserTestUtils.is_hidden(autoplayBlockedIcon()), "Blocked icon not shown");
--- a/browser/base/content/test/permissions/browser_permissions.js +++ b/browser/base/content/test/permissions/browser_permissions.js @@ -263,17 +263,16 @@ add_task(async function testPolicyPermis Services.perms.removeAll(); await closeIdentityPopup(); }); }); add_task(async function testHiddenAfterRefresh() { await BrowserTestUtils.withNewTab(PERMISSIONS_PAGE, async function(browser) { - ok(BrowserTestUtils.is_hidden(gIdentityHandler._identityPopup), "Popup is hidden"); await openIdentityPopup(); ok(!BrowserTestUtils.is_hidden(gIdentityHandler._identityPopup), "Popup is shown"); let reloaded = BrowserTestUtils.browserLoaded(browser, false, PERMISSIONS_PAGE); EventUtils.synthesizeKey("VK_F5", {}, browser.ownerGlobal);
--- a/browser/base/content/test/plugins/browser_CTP_zoom.js +++ b/browser/base/content/test/plugins/browser_CTP_zoom.js @@ -38,17 +38,16 @@ add_task(async function() { await promisePopupNotification("click-to-play-plugins"); }); // Enlarges the zoom level 4 times and tests that the overlay is // visible after each enlargement. add_task(async function() { for (let count = 0; count < 4; count++) { - FullZoom.enlarge(); // Reload the page await promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_zoom.html"); await promiseUpdatePluginBindings(gTestBrowser); await ContentTask.spawn(gTestBrowser, { count }, async function(args) { let doc = content.document; let plugin = doc.getElementById("test");
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_3.js +++ b/browser/base/content/test/popupNotifications/browser_popupNotification_3.js @@ -113,17 +113,16 @@ var tests = [ onShown(popup) { checkPopup(popup, this.notifyObj); triggerMainCommand(popup); // Wait to see if the main command worked executeSoon(function delayedDismissal() { dismissNotification(popup); }); - }, onHidden(popup) { ok(!this.notifyObj.mainActionClicked, "mainAction was not clicked because it was too soon"); ok(this.notifyObj.dismissalCallbackTriggered, "dismissal callback was triggered"); }, }, // test security delay - after delay { id: "Test#5", @@ -136,17 +135,16 @@ var tests = [ }, onShown(popup) { checkPopup(popup, this.notifyObj); // Wait until after the delay to trigger the main action setTimeout(function delayedDismissal() { triggerMainCommand(popup); }, 500); - }, onHidden(popup) { ok(this.notifyObj.mainActionClicked, "mainAction was clicked after the delay"); ok(!this.notifyObj.dismissalCallbackTriggered, "dismissal callback was not triggered"); PopupNotifications.buttonDelay = PREF_SECURITY_DELAY_INITIAL; }, }, // reload removes notification
--- a/browser/base/content/test/sanitize/browser_sanitize-timespans.js +++ b/browser/base/content/test/sanitize/browser_sanitize-timespans.js @@ -16,39 +16,36 @@ function promiseFormHistoryRemoved() { Services.obs.removeObserver(onfh, "satchel-storage-changed"); resolve(); }, "satchel-storage-changed"); }); } function promiseDownloadRemoved(list) { return new Promise(resolve => { - let view = { onDownloadRemoved(download) { list.removeView(view); resolve(); }, }; list.addView(view); - }); } add_task(async function test() { await setupDownloads(); await setupFormHistory(); await setupHistory(); await onHistoryReady(); }); function countEntries(name, message, check) { return new Promise((resolve, reject) => { - var obj = {}; if (name !== null) obj.fieldname = name; let count; FormHistory.count(obj, { handleResult: result => count = result, handleError(error) { reject(error); @@ -56,17 +53,16 @@ function countEntries(name, message, che }, handleCompletion(reason) { if (!reason) { check(count, message); resolve(); } }, }); - }); } async function onHistoryReady() { var hoursSinceMidnight = new Date().getHours(); var minutesSinceMidnight = hoursSinceMidnight * 60 + new Date().getMinutes(); // Should test cookies here, but nsICookieManager/nsICookieService @@ -425,17 +421,16 @@ async function onHistoryReady() { "Pretend visit to before-today.com should now be deleted"); await countEntries("b4today", "b4today form entry should be deleted", checkZero); ok(!(await downloadExists(publicList, "fakefile-old")), "Year old download should now be deleted"); } async function setupHistory() { - let places = []; function addPlace(aURI, aTitle, aVisitDate) { places.push({ uri: aURI, title: aTitle, visitDate: aVisitDate, transition: Ci.nsINavHistoryService.TRANSITION_LINK, @@ -459,20 +454,18 @@ async function setupHistory() { let lastYear = new Date(); lastYear.setFullYear(lastYear.getFullYear() - 1); addPlace("http://before-today.com/", "Before Today", lastYear.getTime() * 1000); await PlacesTestUtils.addVisits(places); } async function setupFormHistory() { - function searchEntries(terms, params) { return new Promise((resolve, reject) => { - let results = []; FormHistory.search(terms, params, { handleResult: result => results.push(result), handleError(error) { reject(error); throw new Error("Error occurred searching form history: " + error); }, handleCompletion(reason) { resolve(results); }, }); @@ -589,17 +582,16 @@ async function setupFormHistory() { await countEntries("4hour", "Checking for 4hour form history entry creation", checkOne); await countEntries("4hour10minutes", "Checking for 4hour10minutes form history entry creation", checkOne); await countEntries("today", "Checking for today form history entry creation", checkOne); await countEntries("b4today", "Checking for b4today form history entry creation", checkOne); is(checks, 9, "9 checks made"); } async function setupDownloads() { - let publicList = await Downloads.getList(Downloads.PUBLIC); let download = await Downloads.createDownload({ source: "https://bugzilla.mozilla.org/show_bug.cgi?id=480169", target: "fakefile-10-minutes", }); download.startTime = new Date(now_mSec - 10 * kMsecPerMin); // 10 minutes ago download.canceled = true;
--- a/browser/base/content/test/static/browser_all_files_referenced.js +++ b/browser/base/content/test/static/browser_all_files_referenced.js @@ -208,17 +208,16 @@ if (!isDevtools) { // services/sync/modules/main.js whitelist.add("resource://services-sync/service.js"); // services/sync/modules/service.js for (let module of ["addons.js", "bookmarks.js", "forms.js", "history.js", "passwords.js", "prefs.js", "tabs.js", "extension-storage.js"]) { whitelist.add("resource://services-sync/engines/" + module); } - } if (AppConstants.MOZ_CODE_COVERAGE) { whitelist.add("chrome://marionette/content/PerTestCoverageUtils.jsm"); } const gInterestingCategories = new Set([ "agent-style-sheets", "addon-provider-module", "webextension-modules",
--- a/browser/base/content/test/sync/browser_fxa_web_channel.js +++ b/browser/base/content/test/sync/browser_fxa_web_channel.js @@ -40,17 +40,16 @@ var gTests = [ }, async function() { await promiseObserver; }); }, }, { desc: "fxa web channel - login messages should notify the fxAccounts object", async run() { - let promiseLogin = new Promise((resolve, reject) => { let login = (accountData) => { Assert.equal(typeof accountData.authAt, "number"); Assert.equal(accountData.email, "testuser@testuser.com"); Assert.equal(accountData.keyFetchToken, "key_fetch_token"); Assert.equal(accountData.sessionToken, "session_token"); Assert.equal(accountData.uid, "uid"); Assert.equal(accountData.unwrapBKey, "unwrap_b_key"); @@ -78,17 +77,16 @@ var gTests = [ }, }, { desc: "fxa web channel - can_link_account messages should respond", async run() { let properUrl = TEST_BASE_URL + "?can_link_account"; let promiseEcho = new Promise((resolve, reject) => { - let webChannelOrigin = Services.io.newURI(properUrl); // responses sent to content are echoed back over the // `fxaccounts_webchannel_response_echo` channel. Ensure the // fxaccounts:can_link_account message is responded to. let echoWebChannel = new WebChannel("fxaccounts_webchannel_response_echo", webChannelOrigin); echoWebChannel.listen((webChannelId, message, target) => { Assert.equal(message.command, "fxaccounts:can_link_account"); Assert.equal(message.messageId, 2);
--- a/browser/base/content/test/tabs/browser_multiselect_tabs_reload.js +++ b/browser/base/content/test/tabs/browser_multiselect_tabs_reload.js @@ -56,17 +56,16 @@ add_task(async function test_usingKeyboa ["VK_F5", {}], ]; if (AppConstants.platform != "macosx") { keys.push(["VK_F5", { accelKey: true }]); } for (let key of keys) { - let tab1 = await addTab(); let tab2 = await addTab(); let tab3 = await addTab(); await BrowserTestUtils.switchTab(gBrowser, tab1); await triggerClickOn(tab2, { ctrlKey: true }); ok(tab1.multiselected, "Tab1 is multi-selected");
--- a/browser/base/content/test/tabs/browser_open_newtab_start_observer_notification.js +++ b/browser/base/content/test/tabs/browser_open_newtab_start_observer_notification.js @@ -1,12 +1,11 @@ "use strict"; add_task(async function test_browser_open_newtab_start_observer_notification() { - let observerFiredPromise = new Promise(resolve => { function observe(subject) { Services.obs.removeObserver(observe, "browser-open-newtab-start"); resolve(subject.wrappedJSObject); } Services.obs.addObserver(observe, "browser-open-newtab-start"); });
--- a/browser/base/content/test/webrtc/browser_devices_get_user_media_multi_process.js +++ b/browser/base/content/test/webrtc/browser_devices_get_user_media_multi_process.js @@ -111,17 +111,16 @@ var gTests = [ ok(!webrtcUI.showGlobalIndicator, "webrtcUI wants the global indicator hidden"); is(webrtcUI.getActiveStreams(true, true, true).length, 0, "0 active streams"); }, }, { desc: "getUserMedia camera in a first process + camera in a second process", run: async function checkMultiProcessCamera() { - // Request camera in the first tab. let promise = promisePopupNotificationShown("webRTC-shareDevices"); await promiseRequestDevice(false, true); await promise; await expectObserverCalled("getUserMedia:request"); checkDeviceSelectors(false, true); @@ -213,17 +212,16 @@ var gTests = [ ok(!webrtcUI.showGlobalIndicator, "webrtcUI wants the global indicator hidden"); is(webrtcUI.getActiveStreams(true, true, true).length, 0, "0 active streams"); }, }, { desc: "getUserMedia screen sharing in a first process + screen sharing in a second process", run: async function checkMultiProcessScreen() { - // Request screen sharing in the first tab. let promise = promisePopupNotificationShown("webRTC-shareDevices"); await promiseRequestDevice(false, true, null, "screen"); await promise; await expectObserverCalled("getUserMedia:request"); is(PopupNotifications.getNotification("webRTC-shareDevices").anchorID, "webRTC-shareScreen-notification-icon", "anchored to device icon");
--- a/browser/base/content/test/webrtc/head.js +++ b/browser/base/content/test/webrtc/head.js @@ -275,58 +275,52 @@ function promiseMessage(aMessage, aActio if (aAction) aAction(); return promise; } function promisePopupNotificationShown(aName, aAction) { return new Promise(resolve => { - // In case the global webrtc indicator has stolen focus (bug 1421724) window.focus(); PopupNotifications.panel.addEventListener("popupshown", function() { ok(!!PopupNotifications.getNotification(aName), aName + " notification shown"); ok(PopupNotifications.isPanelOpen, "notification panel open"); ok(!!PopupNotifications.panel.firstElementChild, "notification panel populated"); executeSoon(resolve); }, {once: true}); if (aAction) aAction(); - }); } function promisePopupNotification(aName) { return new Promise(resolve => { - waitForCondition(() => PopupNotifications.getNotification(aName), () => { ok(!!PopupNotifications.getNotification(aName), aName + " notification appeared"); resolve(); }, "timeout waiting for popup notification " + aName); - }); } function promiseNoPopupNotification(aName) { return new Promise(resolve => { - waitForCondition(() => !PopupNotifications.getNotification(aName), () => { ok(!PopupNotifications.getNotification(aName), aName + " notification removed"); resolve(); }, "timeout waiting for popup notification " + aName + " to disappear"); - }); } const kActionAlways = 1; const kActionDeny = 2; const kActionNever = 3; function activateSecondaryAction(aAction) {
--- a/browser/base/content/urlbarBindings.xml +++ b/browser/base/content/urlbarBindings.xml @@ -373,17 +373,16 @@ file, You can obtain one at http://mozil // At this point, no events have been deferred for this search, and we // need to decide whether `event` is the first one that should be. if (!this._keyCodesToDefer.has(event.keyCode) && !(/Mac/.test(navigator.platform) && event.ctrlKey && (event.key === "n" || event.key === "p") && this.popupOpen)) { - // Not a key that should trigger deferring. return false; } let waitedLongEnough = this._searchStartDate + this._deferredKeyEventTimeoutMs <= Cu.now(); if (waitedLongEnough) { // This is a key that we would defer, but enough time has passed
--- a/browser/base/content/utilityOverlay.js +++ b/browser/base/content/utilityOverlay.js @@ -931,17 +931,16 @@ function makeURLAbsolute(aBase, aUrl) { * The URL to open (as a string). * @param aShiftKey * True if shift key is held. This value is used for the purpose of * determining whether to open in the background. * @param aParams * parameters passed to openLinkIn */ function openNewTabWith(aURL, aShiftKey, aParams = {}) { - // As in openNewWindowWith(), we want to pass the charset of the // current document over to a new tab. if (document.documentElement.getAttribute("windowtype") == "navigator:browser") aParams.charset = gBrowser.selectedBrowser.characterSet; openLinkIn(aURL, aShiftKey ? "tabshifted" : "tab", aParams); }
--- a/browser/components/customizableui/CustomizableUI.jsm +++ b/browser/components/customizableui/CustomizableUI.jsm @@ -1804,17 +1804,16 @@ var CustomizableUIInternal = { if (aEvent.type == "keypress") { if (aEvent.keyCode != aEvent.DOM_VK_RETURN) { return; } // If the user hit enter/return, we don't check preventDefault - it makes sense // that this was prevented, but we probably still want to close the panel. // If consumers don't want this to happen, they should specify the closemenu // attribute. - } else if (aEvent.type != "command") { // mouse events: if (aEvent.defaultPrevented || aEvent.button != 0) { return; } let isInteractive = this._isOnInteractiveElement(aEvent); log.debug("maybeAutoHidePanel: interactive ? " + isInteractive); if (isInteractive) { return;
--- a/browser/components/customizableui/test/browser_1087303_button_preferences.js +++ b/browser/components/customizableui/test/browser_1087303_button_preferences.js @@ -33,17 +33,16 @@ add_task(function asyncCleanup() { BrowserTestUtils.addTab(gBrowser, "about:blank"); gBrowser.removeTab(gBrowser.selectedTab); info("Tabs were restored"); }); function waitForPageLoad(aTab) { return new Promise((resolve, reject) => { - let timeoutId = setTimeout(() => { aTab.linkedBrowser.removeEventListener("load", onTabLoad, true); reject("Page didn't load within " + 20000 + "ms"); }, 20000); async function onTabLoad(event) { clearTimeout(timeoutId); aTab.linkedBrowser.removeEventListener("load", onTabLoad, true);
--- a/browser/components/customizableui/test/browser_newtab_button_customizemode.js +++ b/browser/components/customizableui/test/browser_newtab_button_customizemode.js @@ -81,17 +81,16 @@ add_task(async function addremove_after_ "tabs should have the adjacent newtab attribute"); assertNewTabButton("inner"); CustomizableUI.reset(); ok(gBrowser.tabContainer.hasAttribute("hasadjacentnewtabbutton"), "tabs should still have the adjacent newtab attribute"); assertNewTabButton("inner"); ok(CustomizableUI.inDefaultState, "Should be in default state"); - }); /** * Add and remove items *before* the new tab button outside of customize mode. */ add_task(async function addremove_before_newtab_api() { let index = CustomizableUI.getWidgetIdsInArea("TabsToolbar").indexOf("new-tab-button"); CustomizableUI.addWidgetToArea("home-button", "TabsToolbar", index);
--- a/browser/components/customizableui/test/browser_synced_tabs_menu.js +++ b/browser/components/customizableui/test/browser_synced_tabs_menu.js @@ -104,17 +104,16 @@ async function openPrefsFromMenuPanel(ex e.target.location.href == "about:blank") { info("Skipping spurious 'load' event for " + e.target.location.href); return; } gBrowser.selectedBrowser.removeEventListener("load", handler, true); resolve(); }; gBrowser.selectedBrowser.addEventListener("load", handler, true); - }); newTab = gBrowser.selectedTab; is(gBrowser.currentURI.spec, "about:preferences?entrypoint=" + entryPoint + "#sync", "Firefox Sync preference page opened with `menupanel` entrypoint"); ok(!isOverflowOpen(), "The panel closed"); if (isOverflowOpen()) {
--- a/browser/components/customizableui/test/head.js +++ b/browser/components/customizableui/test/head.js @@ -201,17 +201,16 @@ function endCustomizing(aWindow = window } return new Promise(resolve => { function onCustomizationEnds() { aWindow.gNavToolbox.removeEventListener("aftercustomization", onCustomizationEnds); resolve(); } aWindow.gNavToolbox.addEventListener("aftercustomization", onCustomizationEnds); aWindow.gCustomizeMode.exit(); - }); } function startCustomizing(aWindow = window) { if (aWindow.document.documentElement.getAttribute("customizing") == "true") { return null; } return new Promise(resolve => { @@ -239,17 +238,16 @@ function openAndLoadWindow(aOptions, aWa if (aWaitForDelayedStartup) { Services.obs.addObserver(function onDS(aSubject, aTopic, aData) { if (aSubject != win) { return; } Services.obs.removeObserver(onDS, "browser-delayed-startup-finished"); resolve(win); }, "browser-delayed-startup-finished"); - } else { win.addEventListener("load", function() { resolve(win); }, {once: true}); } }); }
--- a/browser/components/downloads/test/browser/head.js +++ b/browser/components/downloads/test/browser/head.js @@ -36,28 +36,26 @@ function promiseFocus() { } function promisePanelOpened() { if (DownloadsPanel.panel && DownloadsPanel.panel.state == "open") { return Promise.resolve(); } return new Promise(resolve => { - // Hook to wait until the panel is shown. let originalOnPopupShown = DownloadsPanel.onPopupShown; DownloadsPanel.onPopupShown = function() { DownloadsPanel.onPopupShown = originalOnPopupShown; originalOnPopupShown.apply(this, arguments); // Defer to the next tick of the event loop so that we don't continue // processing during the DOM event handler itself. setTimeout(resolve, 0); }; - }); } async function task_resetState() { // Remove all downloads. let publicList = await Downloads.getList(Downloads.PUBLIC); let downloads = await publicList.getAll(); for (let download of downloads) {
--- a/browser/components/enterprisepolicies/content/aboutPolicies.js +++ b/browser/components/enterprisepolicies/content/aboutPolicies.js @@ -48,17 +48,16 @@ function addMissingColumns() { } /* * This function generates the Active Policies content to be displayed by calling * a recursive function called generatePolicy() according to the policy schema. */ function generateActivePolicies(data) { - let new_cont = document.getElementById("activeContent"); new_cont.classList.add("active-policies"); let policy_count = 0; for (let policyName in data) { const color_class = ++policy_count % 2 === 0 ? "even" : "odd";
--- a/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_feedback_commands.js +++ b/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_feedback_commands.js @@ -39,11 +39,10 @@ add_task(async function test_policy_feed buildHelpMenu(); let feedbackPageMenu = document.getElementById("feedbackPage"); is(feedbackPageMenu.getAttribute("disabled"), "true", "The `Submit Feedback...` item should be disabled"); await checkItemsAreDisabled(NORMAL_PAGE); await checkItemsAreDisabled(PHISH_PAGE); - });
--- a/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_masterpassword.js +++ b/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_masterpassword.js @@ -35,17 +35,16 @@ async function checkDeviceManager({butto await BrowserTestUtils.closeWindow(deviceManagerWindow); } async function checkAboutPreferences({checkboxIsDisabled}) { await BrowserTestUtils.withNewTab("about:preferences#privacy", async browser => { is(browser.contentDocument.getElementById("useMasterPassword").disabled, checkboxIsDisabled, "Master Password checkbox is in the correct state: " + checkboxIsDisabled); }); - } add_task(async function test_policy_disable_masterpassword() { ok(!mpToken.hasPassword, "Starting the test with no password"); // No password and no policy: access to setting a master password // should be enabled. await checkDeviceManager({buttonIsDisabled: false});
--- a/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_pocket.js +++ b/browser/components/enterprisepolicies/tests/browser/browser_policy_disable_pocket.js @@ -8,17 +8,16 @@ const PREF_POCKET = "extensions.pocket.e async function checkPocket(shouldBeEnabled) { return BrowserTestUtils.waitForCondition(() => { return !!PageActions.actionForID("pocket") == shouldBeEnabled; }, "Expecting Pocket to be " + shouldBeEnabled); } add_task(async function test_disable_firefox_screenshots() { await BrowserTestUtils.withNewTab("data:text/html,Test", async function() { - // Sanity check to make sure Pocket is enabled on tests await checkPocket(true); await setupPolicyEngineWithJson({ "policies": { "DisablePocket": true, }, });
--- a/browser/components/migration/.eslintrc.js +++ b/browser/components/migration/.eslintrc.js @@ -9,15 +9,14 @@ module.exports = { "new-parens": "error", "no-extend-native": "error", "no-fallthrough": ["error", { "commentPattern": ".*[Ii]ntentional(?:ly)?\\s+fall(?:ing)?[\\s-]*through.*" }], "no-multi-str": "error", "no-return-assign": "error", "no-shadow": "error", "no-throw-literal": "error", "no-unused-vars": ["error", { "args": "after-used", "vars": "all" }], - "padded-blocks": ["error", "never"], "semi-spacing": ["error", {"before": false, "after": true}], "space-in-parens": ["error", "never"], "strict": ["error", "global"], "yoda": "error" } };
--- a/browser/components/newtab/.eslintrc.js +++ b/browser/components/newtab/.eslintrc.js @@ -198,17 +198,16 @@ module.exports = { "nonblock-statement-body-position": 2, "object-curly-newline": [2, {"multiline": true, "consistent": true}], "object-curly-spacing": [2, "never"], "object-property-newline": [2, {"allowMultiplePropertiesPerLine": true}], "one-var": [2, "never"], "one-var-declaration-per-line": [2, "initializations"], "operator-assignment": [2, "always"], "operator-linebreak": [2, "after"], - "padded-blocks": [2, "never"], "padding-line-between-statements": 0, "prefer-arrow-callback": ["error", {"allowNamedFunctions": true}], "prefer-const": 0, // TODO: Change to `1`? "prefer-destructuring": [2, {"AssignmentExpression": {"array": true}, "VariableDeclarator": {"array": true, "object": true}}], "prefer-numeric-literals": 2, "prefer-promise-reject-errors": 2, "prefer-reflect": 0, "prefer-rest-params": 2,
--- a/browser/components/nsBrowserContentHandler.js +++ b/browser/components/nsBrowserContentHandler.js @@ -349,17 +349,16 @@ nsBrowserContentHandler.prototype = { cmdLine.preventDefault = true; } } catch (e) { Cu.reportError(e); } var chromeParam = cmdLine.handleFlagWithParam("chrome", false); if (chromeParam) { - // Handle old preference dialog URLs. if (chromeParam == "chrome://browser/content/pref/pref.xul" || chromeParam == "chrome://browser/content/preferences/preferences.xul") { openPreferences(cmdLine, {origin: "commandLineLegacy"}); cmdLine.preventDefault = true; } else try { let resolvedURI = resolveURIInternal(cmdLine, chromeParam); let isLocal = uri => { @@ -765,17 +764,16 @@ nsDefaultCommandLineHandler.prototype = } catch (e) { } } var URLlist = urilist.filter(shouldLoadURI).map(u => u.spec); if (URLlist.length) { openBrowserWindow(cmdLine, gSystemPrincipal, URLlist); } - } else if (!cmdLine.preventDefault) { if (AppConstants.isPlatformAndVersionAtLeast("win", "10") && cmdLine.state != Ci.nsICommandLine.STATE_INITIAL_LAUNCH && WindowsUIUtils.inTabletMode) { // In windows 10 tablet mode, do not create a new window, but reuse the existing one. let win = BrowserWindowTracker.getTopWindow(); if (win) { win.focus();
--- a/browser/components/nsBrowserGlue.js +++ b/browser/components/nsBrowserGlue.js @@ -1084,17 +1084,16 @@ BrowserGlue.prototype = { SaveToPocket.init(); Services.obs.notifyObservers(null, "browser-ui-startup-complete"); }, _checkForOldBuildUpdates() { // check for update if our build is old if (AppConstants.MOZ_UPDATER && Services.prefs.getBoolPref("app.update.checkInstallTime")) { - let buildID = Services.appinfo.appBuildID; let today = new Date().getTime(); /* eslint-disable no-multi-spaces */ let buildDate = new Date(buildID.slice(0, 4), // year buildID.slice(4, 6) - 1, // months are zero-based. buildID.slice(6, 8), // day buildID.slice(8, 10), // hour buildID.slice(10, 12), // min @@ -2039,17 +2038,16 @@ BrowserGlue.prototype = { } try { // Now apply distribution customized bookmarks. // This should always run after Places initialization. await this._distributionCustomizer.applyBookmarks(); } catch (e) { Cu.reportError(e); } - } else { Cu.reportError(new Error("Unable to find bookmarks.html file.")); } // Reset preferences, so we won't try to import again at next run if (importBookmarksHTML) Services.prefs.setBoolPref("browser.places.importBookmarksHTML", false); if (restoreDefaultBookmarks) @@ -2086,17 +2084,16 @@ BrowserGlue.prototype = { } if (backupAge > BOOKMARKS_BACKUP_MAX_INTERVAL_DAYS) this._bookmarksBackupIdleTime /= 2; } } this._idleService.addIdleObserver(this, this._bookmarksBackupIdleTime); } - })().catch(ex => { Cu.reportError(ex); }).then(() => { // NB: deliberately after the catch so that we always do this, even if // we threw halfway through initializing in the Task above. this._placesBrowserInitComplete = true; Services.obs.notifyObservers(null, "places-browser-init-complete"); }); @@ -3165,17 +3162,16 @@ ContentPermissionPrompt.prototype = { combinedIntegration.createPermissionPrompt(type, request); if (!permissionPrompt) { throw Components.Exception( `Failed to handle permission of type ${type}`, Cr.NS_ERROR_FAILURE); } permissionPrompt.prompt(); - } catch (ex) { Cu.reportError(ex); request.cancel(); throw ex; } let schemeHistogram = Services.telemetry.getKeyedHistogramById("PERMISSION_REQUEST_ORIGIN_SCHEME"); let scheme = 0;
--- a/browser/components/originattributes/test/browser/browser_broadcastChannel.js +++ b/browser/components/originattributes/test/browser/browser_broadcastChannel.js @@ -3,17 +3,16 @@ */ const TEST_DOMAIN = "http://example.net/"; const TEST_PATH = TEST_DOMAIN + "browser/browser/components/originattributes/test/browser/"; const TEST_PAGE = TEST_PATH + "file_broadcastChannel.html"; async function doTest(aBrowser) { let response = await ContentTask.spawn(aBrowser, null, async function() { - let displayItem = content.document.getElementById("display"); // If there is nothing in the 'display', we will try to send a message to // the broadcast channel and wait until this message has been delivered. // The way that how we make sure the message is delivered is based on an // iframe which will reply everything it receives from the broadcast channel // to the current window through the postMessage. So, we can know that the // boradcast message is sent successfully when the window receives a message
--- a/browser/components/originattributes/test/browser/browser_cache.js +++ b/browser/components/originattributes/test/browser/browser_cache.js @@ -126,17 +126,16 @@ async function doInit(aMode) { randomSuffix = Math.random(); stopObservingChannels = startObservingChannels(aMode); } // In the test function, we dynamically generate the video and audio element, // and assign a random suffix to their URL to isolate them across different // test runs. async function doTest(aBrowser) { - let argObj = { randomSuffix, urlPrefix: TEST_DOMAIN + TEST_PATH, }; await ContentTask.spawn(aBrowser, argObj, async function(arg) { let videoURL = arg.urlPrefix + "file_thirdPartyChild.video.ogv"; let audioURL = arg.urlPrefix + "file_thirdPartyChild.audio.ogg";
--- a/browser/components/originattributes/test/browser/browser_favicon_firstParty.js +++ b/browser/components/originattributes/test/browser/browser_favicon_firstParty.js @@ -110,17 +110,16 @@ function observeFavicon(aFirstPartyDomai } 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 = { @@ -139,17 +138,16 @@ function waitOnFaviconResponse(aFaviconU Services.obs.addObserver(observer, "http-on-examine-cached-response"); }); } 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); } }, };
--- a/browser/components/originattributes/test/browser/head.js +++ b/browser/components/originattributes/test/browser/head.js @@ -70,17 +70,16 @@ async function openTabInUserContext(aURL * and the second item indicates the second layer, and so on. The aURL will * be loaded at the deepest layer. This is optional. * * @return tab - The tab object of this tab. * browser - The browser object of this tab. */ async function openTabInFirstParty(aURL, aFirstPartyDomain, aFrameSetting = DEFAULT_FRAME_SETTING) { - // If the first party domain ends with '/', we remove it. if (aFirstPartyDomain.endsWith("/")) { aFirstPartyDomain = aFirstPartyDomain.slice(0, -1); } let basicPageURL = aFirstPartyDomain + gFirstPartyBasicPage; // Open the tab for the basic first party page. @@ -247,17 +246,16 @@ this.IsolationTestTools = { */ _addTab(aMode, aURL, aTabSettingObj, aFrameSetting) { if (aMode === TEST_MODE_CONTAINERS) { return openTabInUserContext(aURL, aTabSettingObj.userContextId); } return openTabInFirstParty(aURL, aTabSettingObj.firstPartyDomain, aFrameSetting); - }, /** * Run isolation tests. The framework will run tests with standard combinations * of prefs and tab settings, and checks whether the isolation is working. * * @param aURL * The URL of the page that will be tested or an object contains 'url',
--- a/browser/components/payments/.eslintrc.js +++ b/browser/components/payments/.eslintrc.js @@ -55,17 +55,16 @@ module.exports = { "no-unused-expressions": "error", "no-unused-vars": ["error", { args: "none", vars: "all" }], "no-use-before-define": ["error", { functions: false, }], - "padded-blocks": ["error", "never"], radix: "error", "semi-spacing": ["error", {"before": false, "after": true}], "space-in-parens": ["error", "never"], "valid-jsdoc": ["error", { prefer: { return: "returns", }, preferType: {
--- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js +++ b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js @@ -8,17 +8,16 @@ const DUMMY_URL = BASE_URL + "bookmarkle function makeBookmarkFor(url, keyword) { return Promise.all([ PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, title: "bookmarklet", url }), PlacesUtils.keywords.insert({url, keyword}), ]); - } add_task(async function openKeywordBookmarkWithWindowOpen() { // This is the current default, but let's not assume that... await SpecialPowers.pushPrefEnv({"set": [ [ "browser.link.open_newwindow", 3 ], [ "dom.disable_open_during_load", true ], ]});
--- a/browser/components/places/tests/browser/browser_bug427633_no_newfolder_if_noip.js +++ b/browser/components/places/tests/browser/browser_bug427633_no_newfolder_if_noip.js @@ -35,10 +35,9 @@ add_task(async function() { window.gEditItemOverlay.toggleFolderTreeVisibility(); let tree = gEditItemOverlay._element("folderTree"); tree.view.selection.clearSelection(); ok(document.getElementById("editBMPanel_newFolderButton").disabled, "New folder button is disabled if there's no selection"); - });
--- a/browser/components/places/tests/browser/browser_library_views_liveupdate.js +++ b/browser/components/places/tests/browser/browser_library_views_liveupdate.js @@ -167,17 +167,16 @@ async function removeAndCheckItem(itemDa * * @param aItemGuid * item guid of the item to search. * @param aTree * Tree to search in. * @returns [node, index, cellText] or [null, null, ""] if not found. */ function getNodeForTreeItem(aItemGuid, aTree) { - function findNode(aContainerIndex) { if (aTree.view.isContainerEmpty(aContainerIndex)) return [null, null, ""]; // 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 (let i = aContainerIndex + 1; i < aTree.view.rowCount; i++) { let node = aTree.view.nodeForTreeIndex(i);
--- a/browser/components/places/tests/browser/browser_sidebarpanels_click.js +++ b/browser/components/places/tests/browser/browser_sidebarpanels_click.js @@ -32,17 +32,16 @@ add_task(async function test_sidebarpane _bookmark: null, async init() { // Add a bookmark to the Unfiled Bookmarks folder. this._bookmark = await PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid, title: "test", url: TEST_URL, }); - }, prepare() { }, async selectNode(tree) { tree.selectItems([this._bookmark.guid]); }, cleanup(aCallback) { return PlacesUtils.bookmarks.remove(this._bookmark);
--- a/browser/components/pocket/content/main.js +++ b/browser/components/pocket/content/main.js @@ -47,17 +47,16 @@ ChromeUtils.defineModuleGetter(this, "PrivateBrowsingUtils", "resource://gre/modules/PrivateBrowsingUtils.jsm"); ChromeUtils.defineModuleGetter(this, "ReaderMode", "resource://gre/modules/ReaderMode.jsm"); ChromeUtils.defineModuleGetter(this, "pktApi", "chrome://pocket/content/pktApi.jsm"); var pktUI = (function() { - // -- Initialization (on startup and new windows) -- // // Init panel id at 0. The first actual panel id will have the number 1 so // in case at some point any panel has the id 0 we know there is something // wrong var _panelId = 0; var overflowMenuWidth = 230; @@ -146,17 +145,16 @@ var pktUI = (function() { }); }); } /** * Show the logged-out state / sign-up panel */ function saveAndShowConfirmation(url, title) { - // Validate input parameter if (typeof url !== "undefined" && url.startsWith("about:reader?url=")) { url = ReaderMode.getOriginalUrl(url); } var isValidURL = (typeof url !== "undefined" && (url.startsWith("http") || url.startsWith("https"))); var inOverflowMenu = isInOverflowMenu(); @@ -465,17 +463,16 @@ var pktUI = (function() { if (str.key in data) { strings[str.key] = bundle.formatStringFromName(str.key, data[str.key], data[str.key].length); } else { strings[str.key] = str.value; } } pktUIMessaging.sendResponseMessageToPanel(panelId, _initL10NMessageId, { strings }); }); - } // -- Browser Navigation -- // /** * Open a new tab with a given url and notify the iframe panel that it was opened */ @@ -570,17 +567,16 @@ var pktUI = (function() { tryToSaveUrl, tryToSaveCurrentPage, }; }()); // -- Communication to Background -- // // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages var pktUIMessaging = (function() { - /** * Prefix message id for message listening */ function prefixedMessageId(messageId) { return "PKT_" + messageId; } /** @@ -597,25 +593,23 @@ var pktUIMessaging = (function() { // Pass in information to callback var payload = JSON.parse(e.target.getAttribute("payload"))[0]; var panelId = payload.panelId; var data = payload.data; callback(panelId, data, nodePrincipal); // Cleanup the element e.target.remove(); - }, false, true); } /** * Send a message to the panel's iframe */ function sendMessageToPanel(panelId, messageId, payload) { - if (!isPanelIdValid(panelId)) { return; } var panelFrame = pktUI.getPanelFrame(); if (!isPocketPanelFrameValid(panelFrame)) { return; } var doc = panelFrame.contentWindow.document; var documentElement = doc.documentElement;
--- a/browser/components/pocket/content/panels/js/messages.js +++ b/browser/components/pocket/content/panels/js/messages.js @@ -1,13 +1,12 @@ // Documentation of methods used here are at: // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages var pktPanelMessaging = (function() { - function panelIdFromURL(url) { var panelId = url.match(/panelId=([\w|\d|\.]*)&?/); if (panelId && panelId.length > 1) { return panelId[1]; } return 0; } @@ -17,24 +16,21 @@ var pktPanelMessaging = (function() { } function panelPrefixedMessageId(panelId, messageId) { return prefixedMessageId(panelId + "_" + messageId); } function addMessageListener(panelId, messageId, callback) { document.addEventListener(panelPrefixedMessageId(panelId, messageId), function(e) { - callback(JSON.parse(e.target.getAttribute("payload"))[0]); // TODO: Figure out why e.target.parentNode is null // e.target.parentNode.removeChild(e.target); - }); - } function removeMessageListener(panelId, messageId, callback) { document.removeEventListener(panelPrefixedMessageId(panelId, messageId), callback); } function sendMessage(panelId, messageId, payload, callback) { // Payload needs to be an object in format:
--- a/browser/components/pocket/content/panels/js/saved.js +++ b/browser/components/pocket/content/panels/js/saved.js @@ -547,17 +547,16 @@ PKT_SAVED.prototype = { } else { myself.overlay.showStateError(myself.overlay.dictJSON.pagenotsaved, myself.overlay.dictJSON.errorgeneric); } return; } myself.overlay.showStateSaved(resp); }); - }, }; $(function() { if (!window.thePKT_SAVED) { var thePKT_SAVED = new PKT_SAVED(); /* global thePKT_SAVED */ window.thePKT_SAVED = thePKT_SAVED;
--- a/browser/components/pocket/content/panels/js/sendtomobile.js +++ b/browser/components/pocket/content/panels/js/sendtomobile.js @@ -1,12 +1,11 @@ /* global $:false, Handlebars:false, thePKT_SAVED:false, */ var PKT_SENDTOMOBILE = (function() { - var width = 350; var ctaHeight = 200; var confirmHeight = 275; var premDetailsHeight = 110; var email = null; function _initPanelOneClicks() { $("#pkt_ext_sendtomobile_button").click(function() {
--- a/browser/components/pocket/content/panels/js/signup.js +++ b/browser/components/pocket/content/panels/js/signup.js @@ -51,17 +51,16 @@ var PKT_SIGNUP_OVERLAY = function(option } return String(s).replace(/[&<>"']/g, function(str) { return sanitizeMap[str]; }); }; this.getTranslations = function() { this.dictJSON = window.pocketStrings; }; - }; PKT_SIGNUP_OVERLAY.prototype = { create() { var controlvariant = window.location.href.match(/controlvariant=([\w|\.]*)&?/); if (controlvariant && controlvariant.length > 1) { this.controlvariant = controlvariant[1]; }
--- a/browser/components/pocket/content/pktApi.jsm +++ b/browser/components/pocket/content/pktApi.jsm @@ -46,17 +46,16 @@ var EXPORTED_SYMBOLS = ["pktApi"]; const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); XPCOMUtils.defineLazyGlobalGetters(this, ["XMLHttpRequest"]); XPCOMUtils.defineLazyPreferenceGetter(this, "gCookieFirstPartyIsolate", "privacy.firstparty.isolate", false); var pktApi = (function() { - /** * Configuration */ // Base url for all api calls var pocketAPIhost = Services.prefs.getCharPref("extensions.pocket.api"); // api.getpocket.com var pocketSiteHost = Services.prefs.getCharPref("extensions.pocket.site"); // getpocket.com var baseAPIUrl = "https://" + pocketAPIhost + "/v3"; @@ -321,17 +320,16 @@ var pktApi = (function() { /** * Add a new link to Pocket * @param {string} url URL of the link * @param {Object | undefined} options Can provide a string-based title, a * `success` callback and an `error` callback. * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function addLink(url, options) { - var since = getSetting("latestSince"); var accessToken = getAccessToken(); var sendData = { access_token: accessToken, url, since: since ? since : 0, }; @@ -538,17 +536,16 @@ var pktApi = (function() { }; action = extend(action, actionPart); // Backup the success callback as we need it later var finalSuccessCallback = options.success; // Switch the success callback options.success = function(data) { - // Update used tags var usedTagsJSON = getSetting("usedTags"); var usedTags = usedTagsJSON ? JSON.parse(usedTagsJSON) : {}; // Check for each tag if it's already in the used tags for (var i = 0; i < tags.length; i++) { var tagToSave = tags[i].trim(); var newUsedTagObject = { @@ -570,17 +567,16 @@ var pktApi = (function() { } /** * Get all cached tags and used tags within the callback * @param {function(Array, Array, Boolean)} callback * Function with tags and used tags as parameter. */ function getTags(callback) { - var tagsFromSettings = function() { var tagsJSON = getSetting("tags"); if (typeof tagsJSON !== "undefined") { return JSON.parse(tagsJSON); } return []; }; @@ -646,17 +642,16 @@ var pktApi = (function() { return getSuggestedTags({url}, options); } /** * Helper function to get suggested tags * @return {Boolean} Returns Boolean whether the api call started sucessfully */ function getSuggestedTags(data, options) { - data = data || {}; options = options || {}; data.access_token = getAccessToken(); return apiRequest({ path: "/getSuggestedTags", data, @@ -702,17 +697,16 @@ var pktApi = (function() { }); // Get a random test variant and set the user to it assignedValue = valArray[Math.floor(Math.random() * valArray.length)]; setSetting(settingName, assignedValue); } return assignedValue; - } /** * Public functions */ return { isUserLoggedIn, clearUserData,
--- a/browser/components/preferences/in-content/main.js +++ b/browser/components/preferences/in-content/main.js @@ -2104,17 +2104,16 @@ var gMainPane = { this.rebuildActionsMenu(); // update the richlistitem too. Will be visible when selecting another row this.selectedHandlerListItem.refreshAction(); }; gSubDialog.open("chrome://browser/content/preferences/applicationManager.xul", "resizable=no", handlerInfo, onComplete); - }, chooseApp(aEvent) { // Don't let the normal "on select action" handler get this event, // as we handle it specially ourselves. aEvent.stopPropagation(); var handlerApp;
--- a/browser/components/preferences/in-content/tests/browser_security-2.js +++ b/browser/components/preferences/in-content/tests/browser_security-2.js @@ -48,17 +48,16 @@ add_task(async function() { 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"); - } await checkPrefSwitch(true); await checkPrefSwitch(false); }); requestLongerTimeout(2); // test the unwanted/uncommon software warning preference @@ -101,21 +100,19 @@ add_task(async function() { is(malwareTable.includes("goog-unwanted-proto"), !checked, "malware table doesn't include goog-unwanted-proto"); } 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"); - } await checkPrefSwitch(true, true, false); await checkPrefSwitch(false, true, false); await checkPrefSwitch(true, false, false); await checkPrefSwitch(false, false, false); await checkPrefSwitch(true, true, true); await checkPrefSwitch(false, true, true); await checkPrefSwitch(true, false, true); await checkPrefSwitch(false, false, true); - });
--- a/browser/components/preferences/in-content/tests/browser_subdialogs.js +++ b/browser/components/preferences/in-content/tests/browser_subdialogs.js @@ -188,17 +188,16 @@ add_task(async function check_opening_wh await open_subdialog_and_test_generic_start_state(tab.linkedBrowser); info("closing"); content.window.gSubDialog._topDialog.close(); info("reopening immediately after calling .close()"); await open_subdialog_and_test_generic_start_state(tab.linkedBrowser); await close_subdialog_and_test_generic_end_state(tab.linkedBrowser, function() { content.window.gSubDialog._topDialog._frame.contentDocument.documentElement.acceptDialog(); }, "accept", 1); - }); add_task(async function window_close_on_dialog() { await open_subdialog_and_test_generic_start_state(tab.linkedBrowser); info("canceling the dialog"); await close_subdialog_and_test_generic_end_state(tab.linkedBrowser, function() { content.window.gSubDialog._topDialog._frame.contentWindow.window.close(); },
--- a/browser/components/preferences/in-content/tests/head.js +++ b/browser/components/preferences/in-content/tests/head.js @@ -119,17 +119,16 @@ function openPreferencesViaOpenPreferenc let win = gBrowser.contentWindow; let selectedPane = win.history.state; await finalPrefPaneLoaded; if (!aOptions || !aOptions.leaveOpen) gBrowser.removeCurrentTab(); resolve({ selectedPane }); }, { once: true }); }, { capture: true, once: true }); - }); } async function evaluateSearchResults(keyword, searchReults) { searchReults = Array.isArray(searchReults) ? searchReults : [searchReults]; searchReults.push("header-searchResults"); let searchInput = gBrowser.contentDocument.getElementById("searchInput");
--- a/browser/components/preferences/in-content/tests/siteData/head.js +++ b/browser/components/preferences/in-content/tests/siteData/head.js @@ -79,17 +79,16 @@ function openPreferencesViaOpenPreferenc let win = gBrowser.contentWindow; let selectedPane = win.history.state; await finalPrefPaneLoaded; if (!aOptions || !aOptions.leaveOpen) gBrowser.removeCurrentTab(); resolve({ selectedPane }); }, { once: true }); }, { capture: true, once: true }); - }); } function openSiteDataSettingsDialog() { let doc = gBrowser.selectedBrowser.contentDocument; let settingsBtn = doc.getElementById("siteDataSettings"); let dialogOverlay = content.gSubDialog._preloadDialog._overlay; let dialogLoadPromise = promiseLoadSubDialog("chrome://browser/content/preferences/siteDataSettings.xul");
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js +++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_cache.js @@ -6,17 +6,16 @@ // This test covers MozTrap test 6047 // bug 880621 var tmp = {}; const {Sanitizer} = ChromeUtils.import("resource:///modules/Sanitizer.jsm"); function test() { - waitForExplicitFinish(); Sanitizer.sanitize(["cache"], {ignoreTimespan: false}); getStorageEntryCount("regular", function(nrEntriesR1) { is(nrEntriesR1, 0, "Disk cache reports 0KB and has no entries"); get_cache_for_private_window(); @@ -51,28 +50,25 @@ function getStorageEntryCount(device, go }, }; 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 = BrowserTestUtils.addTab(win.gBrowser, "http://example.org"); win.gBrowser.selectedTab = tab; let newTabBrowser = win.gBrowser.getBrowserForTab(tab); BrowserTestUtils.browserLoaded(newTabBrowser).then(function() { 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"); win.close(); finish();
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js +++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_favicon.js @@ -101,17 +101,16 @@ function observeFavicon(aIsPrivate, aExp } 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 = { @@ -130,17 +129,16 @@ function waitOnFaviconResponse(aFaviconU Services.obs.addObserver(observer, "http-on-examine-cached-response"); }); } 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); } }, };
--- a/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js +++ b/browser/components/privatebrowsing/test/browser/browser_privatebrowsing_popupblocker.js @@ -9,17 +9,16 @@ add_task(async function test() { let oldPopupPolicy = Services.prefs.getBoolPref("dom.disable_open_during_load"); Services.prefs.setBoolPref("dom.disable_open_during_load", true); registerCleanupFunction(() => { Services.prefs.setBoolPref("dom.disable_open_during_load", oldPopupPolicy); }); function testPopupBlockerMenuItem(aExpectedDisabled, aWindow, aCallback) { - aWindow.gBrowser.addEventListener("DOMUpdateBlockedPopups", function() { 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 listener(event) { @@ -38,17 +37,16 @@ add_task(async function test() { dump("CMI: out\n"); } checkMenuItem(function() { aCallback(); }); notification.querySelector("button").doCommand(); }); - }, {once: true}); BrowserTestUtils.loadURI(aWindow.gBrowser.selectedBrowser, testURI); } let win1 = await BrowserTestUtils.openNewBrowserWindow(); await new Promise(resolve => waitForFocus(resolve, win1)); await new Promise(resolve => testPopupBlockerMenuItem(false, win1, resolve));
--- a/browser/components/resistfingerprinting/test/browser/browser_netInfo.js +++ b/browser/components/resistfingerprinting/test/browser/browser_netInfo.js @@ -22,17 +22,16 @@ async function testWindow() { } async function testWorker() { // Open a tab to test network information in a worker. let tab = await BrowserTestUtils.openNewForegroundTab( gBrowser, TEST_PATH + "file_dummy.html"); await ContentTask.spawn(tab.linkedBrowser, null, async function() { - await new Promise(resolve => { let worker = new content.Worker("file_workerNetInfo.js"); worker.onmessage = function(e) { if (e.data.type == "status") { ok(e.data.status, e.data.msg); } else if (e.data.type == "finish") { resolve();
--- a/browser/components/resistfingerprinting/test/browser/browser_performanceAPI.js +++ b/browser/components/resistfingerprinting/test/browser/browser_performanceAPI.js @@ -110,17 +110,16 @@ add_task(async function runRPTests() { content.performance.mark("Test"); content.performance.mark("Test-End"); content.performance.measure("Test-Measure", "Test", "Test-End"); // Check that no entries for performance.getEntries/getEntriesByType/getEntriesByName. is(content.performance.getEntries().length, 0, "For resistFingerprinting, there should be no entries for performance.getEntries()"); is(content.performance.getEntriesByType("resource").length, 0, "For resistFingerprinting, there should be no entries for performance.getEntriesByType()"); is(content.performance.getEntriesByName("Test", "mark").length, 0, "For resistFingerprinting, there should be no entries for performance.getEntriesByName()"); - }; await setupTest(tab, true, true, 100, runTests); await setupTest(tab, true, false, 13, runTests); await setupTest(tab, true, false, .13, runTests); BrowserTestUtils.removeTab(tab); });
--- a/browser/components/resistfingerprinting/test/browser/browser_timezone.js +++ b/browser/components/resistfingerprinting/test/browser/browser_timezone.js @@ -26,14 +26,13 @@ add_task(async function test_timezone() "The date string is in UTC timezone."); is(dateObj.getFullYear(), dateObj.getUTCFullYear(), "The full year reports in UTC timezone."); is(dateObj.getMonth(), dateObj.getUTCMonth(), "The month reports in UTC timezone."); is(dateObj.getDate(), dateObj.getUTCDate(), "The month reports in UTC timezone."); is(dateObj.getDay(), dateObj.getUTCDay(), "The day reports in UTC timezone."); is(dateObj.getHours(), dateObj.getUTCHours(), "The hours reports in UTC timezone."); is(dateObj.getTimezoneOffset(), 0, "The difference with UTC timezone is 0."); - } ); BrowserTestUtils.removeTab(tab); });
--- a/browser/components/resistfingerprinting/test/browser/head.js +++ b/browser/components/resistfingerprinting/test/browser/head.js @@ -172,17 +172,16 @@ async function testWindowSizeSetting(aBr settingHeight: aSettingHeight + (aTestOuter ? aPopupChromeUIHeight : 0), targetWidth: aTargetWidth, targetHeight: aTargetHeight, testOuter: aTestOuter, }; await ContentTask.spawn(aBrowser, testParams, async function(input) { - let win; // Open a new window and wait until it loads. await new Promise(resolve => { // Given a initial window size which should be different from target // size. We need this to trigger 'onresize' event. let initWinFeatures = "width=" + input.initWidth + ",height=" + input.initHeight; win = content.open("http://example.net/", "", initWinFeatures); win.onload = () => resolve();
--- a/browser/components/resistfingerprinting/test/mochitest/file_animation_api.html +++ b/browser/components/resistfingerprinting/test/mochitest/file_animation_api.html @@ -67,17 +67,16 @@ }; const testDiv = document.getElementById("testDiv"); const animation = testDiv.animate({ opacity: [0, 1] }, 100000); animation.play(); waitForCondition( () => animation.currentTime > 100, () => { - // We have disabled Time Precision Reduction for CSS Animations, so we expect those tests to fail. // If we are testing that preference, we accept either rounded or not rounded values as A-OK. var maybeAcceptEverything = function(value) { if (opener.prefName.includes("privacy.reduceTimerPrecision") && !opener.prefName.includes("privacy.resistFingerprinting")) return true; return value; };
--- a/browser/components/resistfingerprinting/test/mochitest/test_animation_api.html +++ b/browser/components/resistfingerprinting/test/mochitest/test_animation_api.html @@ -39,17 +39,16 @@ https://bugzilla.mozilla.org/show_bug.cg SpecialPowers.pushPrefEnv({"set": [ ["dom.animations-api.timelines.enabled", true], ["privacy.resistFingerprinting", resistFingerprinting], ["privacy.reduceTimerPrecision", reduceTimerPrecision], ["privacy.resistFingerprinting.reduceTimerPrecision.microseconds", expectedPrecision], ], }, runTest); - } var testIndx = 0; var testSequence = [ [true, false, 100000], [false, true, 100000], [true, false, 50000], [false, true, 50000],
--- a/browser/components/resistfingerprinting/test/mochitest/test_pointer_event.html +++ b/browser/components/resistfingerprinting/test/mochitest/test_pointer_event.html @@ -189,17 +189,16 @@ https://bugzilla.mozilla.org/show_bug.cg synthesizeMouse(target0, 5, 5, { type: "mousemove", inputSource: MouseEvent.MOZ_SOURCE_TOUCH }); synthesizeMouse(target0, 5, 5, { type: "mouseup", inputSource: MouseEvent.MOZ_SOURCE_TOUCH }); await Promise.all(eventPromises); } // A test for assuring that script generated events won't be spoofed. function doTestNoSpoofingForScriptGeneratedEvent() { - return new Promise(resolve => { // Generate a custom pointer event by script. let pointerEventCustom = new PointerEvent("pointerover", { pointerId: utils.DEFAULT_TOUCH_POINTER_ID, pointerType: "touch", width: 5, height: 5, pressure: 0.75,
--- a/browser/components/search/content/searchbar.js +++ b/browser/components/search/content/searchbar.js @@ -4,17 +4,16 @@ "use strict"; /* globals XULCommandEvent */ // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - const inheritsMap = { ".searchbar-textbox": ["disabled", "disableautocomplete", "searchengine", "src", "newlines"], ".searchbar-search-button": ["addengines"], }; function inheritAttribute(parent, child, attr) { if (!parent.hasAttribute(attr)) { child.removeAttribute(attr); @@ -22,17 +21,16 @@ function inheritAttribute(parent, child, child.setAttribute(attr, parent.getAttribute(attr)); } } /** * Defines the search bar element. */ class MozSearchbar extends MozXULElement { - static get observedAttributes() { let unique = new Set(); for (let i in inheritsMap) { inheritsMap[i].forEach(attr => unique.add(attr)); } return Array.from(unique); } @@ -478,15 +476,13 @@ class MozSearchbar extends MozXULElement } // Open the suggestions whenever clicking on the search icon or if there // is text in the textbox. if (isIconClick || this._textbox.value) { this.openSuggestionsPanel(true); } }); - } } customElements.define("searchbar", MozSearchbar); - }
--- a/browser/components/sessionstore/SessionStore.jsm +++ b/browser/components/sessionstore/SessionStore.jsm @@ -4829,18 +4829,16 @@ var SessionStoreInternal = { state.selectedWindow -= 1; else if (wIndex + 1 == state.selectedWindow) defaultState.selectedIndex = defaultState.windows.length + 1; state.windows.splice(wIndex, 1); // We don't want to increment wIndex here. continue; } - - } wIndex++; } return [defaultState, state]; }, _sendRestoreCompletedNotifications: function ssi_sendRestoreCompletedNotifications() { @@ -4871,17 +4869,16 @@ var SessionStoreInternal = { /** * Set the given window's busy state * @param aWindow the window * @param aValue the window's busy state */ _setWindowStateBusyValue: function ssi_changeWindowStateBusyValue(aWindow, aValue) { - this._windows[aWindow.__SSi].busy = aValue; // Keep the to-be-restored state in sync because that is returned by // getWindowState() as long as the window isn't loaded, yet. if (!this._isWindowLoaded(aWindow)) { let stateToRestore = this._statesToRestore[WINDOW_RESTORE_IDS.get(aWindow)].windows[0]; stateToRestore.busy = aValue; }
--- a/browser/components/sessionstore/SessionWorker.js +++ b/browser/components/sessionstore/SessionWorker.js @@ -156,17 +156,16 @@ var Agent = { } } } let stateString = JSON.stringify(state); let data = Encoder.encode(stateString); try { - if (this.state == STATE_CLEAN || this.state == STATE_EMPTY) { // The backups directory may not exist yet. In all other cases, // we have either already read from or already written to this // directory, so we are satisfied that it exists. File.makeDir(this.Paths.backups); } if (this.state == STATE_CLEAN) { @@ -219,17 +218,16 @@ var Agent = { tmpPath: this.Paths.recovery + ".tmp", compression: "lz4", }); fileStat = File.stat(this.Paths.recovery); } telemetry.FX_SESSION_RESTORE_WRITE_FILE_MS = Date.now() - startWriteMs; telemetry.FX_SESSION_RESTORE_FILE_SIZE_BYTES = fileStat.size; - } catch (ex) { // Don't throw immediately exn = exn || ex; } // If necessary, perform an upgrade backup let upgradeBackupComplete = false; if (this.upgradeBackupNeeded @@ -274,17 +272,16 @@ var Agent = { if (i < backups.length - this.maxUpgradeBackups) { File.remove(file); } }); } } if (options.performShutdownCleanup && !exn) { - // During shutdown, if auto-restore is disabled, we need to // remove possibly sensitive data that has been stored purely // for crash recovery. Note that this slightly decreases our // ability to recover from OS-level/hardware-level issue. // If an exception was raised, we assume that we still need // these files. File.remove(this.Paths.recoveryBackup); @@ -304,17 +301,16 @@ var Agent = { telemetry, }; }, /** * Wipes all files holding session data from disk. */ wipe() { - // Don't stop immediately in case of error. let exn = null; // Erase main session state file try { File.remove(this.Paths.clean); // Remove old extension ones. File.remove(this.Paths.clean.replace("jsonlz4", "js"), {ignoreAbsent: true});
--- a/browser/components/sessionstore/test/browser_589246.js +++ b/browser/components/sessionstore/test/browser_589246.js @@ -211,17 +211,16 @@ function onWindowUnloaded() { // 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.gBrowser.selectedBrowser.addEventListener("load", function() { // Good enough for checking the state afterTestCallback(previousClosedWindowData, ss.getClosedWindowData()); afterTestCleanup(newWin); }, {capture: true, once: true}); - }, {once: true}); } function afterTestCleanup(aNewWin) { executeSoon(function() { BrowserTestUtils.closeWindow(aNewWin).then(() => { document.documentElement.setAttribute("windowtype", originalWindowType); runNextTestOrFinish();
--- a/browser/components/sessionstore/test/browser_739531.js +++ b/browser/components/sessionstore/test/browser_739531.js @@ -18,17 +18,16 @@ function test() { removeFunc = BrowserTestUtils.addContentEventListener(tab.linkedBrowser, "load", function onLoad(aEvent) { // make sure both the page and the frame are loaded if (++loadCount < 2) return; removeFunc(); // 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); }
--- a/browser/components/sessionstore/test/browser_cleaner.js +++ b/browser/components/sessionstore/test/browser_cleaner.js @@ -125,17 +125,16 @@ add_task(async function test_old_data() 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"); await promiseCleanup(); }); add_task(async function test_cleanup() { - info("5. Altering closedAt to an old date, making sure that stuff gets collected, eventually"); await 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;
--- a/browser/components/sessionstore/test/browser_privatetabs.js +++ b/browser/components/sessionstore/test/browser_privatetabs.js @@ -43,17 +43,16 @@ add_task(async function() { 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); } }
--- a/browser/components/shell/test/unit/test_421977.js +++ b/browser/components/shell/test/unit/test_421977.js @@ -32,38 +32,35 @@ function hexToColor(aString) { } /** * 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); Assert.equal(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); Assert.equal(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"]. @@ -78,17 +75,16 @@ function run_test() { 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"); @@ -107,13 +103,12 @@ function run_test() { 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); } }
--- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js +++ b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js @@ -125,17 +125,16 @@ add_task(async function testSyncedTabsSi 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(async function testSyncedTabsSidebarFilteredList() { await SidebarUI.show("viewTabsSidebar"); let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
--- a/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js +++ b/browser/components/syncedtabs/test/xpcshell/test_SyncedTabsListStore.js @@ -184,17 +184,16 @@ add_task(async function testRowSelection 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(async function testFilterAndClearFilter() { let store = new SyncedTabsListStore(SyncedTabs); let spy = sinon.spy(); sinon.stub(SyncedTabs, "getTabClients", () => {
--- a/browser/components/tests/startupRecorder.js +++ b/browser/components/tests/startupRecorder.js @@ -71,17 +71,16 @@ startupRecorder.prototype = { } catch (e) { return false; } }), }; }, observe(subject, topic, data) { - if (topic == "app-startup") { // We can't ensure our observer will be called first or last, so the list of // topics we observe here should avoid the topics used to trigger things // during startup (eg. the topics observed by nsBrowserGlue.js). let topics = [ "profile-do-change", // This catches stuff loaded during app-startup "toplevel-window-ready", // Catches stuff from final-ui-startup "image-loading",
--- a/browser/components/translation/BingTranslator.jsm +++ b/browser/components/translation/BingTranslator.jsm @@ -233,17 +233,16 @@ this.BingTranslator.prototype = { } text = escapeXML(text); let newCurSize = currentDataSize + text.length; let newChunks = currentChunks + 1; if (newCurSize > MAX_REQUEST_DATA || newChunks > MAX_REQUEST_CHUNKS) { - // If we've reached the API limits, let's stop accumulating data // for this request and return. We return information useful for // the caller to pass back on the next call, so that the function // can keep working from where it stopped. return { data: output, finished: false, lastIndex: i,
--- a/browser/components/translation/GoogleTranslator.jsm +++ b/browser/components/translation/GoogleTranslator.jsm @@ -208,17 +208,16 @@ this.GoogleTranslator.prototype = { continue; } let newCurSize = currentDataSize + text.length; let newChunks = currentChunks + 1; if (newCurSize > MAX_REQUEST_DATA || newChunks > MAX_REQUEST_CHUNKS) { - // If we've reached the API limits, let's stop accumulating data // for this request and return. We return information useful for // the caller to pass back on the next call, so that the function // can keep working from where it stopped. return { data: output, finished: false, lastIndex: i,
--- a/browser/components/translation/TranslationDocument.jsm +++ b/browser/components/translation/TranslationDocument.jsm @@ -559,62 +559,58 @@ function swapTextForItem(item, target) { curNode.nodeValue.trim() == "") { curNode = curNode.nextSibling; } // Now let's walk through all items in the `target` array of the // TranslationItem. This means either the TranslationItem.original or // TranslationItem.translation array. for (let targetItem of curItem[target]) { - if (targetItem instanceof TranslationItem) { // If the array element is another TranslationItem object, let's // add it to the stack to be visited. visitStack.push(targetItem); let targetNode = targetItem.nodeRef; // If the node is not in the expected position, let's reorder // it into position... if (curNode != targetNode && // ...unless the page has reparented this node under a totally // different node (or removed it). In this case, all bets are off // on being able to do anything correctly, so it's better not to // bring back the node to this parent. targetNode.parentNode == domNode) { - // We don't need to null-check curNode because insertBefore(..., null) // does what we need in that case: reorder this node to the end // of child nodes. domNode.insertBefore(targetNode, curNode); curNode = targetNode; } // Move pointer forward. Since we do not add empty text nodes to the // list of translation items, we must skip them here too while // traversing the DOM in order to get better alignment between the // text nodes and the translation items. if (curNode) { curNode = getNextSiblingSkippingEmptyTextNodes(curNode); } - } else if (targetItem === TranslationItem_NodePlaceholder) { // If the current item is a placeholder node, we need to move // our pointer "past" it, jumping from one side of a block of // elements + empty text nodes to the other side. Even if // non-placeholder elements exists inside the jumped block, // they will be pulled correctly later in the process when the // targetItem for those nodes are handled. while (curNode && (curNode.nodeType != curNode.TEXT_NODE || curNode.nodeValue.trim() == "")) { curNode = curNode.nextSibling; } - } else { // Finally, if it's a text item, we just need to find the next // text node to use. Text nodes don't need to be reordered, so // the first one found can be used. while (curNode && curNode.nodeType != curNode.TEXT_NODE) { curNode = curNode.nextSibling; }
--- a/browser/components/translation/YandexTranslator.jsm +++ b/browser/components/translation/YandexTranslator.jsm @@ -238,17 +238,16 @@ this.YandexTranslator.prototype = { continue; } let newCurSize = currentDataSize + text.length; let newChunks = currentChunks + 1; if (newCurSize > MAX_REQUEST_DATA || newChunks > MAX_REQUEST_CHUNKS) { - // If we've reached the API limits, let's stop accumulating data // for this request and return. We return information useful for // the caller to pass back on the next call, so that the function // can keep working from where it stopped. return { data: output, finished: false, lastIndex: i, @@ -317,17 +316,16 @@ YandexRequest.prototype = { onError(e, responseText, xhr) { reject(xhr); }, postData: params, }; // Fire the request. this.networkRequest = httpRequest(url, options); - }); })(); }, }; /** * Fetch an auth token (clientID or client secret), which may be overridden by * a pref if it's set.
--- a/browser/components/translation/test/browser_translation_bing.js +++ b/browser/components/translation/test/browser_translation_bing.js @@ -21,17 +21,16 @@ add_task(async function setup() { Services.prefs.clearUserPref(kClientSecretPref); }); }); /** * Checks if the translation is happening. */ add_task(async 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 = await promiseTestPageLoad(url); // Translating the contents of the loaded tab. @@ -58,17 +57,16 @@ add_task(async function test_bing_transl /** * 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(async 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 = await promiseTestPageLoad(url); // Translating the contents of the loaded tab.
--- a/browser/components/translation/test/browser_translation_exceptions.js +++ b/browser/components/translation/test/browser_translation_exceptions.js @@ -59,42 +59,37 @@ function getInfoBar() { if (!infobar) { resolve(); } else { // Wait for all animations to finish Promise.all(infobar.getAnimations().map(animation => animation.finished)) .then(() => resolve(infobar)); } - }); } function openPopup(aPopup) { return new Promise(resolve => { - aPopup.addEventListener("popupshown", function() { TestUtils.executeSoon(resolve); }, {once: true}); aPopup.focus(); // One down event to open the popup. EventUtils.synthesizeKey("VK_DOWN", { altKey: !navigator.platform.includes("Mac") }); - }); } function waitForWindowLoad(aWin) { return new Promise(resolve => { - aWin.addEventListener("load", function() { TestUtils.executeSoon(resolve); }, {capture: true, once: true}); - }); } var gTests = [ { desc: "clean exception lists at startup",
--- a/browser/components/translation/test/browser_translation_telemetry.js +++ b/browser/components/translation/test/browser_translation_telemetry.js @@ -268,17 +268,16 @@ add_task(async function test_never_offer autoRejectedOffers: 1, }); gBrowser.removeTab(tab); Services.prefs.clearUserPref("browser.translation.neverForLanguages"); }); add_task(async 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}}, @@ -290,10 +289,9 @@ add_task(async function test_translation MetricsChecker.reset(); Services.prefs.setBoolPref(preference, check.value); // Preference metrics are collected once when the provider is initialized. TranslationTelemetry.init(); await MetricsChecker.checkAdditions(check.expected); } Services.prefs.clearUserPref(preference); } - });
--- a/browser/components/translation/test/browser_translation_yandex.js +++ b/browser/components/translation/test/browser_translation_yandex.js @@ -32,17 +32,16 @@ add_task(async function setup() { }); }); /** * Ensure that the translation engine behaives as expected when translating * a sample page. */ add_task(async function test_yandex_translation() { - // Loading the fixture page. let url = constructFixtureURL("bug1022725-fr.html"); let tab = await promiseTestPageLoad(url); // Translating the contents of the loaded tab. gBrowser.selectedTab = tab; let browser = tab.linkedBrowser;
--- a/browser/components/uitour/test/browser_UITour.js +++ b/browser/components/uitour/test/browser_UITour.js @@ -250,17 +250,16 @@ var tests = [ is(buttons.hasChildNodes(), false, "Popup should have no buttons"); popup.addEventListener("popuphidden", function() { popup.addEventListener("popupshown", function() { done(); }, {once: true}); gContentAPI.showInfo("urlbar", "test title", "test text"); - }, {once: true}); gContentAPI.hideInfo(); }, {once: true}); gContentAPI.showInfo("urlbar", "test title", "test text"); }, taskify(async function test_info_2() { let popup = document.getElementById("UITourTooltip");
--- a/browser/components/uitour/test/browser_no_tabs.js +++ b/browser/components/uitour/test/browser_no_tabs.js @@ -56,17 +56,16 @@ add_task(async function test_windowless_ // Allow the URL to use the UITour. info("Adding UITour permission to the test page."); let pageURI = Services.io.newURI(pageURL); Services.perms.add(pageURI, "uitour", Services.perms.ALLOW_ACTION); // UITour's ping will resolve this promise. await new Promise(resolve => { - // 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);
--- a/browser/components/uitour/test/browser_trackingProtection.js +++ b/browser/components/uitour/test/browser_trackingProtection.js @@ -29,17 +29,16 @@ add_task(async function test_benignPage( await BrowserTestUtils.withNewTab({gBrowser, url: BENIGN_PAGE}, async function() { await waitForConditionPromise(() => { return BrowserTestUtils.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(async function test_trackingPages() { info("Load a test page containing tracking elements"); allowOneIntro(); await BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, async function() { await new Promise((resolve, reject) => { @@ -78,11 +77,10 @@ add_task(async function test_trackingPag await BrowserTestUtils.withNewTab({gBrowser, url: TRACKING_PAGE}, async function() { await waitForConditionPromise(() => { return BrowserTestUtils.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"); }); - }); });
--- a/browser/components/urlbar/tests/legacy/browser_autocomplete_edit_completed.js +++ b/browser/components/urlbar/tests/legacy/browser_autocomplete_edit_completed.js @@ -39,10 +39,9 @@ add_task(async function() { gBrowser.selectedBrowser); info("Press return to load edited URL."); EventUtils.synthesizeKey("KEY_Enter"); await Promise.all([ promisePopupHidden(gURLBar.popup), docLoad, ]); - });
--- a/browser/components/urlbar/tests/legacy/browser_search_favicon.js +++ b/browser/components/urlbar/tests/legacy/browser_search_favicon.js @@ -13,17 +13,16 @@ add_task(async function() { Services.prefs.setBoolPref(gRestyleSearchesPref, true); // This test is sensitive to the mouse position hovering awesome // bar elements, so make sure it doesnt await EventUtils.synthesizeNativeMouseMove(document.documentElement, 0, 0); }); add_task(async function() { - Services.search.addEngineWithDetails("SearchEngine", "", "", "", "GET", "http://s.example.com/search"); gEngine = Services.search.getEngineByName("SearchEngine"); gEngine.addParam("q", "{searchTerms}", null); gOriginalEngine = Services.search.defaultEngine; Services.search.defaultEngine = gEngine; let uri = NetUtil.newURI("http://s.example.com/search?q=foobar&client=1");
--- a/browser/extensions/formautofill/.eslintrc.js +++ b/browser/extensions/formautofill/.eslintrc.js @@ -87,19 +87,16 @@ module.exports = { // Disallow use of assignment in return statement. It is preferable for a // single line of code to have only one easily predictable effect. "no-return-assign": "error", // Disallow throwing literals (eg. throw "error" instead of // throw new Error("error")). "no-throw-literal": "error", - // Disallow padding within blocks. - "padded-blocks": ["error", "never"], - // Require use of the second argument for parseInt(). "radix": "error", // Enforce spacing after semicolons. "semi-spacing": ["error", {"before": false, "after": true}], // Require "use strict" to be defined globally in the script. "strict": ["error", "global"],
--- a/browser/extensions/pdfjs/content/PdfJsNetwork.jsm +++ b/browser/extensions/pdfjs/content/PdfJsNetwork.jsm @@ -20,17 +20,16 @@ const {Services} = ChromeUtils.import("r var EXPORTED_SYMBOLS = ["NetworkManager"]; function log(aMsg) { // eslint-disable-line no-unused-vars var msg = "PdfJsNetwork.jsm: " + (aMsg.join ? aMsg.join("") : aMsg); Services.console.logStringMessage(msg); } var NetworkManager = (function NetworkManagerClosure() { - const OK_RESPONSE = 200; const PARTIAL_CONTENT_RESPONSE = 206; function getArrayBuffer(xhr) { var data = xhr.response; if (typeof data !== "string") { return data; }
--- a/browser/extensions/pdfjs/content/PdfStreamConverter.jsm +++ b/browser/extensions/pdfjs/content/PdfStreamConverter.jsm @@ -543,17 +543,16 @@ class ChromeActions { } /** * This is for range requests. */ class RangedChromeActions extends ChromeActions { constructor(domWindow, contentDispositionFilename, originalRequest, rangeEnabled, streamingEnabled, dataListener) { - super(domWindow, contentDispositionFilename); this.dataListener = dataListener; this.originalRequest = originalRequest; this.rangeEnabled = rangeEnabled; this.streamingEnabled = streamingEnabled; this.pdfUrl = originalRequest.URI.spec; this.contentLength = originalRequest.contentLength;
--- a/browser/extensions/webcompat-reporter/.eslintrc.js +++ b/browser/extensions/webcompat-reporter/.eslintrc.js @@ -82,19 +82,16 @@ module.exports = { // Disallow use of assignment in return statement. It is preferable for a // single line of code to have only one easily predictable effect. "no-return-assign": "error", // Disallow throwing literals (eg. throw "error" instead of // throw new Error("error")). "no-throw-literal": "error", - // Disallow padding within blocks. - "padded-blocks": ["error", "never"], - // Require use of the second argument for parseInt(). "radix": "error", // Enforce spacing after semicolons. "semi-spacing": ["error", {"before": false, "after": true}], // Require "use strict" to be defined globally in the script. "strict": ["error", "global"],
--- a/browser/modules/SitePermissions.jsm +++ b/browser/modules/SitePermissions.jsm @@ -488,17 +488,16 @@ var SitePermissions = { * The state of the permission. * @param {SitePermissions scope} scope (optional) * The scope of the permission. Defaults to SCOPE_PERSISTENT. * @param {Browser} browser (optional) * The browser object to set temporary permissions on. * This needs to be provided if the scope is SCOPE_TEMPORARY! */ set(uri, permissionID, state, scope = this.SCOPE_PERSISTENT, browser = null) { - if (scope == this.SCOPE_GLOBAL && state == this.BLOCK) { GloballyBlockedPermissions.set(browser, permissionID); browser.dispatchEvent(new browser.ownerGlobal.CustomEvent("PermissionStateChange")); return; } if (state == this.UNKNOWN || state == this.getDefault(permissionID)) { // Because they are controlled by two prefs with many states that do not
--- a/browser/modules/test/browser/browser_SitePermissions_tab_urls.js +++ b/browser/modules/test/browser/browser_SitePermissions_tab_urls.js @@ -7,17 +7,16 @@ ChromeUtils.import("resource:///modules/SitePermissions.jsm", this); function newURI(url) { return Services.io.newURI(url); } // This tests the key used to store the URI -> permission map on a tab. add_task(async function testTemporaryPermissionTabURLs() { - // Prevent showing a dialog for https://name:password@example.com SpecialPowers.pushPrefEnv({set: [ ["network.http.phishy-userpass-length", 2048], ]}); // This usually takes about 60 seconds on 32bit Linux debug, // due to the combinatory nature of the test that is hard to fix. requestLongerTimeout(2); @@ -79,11 +78,10 @@ add_task(async function testTemporaryPer scope: SitePermissions.SCOPE_PERSISTENT, }, `${uri.spec} should not share tab permissions with ${uri2.spec}`); } } SitePermissions.clearTemporaryPermissions(browser); } }); - });
--- a/browser/modules/webrtcUI.jsm +++ b/browser/modules/webrtcUI.jsm @@ -199,17 +199,16 @@ var webrtcUI = { off(...args) { return this.emitter.off(...args); }, // Listeners and observers are registered in nsBrowserGlue.js receiveMessage(aMessage) { switch (aMessage.name) { - case "rtcpeer:Request": { let params = Object.freeze(Object.assign({ origin: aMessage.target.contentPrincipal.origin, }, aMessage.data)); let blockers = Array.from(this.peerConnectionBlockers); (async function() { @@ -888,17 +887,16 @@ function prompt(aBrowser, aRequest) { devices: allowedDevices}); }; return false; }, }; // Don't offer "always remember" action in PB mode. if (!PrivateBrowsingUtils.isBrowserPrivate(aBrowser)) { - // Disable the permanent 'Allow' action if the connection isn't secure, or for // screen/audio sharing (because we can't guess which window the user wants to // share without prompting). let reasonForNoPermanentAllow = ""; if (sharingScreen) { reasonForNoPermanentAllow = "getUserMedia.reasonForNoPermanentAllow.screen3"; } else if (sharingAudio) { reasonForNoPermanentAllow = "getUserMedia.reasonForNoPermanentAllow.audio";
--- a/caps/tests/mochitest/browser_checkloaduri.js +++ b/caps/tests/mochitest/browser_checkloaduri.js @@ -253,11 +253,10 @@ add_task(async function() { baseFlags | ssm.DISALLOW_INHERIT_PRINCIPAL); testURL(contentPrincipal, "view-source:" + contentBlobURI, false, false, true, baseFlags); testURL(contentPrincipal, "view-source:" + contentBlobURI, false, false, true, baseFlags | ssm.DISALLOW_INHERIT_PRINCIPAL); } ); - }); });
--- a/chrome/test/unit/test_bug564667.js +++ b/chrome/test/unit/test_bug564667.js @@ -32,17 +32,16 @@ function test_removed_mapping(chromeURL, gCR.convertChromeURL(uri); do_throw(chromeURL + " not removed"); } catch (ex) { // This should throw } } function testManifest(manifestPath, baseURI) { - // ------------------ Add manifest file ------------------------ Components.manager.addBootstrappedManifestLocation(manifestPath); // Test Adding Content URL test_mapping("chrome://test1/content", baseURI + "test/test1.xul"); // Test Adding Locale URL test_mapping("chrome://test1/locale", baseURI + "test/test1.dtd");
--- a/chrome/test/unit/test_bug848297.js +++ b/chrome/test/unit/test_bug848297.js @@ -16,23 +16,21 @@ var chromeReg = Cc["@mozilla.org/chrome/ .QueryInterface(Ci.nsIToolkitChromeRegistry); chromeReg.checkForNewChrome(); function enum_to_array(strings) { return Array.from(strings).sort(); } function run_test() { - // without override Services.locale.requestedLocales = ["de"]; Assert.equal(chromeReg.getSelectedLocale("basepack"), "en-US"); Assert.equal(chromeReg.getSelectedLocale("overpack"), "de"); Assert.deepEqual(enum_to_array(chromeReg.getLocalesForPackage("basepack")), ["en-US", "fr"]); // with override Services.prefs.setCharPref("chrome.override_package.basepack", "overpack"); Assert.equal(chromeReg.getSelectedLocale("basepack"), "de"); Assert.deepEqual(enum_to_array(chromeReg.getLocalesForPackage("basepack")), ["de", "en-US"]); - }
--- a/chrome/test/unit/test_data_protocol_registration.js +++ b/chrome/test/unit/test_data_protocol_registration.js @@ -40,17 +40,16 @@ function run_test() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); // Register our factories for (let i = 0; i < factories.length; i++) { let factory = factories[i]; // Make sure the class ID has not already been registered if (!registrar.isCIDRegistered(factory.CID)) { - // Check to see if a contract was already registered and // register it if it is not. Otherwise, store the previous one // to be restored later and register the new one. if (registrar.isContractIDRegistered(factory.contractID)) { dump(factory.scheme + " is already registered. Storing currently registered object for restoration later."); old_factories.push({ CID: registrar.contractIDToCID(factory.contractID), factory: Components.manager.getClassObject(Cc[factory.contractID], Ci.nsIFactory),
--- a/chrome/test/unit/test_no_remote_registration.js +++ b/chrome/test/unit/test_no_remote_registration.js @@ -113,17 +113,16 @@ function run_test() { registrar.registerFactory(factory.CID, "test-" + factory.scheme, factory.contractID, factory); } // Register the XULAppInfoFactory // Make sure the class ID has not already been registered let old_factory = {CID: "", factory: null}; if (!registrar.isCIDRegistered(XULAppInfoFactory.CID)) { - // Check to see if a contract was already registered and // register it if it is not. Otherwise, store the previous one // to be restored later and register the new one. if (registrar.isContractIDRegistered(XULAppInfoFactory.contractID)) { dump(XULAppInfoFactory.scheme + " is already registered. Storing currently registered object for restoration later."); old_factory.CID = registrar.contractIDToCID(XULAppInfoFactory.contractID); old_factory.factory = Components.manager.getClassObject(Cc[XULAppInfoFactory.contractID], Ci.nsIFactory); registrar.unregisterFactory(old_factory.CID, old_factory.factory);
--- a/devtools/.eslintrc.js +++ b/devtools/.eslintrc.js @@ -373,18 +373,16 @@ module.exports = { // Allow using TODO/FIXME comments. "no-warning-comments": "off", // Don't require method and property shorthand syntax for object literals. // We use this in the code a lot, but not consistently, and this seems more // like something to check at code review time. "object-shorthand": "off", // Allow more than one variable declaration per function. "one-var": "off", - // Disallow padding within blocks. - "padded-blocks": ["error", "never"], // Enforce using `let` only when variables are reassigned. "prefer-const": ["error", { "destructuring": "all" }], // Don't require quotes around object literal property names. "quote-props": "off", // Require use of the second argument for parseInt(). "radix": "error", // Enforce spacing after semicolons. "semi-spacing": ["error", {"before": false, "after": true}],
--- a/docshell/test/navigation/NavigationUtils.js +++ b/docshell/test/navigation/NavigationUtils.js @@ -94,17 +94,16 @@ function isInaccessible(wnd, message) { } // ///////////////////////////////////////////////////////////////////////// // Functions that require UniversalXPConnect privilege // ///////////////////////////////////////////////////////////////////////// // Replacing the getService with Services.ww format causes test errors, so ignore for now /* eslint-disable mozilla/use-services */ function xpcEnumerateContentWindows(callback) { - var Ci = SpecialPowers.Ci; var ww = SpecialPowers.Cc["@mozilla.org/embedcomp/window-watcher;1"] .getService(Ci.nsIWindowWatcher); var contentWindows = []; for (let win of ww.getWindowEnumerator()) { if (win.isChromeWindow) { @@ -180,17 +179,16 @@ function xpcWaitForFinishedFrames(callba function searchForFinishedFrames(win) { if ((win.location.href.endsWith(target_url) || win.location.href.endsWith(target_popup_url)) && win.document && win.document.body && (win.document.body.textContent.trim() == body || win.document.body.textContent.trim() == popup_body) && win.document.readyState == "complete") { - var windowId = win.windowUtils.outerWindowID; if (!contains(windowId, finishedWindows)) { finishedWindows.push(windowId); frameFinished(); } } for (var i = 0; i < win.frames.length; i++) searchForFinishedFrames(win.frames[i]);
--- a/docshell/test/navigation/browser_bug343515.js +++ b/docshell/test/navigation/browser_bug343515.js @@ -30,17 +30,16 @@ function oneShotListener(aBrowser, aType function waitForPageshow(aBrowser, callback) { return ContentTask.spawn(aBrowser, null, async function() { await ContentTaskUtils.waitForEvent(this, "pageshow"); }).then(callback); } // Entry point from Mochikit function test() { - // Lots of callbacks going on here waitForExplicitFinish(); // Begin the test step1(); } async function step1() { @@ -173,17 +172,16 @@ function step5() { // bug343515_pg3.html consists of a page with two iframes, one of which // contains another iframe, so there'll be a total of 4 load events nShotsListener(ctx.tab1Browser, "load", step6, 4); }); } function step6() { - // Check everything ok(!ctx.tab0Browser.docShellIsActive, "Tab 0 should be inactive"); ok(ctx.tab1Browser.docShellIsActive, "Tab 1 should be active"); ContentTask.spawn(ctx.tab1Browser, null, async function() { function isActive(aWindow) { var docshell = aWindow.docShell; return docshell.isActive; } @@ -235,16 +233,15 @@ function step7() { }).then(() => { // That's probably enough allDone(); }); } function allDone() { - // Close the tabs we made gBrowser.removeTab(ctx.tab1); gBrowser.removeTab(ctx.tab2); // Tell the framework we're done finish(); }
--- a/docshell/test/navigation/test_bug386782.html +++ b/docshell/test/navigation/test_bug386782.html @@ -83,17 +83,16 @@ https://bugzilla.mozilla.org/show_bug.cg gTest.window.close(); goNext(); } }; gTest.window.history.back(); } function checkStillEditable() { - // Check that the contents are correct. is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterEdit, "Edited contents still correct?"); // Check that we can undo/redo and the contents are correct. gTest.window.document.execCommand("undo", false, null); is(gTest.window.document.body.innerHTML, gTest.expectedBodyBeforeEdit, "Can we undo?"); gTest.window.document.execCommand("redo", false, null); @@ -101,17 +100,16 @@ https://bugzilla.mozilla.org/show_bug.cg // Check that we can still edit the page. gTest.window.document.body.focus(); sendString("TWICE ", gTest.window); is(gTest.window.document.body.innerHTML, gTest.expectedBodyAfterSecondEdit, "Can we still edit?"); gTest.window.close(); goNext(); - } </script> </head> <body> <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=386782">Mozilla Bug 386782</a> <p id="display"></p>
--- a/docshell/test/unit/test_nsDefaultURIFixup_info.js +++ b/docshell/test/unit/test_nsDefaultURIFixup_info.js @@ -550,17 +550,16 @@ function do_single_test_run() { for (let { input: testInput, fixedURI: expectedFixedURI, alternateURI: alternativeURI, keywordLookup: expectKeywordLookup, protocolChange: expectProtocolChange, inWhitelist: inWhitelist, affectedByDNSForSingleHosts: affectedByDNSForSingleHosts, } of relevantTests) { - // Explicitly force these into a boolean expectKeywordLookup = !!expectKeywordLookup; expectProtocolChange = !!expectProtocolChange; inWhitelist = !!inWhitelist; affectedByDNSForSingleHosts = !!affectedByDNSForSingleHosts; expectKeywordLookup = expectKeywordLookup && (!affectedByDNSForSingleHosts || !gSingleWordHostLookup);
--- a/dom/base/test/unit/test_cancelPrefetch.js +++ b/dom/base/test/unit/test_cancelPrefetch.js @@ -23,17 +23,16 @@ function run_test() { node1 = doc.getElementById("node1"); node2 = doc.getElementById("node2"); run_next_test(); } add_test(function test_cancel1() { - var uri = ios.newURI("http://localhost/1"); prefetch.prefetchURI(uri, uri, node1, true); Assert.ok(prefetch.hasMoreElements(), "There is a request in the queue"); // Trying to prefetch again the same uri with the same node will fail. var didFail = 0;
--- a/dom/base/test/unit/test_isequalnode.js +++ b/dom/base/test/unit/test_isequalnode.js @@ -17,17 +17,16 @@ function run_test() { test_isEqualNode_variety(); test_isEqualNode_normalization(); test_isEqualNode_whitespace(); test_isEqualNode_namespaces(); test_isEqualNode_wholeDoc(); // XXX should Node.isEqualNode(null) throw or return false? // test_isEqualNode_null(); - } // TEST CODE var doc, root; // cache for use in all tests function init() { doc = ParseFile("isequalnode_data.xml");
--- a/dom/base/test/unit/test_nodelist.js +++ b/dom/base/test/unit/test_nodelist.js @@ -1,19 +1,17 @@ /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ function run_test() { - test_getElementsByTagName(); test_getElementsByTagNameNS(); test_getElementsByAttribute(); test_getElementsByAttributeNS(); // What else should we test? // XXXbz we need more tests here to test liveness! - } function test_getElementsByTagName() { var doc = ParseFile("nodelist_data_1.xml"); var root = doc.documentElement; // Check that getElementsByTagName returns an HTMLCollection. Assert.equal(ChromeUtils.getClassName(doc.getElementsByTagName("*")),
--- a/dom/base/test/unit/test_xml_serializer.js +++ b/dom/base/test/unit/test_xml_serializer.js @@ -1,17 +1,16 @@ // The xml serializer uses the default line break of the plateform. // So we need to know the value of this default line break, in order // to build correctly the reference strings for tests. // This variable will contain this value. var LB; function run_test() { - if (mozinfo.os == "win") { LB = "\r\n"; } else { LB = "\n"; } for (var i = 0; i < tests.length && tests[i]; ++i) { tests[i].call(); @@ -87,17 +86,16 @@ function test3() { doc = ParseXML('<prefix:root xmlns:prefix="ns1"/>'); root = doc.documentElement; child = doc.createElementNS("ns2", "prefix:child"); root.appendChild(child); do_check_serialize(doc); Assert.equal(SerializeXML(doc), '<prefix:root xmlns:prefix="ns1"><a0:child xmlns:a0="ns2"/>' + "</prefix:root>"); - } function test4() { // setAttributeNS tests var doc = ParseXML('<root xmlns="ns1"/>'); var root = doc.documentElement; root.setAttributeNS("ns1", "prefix:local", "val");
--- a/dom/console/tests/test_console_binding.html +++ b/dom/console/tests/test_console_binding.html @@ -21,17 +21,16 @@ consoleListener.prototype = { if (order + 1 == parseInt(obj.arguments[0])) { ok(true, "Message received: " + obj.arguments[0]); order++; } if (order == 3) { SpecialPowers.removeObserver(this, "console-api-log-event"); SimpleTest.finish(); - } } }, }; var cl = new consoleListener(); SimpleTest.waitForExplicitFinish();
--- a/dom/console/tests/test_devtools_pref.html +++ b/dom/console/tests/test_devtools_pref.html @@ -15,17 +15,16 @@ function consoleListener(expected) { let observer = { observe: function listener(aSubject, aTopic, aData) { var obj = aSubject.wrappedJSObject; messages.push(parseInt(obj.arguments[0])); if (messages.length == expected) { SpecialPowers.removeObserver(observer, "console-api-log-event"); SpecialPowers.removeObserver(observer, "console-api-profiler"); done(messages); - } }, }; SpecialPowers.addObserver(observer, "console-api-log-event"); SpecialPowers.addObserver(observer, "console-api-profiler"); }); }
--- a/dom/credentialmanagement/tests/mochitest/test_credman_iframes.html +++ b/dom/credentialmanagement/tests/mochitest/test_credman_iframes.html @@ -46,13 +46,12 @@ function handleEventMessage(event) { window.addEventListener("message", handleEventMessage); SpecialPowers.pushPrefEnv({"set": [["security.webauth.webauthn", true], ["security.webauth.webauthn_enable_softtoken", true], ["security.webauth.webauthn_enable_usbtoken", false]]}, function() { document.getElementById("frame_top").src = "https://example.com/tests/dom/credentialmanagement/tests/mochitest/frame_credman_iframes.html"; document.getElementById("frame_bottom").src = "https://test1.example.com/tests/dom/credentialmanagement/tests/mochitest/frame_credman_iframes.html"; - }); </script> </body> </html>
--- a/dom/crypto/test/test_WebCrypto_Wrap_Unwrap.html +++ b/dom/crypto/test/test_WebCrypto_Wrap_Unwrap.html @@ -237,17 +237,16 @@ TestArray.addTest( crypto.subtle.importKey("jwk", tv.aes_kw.key, "AES-GCM", true, ["encrypt"]), ]) .then(doWrap) .then( memcmp_complete(that, tv.aes_kw.wrapped_key), error(that) ); - } ); // ----------------------------------------------------------------------------- TestArray.addTest( "AES-KW unwrap failure on tampered key data", function() { var that = this;
--- a/dom/filesystem/compat/tests/test_basic.html +++ b/dom/filesystem/compat/tests/test_basic.html @@ -104,17 +104,16 @@ function test_directoryEntry_createReade // Called twice: reader.readEntries(function(a1) { ok(Array.isArray(a1), "We want an array."); is(a1.length, 0, "reader.readyEntries returns 0 elements."); next(); }, function() { ok(false, "Something when wrong!"); }); - }, function() { ok(false, "Something when wrong!"); }); } function test_directoryEntry_getParent() { directoryEntry.getParent(function(entry) { is(directoryEntry.fullPath, entry.fullPath, "Top level FileEntry should return itself as parent.");
--- a/dom/indexedDB/test/leaving_page_iframe.html +++ b/dom/indexedDB/test/leaving_page_iframe.html @@ -27,16 +27,15 @@ function madeMod() { // Make this transaction run until the end of time or until the page is // navigated away, whichever comes first. function doGet() { store.get(42).onsuccess = doGet; } doGet(); document.location = "about:blank"; }; - } </script> </head> <body onload="startDBWork();"> This is page one. </body> </html>
--- a/dom/indexedDB/test/test_blob_simple.html +++ b/dom/indexedDB/test/test_blob_simple.html @@ -209,17 +209,16 @@ function workerScript() { /* eslint-env worker */ onmessage = function(event) { var reader = new FileReaderSync(); postMessage(reader.readAsText(event.data)); var slice = event.data.slice(1, 2); postMessage(reader.readAsText(slice)); - }; } let url = URL.createObjectURL(new Blob(["(", workerScript.toSource(), ")()"])); let worker = new Worker(url); worker.postMessage(slice);
--- a/dom/ipc/tests/browser_domainPolicy.js +++ b/dom/ipc/tests/browser_domainPolicy.js @@ -7,17 +7,16 @@ function activateDomainPolicy() { function deactivateDomainPolicy() { if (policy) { policy.deactivate(); policy = null; } } async function test_domainPolicy() { - ChromeUtils.defineModuleGetter(this, "Promise", "resource://gre/modules/Promise.jsm"); let outerDeferred = Promise.defer(); let currentTask = outerDeferred.promise; SpecialPowers.pushPrefEnv( {set: [["dom.ipc.browser_frames.oop_by_default", false], ["browser.pagethumbnails.capturing_disabled", false], ["dom.mozBrowserFramesEnabled", false]]}, () => { return outerDeferred.resolve(); });
--- a/dom/ipc/tests/test_CrashService_crash.html +++ b/dom/ipc/tests/test_CrashService_crash.html @@ -16,33 +16,31 @@ Ensures that content crashes are reporte SimpleTest.waitForExplicitFinish(); SimpleTest.requestFlakyTimeout("untriaged"); SpecialPowers.addPermission("browser", true, document); SpecialPowers.pushPrefEnv({"set": [ ["dom.mozBrowserFramesEnabled", true], ["network.disable.ipc.security", true], ["dom.ipc.tabs.disabled", false], ]}, function() { - var iframe = document.createElementNS("http://www.w3.org/1999/xhtml", "iframe"); iframe.setAttribute("remote", "true"); SpecialPowers.wrap(iframe).mozbrowser = true; document.documentElement.appendChild(iframe); SimpleTest.expectChildProcessCrash(); var crashMan = SpecialPowers.Cu.import("resource://gre/modules/Services.jsm"). Services.crashmanager; // First, clear the crash record store. info("Waiting for pruneOldCrashes"); var future = new Date(Date.now() + 1000 * 60 * 60 * 24); crashMan.pruneOldCrashes(future).then(function() { - var crashDateMS = Date.now(); // Inject a frame script that crashes the content process. var mm = SpecialPowers.getBrowserFrameMessageManager(iframe); mm.loadFrameScript("data:,new " + function ContentScriptScope() { const {ctypes} = ChromeUtils.import("resource://gre/modules/ctypes.jsm"); let crash = function() { let zero = new ctypes.intptr_t(8); @@ -76,17 +74,16 @@ SpecialPowers.pushPrefEnv({"set": [ setTimeout(tryGetCrash, 1000); } }), function(err) { ok(false, "Error getting crashes: " + err); SimpleTest.finish(); }); } setTimeout(tryGetCrash, 1000); - }, function() { ok(false, "pruneOldCrashes error"); SimpleTest.finish(); }); }); </script> </body>
--- a/dom/ipc/tests/test_child_docshell.html +++ b/dom/ipc/tests/test_child_docshell.html @@ -14,17 +14,16 @@ SimpleTest.waitForExplicitFinish(); SpecialPowers.addPermission("browser", true, document); SpecialPowers.pushPrefEnv({"set": [ ["dom.mozBrowserFramesEnabled", true], ["network.disable.ipc.security", true], ["dom.ipc.tabs.disabled", false], ]}, function() { - var iframe = document.createElementNS("http://www.w3.org/1999/xhtml", "iframe"); iframe.setAttribute("remote", "true"); SpecialPowers.wrap(iframe).mozbrowser = true; document.documentElement.appendChild(iframe); var mm = SpecialPowers.getBrowserFrameMessageManager(iframe); mm.addMessageListener("chromeEventHandler", function(msg) { msg = SpecialPowers.wrap(msg);
--- a/dom/manifest/Manifest.jsm +++ b/dom/manifest/Manifest.jsm @@ -53,17 +53,16 @@ const MANIFESTS_DIR = OS.Path.join(OS.Co // whether a given url is within the scope of a previously installed manifest const MANIFESTS_FILE = "manifest-scopes.json"; /** * Manifest object */ class Manifest { - constructor(browser, manifestUrl) { this._manifestUrl = manifestUrl; // The key for this is the manifests URL that is required to be unique. // However arbitrary urls are not safe file paths so lets hash it. const fileName = generateHash(manifestUrl) + ".json"; this._path = OS.Path.join(MANIFESTS_DIR, fileName); this._browser = browser; } @@ -136,40 +135,37 @@ class Manifest { } /* * Manifests maintains the list of installed manifests */ var Manifests = { async initialise() { - if (this.started) { return this.started; } this.started = (async () => { - // Make sure the manifests have the folder needed to save into await OS.File.makeDir(MANIFESTS_DIR, {ignoreExisting: true}); // Ensure any existing scope data we have about manifests is loaded this._path = OS.Path.join(OS.Constants.Path.profileDir, MANIFESTS_FILE); this._store = new JSONFile({path: this._path}); await this._store.load(); // If we dont have any existing data, initialise empty if (!this._store.data.hasOwnProperty("scopes")) { this._store.data.scopes = new Map(); } // Cache the Manifest objects creates as they are references to files // and we do not want multiple file handles this.manifestObjs = {}; - })(); return this.started; }, // When a manifest is installed, we save its scope so we can determine if // fiture visits fall within this manifests scope manifestInstalled(manifest) { @@ -186,17 +182,16 @@ var Manifests = { } } return null; }, // Get the manifest given a url, or if not look for a manifest that is // tied to the current page async getManifest(browser, manifestUrl) { - // Ensure we have all started up await this.initialise(); // If the client does not already know its manifestUrl, we take the // url of the client and see if it matches the scope of any installed // manifests if (!manifestUrl) { const url = stripQuery(browser.currentURI.spec);
--- a/dom/manifest/test/browser_Manifest_install.js +++ b/dom/manifest/test/browser_Manifest_install.js @@ -14,21 +14,19 @@ function makeTestURL() { const url = new URL(defaultURL); const body = `<link rel="manifest" href='${manifestUrl}'>`; url.searchParams.set("Content-Type", "text/html; charset=utf-8"); url.searchParams.set("body", encodeURIComponent(body)); return url.href; } add_task(async function() { - const tabOptions = {gBrowser, url: makeTestURL()}; await BrowserTestUtils.withNewTab(tabOptions, async function(browser) { - let manifest = await Manifests.getManifest(browser, manifestUrl); is(manifest.installed, false, "We havent installed this manifest yet"); await manifest.install(browser); is(manifest.name, "hello World", "Manifest has correct name"); is(manifest.installed, true, "Manifest is installed"); is(manifest.url, manifestUrl, "has correct url"); @@ -39,10 +37,9 @@ add_task(async function() { is(manifest.installed, true, "Will find manifest without being given url"); let foundManifest = Manifests.findManifestUrl("http://example.org/browser/dom/"); is(foundManifest, manifestUrl, "Finds manifests within scope"); foundManifest = Manifests.findManifestUrl("http://example.org/"); is(foundManifest, null, "Does not find manifests outside scope"); }); - });
--- a/dom/media/PeerConnection.js +++ b/dom/media/PeerConnection.js @@ -568,17 +568,16 @@ class RTCPeerConnection { if (!closed && this._closed) { await new Promise(() => {}); } throw e; } } async _legacyCloseWrapper(onSucc, onErr, func) { - let wrapCallback = cb => result => { try { cb && cb(result); } catch (e) { this.logErrorAndCallOnError(e); } }; @@ -609,17 +608,16 @@ class RTCPeerConnection { * { urls: ["turn:turn1.x.org", "turn:turn2.x.org"], * username:"jib", credential:"mypass"} ] } * * This function normalizes the structure of the input for rtcConfig.iceServers for us, * so we test well-formed stun/turn urls before passing along to C++. * msg - Error message to detail which array-entry failed, if any. */ _mustValidateRTCConfiguration({ iceServers }, msg) { - // Normalize iceServers input iceServers.forEach(server => { if (typeof server.urls === "string") { server.urls = [server.urls]; } else if (!server.urls && server.url) { // TODO: Remove support for legacy iceServer.url eventually (Bug 1116766) server.urls = [server.url]; this.logWarning("RTCIceServer.url is deprecated! Use urls instead."); @@ -1680,17 +1678,16 @@ class PeerConnectionObserver { let win = this._dompc._win; if (candidate) { if (candidate.includes(" typ relay ")) { this._dompc._iceGatheredRelayCandidates = true; } candidate = new win.RTCIceCandidate({ candidate, sdpMid, sdpMLineIndex }); } else { candidate = null; - } this.dispatchEvent(new win.RTCPeerConnectionIceEvent("icecandidate", { candidate })); } // This method is primarily responsible for updating iceConnectionState. // This state is defined in the WebRTC specification as follows: //
--- a/dom/media/mediasource/test/mediasource.js +++ b/dom/media/mediasource/test/mediasource.js @@ -109,17 +109,16 @@ async function loadSegment(sb, typedArra const p = once(sb, "update"); sb.appendBuffer(typedArray); await p; const afterBuffered = timeRangeToString(sb.buffered); info(`SourceBuffer buffered ranges grew from ${beforeBuffered} to ${afterBuffered}`); } async function fetchAndLoad(sb, prefix, chunks, suffix) { - // Fetch the buffers in parallel. const buffers = await Promise.all(chunks.map(c => fetchWithXHR(prefix + c + suffix))); // Load them in series, as required per spec. for (const buffer of buffers) { await loadSegment(sb, buffer); } } @@ -131,17 +130,16 @@ function loadSegmentAsync(sb, typedArray const beforeBuffered = timeRangeToString(sb.buffered); return sb.appendBufferAsync(typedArray).then(() => { const afterBuffered = timeRangeToString(sb.buffered); info(`SourceBuffer buffered ranges grew from ${beforeBuffered} to ${afterBuffered}`); }); } function fetchAndLoadAsync(sb, prefix, chunks, suffix) { - // Fetch the buffers in parallel. const buffers = {}; const fetches = []; for (const chunk of chunks) { fetches.push(fetchWithXHR(prefix + chunk + suffix).then(((c, x) => buffers[c] = x).bind(null, chunk))); } // Load them in series, as required per spec.
--- a/dom/media/mediasource/test/test_AVC3_mp4.html +++ b/dom/media/mediasource/test/test_AVC3_mp4.html @@ -8,17 +8,16 @@ </head> <body> <pre id="test"> <script class="testbody" type="text/javascript"> SimpleTest.waitForExplicitFinish(); runWithMSE(async (ms, el) => { - await once(ms, "sourceopen"); ok(true, "Receive a sourceopen event"); const videosb = ms.addSourceBuffer("video/mp4"); await fetchAndLoad(videosb, "avc3/init", [""], ".mp4"); const p = once(el, "loadeddata"); await fetchAndLoad(videosb, "avc3/segment", range(1, 2), ".m4s"); await p;
--- a/dom/media/mediasource/test/test_SeekToEnd_mp4.html +++ b/dom/media/mediasource/test/test_SeekToEnd_mp4.html @@ -8,17 +8,16 @@ </head> <body> <pre id="test"> <script class="testbody" type="text/javascript"> SimpleTest.waitForExplicitFinish(); runWithMSE(async (ms, el) => { - await once(ms, "sourceopen"); ok(true, "Receive a sourceopen event"); const videosb = ms.addSourceBuffer("video/mp4"); const audiosb = ms.addSourceBuffer("audio/mp4"); await fetchAndLoad(videosb, "bipbop/bipbop_video", ["init"], ".mp4"); await fetchAndLoad(videosb, "bipbop/bipbop_video", range(1, 6), ".m4s"); await fetchAndLoad(audiosb, "bipbop/bipbop_audio", ["init"], ".mp4");
--- a/dom/media/mediasource/test/test_TimestampOffset_mp4.html +++ b/dom/media/mediasource/test/test_TimestampOffset_mp4.html @@ -8,17 +8,16 @@ </head> <body> <pre id="test"> <script class="testbody" type="text/javascript"> SimpleTest.waitForExplicitFinish(); runWithMSE(async (ms, el) => { - const eps = 0.01; await once(ms, "sourceopen"); ok(true, "Receive a sourceopen event"); const audiosb = ms.addSourceBuffer("audio/mp4"); const videosb = ms.addSourceBuffer("video/mp4"); // We divide the video into 3 chunks: // chunk 0: segments 1-4
--- a/dom/presentation/tests/mochitest/PresentationSessionChromeScript1UA.js +++ b/dom/presentation/tests/mochitest/PresentationSessionChromeScript1UA.js @@ -221,17 +221,16 @@ const mockRequestUIGlue = { return this.QueryInterface(aIID); }, sendRequest(aUrl, aSessionId) { return this.promise; }, }; function initMockAndListener() { - function registerMockFactory(contractId, mockClassId, mockFactory) { var originalClassId, originalFactory; var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); if (!registrar.isCIDRegistered(mockClassId)) { try { originalClassId = registrar.contractIDToCID(contractId); originalFactory = Cm.getClassObject(Cc[contractId], Ci.nsIFactory); @@ -329,17 +328,16 @@ function initMockAndListener() { debug("Got observer: setup-request-promise"); Services.obs.removeObserver(setupRequestPromiseHandler, aTopic); mockRequestUIGlue.promise = aSubject; sendAsyncMessage("promise-setup-ready"); }, "setup-request-promise"); } function teardown() { - function registerOriginalFactory(contractId, mockedClassId, mockedFactory, originalClassId, originalFactory) { if (originalFactory) { var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(mockedClassId, mockedFactory); registrar.registerFactory(originalClassId, "", contractId, originalFactory); } }
--- a/dom/presentation/tests/mochitest/test_presentation_1ua_sender_and_receiver.js +++ b/dom/presentation/tests/mochitest/test_presentation_1ua_sender_and_receiver.js @@ -21,17 +21,16 @@ const TYPED_DATA_ARRAY = new Uint8Array( TYPED_DATA_ARRAY.set(DATA_ARRAY); function postMessageToIframe(aType) { receiverIframe.src = receiverUrl + "#" + encodeURIComponent(JSON.stringify({ type: aType })); } function setup() { - gScript.addMessageListener("device-prompt", function devicePromptHandler() { debug("Got message: device-prompt"); gScript.removeMessageListener("device-prompt", devicePromptHandler); gScript.sendAsyncMessage("trigger-device-prompt-select"); }); gScript.addMessageListener("control-channel-established", function controlChannelEstablishedHandler() { gScript.removeMessageListener("control-channel-established",
--- a/dom/presentation/tests/mochitest/test_presentation_datachannel_sessiontransport.html +++ b/dom/presentation/tests/mochitest/test_presentation_datachannel_sessiontransport.html @@ -226,17 +226,16 @@ function runTests() { Services.prefs.setIntPref(loadingTimeoutPref, 30000); testBuilder() .then(testClientSendMessage) .then(testServerSendMessage) .then(testCloseSessionTransport) .then(finish) .catch(error); - } window.addEventListener("load", function() { runTests(); }); </script> </pre>
--- a/dom/presentation/tests/mochitest/test_presentation_tcp_sender.html +++ b/dom/presentation/tests/mochitest/test_presentation_tcp_sender.html @@ -33,17 +33,16 @@ function testSetup() { gScript.sendAsyncMessage("trigger-device-add"); }, function(aError) { ok(false, "Error occurred when getting availability: " + aError); teardown(); aReject(); } ); - }); } function testStartConnection() { return new Promise(function(aResolve, aReject) { gScript.addMessageListener("device-prompt", function devicePromptHandler() { gScript.removeMessageListener("device-prompt", devicePromptHandler); info("Device prompt is triggered.");
--- a/dom/presentation/tests/xpcshell/test_multicast_dns_device_provider.js +++ b/dom/presentation/tests/xpcshell/test_multicast_dns_device_provider.js @@ -25,26 +25,24 @@ const SERVICE_TYPE = "_presentation-ctrl const versionAttr = Cc["@mozilla.org/hash-property-bag;1"] .createInstance(Ci.nsIWritablePropertyBag2); versionAttr.setPropertyAsUint32("version", LATEST_VERSION); var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar); function sleep(aMs) { return new Promise(resolve => { - let timer = Cc["@mozilla.org/timer;1"] .createInstance(Ci.nsITimer); timer.initWithCallback({ notify() { resolve(); }, }, aMs, timer.TYPE_ONE_SHOT); - }); } function MockFactory(aClass) { this._cls = aClass; } MockFactory.prototype = { createInstance(aOuter, aIID) {
--- a/dom/system/NetworkGeolocationProvider.js +++ b/dom/system/NetworkGeolocationProvider.js @@ -304,17 +304,16 @@ WifiGeoPositionProvider.prototype = { this.listener = null; this.started = false; }, setHighAccuracy(enable) { }, onChange(accessPoints) { - // we got some wifi data, rearm the timer. this.resetTimer(); function isPublic(ap) { let mask = "_nomap"; let result = ap.ssid.indexOf(mask, ap.ssid.length - mask.length); if (result != -1) { LOG("Filtering out " + ap.ssid + " " + result);
--- a/dom/tests/browser/browser_ConsoleAPITests.js +++ b/dom/tests/browser/browser_ConsoleAPITests.js @@ -269,17 +269,16 @@ async function startTraceTest(browser) { dump("Observer attached\n"); gLevel = "trace"; gArgs = [ {columnNumber: 9, filename: TEST_URI, functionName: "window.foobar585956c", lineNumber: 6}, {columnNumber: 16, filename: TEST_URI, functionName: "foobar585956b", lineNumber: 11}, {columnNumber: 16, filename: TEST_URI, functionName: "foobar585956a", lineNumber: 15}, {columnNumber: 1, filename: TEST_URI, functionName: "onclick", lineNumber: 1}, ]; - }); BrowserTestUtils.synthesizeMouseAtCenter("#test-trace", {}, browser); await waitForResolve(browser); } function testLocationData(aMessageObject) { let messageWindow = Services.wm.getOuterWindowWithId(aMessageObject.ID);
--- a/dom/tests/browser/browser_bug396843.js +++ b/dom/tests/browser/browser_bug396843.js @@ -1,12 +1,11 @@ /** Test for Bug 396843 **/ function testInDocument(doc, documentID) { - var allNodes = []; var XMLNodes = []; // HTML function HTML_TAG(name) { allNodes.push(doc.createElement(name)); }
--- a/dom/tests/browser/browser_frame_elements.js +++ b/dom/tests/browser/browser_frame_elements.js @@ -8,17 +8,16 @@ const TEST_URI = "http://example.com/bro add_task(async function test() { await BrowserTestUtils.withNewTab({ gBrowser, url: TEST_URI }, async function(browser) { if (!browser.isRemoteBrowser) { // Non-e10s, access contentWindow and confirm its container is the browser: let windowUtils = browser.contentWindow.windowUtils; is(windowUtils.containerElement, browser, "Container element for main window is xul:browser"); - } await ContentTask.spawn(browser, null, startTests); await mozBrowserTests(browser); }); }); function startTests() {
--- a/dom/tests/browser/browser_persist_mixed_content_image.js +++ b/dom/tests/browser/browser_persist_mixed_content_image.js @@ -93,10 +93,9 @@ add_task(async function test_image_downl let popupHidden = BrowserTestUtils.waitForEvent(popup, "popuphidden"); popup.querySelector("#context-saveimage").click(); popup.hidePopup(); await popupHidden; info("Context menu hidden, waiting for download to finish"); let imageDownload = await downloadFinishedPromise; ok(imageDownload.succeeded, "Image should have downloaded successfully"); }); - });
--- a/dom/tests/browser/perfmetrics/browser_test_unresponsive.js +++ b/dom/tests/browser/perfmetrics/browser_test_unresponsive.js @@ -22,10 +22,9 @@ add_task(async function test() { dataBack += 1; } } } let results = await ChromeUtils.requestPerformanceMetrics(); exploreResults(results); Assert.ok(dataBack == 0); }); - });
--- a/editor/composer/test/test_bug384147.html +++ b/editor/composer/test/test_bug384147.html @@ -25,17 +25,16 @@ SimpleTest.waitForExplicitFinish(); var editor = document.getElementById("editor"); editor.innerHTML = "<ol><li>Item 1</li><li>Item 2</li><ol><li>Item 3</li></ol></ol><ul><li>Item 4</li><li>Item 5</li></ul>"; editor.focus(); // If executed directly, a race condition exists that will cause execCommand // to fail occasionally (but often). Defer test execution to page load. addLoadEvent(function() { - var sel = window.getSelection(); // Test the effect that the tab key has on list items. Each test is // documented with the initial state of the list on the left, and the // expected state of the list on the right. {\t} indicates the list item // that will be indented. {\st} indicates that a shift-tab will be simulated // on that list item, outdenting it. //
--- a/editor/libeditor/tests/test_bug1140105.html +++ b/editor/libeditor/tests/test_bug1140105.html @@ -43,17 +43,16 @@ SimpleTest.waitForFocus(function() { is(anyHas.value, true, "Test for Arial: anyHas: true expected"); is(allHas.value, true, "Test for Arial: allHas: true expected"); editor.getInlineProperty("font", "face", "Courier", firstHas, anyHas, allHas); is(firstHas.value, false, "Test for Courier: firstHas: false expected"); is(anyHas.value, false, "Test for Courier: anyHas: false expected"); is(allHas.value, false, "Test for Courier: allHas: false expected"); SimpleTest.finish(); - }); function getEditor() { var Ci = SpecialPowers.Ci; var editingSession = SpecialPowers.wrap(window).docShell.editingSession; var editor = editingSession.getEditorForWindow(window); editor.QueryInterface(Ci.nsIHTMLEditor); return editor;
--- a/editor/libeditor/tests/test_bug1250010.html +++ b/editor/libeditor/tests/test_bug1250010.html @@ -23,17 +23,16 @@ https://bugzilla.mozilla.org/show_bug.cg function getImageDataURI() { return document.getElementsByTagName("img")[0].getAttribute("src"); } /** Test for Bug 1250010 **/ SimpleTest.waitForExplicitFinish(); SimpleTest.waitForFocus(function() { - // First test: Empty paragraph is split correctly. var div = document.getElementById("test1"); div.focus(); synthesizeMouseAtCenter(div, {}); var sel = window.getSelection(); var selRange = sel.getRangeAt(0); is(selRange.endContainer.nodeName, "#text", "selection should be at the end of text node"); @@ -78,15 +77,14 @@ SimpleTest.waitForFocus(function() { is(newHTML, expectedHTML, "unexpected HTML"); // In case the empty tag gets deleted some day, let them know that something improved. expectedHTML = "<p><tt>xyz</tt></p><p><tt><img src=\"" + getImageDataURI() + "\"><br></tt></p>" + "<p><tt>A</tt><br></p>"; todo_is(newHTML, expectedHTML, "unexpected HTML"); SimpleTest.finish(); - }); </script> </body> </html>
--- a/editor/libeditor/tests/test_bug1257363.html +++ b/editor/libeditor/tests/test_bug1257363.html @@ -21,17 +21,16 @@ https://bugzilla.mozilla.org/show_bug.cg <pre id="test"> </pre> <script class="testbody" type="application/javascript"> /** Test for Bug 1257363 **/ SimpleTest.waitForExplicitFinish(); SimpleTest.waitForFocus(function() { - // ***** Backspace test ***** var div = document.getElementById("backspaceCSS"); div.focus(); synthesizeMouse(div, 100, 2, {}); /* click behind and down */ var sel = window.getSelection(); var selRange = sel.getRangeAt(0); is(selRange.endContainer.nodeName, "#text", "selection should be at the end of text node"); @@ -168,15 +167,14 @@ SimpleTest.waitForFocus(function() { // Add an "a" to the start of the paragraph. sendString("a"); is(div.innerHTML, "<p><font color=\"red\">ay</font></p>", "unexpected HTML"); SimpleTest.finish(); - }); </script> </body> </html>
--- a/editor/libeditor/tests/test_bug1330796.html +++ b/editor/libeditor/tests/test_bug1330796.html @@ -58,17 +58,16 @@ var tests = [ "<span>> mailcite</span><br>x<br>" ], ]; /** Test for Bug 1330796 **/ SimpleTest.waitForExplicitFinish(); SimpleTest.waitForFocus(function() { - var sel = window.getSelection(); var theEdit = document.getElementById("editable"); makeMailEditor(); for (let i = 0; i < tests.length; i++) { theEdit.innerHTML = tests[i][0]; theEdit.focus(); var theText = theEdit.firstChild.firstChild; @@ -76,17 +75,16 @@ SimpleTest.waitForFocus(function() { sel.collapse(theText, tests[i][1]); synthesizeKey("KEY_Enter"); sendString("x"); is(theEdit.innerHTML, tests[i][2], "unexpected HTML for test " + i.toString()); } SimpleTest.finish(); - }); function makeMailEditor() { var Ci = SpecialPowers.Ci; var editingSession = SpecialPowers.wrap(window).docShell.editingSession; var editor = editingSession.getEditorForWindow(window); editor.flags |= Ci.nsIPlaintextEditor.eEditorMailMask; }
--- a/editor/libeditor/tests/test_bug1368544.html +++ b/editor/libeditor/tests/test_bug1368544.html @@ -24,17 +24,16 @@ SimpleTest.waitForFocus(() => { let spellChecker = SpecialPowers.Cu.createSpellChecker(); spellChecker.InitSpellChecker(editor, false); textarea.focus(); SpecialPowers.Cu.import( "resource://testing-common/AsyncSpellCheckTestHelper.jsm") .onSpellCheck(textarea, () => { - spellChecker.UpdateCurrentDictionary(() => { textarea.value = "ABC"; ok(editor.rootElement.hasChildNodes(), "editor of textarea has child nodes"); sendString("D"); is(textarea.value, "ABCD", "D is last character"); ok(editor.rootElement.hasChildNodes(), "editor of textarea has child nodes");
--- a/editor/libeditor/tests/test_bug291780.html +++ b/editor/libeditor/tests/test_bug291780.html @@ -21,17 +21,16 @@ https://bugzilla.mozilla.org/show_bug.cg SimpleTest.waitForExplicitFinish(); var original = '<ul style="margin-left: 40px;"><li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li></ul>'; var editor = document.getElementById("editor"); editor.innerHTML = original; editor.focus(); addLoadEvent(function() { - var sel = window.getSelection(); sel.removeAllRanges(); var lis = document.getElementsByTagName("li"); var range = document.createRange(); range.setStart(lis[1], 0); range.setEnd(lis[2], lis[2].childNodes.length); sel.addRange(range); document.execCommand("indent", false, false);
--- a/editor/libeditor/tests/test_bug414526.html +++ b/editor/libeditor/tests/test_bug414526.html @@ -14,17 +14,16 @@ </pre> <script class="testbody" type="application/javascript"> SimpleTest.waitForExplicitFinish(); SimpleTest.waitForFocus(runTests); function runTests() { - var container = document.getElementById("display"); function reset() { document.execCommand("Undo", false, null); } var selection = window.getSelection(); function moveCaretToStartOf(aEditor) {
--- a/editor/libeditor/tests/test_bug455992.html +++ b/editor/libeditor/tests/test_bug455992.html @@ -2,17 +2,16 @@ <html><head> <title>Test for bug 455992</title> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script> <script class="testbody" type="application/javascript"> function runTest() { - function select(id) { var e = document.getElementById(id); e.focus(); return e; } function setupIframe(id) { var e = document.getElementById(id);
--- a/editor/libeditor/tests/test_bug456244.html +++ b/editor/libeditor/tests/test_bug456244.html @@ -2,17 +2,16 @@ <html><head> <title>Test for bug 456244</title> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script> <script class="testbody" type="application/javascript"> function runTest() { - function select(id) { var e = document.getElementById(id); e.focus(); return e; } function setupIframe(id) { var e = document.getElementById(id);
--- a/editor/libeditor/tests/test_bug471722.html +++ b/editor/libeditor/tests/test_bug471722.html @@ -31,17 +31,16 @@ https://bugzilla.mozilla.org/show_bug.cg var t1 = $("t1"); var editor = SpecialPowers.wrap(t1).editor; ok(editor, "able to get editor for the element"); t1.focus(); t1.select(); try { - // Cut the initial text in the textbox ok(editor.canCut(), "can cut text"); editor.cut(); is(t1.value, "", "initial text was removed"); // So now we will have emptied the textfield // and the editor will have created a bogus node // Check the transaction is in the undo stack...
--- a/editor/libeditor/tests/test_bug487524.html +++ b/editor/libeditor/tests/test_bug487524.html @@ -2,17 +2,16 @@ <html><head> <title>Test for bug 487524</title> <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/> <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script> <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script> <script class="testbody" type="application/javascript"> function runTest() { - function setupIframe(e, html, focus_id) { var doc = e.contentDocument; doc.body.innerHTML = html; doc.designMode = "on"; e = doc.getElementById(focus_id); doc.defaultView.focus(); if (e) e.focus(); return e;
--- a/editor/libeditor/tests/test_bug552782.html +++ b/editor/libeditor/tests/test_bug552782.html @@ -21,17 +21,16 @@ https://bugzilla.mozilla.org/show_bug.cg SimpleTest.waitForExplicitFinish(); var original = "<ol><li>Item 1</li><ol><li>Item 2</li><li>Item 3</li><li>Item 4</li></ol></ol>"; var editor = document.getElementById("editor"); editor.innerHTML = original; editor.focus(); addLoadEvent(function() { - var sel = window.getSelection(); sel.removeAllRanges(); var lis = document.getElementsByTagName("li"); sel.selectAllChildren(lis[2]); document.execCommand("outdent", false, false); var expected = "<ol><li>Item 1</li><ol><li>Item 2</li></ol><li>Item 3</li><ol><li>Item 4</li></ol></ol>"; is(editor.innerHTML, expected, "outdenting third item in a partially indented numbered list"); document.execCommand("indent", false, false);
--- a/editor/libeditor/tests/test_bug772796.html +++ b/editor/libeditor/tests/test_bug772796.html @@ -141,17 +141,16 @@ https://bugzilla.mozilla.org/show_bug.cg /* 72*/[ "<div>test</div><pre>\n\nfoo\nbar</pre>", "<div>test</div><pre>foo\nbar</pre>", "<div>test\n</div><pre>foo\nbar</pre>" ], ]; /** Test for Bug 772796 **/ SimpleTest.waitForExplicitFinish(); SimpleTest.waitForFocus(function() { - var sel = window.getSelection(); var theEdit = document.getElementById("editable"); var testName; var theDiv; for (let i = 0; i < tests.length; i++) { testName = "test" + i.toString(); @@ -206,16 +205,15 @@ https://bugzilla.mozilla.org/show_bug.cg var expected = tests[i][1].replace("testfoo", "tesoo") .replace("test<b>foo", "tes<b>oo") .replace("test<span class=\"pre\">foo", "tes<span class=\"pre\">oo") .replace("test<span class=\"pre\"><b>foo", "tes<span class=\"pre\"><b>oo"); is(theDiv.innerHTML, expected, "delete(non-collapsed): inner HTML for " + testName); } SimpleTest.finish(); - }); </script> </pre> </body> </html>
--- a/editor/libeditor/tests/test_css_chrome_load_access.html +++ b/editor/libeditor/tests/test_css_chrome_load_access.html @@ -16,17 +16,16 @@ https://bugzilla.mozilla.org/show_bug.cg </div> <pre id="test"> <script class="testbody" type="text/javascript"> const Ci = SpecialPowers.Ci; var styleSheets = null; function runTest() { - var editframe = window.frames[0]; var editdoc = editframe.document; editdoc.designMode = "on"; var editor = SpecialPowers.wrap(editframe).docShell.editingSession .getEditorForWindow(editframe); styleSheets = editor.QueryInterface(Ci.nsIEditorStyleSheets);
--- a/editor/spellchecker/tests/test_bug1200533.html +++ b/editor/spellchecker/tests/test_bug1200533.html @@ -124,17 +124,16 @@ function continueTest(evt) { content.src = "http://mochi.test:8888/tests/editor/spellchecker/tests/bug1200533_subframe.html?firstload=false"; } else { // Remove the fake dictionaries again, since it's otherwise picked up by later tests. script.sendSyncMessage("destroy"); SimpleTest.finish(); } }); - } content.addEventListener("load", loadListener); content.src = "http://mochi.test:8888/tests/editor/spellchecker/tests/bug1200533_subframe.html?firstload=true"; </script> </pre>
--- a/editor/spellchecker/tests/test_bug717433.html +++ b/editor/spellchecker/tests/test_bug717433.html @@ -25,17 +25,16 @@ var content = document.getElementById("c // At second load, it will return the current dictionary. We can check that the // dictionary is correctly remembered between loads. var firstLoad = true; var expected = ""; var script; var loadListener = function(evt) { - if (firstLoad) { /* eslint-env mozilla/frame-script */ script = SpecialPowers.loadChromeScript(function() { // eslint-disable-next-line mozilla/use-services var dir = Cc["@mozilla.org/file/directory_service;1"] .getService(Ci.nsIProperties) .get("CurWorkD", Ci.nsIFile); dir.append("tests");
--- a/extensions/pref/autoconfig/src/prefcalls.js +++ b/extensions/pref/autoconfig/src/prefcalls.js @@ -15,24 +15,22 @@ const PrefServiceContractID = "@mozilla. // ChromeUtils isn't available here, so we can't use Services.* /* eslint-disable mozilla/use-services */ var gVersion; var gIsUTF8; function getPrefBranch() { - var prefService = Cc[PrefServiceContractID] .getService(nsIPrefService); return prefService.getBranch(null); } function pref(prefName, value) { - try { var prefBranch = getPrefBranch(); if (typeof value == "string") { if (gIsUTF8) { prefBranch.setStringPref(prefName, value); return; } @@ -43,17 +41,16 @@ function pref(prefName, value) { prefBranch.setBoolPref(prefName, value); } } catch (e) { displayError("pref", e); } } function defaultPref(prefName, value) { - try { var prefService = Cc[PrefServiceContractID] .getService(nsIPrefService); var prefBranch = prefService.getDefaultBranch(null); if (typeof value == "string") { if (gIsUTF8) { prefBranch.setStringPref(prefName, value); return; @@ -65,49 +62,44 @@ function defaultPref(prefName, value) { prefBranch.setBoolPref(prefName, value); } } catch (e) { displayError("defaultPref", e); } } function lockPref(prefName, value) { - try { var prefBranch = getPrefBranch(); if (prefBranch.prefIsLocked(prefName)) prefBranch.unlockPref(prefName); defaultPref(prefName, value); prefBranch.lockPref(prefName); } catch (e) { displayError("lockPref", e); } } function unlockPref(prefName) { - try { - var prefBranch = getPrefBranch(); prefBranch.unlockPref(prefName); } catch (e) { displayError("unlockPref", e); } } function getPref(prefName) { - try { var prefBranch = getPrefBranch(); switch (prefBranch.getPrefType(prefName)) { - case prefBranch.PREF_STRING: if (gIsUTF8) { return prefBranch.getStringPref(prefName); } return prefBranch.getCharPref(prefName); case prefBranch.PREF_INT: return prefBranch.getIntPref(prefName); @@ -119,32 +111,29 @@ function getPref(prefName) { } } catch (e) { displayError("getPref", e); } return undefined; } function clearPref(prefName) { - try { var prefBranch = getPrefBranch(); prefBranch.clearUserPref(prefName); } catch (e) { } - } function setLDAPVersion(version) { gVersion = version; } function getLDAPAttributes(host, base, filter, attribs, isSecure) { - try { var urlSpec = "ldap" + (isSecure ? "s" : "") + "://" + host + (isSecure ? ":636" : "") + "/" + base + "?" + attribs + "?sub?" + filter; var url = Cc["@mozilla.org/network/io-service;1"] .getService(Ci.nsIIOService) .newURI(urlSpec) .QueryInterface(Ci.nsILDAPURL); @@ -157,17 +146,16 @@ function getLDAPAttributes(host, base, f // user supplied method processLDAPValues(ldapquery.getQueryResults(url, gVersion)); } catch (e) { displayError("getLDAPAttibutes", e); } } function getLDAPValue(str, key) { - try { if (str == null || key == null) return null; var search_key = "\n" + key + "="; var start_pos = str.indexOf(search_key); if (start_pos == -1) @@ -182,17 +170,16 @@ function getLDAPValue(str, key) { return str.substring(start_pos, end_pos); } catch (e) { displayError("getLDAPValue", e); } return undefined; } function displayError(funcname, message) { - try { var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"] .getService(Ci.nsIPromptService); var bundle = Cc["@mozilla.org/intl/stringbundle;1"] .getService(Ci.nsIStringBundleService) .createBundle("chrome://autoconfig/locale/autoconfig.properties"); var title = bundle.GetStringFromName("autoConfigTitle");
--- a/extensions/pref/autoconfig/test/unit/test_autoconfig.js +++ b/extensions/pref/autoconfig/test/unit/test_autoconfig.js @@ -50,17 +50,16 @@ function run_test() { equal("getpref", prefs.getStringPref("_autoconfig_.test.getpref")); equal("getenv", prefs.getStringPref("_autoconfig_.test.getenv")); equal("function", prefs.getStringPref("_autoconfig_.test.displayerror")); Services.prefs.resetPrefs(); - } finally { try { let autoConfigJS = defaultPrefD.clone(); autoConfigJS.append("autoconfig.js"); autoConfigJS.remove(false); } catch (e) { if (e.result != Cr.NS_ERROR_FILE_NOT_FOUND) { throw e;
--- a/extensions/pref/autoconfig/test/unit/test_autoconfig_nonascii.js +++ b/extensions/pref/autoconfig/test/unit/test_autoconfig_nonascii.js @@ -64,17 +64,16 @@ function run_test() { Services.prefs.resetPrefs(); // Make sure pref values are reset. for (let prefName in test.prefs) { Assert.equal(Ci.nsIPrefBranch.PREF_INVALID, Services.prefs.getPrefType(prefName)); } } tests.forEach(testAutoConfig); - } finally { try { let autoConfigJS = defaultPrefD.clone(); autoConfigJS.append("autoconfig.js"); autoConfigJS.remove(false); } catch (e) { if (e.result != Cr.NS_ERROR_FILE_NOT_FOUND) { throw e;
--- a/gfx/layers/layerviewer/layerTreeView.js +++ b/gfx/layers/layerviewer/layerTreeView.js @@ -428,17 +428,16 @@ function parseLayers(layersDumpLines) { // dump("Fields: " + JSON.stringify(fields) + "\n"); } root.compositeTime = layersDumpLines.compositeTime; // dump("OBJECTS: " + JSON.stringify(root) + "\n"); return root; } function populateLayers(root, displayList, pane, previewParent, hasSeenRoot, contentScale, rootPreviewParent) { - contentScale = contentScale || 1; rootPreviewParent = rootPreviewParent || previewParent; function getDisplayItemForLayer(displayList) { var items = []; if (!displayList) { return items; }
--- a/gfx/tests/mochitest/test_acceleration.html +++ b/gfx/tests/mochitest/test_acceleration.html @@ -85,17 +85,16 @@ function runTest() { is(acceleratedWindows, 0, "Acceleration not supported on Windows 2000"); } else { // Workaround for SeaMonkey tinderboxes which don't support acceleration. if (navigator.userAgent.match(/ SeaMonkey\//)) { if (acceleratedWindows == 0) { todo(false, "Acceleration not supported on Windows XP or newer" + " (This is expected on SeaMonkey (tinderboxes).)"); break; - } } isnot(acceleratedWindows, 0, "Acceleration enabled on Windows XP or newer"); } var gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo); if (version < 6.2) {
--- a/intl/l10n/Fluent.jsm +++ b/intl/l10n/Fluent.jsm @@ -23,17 +23,16 @@ /** * The `FluentType` class is the base of Fluent's type system. * * Fluent types wrap JavaScript values and store additional configuration for * them, which can then be used in the `toString` method together with a proper * `Intl` formatter. */ class FluentType { - /** * Create an `FluentType` instance. * * @param {Any} value - JavaScript value to wrap. * @param {Object} opts - Configuration. * @returns {FluentType} */ constructor(value, opts) { @@ -1022,17 +1021,16 @@ class FluentResource extends Map { * bundle. Translations can contain references to other entities or variables, * conditional logic in form of select expressions, traits which describe their * grammatical features, and can use Fluent builtins which make use of the * `Intl` formatters to format numbers, dates, lists and more into the * bundle's language. See the documentation of the Fluent syntax for more * information. */ class FluentBundle { - /** * Create an instance of `FluentBundle`. * * The `locales` argument is used to instantiate `Intl` formatters used by * translations. The `options` object can be used to configure the bundle. * * Examples: *
--- a/intl/l10n/test/dom/test_domloc_overlay_missing_all.html +++ b/intl/l10n/test/dom/test_domloc_overlay_missing_all.html @@ -15,17 +15,16 @@ async function* mockGenerateMessages(locales, resourceIds) { const bundle = new FluentBundle(locales); // No translations! yield bundle; } SimpleTest.waitForExplicitFinish(); addLoadEvent(async () => { - const domLoc = new DOMLocalization( [], mockGenerateMessages ); await domLoc.translateFragment(document.body).then(() => { ok(false, "Expected translateFragment to throw on missing l10n-id"); }, () => {
--- a/intl/l10n/test/test_pseudo.js +++ b/intl/l10n/test/test_pseudo.js @@ -4,17 +4,16 @@ const { Localization } = ChromeUtils.import("resource://gre/modules/Localization.jsm"); const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); const { L10nRegistry, FileSource } = ChromeUtils.import("resource://gre/modules/L10nRegistry.jsm"); const originalValues = {}; function addMockFileSource() { - const fs = { "/localization/de/browser/menu.ftl": ` key = This is a single message .tooltip = This is a tooltip .accesskey = f`, }; originalValues.load = L10nRegistry.load; originalValues.requested = Services.locale.requestedLocales;
--- a/js/src/builtin/Sorting.js +++ b/js/src/builtin/Sorting.js @@ -393,13 +393,12 @@ function QuickSort(array, len, comparefn stack[top++] = start; stack[top++] = pivotIndex - 1; start = pivotIndex + 1; } else { stack[top++] = pivotIndex + 1; stack[top++] = end; end = pivotIndex - 1; } - } } return array; }
--- a/js/src/builtin/TypedObject.js +++ b/js/src/builtin/TypedObject.js @@ -857,17 +857,16 @@ function ReduceTypedSeqImpl(array, outpu value = array[0]; } else { start = 0; value = outputType(initial); } for (var i = start; i < array.length; i++) value = outputType(func(value, array[i])); - } else { if (initial === undefined) { start = 1; value = new outputType(array[0]); } else { start = 0; value = initial; }
--- a/js/src/shell/ModuleLoader.js +++ b/js/src/shell/ModuleLoader.js @@ -238,10 +238,9 @@ setModuleResolveHook((referencingInfo, r setModuleMetadataHook((module, metaObject) => { ReflectLoader.populateImportMeta(module, metaObject); }); setModuleDynamicImportHook((referencingInfo, specifier, promise) => { ReflectLoader.dynamicImport(referencingInfo, specifier, promise); }); - }
--- a/memory/replace/dmd/test/test_dmd.js +++ b/memory/replace/dmd/test/test_dmd.js @@ -86,17 +86,16 @@ function test(aPrefix, aArgs) { // we do a string compare of the file contents and then print them both if // they don't match. let success; try { let rv = runProcess(new FileUtils.File("/usr/bin/diff"), ["-u", expectedFile.path, actualFile.path]); success = rv == 0; - } catch (e) { let expectedData = readFile(expectedFile); let actualData = readFile(actualFile); success = expectedData === actualData; if (!success) { expectedData = expectedData.split("\n"); actualData = actualData.split("\n"); for (let i = 0; i < expectedData.length; i++) {
--- a/mobile/android/chrome/geckoview/GeckoViewMediaChild.js +++ b/mobile/android/chrome/geckoview/GeckoViewMediaChild.js @@ -421,13 +421,12 @@ class GeckoViewMediaChild extends GeckoV }); } notifyMediaRemoveAll() { this.eventDispatcher.sendRequest({ type: "GeckoView:MediaRemoveAll", }); } - } const {debug, warn} = GeckoViewMediaChild.initLogging("GeckoViewMedia"); const module = GeckoViewMediaChild.create(this);
--- a/mobile/android/chrome/geckoview/GeckoViewSelectionActionChild.js +++ b/mobile/android/chrome/geckoview/GeckoViewSelectionActionChild.js @@ -146,17 +146,16 @@ class GeckoViewSelectionActionChild exte } debug `handleEvent: ${reason}`; if (["longpressonemptycontent", "releasecaret", "taponcaret", "updateposition"].includes(reason)) { - const actions = this._actions.filter( action => action.predicate.call(this, aEvent)); const offset = this._getFrameOffset(aEvent); const password = this._isPasswordField(aEvent); const msg = { type: "GeckoView:ShowSelectionAction", @@ -207,22 +206,20 @@ class GeckoViewSelectionActionChild exte } else { warn `Invalid action ${response.id}`; } }, onError: _ => { // Do nothing; we can get here if the delegate was just unregistered. }, }); - } else if (["invisibleselection", "presscaret", "scroll", "visibilitychange"].includes(reason)) { - if (!this._isActive) { return; } this._isActive = false; // Mark previous actions as stale. Don't do this for "invisibleselection" // or "scroll" because previous actions should still be valid even after @@ -230,17 +227,16 @@ class GeckoViewSelectionActionChild exte if (reason !== "invisibleselection" && reason !== "scroll") { this._seqNo++; } this.eventDispatcher.sendRequest({ type: "GeckoView:HideSelectionAction", reason: reason, }); - } else { warn `Unknown reason: ${reason}`; } } } let {debug, warn} = GeckoViewSelectionActionChild.initLogging("GeckoViewSelectionAction");
--- a/mobile/android/chrome/geckoview/config.js +++ b/mobile/android/chrome/geckoview/config.js @@ -532,17 +532,16 @@ Pref.prototype = { case Services.prefs.PREF_BOOL: return Services.prefs.getBoolPref(this.name); case Services.prefs.PREF_INT: return Services.prefs.getIntPref(this.name); case Services.prefs.PREF_STRING: default: return Services.prefs.getCharPref(this.name); } - }, set value(aPrefValue) { switch (this.type) { case Services.prefs.PREF_BOOL: Services.prefs.setBoolPref(this.name, aPrefValue); break; case Services.prefs.PREF_INT: Services.prefs.setIntPref(this.name, aPrefValue); @@ -655,17 +654,16 @@ Pref.prototype = { setTimeout(this._valueSetup.bind(this), INNERHTML_VALUE_DELAY); } return this.li; }, // Initialize list item object values _valueSetup: function AC_valueSetup() { - this.li.setAttribute("type", this.type); this.li.setAttribute("value", this.value); let valDiv = this.li.querySelector(".pref-value"); valDiv.value = this.value; switch (this.type) { case Services.prefs.PREF_BOOL:
--- a/mobile/android/components/ContentDispatchChooser.js +++ b/mobile/android/components/ContentDispatchChooser.js @@ -41,23 +41,21 @@ ContentDispatchChooser.prototype = ask: function ask(aHandler, aWindowContext, aURI, aReason) { let window = null; try { if (aWindowContext) window = aWindowContext.getInterface(Ci.nsIDOMWindow); } catch (e) { /* it's OK to not have a window */ } if (!aURI.schemeIs("content")) { - // The current list is based purely on the scheme. Redo the query using the url to get more // specific results. aHandler = this.protoSvc.getProtocolHandlerInfoFromOS(aURI.spec, {}); if (aHandler.possibleApplicationHandlers.length > 1) { - // The first handler in the set is the Android Application Chooser (which will fall back to a default if one is set) // If we have more than one option, let the OS handle showing a list (if needed). aHandler.launchWithURI(aURI, aWindowContext); this._closeBlankWindow(window); return; } } // xpcshell tests do not have an Android Bridge but we require Android @@ -71,17 +69,16 @@ ContentDispatchChooser.prototype = let msg = { type: "Intent:OpenNoHandler", uri: aURI.spec, }; EventDispatcher.instance.sendRequestForResult(msg).then(() => { // Java opens an app on success: take no action. this._closeBlankWindow(window); - }, (data) => { if (data.isFallback) { // We always want to open a fallback url window.location.href = data.uri; return; } // We couldn't open this. If this was from a click, it's likely that we just
--- a/mobile/android/components/PresentationRequestUIGlue.js +++ b/mobile/android/components/PresentationRequestUIGlue.js @@ -32,17 +32,16 @@ PresentationRequestUIGlue.prototype = { /* XXX: Currently, Fennec only support 1-UA devices. Remove this * Promise.reject() when it starts to support 2-UA devices. */ log("Not an 1-UA device."); return new Promise.reject(); } return new Promise((aResolve, aReject) => { - let uuidGenerator = Cc["@mozilla.org/uuid-generator;1"] .getService(Ci.nsIUUIDGenerator); let requestId = uuidGenerator.generateUUID().toString(); let handleObserve = (aSubject, aTopic, aData) => { log("Got observe: aTopic=" + aTopic); let data = JSON.parse(aData);
--- a/mobile/android/components/SessionStore.js +++ b/mobile/android/components/SessionStore.js @@ -1568,17 +1568,16 @@ SessionStore.prototype = { } }, get canUndoLastCloseTab() { return this._lastClosedTabIndex > INVALID_TAB_INDEX; }, _sendClosedTabsToJava(aWindow) { - // If the app is shutting down, we don't need to do anything. if (this._loadState <= STATE_QUITTING) { return; } if (!aWindow.__SSID) { throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG); }
--- a/mobile/android/components/geckoview/GeckoViewPrompt.js +++ b/mobile/android/components/geckoview/GeckoViewPrompt.js @@ -393,17 +393,16 @@ PromptDelegate.prototype = { event.initEvent(aEntering ? "DOMWillOpenModalDialog" : "DOMModalDialogClosed", true, true); winUtils.dispatchEventToChromeOnly(this._domWin, event); if (aEntering) { winUtils.enterModalState(); } return true; - } catch (ex) { Cu.reportError("Failed to change modal state: " + ex); } return false; }, /** * Shows a native prompt, and then spins the event loop for this thread while we wait
--- a/mobile/android/extensions/report-site-issue/.eslintrc.js +++ b/mobile/android/extensions/report-site-issue/.eslintrc.js @@ -82,19 +82,16 @@ module.exports = { // Disallow use of assignment in return statement. It is preferable for a // single line of code to have only one easily predictable effect. "no-return-assign": "error", // Disallow throwing literals (eg. throw "error" instead of // throw new Error("error")). "no-throw-literal": "error", - // Disallow padding within blocks. - "padded-blocks": ["error", "never"], - // Require use of the second argument for parseInt(). "radix": "error", // Enforce spacing after semicolons. "semi-spacing": ["error", {"before": false, "after": true}], // Require "use strict" to be defined globally in the script. "strict": ["error", "global"],
--- a/mobile/android/modules/FxAccountsWebChannel.jsm +++ b/mobile/android/modules/FxAccountsWebChannel.jsm @@ -274,17 +274,16 @@ this.FxAccountsWebChannel.prototype = { } return Accounts.updateFirefoxAccountFromJSON(data).then(success => { if (!success) { throw new Error("Could not update Firefox Account!"); } UITelemetry.addEvent("action.1", "content", null, "fxaccount-login"); return success; }); - }) .then(success => { if (!success) { throw new Error("Could not create or update Firefox Account!"); } // Remember who it is so we can show a relink warning when appropriate. this._helpers.setPreviousAccountNameHashPref(data.email);
--- a/mobile/android/modules/HelperApps.jsm +++ b/mobile/android/modules/HelperApps.jsm @@ -155,17 +155,16 @@ var HelperApps = { if (data === null) { throw new Error("Intent:GetHandler did not return data"); } return parseData(data); } EventDispatcher.instance.sendRequestForResult(msg).then(function(data) { callback(parseData(data)); }); - }, launchUri: function launchUri(uri) { let msg = this._getMessage("Intent:Open", uri); EventDispatcher.instance.sendRequest(msg); }, _parseApps: function _parseApps(appInfo) {
--- a/mobile/android/modules/Prompt.jsm +++ b/mobile/android/modules/Prompt.jsm @@ -227,17 +227,16 @@ Prompt.prototype = { if (item.showAsActions) obj.showAsActions = item.showAsActions; if (item.icon) obj.icon = item.icon; this.msg.listitems.push(obj); - }, this); return this; }, setSingleChoiceItems: function(aItems) { return this._setListItems(aItems); },
--- a/mobile/android/modules/Snackbars.jsm +++ b/mobile/android/modules/Snackbars.jsm @@ -13,17 +13,16 @@ const LENGTH_LONG = 0; const LENGTH_SHORT = -1; var Snackbars = { LENGTH_INDEFINITE: LENGTH_INDEFINITE, LENGTH_LONG: LENGTH_LONG, LENGTH_SHORT: LENGTH_SHORT, show: function(aMessage, aDuration, aOptions) { - // Takes care of the deprecated toast calls if (typeof aDuration === "string") { [aDuration, aOptions] = migrateToastIfNeeded(aDuration, aOptions); } let msg = { type: "Snackbar:Show", message: aMessage,
--- a/mobile/android/modules/WebrtcUI.jsm +++ b/mobile/android/modules/WebrtcUI.jsm @@ -236,28 +236,26 @@ var WebrtcUI = { return Strings.browser.formatStringFromName("getUserMedia." + aType + ".default", [defaultCount], 1); } return device.name; }, this); }, _addDevicesToOptions: function(aDevices, aType, aOptions) { if (aDevices.length) { - // Filter out empty items from the list let list = this._getList(aDevices, aType); if (list.length > 0) { aOptions.inputs.push({ id: aType, type: "menulist", label: Strings.browser.GetStringFromName("getUserMedia." + aType + ".prompt"), values: list, }); - } } }, showBlockMessage: function(aWindow, aDevices) { let microphone = false; let camera = false;
--- a/mobile/android/modules/geckoview/GeckoViewAutoFill.jsm +++ b/mobile/android/modules/geckoview/GeckoViewAutoFill.jsm @@ -144,17 +144,16 @@ class GeckoViewAutoFill { // Add highlighting for autofilled fields. winUtils.addManuallyManagedState(element, AUTOFILL_STATE); // Remove highlighting when the field is changed. element.addEventListener("input", _ => winUtils.removeManuallyManagedState(element, AUTOFILL_STATE), { mozSystemGroup: true, once: true }); } - } else if (element) { warn `Don't know how to auto-fill ${element.tagName}`; } } }, onError: error => { warn `Cannot perform autofill ${error}`; },
--- a/mobile/android/tests/browser/robocop/robocop_head.js +++ b/mobile/android/tests/browser/robocop/robocop_head.js @@ -537,17 +537,16 @@ function pattern_matcher(pattern) { return function(value) { return true; }; } return function(value, diagnosis) { if (value !== pattern) { return explain(diagnosis, "pattern " + uneval(pattern) + " not === to value " + uneval(value)); } return true; }; - } // Format an explanation for a pattern match failure, as stored in the // second argument to a matching function. function format_pattern_match_failure(diagnosis, indent = "") { var a; if (!diagnosis) { a = "Matcher did not explain reason for mismatch."; @@ -756,17 +755,16 @@ function run_next_test() { /** * JavaBridge facilitates communication between Java and JS. See * JavascriptBridge.java for the corresponding JavascriptBridge and docs. */ function JavaBridge(obj) { - this._EVENT_TYPE = "Robocop:JS"; this._JAVA_EVENT_TYPE = "Robocop:Java"; this._target = obj; // The number of replies needed to answer all outstanding sync calls. this._repliesNeeded = 0; this._EventDispatcher.registerListener(this, this._EVENT_TYPE); this._sendMessage("notify-loaded", []);
--- a/mobile/android/tests/browser/robocop/testUITelemetry.js +++ b/mobile/android/tests/browser/robocop/testUITelemetry.js @@ -112,17 +112,16 @@ function expectedArraysToObjs(expectedAr if (type === "event") { return { type: type, action: arr[1], method: arr[2], sessions: arr[3].sort(), // Sort, just in case it's not sorted by hand! extras: arr[4], }; - } else if (type === "session") { return { type: type, name: arr[1], reason: arr[2], }; } });
--- a/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm +++ b/netwerk/dns/mdns/libmdns/fallback/MulticastDNS.jsm @@ -425,17 +425,16 @@ class MulticastDNS { }); }); } _clearExpiredDiscoveries() { this._discovered.forEach((discovery, key) => { if (discovery.expireTime < Date.now()) { this._discovered.delete(key); - } }); } _handleQueryPacket(packet, message) { packet.getRecords(["QD"]).forEach((record) => { // Don't respond if the query's class code is not IN or ANY. if (record.classCode !== DNS_CLASS_CODES.IN &&
--- a/parser/htmlparser/tests/mochitest/test_bug715739.html +++ b/parser/htmlparser/tests/mochitest/test_bug715739.html @@ -55,17 +55,16 @@ function tick() { f.contentWindow.location.reload(); return; } if (runNumber == 3) { text = textChildren(d.body); is(text, "XYZ", "Wrong text after reload."); SimpleTest.finish(); - } } </script> </pre> <div id="content" style="display: none"> <iframe></iframe> </div>
--- a/security/.eslintrc.js +++ b/security/.eslintrc.js @@ -60,19 +60,16 @@ module.exports = { "no-unmodified-loop-condition": "error", // No expressions where a statement is expected "no-unused-expressions": "error", // Disallow unnecessary escape usage in strings and regular expressions. "no-useless-escape": "error", - // Disallow blank line padding within blocks. - "padded-blocks": ["error", "never"], - // Enforce spacing after semicolons. "semi-spacing": ["error", { "before": false, "after": true }], // Never use spaces before named function parentheses, but always for async // arrow functions. "space-before-function-paren": ["error", { "anonymous": "ignore", "asyncArrow": "always",
--- a/services/common/kinto-storage-adapter.js +++ b/services/common/kinto-storage-adapter.js @@ -208,17 +208,16 @@ class FirefoxAdapter extends Kinto.adapt * * This will be called automatically by open(). */ static async _init(connection) { await connection.executeTransaction(async function doSetup() { const schema = await connection.getSchemaVersion(); if (schema == 0) { - for (let statementName of createStatements) { await connection.execute(statements[statementName]); } await connection.setSchemaVersion(currentSchemaVersion); } else if (schema != 1) { throw new Error("Unknown database schema: " + schema); }
--- a/services/common/rest.js +++ b/services/common/rest.js @@ -503,17 +503,16 @@ RESTRequest.prototype = { let isSameURI = newChannel.URI.equals(oldChannel.URI); this._log.debug("Channel redirect: " + oldChannel.URI.spec + ", " + newChannel.URI.spec + ", internal = " + isInternal); return isInternal && isSameURI; }, /** nsIChannelEventSink **/ asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) { - let oldSpec = (oldChannel && oldChannel.URI) ? oldChannel.URI.spec : "<undefined>"; let newSpec = (newChannel && newChannel.URI) ? newChannel.URI.spec : "<undefined>"; this._log.debug("Channel redirect: " + oldSpec + ", " + newSpec + ", " + flags); try { newChannel.QueryInterface(Ci.nsIHttpChannel); } catch (ex) { this._log.error("Unexpected error: channel not nsIHttpChannel!");
--- a/services/common/tests/unit/test_blocklist_certificates.js +++ b/services/common/tests/unit/test_blocklist_certificates.js @@ -226,10 +226,9 @@ function getSampleResponse(req, port) { "pubKeyHash": "VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=", "id": "dabafde9-df4a-ddba-2548-748da04cc02g", "last_modified": 5000, }]}), }, }; return responses[`${req.method}:${req.path}?${req.queryString}`] || responses[req.method]; - }
--- a/services/common/tests/unit/test_blocklist_clients.js +++ b/services/common/tests/unit/test_blocklist_clients.js @@ -661,10 +661,9 @@ function getSampleResponse(req, port) { }], "id": "75a06bd3-f906-427d-a448-02092ee589fc", }]}), }, }; return responses[`${req.method}:${req.path}?${req.queryString}`] || responses[`${req.method}:${req.path}`] || responses[req.method]; - }
--- a/services/common/tests/unit/test_blocklist_pinning.js +++ b/services/common/tests/unit/test_blocklist_pinning.js @@ -298,10 +298,9 @@ function getSampleResponse(req, port) { "versions": [Services.appinfo.version, "some version that won't match"], "id": "dabafde9-df4a-ddba-2548-748da04cc032", "last_modified": 5000, }]}), }, }; return responses[`${req.method}:${req.path}?${req.queryString}`] || responses[req.method]; - }
--- a/services/common/tests/unit/test_kinto.js +++ b/services/common/tests/unit/test_kinto.js @@ -449,10 +449,9 @@ function getSampleResponse(req, port) { "id": "some-manually-chosen-id", "title": "New record with custom ID", }], }), }, }; return responses[`${req.method}:${req.path}?${req.queryString}`] || responses[req.method]; - }
--- a/services/common/uptake-telemetry.js +++ b/services/common/uptake-telemetry.js @@ -12,17 +12,16 @@ const { Services } = ChromeUtils.import( // Telemetry report results. const TELEMETRY_HISTOGRAM_ID = "UPTAKE_REMOTE_CONTENT_RESULT_1"; /** * A Telemetry helper to report uptake of remote content. */ class UptakeTelemetry { - /** * Supported uptake statuses: * * - `UP_TO_DATE`: Local content was already up-to-date with remote content. * - `SUCCESS`: Local content was updated successfully. * - `BACKOFF`: Remote server asked clients to backoff. * - `PARSE_ERROR`: Parsing server response has failed. * - `CONTENT_ERROR`: Server response has unexpected content.
--- a/services/common/utils.js +++ b/services/common/utils.js @@ -556,17 +556,16 @@ var CommonUtils = { * not defined or invalid. * @param log * (Log.Logger) Logger to write warnings to. * @param oldestYear * (Number) Oldest year to accept in read values. */ getDatePref: function getDatePref(branch, pref, def = 0, log = null, oldestYear = 2010) { - let valueInt = this.getEpochPref(branch, pref, def, log); let date = new Date(valueInt); if (valueInt == def || date.getFullYear() >= oldestYear) { return date; } if (log) {
--- a/services/crypto/tests/unit/head_helpers.js +++ b/services/crypto/tests/unit/head_helpers.js @@ -2,17 +2,16 @@ var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); try { // In the context of xpcshell tests, there won't be a default AppInfo // eslint-disable-next-line mozilla/use-services Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo); } catch (ex) { - // Make sure to provide the right OS so crypto loads the right binaries var OS = "XPCShell"; if (mozinfo.os == "win") OS = "WINNT"; else if (mozinfo.os == "mac") OS = "Darwin"; else OS = "Linux";
--- a/services/fxaccounts/FxAccountsOAuthGrantClient.jsm +++ b/services/fxaccounts/FxAccountsOAuthGrantClient.jsm @@ -31,17 +31,16 @@ const ALLOW_HTTP_PREF = "identity.fxacco * OAuth id returned from client registration * @param {String} options.parameters.serverURL * The FxA OAuth server URL * @param [authorizationEndpoint] {String} * Optional authorization endpoint for the OAuth server * @constructor */ var FxAccountsOAuthGrantClient = function(options) { - this._validateOptions(options); this.parameters = options; try { this.serverURL = new URL(this.parameters.serverURL); } catch (e) { throw new Error("Invalid 'serverURL'"); }
--- a/services/fxaccounts/FxAccountsWebChannel.jsm +++ b/services/fxaccounts/FxAccountsWebChannel.jsm @@ -277,17 +277,16 @@ this.FxAccountsWebChannelHelpers.prototy }, /** * stores sync login info it in the fxaccounts service * * @param accountData the user's account data and credentials */ login(accountData) { - // We don't act on customizeSync anymore, it used to open a dialog inside // the browser to selecte the engines to sync but we do it on the web now. delete accountData.customizeSync; if (accountData.offeredSyncEngines) { EXTRA_ENGINES.forEach(engine => { if (accountData.offeredSyncEngines.includes(engine) && !accountData.declinedSyncEngines.includes(engine)) {
--- a/services/fxaccounts/tests/mochitest/test_invalidEmailCase.html +++ b/services/fxaccounts/tests/mochitest/test_invalidEmailCase.html @@ -81,22 +81,20 @@ function runTest() { is(true, !!client, "Couldn't mock fxa client"); is(client.host, TEST_SERVER, "Should be using the test auth server uri"); // First try to sign in using the email with the wrong capitalization. The // FxAccountsClient will receive a 400 from the server with the corrected email. // It will automatically try to sign in again. We expect this to succeed. client.signIn(wrongEmail, password).then( user => { - // Now store the signed-in user state. This will include the correct // email capitalization. fxa.setSignedInUser(user).then( () => { - // Confirm that the correct email got stored. fxa.getSignedInUser().then( data => { is(data.email, rightEmail); SimpleTest.finish(); }, getUserError => { ok(false, JSON.stringify(getUserError));
--- a/services/fxaccounts/tests/xpcshell/test_accounts.js +++ b/services/fxaccounts/tests/xpcshell/test_accounts.js @@ -1104,17 +1104,16 @@ add_test(function test_getOAuthToken() { (result) => { Assert.ok(getTokenFromAssertionCalled); Assert.equal(result, "token"); run_next_test(); } ); } ); - }); add_test(function test_getOAuthTokenScoped() { let fxa = new MockFxAccounts(); let alice = getTestUser("alice"); alice.verified = true; let getTokenFromAssertionCalled = false; @@ -1137,17 +1136,16 @@ add_test(function test_getOAuthTokenScop (result) => { Assert.ok(getTokenFromAssertionCalled); Assert.equal(result, "token"); run_next_test(); } ); } ); - }); add_task(async function test_getOAuthTokenCached() { let fxa = new MockFxAccounts(); let alice = getTestUser("alice"); alice.verified = true; let numTokenFromAssertionCalls = 0;
--- a/services/settings/RemoteSettingsClient.jsm +++ b/services/settings/RemoteSettingsClient.jsm @@ -108,17 +108,16 @@ async function fetchRemoteRecords(bucket /** * Minimalist event emitter. * * Note: we don't use `toolkit/modules/EventEmitter` because **we want** to throw * an error when a listener fails to execute. */ class EventEmitter { - constructor(events) { this._listeners = new Map(); for (const event of events) { this._listeners.set(event, []); } } /** @@ -161,17 +160,16 @@ class EventEmitter { } else { callbacks.splice(i, 1); } } } class RemoteSettingsClient extends EventEmitter { - constructor(collectionName, { bucketNamePref, signerName, filterFunc, localFields = [], lastCheckTimePref }) { super(["sync"]); // emitted events this.collectionName = collectionName; this.signerName = signerName; this.filterFunc = filterFunc; this.localFields = localFields; this._lastCheckTimePref = lastCheckTimePref; @@ -368,17 +366,16 @@ class RemoteSettingsClient extends Event if (filteredSyncResult) { try { await this.emit("sync", { data: filteredSyncResult }); } catch (e) { reportStatus = UptakeTelemetry.STATUS.APPLY_ERROR; throw e; } } - } catch (e) { // No specific error was tracked, mark it as unknown. if (reportStatus === null) { reportStatus = UptakeTelemetry.STATUS.UNKNOWN_ERROR; } throw e; } finally { // No error was reported, this is a success!
--- a/services/settings/RemoteSettingsWorker.jsm +++ b/services/settings/RemoteSettingsWorker.jsm @@ -8,17 +8,16 @@ * Interface to a dedicated thread handling for Remote Settings heavy operations. */ // ChromeUtils.import("resource://gre/modules/PromiseWorker.jsm", this); var EXPORTED_SYMBOLS = ["RemoteSettingsWorker"]; class Worker { - constructor(source) { this.worker = new ChromeWorker(source); this.worker.onmessage = this._onWorkerMessage.bind(this); this.callbacks = new Map(); this.lastCallbackId = 0; }
--- a/services/settings/test/unit/test_remote_settings.js +++ b/services/settings/test/unit/test_remote_settings.js @@ -558,10 +558,9 @@ function getSampleResponse(req, port) { "last_modified": 713705, }], }, }, }; return responses[`${req.method}:${req.path}?${req.queryString}`] || responses[`${req.method}:${req.path}`] || responses[req.method]; - }
--- a/services/sync/modules/SyncDisconnect.jsm +++ b/services/sync/modules/SyncDisconnect.jsm @@ -169,17 +169,16 @@ this.SyncDisconnectInternal = { // blocker doesn't allow it to finish, we should still at least be in // a disconnected state on the next startup. log.info("disconnecting account"); await this.doSyncAndAccountDisconnect(locked); if (sanitizeBrowserData) { await this.doSanitizeBrowserData(); } - }, async disconnect(options) { if (this.promiseDisconnectFinished) { throw new Error("A disconnect is already in progress"); } let abortController = new AbortController(); let promiseDisconnectFinished = this._startDisconnect(abortController, options);
--- a/services/sync/modules/addonsreconciler.js +++ b/services/sync/modules/addonsreconciler.js @@ -320,17 +320,16 @@ AddonsReconciler.prototype = { if (!installs) { installs = await AddonManager.getAllInstalls(); } let installFound = false; for (let install of installs) { if (install.addon && install.addon.id == id && install.state == AddonManager.STATE_INSTALLED) { - installFound = true; break; } } if (installFound) { continue; }
--- a/services/sync/modules/addonutils.js +++ b/services/sync/modules/addonutils.js @@ -241,17 +241,16 @@ AddonUtilsInternal.prototype = { } catch (ex) { this._log.warn("Unable to QI sourceURI to nsIURL: " + addon.sourceURI.spec); continue; } let params = addon.sourceURI.query.split("&").map( function rewrite(param) { - if (param.indexOf("src=") == 0) { return "src=sync"; } return param; }); addon.sourceURI = addon.sourceURI.mutate() .setQuery(params.join("&"))
--- a/services/sync/modules/bookmark_repair.js +++ b/services/sync/modules/bookmark_repair.js @@ -392,17 +392,16 @@ class BookmarkRepairRequestor extends Co // No repair is in progress. This is a common case, so only log trace. log.trace("continue repairs called but no repair in progress."); break; default: log.error(`continue repairs finds itself in an unknown state ${state}`); state = STATE.ABORTED; break; - } return state; } /* Handle being in the SENT_REQUEST or SENT_SECOND_REQUEST state with an explicit response. */ _handleResponse(state, response) {
--- a/services/sync/modules/bookmark_validator.js +++ b/services/sync/modules/bookmark_validator.js @@ -961,12 +961,11 @@ class BookmarkValidator { return { duration, version: this.version, problems: result.problemData, recordCount: serverRecordCount, }; } - } BookmarkValidator.prototype.version = BOOKMARK_VALIDATOR_VERSION;
--- a/services/sync/modules/engines/history.js +++ b/services/sync/modules/engines/history.js @@ -111,32 +111,30 @@ function HistoryStore(name, engine) { HistoryStore.prototype = { __proto__: Store.prototype, // We try and only update this many visits at one time. MAX_VISITS_PER_INSERT: 500, // Some helper functions to handle GUIDs async setGUID(uri, guid) { - if (!guid) { guid = Utils.makeGUID(); } try { await PlacesSyncUtils.history.changeGuid(uri, guid); } catch (e) { this._log.error("Error setting GUID ${guid} for URI ${uri}", guid, uri); } return guid; }, async GUIDForUri(uri, create) { - // Use the existing GUID if it exists let guid; try { guid = await PlacesSyncUtils.history.fetchGuidForURL(uri); } catch (e) { this._log.error("Error fetching GUID for URL ${uri}", uri); }
--- a/services/sync/modules/policies.js +++ b/services/sync/modules/policies.js @@ -147,17 +147,16 @@ SyncScheduler.prototype = { } } catch (ex) { this._log.warn("Could not determine network status.", ex); } return false; }, _initPrefGetters() { - XPCOMUtils.defineLazyPreferenceGetter(this, "idleTime", "services.sync.scheduler.idleTime"); XPCOMUtils.defineLazyPreferenceGetter(this, "maxResyncs", "services.sync.maxResyncs", 0); // The number of clients we have is maintained in preferences via the // clients engine, and only updated after a successsful sync. XPCOMUtils.defineLazyPreferenceGetter(this,
--- a/services/sync/modules/record.js +++ b/services/sync/modules/record.js @@ -469,17 +469,16 @@ CollectionKeyManager.prototype = { newKeys[c] = b; } return new CollectionKeyManager(this.lastModified, this._default, newKeys); }, // Take the fetched info/collections WBO, checking the change // time of the crypto collection. updateNeeded(info_collections) { - this._log.info("Testing for updateNeeded. Last modified: " + this.lastModified); // No local record of modification time? Need an update. if (!this.lastModified) { return true; } // No keys on the server? We need an update, though our @@ -497,17 +496,16 @@ CollectionKeyManager.prototype = { // Returns one of three values: // // * If the default key was modified, return true. // * If the default key was not modified, but per-collection keys were, // return an array of such. // * Otherwise, return false -- we were up-to-date. // setContents: function setContents(payload, modified) { - let self = this; this._log.info("Setting collection keys contents. Our last modified: " + this.lastModified + ", input modified: " + modified + "."); if (!payload) { throw new Error("No payload in CollectionKeyManager.setContents()."); }
--- a/services/sync/modules/service.js +++ b/services/sync/modules/service.js @@ -154,17 +154,16 @@ Sync11Service.prototype = { _checkCrypto: function _checkCrypto() { let ok = false; try { let iv = Weave.Crypto.generateRandomIV(); if (iv.length == 24) { ok = true; } - } catch (e) { this._log.debug("Crypto check failed: " + e); } return ok; }, /** @@ -238,17 +237,16 @@ Sync11Service.prototype = { if (uploadResp.success) { this._log.info("Successfully re-uploaded keys. Continuing sync."); } else { this._log.warn("Got error response re-uploading keys. " + "Continuing sync; let's try again later."); } return false; // Don't try again: same keys. - } catch (ex) { this._log.warn("Got exception fetching and handling crypto keys. " + "Will try again later.", ex); return false; } }, async handleFetchedKeys(syncKey, cryptoKeys, skipReset) { @@ -536,17 +534,16 @@ Sync11Service.prototype = { if (!info.success) { this._log.error("Aborting sync: failed to get collections."); throw info; } return info; }, async verifyAndFetchSymmetricKeys(infoResponse) { - this._log.debug("Fetching and verifying -- or generating -- symmetric keys."); let syncKeyBundle = this.identity.syncKeyBundle; if (!syncKeyBundle) { this.status.login = LOGIN_FAILED_NO_PASSPHRASE; this.status.sync = CREDENTIALS_CHANGED; return false; } @@ -934,17 +931,16 @@ Sync11Service.prototype = { this._log.debug("Fetching global metadata record"); let meta = await this.recordManager.get(this.metaURL); // Checking modified time of the meta record. if (infoResponse && (infoResponse.obj.meta != this.metaModified) && (!meta || !meta.isNew)) { - // Delete the cached meta record... this._log.debug("Clearing cached meta record. metaModified is " + JSON.stringify(this.metaModified) + ", setting to " + JSON.stringify(infoResponse.obj.meta)); this.recordManager.del(this.metaURL); // ... fetch the current record from the server, and COPY THE FLAGS. @@ -987,17 +983,16 @@ Sync11Service.prototype = { this._log.debug(["Weave Version:", WEAVE_VERSION, "Local Storage:", STORAGE_VERSION, "Remote Storage:", remoteVersion].join(" ")); // Check for cases that require a fresh start. When comparing remoteVersion, // we need to convert it to a number as older clients used it as a string. if (!meta || !meta.payload.storageVersion || !meta.payload.syncID || STORAGE_VERSION > parseFloat(remoteVersion)) { - this._log.info("One of: no meta, no meta storageVersion, or no meta syncID. Fresh start needed."); // abort the server wipe if the GET status was anything other than 404 or 200 let status = this.recordManager.response.status; if (status != 200 && status != 404) { this.status.sync = METARECORD_DOWNLOAD_FAIL; this.errorHandler.checkServerError(this.recordManager.response); this._log.warn("Unknown error while downloading metadata record. " + @@ -1022,17 +1017,16 @@ Sync11Service.prototype = { this._log.info("Wiped server; incompatible metadata: " + remoteVersion); } return true; } else if (remoteVersion > STORAGE_VERSION) { this.status.sync = VERSION_OUT_OF_DATE; this._log.warn("Upgrade required to access newer storage version."); return false; } else if (meta.payload.syncID != this.syncID) { - this._log.info("Sync IDs differ. Local is " + this.syncID + ", remote is " + meta.payload.syncID); await this.resetClient(); this.collectionKeys.clear(); this.syncID = meta.payload.syncID; this._log.debug("Clear cached values and take syncId: " + this.syncID); if (!(await this.verifyAndFetchSymmetricKeys(infoResponse))) { this._log.warn("Failed to fetch symmetric keys. Failing remote setup."); @@ -1126,17 +1120,16 @@ Sync11Service.prototype = { }, /** * Sync up engines with the server. */ async _lockedSync(engineNamesToSync, why) { return this._lock("service.js: sync", this._notify("sync", JSON.stringify({why}), async function onNotify() { - let histogram = Services.telemetry.getHistogramById("WEAVE_START_COUNT"); histogram.add(1); let synchronizer = new EngineSynchronizer(this); await synchronizer.sync(engineNamesToSync, why); // Might throw! histogram = Services.telemetry.getHistogramById("WEAVE_COMPLETE_SUCCESS_COUNT"); histogram.add(1);
--- a/services/sync/modules/telemetry.js +++ b/services/sync/modules/telemetry.js @@ -787,13 +787,12 @@ class SyncTelemetryImpl { msg = JSON.stringify(error); } } return { name: "unexpectederror", error: cleanErrorMessage(msg), }; } - } /* global SyncTelemetry */ var SyncTelemetry = new SyncTelemetryImpl(ENGINES);
--- a/services/sync/modules/util.js +++ b/services/sync/modules/util.js @@ -483,25 +483,23 @@ var Utils = { normalizePassphrase: function normalizePassphrase(pp) { // Short var name... have you seen the lines below?! // Allow leading and trailing whitespace. pp = pp.trim().toLowerCase(); // 20-char sync key. if (pp.length == 23 && [5, 11, 17].every(i => pp[i] == "-")) { - return pp.slice(0, 5) + pp.slice(6, 11) + pp.slice(12, 17) + pp.slice(18, 23); } // "Modern" 26-char key. if (pp.length == 31 && [1, 7, 13, 19, 25].every(i => pp[i] == "-")) { - return pp.slice(0, 1) + pp.slice(2, 7) + pp.slice(8, 13) + pp.slice(14, 19) + pp.slice(20, 25) + pp.slice(26, 31); } // Something else -- just return. return pp; },
--- a/services/sync/tests/unit/head_http_server.js +++ b/services/sync/tests/unit/head_http_server.js @@ -580,17 +580,16 @@ function sync_httpd_setup(handlers) { * * XXX - DO NOT USE IN NEW TESTS * * This code has very limited and very hacky timestamp support - the test * server now has more complete and correct support - using this helper * may cause strangeness wrt timestamp headers and 412 responses. */ function track_collections_helper() { - /* * Our tracking object. */ let collections = {}; /* * Update the timestamp of a collection. */ @@ -720,17 +719,16 @@ SyncServer.prototype = { } catch (ex) { _("=========================================="); _("Got exception starting Sync HTTP server."); _("Error: " + Log.exceptionStr(ex)); _("Is there a process already listening on port " + port + "?"); _("=========================================="); do_throw(ex); } - }, /** * Stop the SyncServer's HTTP server. * * @param cb * A callback function. Invoked after the server has been stopped. *
--- a/services/sync/tests/unit/test_addon_utils.js +++ b/services/sync/tests/unit/test_addon_utils.js @@ -97,17 +97,16 @@ add_task(async function test_source_uri_ // skewed. // We resort to monkeypatching because of the API design. let oldFunction = AddonUtils.__proto__.installAddonFromSearchResult; let installCalled = false; AddonUtils.__proto__.installAddonFromSearchResult = async function testInstallAddon(addon, metadata) { - Assert.equal(SERVER_ADDRESS + "/require.xpi?src=sync", addon.sourceURI.spec); installCalled = true; const install = await AddonUtils.getInstallFromSearchResult(addon); Assert.equal(SERVER_ADDRESS + "/require.xpi?src=sync", install.sourceURI.spec);
--- a/services/sync/tests/unit/test_bookmark_decline_undecline.js +++ b/services/sync/tests/unit/test_bookmark_decline_undecline.js @@ -37,15 +37,14 @@ add_task(async function test_decline_und engine.enabled = false; await Service.sync(); ok(!getBookmarkWBO(server, bzGuid), "Shouldn't be present on server anymore"); engine.enabled = true; await Service.sync(); ok(getBookmarkWBO(server, bzGuid), "Should be present on server again"); - } finally { await PlacesSyncUtils.bookmarks.reset(); await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_bookmark_duping.js +++ b/services/sync/tests/unit/test_bookmark_duping.js @@ -604,17 +604,16 @@ add_task(async function test_dupe_repare // * When the parent *did* eventually arrive we used the parent annotation // to correctly reparent - but that reparenting process does not change // the server record. // Hence, newGUID is a child of both those server records :( { name: "multipleParents", count: 1 }, { name: "parentChildMismatches", count: 1 }, ]; await validate(collection, expected); - } finally { await cleanup(engine, server); } }); add_task(async function test_dupe_empty_folder() { _("Ensure that an empty folder we consider a dupe is handled correctly."); // Empty folders aren't particularly interesting in practice (as that seems
--- a/services/sync/tests/unit/test_bookmark_engine.js +++ b/services/sync/tests/unit/test_bookmark_engine.js @@ -238,17 +238,16 @@ add_bookmark_test(async function test_pr let store = engine._store; let server = await serverForFoo(engine); await SyncTestingInfrastructure(server); let collection = server.user("foo").collection("bookmarks"); try { - let folder1 = await PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid, type: PlacesUtils.bookmarks.TYPE_FOLDER, title: "Folder 1", }); let bmk1 = await PlacesUtils.bookmarks.insert({ parentGuid: folder1.guid, @@ -302,17 +301,16 @@ add_bookmark_test(async function test_pr folder1_record = await store.createRecord(folder1.guid); let new_children = folder1_record.children; Assert.deepEqual(new_children.sort(), [folder1_payload.children[0], folder1_payload.children[1]].sort()); let localChildIds = await PlacesSyncUtils.bookmarks.fetchChildRecordIds( folder1.guid); Assert.deepEqual(localChildIds.sort(), [bmk2.guid, bmk1.guid].sort()); - } finally { await cleanup(engine, server); } }); add_bookmark_test(async function test_restorePromptsReupload(engine) { await test_restoreOrImport(engine, { replace: true }); }); @@ -333,17 +331,16 @@ async function test_restoreOrImport(engi let server = await serverForFoo(engine); await SyncTestingInfrastructure(server); let collection = server.user("foo").collection("bookmarks"); engine._tracker.start(); // We skip usual startup... try { - let folder1 = await PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid, type: PlacesUtils.bookmarks.TYPE_FOLDER, title: "Folder 1", }); _("Create a single record."); let bmk1 = await PlacesUtils.bookmarks.insert({ @@ -475,17 +472,16 @@ async function test_restoreOrImport(engi let expectedFolders; if (replace) { expectedFolders = [expectedFolder1]; } else { expectedFolders = [expectedFolder1, expectedFolder1]; } doCheckWBOs(folderWBOs, expectedFolders); - } finally { await cleanup(engine, server); } } function doCheckWBOs(WBOs, expected) { Assert.equal(WBOs.length, expected.length); for (let i = 0; i < expected.length; i++) { @@ -879,19 +875,16 @@ add_bookmark_test(async function test_sy collection.insert(item2GUID, encryptPayload(item2.cleartext), now / 1000 - 10); engine.lastModified = null; await sync_engine_and_validate_telem(engine, false); let newerRecord2 = await store.createRecord(item2GUID); equal(newerRecord2.dateAdded, newRecord2.dateAdded, "dateAdded update should be ignored for later date if we know an earlier one "); - - - } finally { await cleanup(engine, server); } }); add_task(async function test_buffer_hasDupe() { await Service.recordManager.clearCache(); await PlacesSyncUtils.bookmarks.reset(); @@ -1087,17 +1080,16 @@ add_task(async function test_resume_buff engine._store.applyIncomingBatch = origApplyIncomingBatch; await sync_engine_and_validate_telem(engine, false); // Check that all the children made it onto the correct record. let toolbarRecord = await engine._store.createRecord("toolbar"); Assert.deepEqual(toolbarRecord.children.sort(), children.sort()); - } finally { await cleanup(engine, server); await engine.finalize(); } }); // The buffered engine stores the sync ID and last sync time in three places: // prefs, Places, and the mirror. We can remove the prefs entirely in bug
--- a/services/sync/tests/unit/test_bookmark_repair.js +++ b/services/sync/tests/unit/test_bookmark_repair.js @@ -87,17 +87,16 @@ add_task(async function test_bookmark_re let server = await serverForFoo(bookmarksEngine); await SyncTestingInfrastructure(server); let user = server.user("foo"); let initialID = Service.clientsEngine.localID; let remoteID = Utils.makeGUID(); try { - _("Syncing to initialize crypto etc."); await Service.sync(); _("Create remote client record"); server.insertWBO("foo", "clients", new ServerWBO(remoteID, encryptPayload({ id: remoteID, name: "Remote client", type: "desktop", @@ -352,17 +351,16 @@ add_task(async function test_repair_clie _("Ensure that a record missing from the client only will get re-downloaded from the server"); let server = await serverForFoo(bookmarksEngine); await SyncTestingInfrastructure(server); let remoteID = Utils.makeGUID(); try { - _("Syncing to initialize crypto etc."); await Service.sync(); _("Create remote client record"); server.insertWBO("foo", "clients", new ServerWBO(remoteID, encryptPayload({ id: remoteID, name: "Remote client", type: "desktop", @@ -428,17 +426,16 @@ add_task(async function test_repair_serv let server = await serverForFoo(bookmarksEngine); await SyncTestingInfrastructure(server); let user = server.user("foo"); let remoteID = Utils.makeGUID(); try { - _("Syncing to initialize crypto etc."); await Service.sync(); _("Create remote client record"); server.insertWBO("foo", "clients", new ServerWBO(remoteID, encryptPayload({ id: remoteID, name: "Remote client", type: "desktop", @@ -490,17 +487,16 @@ add_task(async function test_repair_serv _("Ensure that a record marked as deleted on the server but present on the client will get deleted on the client"); let server = await serverForFoo(bookmarksEngine); await SyncTestingInfrastructure(server); let remoteID = Utils.makeGUID(); try { - _("Syncing to initialize crypto etc."); await Service.sync(); _("Create remote client record"); server.insertWBO("foo", "clients", new ServerWBO(remoteID, encryptPayload({ id: remoteID, name: "Remote client", type: "desktop",
--- a/services/sync/tests/unit/test_bookmark_store.js +++ b/services/sync/tests/unit/test_bookmark_store.js @@ -154,17 +154,16 @@ add_task(async function test_bookmark_cr parentGuid: PlacesUtils.bookmarks.toolbarGuid, url: "http://getfirefox.com/", }); _("Verify that the record is created accordingly."); let record = await store.createRecord(bmk1.guid); Assert.equal(record.title, ""); Assert.equal(record.keyword, null); - } finally { _("Clean up."); await store.wipe(); } }); add_task(async function test_folder_create() { let engine = new BookmarksEngine(Service); @@ -228,17 +227,16 @@ add_task(async function test_folder_crea let record = await store.createRecord(folder1.guid); Assert.ok(record instanceof BookmarkFolder); Assert.equal(record.title, "Folder1"); Assert.equal(record.parentid, "toolbar"); Assert.equal(record.parentName, BookmarksToolbarTitle); _("Verify the folder's children. Ensures that the bookmarks were given GUIDs."); Assert.deepEqual(record.children, [bmk1.guid, bmk2.guid]); - } finally { _("Clean up."); await store.wipe(); } }); add_task(async function test_deleted() { let engine = new BookmarksEngine(Service); @@ -258,17 +256,16 @@ add_task(async function test_deleted() { await store.applyIncoming(record); await store.deletePending(); _("Ensure it has been deleted."); let item = await PlacesUtils.bookmarks.fetch(bmk1.guid); Assert.equal(null, item); let newrec = await store.createRecord(bmk1.guid); Assert.equal(newrec.deleted, true); - } finally { _("Clean up."); await store.wipe(); await engine.finalize(); } }); add_task(async function test_move_folder() { @@ -345,31 +342,29 @@ add_task(async function test_move_order( await store._orderChildren(); tracker.ignoreAll = false; delete store._childrenToOrder; _("Verify new order."); let newChildIds = await PlacesSyncUtils.bookmarks.fetchChildRecordIds( "toolbar"); Assert.deepEqual(newChildIds, [bmk2.guid, bmk1.guid]); - } finally { await tracker.stop(); _("Clean up."); await store.wipe(); await engine.finalize(); } }); add_task(async function test_orphan() { let engine = new BookmarksEngine(Service); let store = engine._store; try { - _("Add a new bookmark locally."); let bmk1 = await PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.toolbarGuid, url: "http://getfirefox.com/", title: "Get Firefox!", }); let bmk1_id = await PlacesUtils.promiseItemId(bmk1.guid); do_check_throws(function() { @@ -383,17 +378,16 @@ add_task(async function test_orphan() { await store.applyIncoming(record); _("Verify that bookmark has been flagged as orphan, has not moved."); let item = await PlacesUtils.bookmarks.fetch(bmk1.guid); Assert.equal(item.parentGuid, PlacesUtils.bookmarks.toolbarGuid); let orphanAnno = PlacesUtils.annotations.getItemAnnotation(bmk1_id, PlacesSyncUtils.bookmarks.SYNC_PARENT_ANNO); Assert.equal(orphanAnno, "non-existent"); - } finally { _("Clean up."); await store.wipe(); await engine.finalize(); } }); add_task(async function test_reparentOrphans() { @@ -416,17 +410,16 @@ add_task(async function test_reparentOrp record.title = "New title for Folder 1"; store._childrenToOrder = {}; await store.applyIncoming(record); _("Verify that is has been marked as an orphan even though it couldn't be moved into itself."); let orphanAnno = PlacesUtils.annotations.getItemAnnotation(folder1_id, PlacesSyncUtils.bookmarks.SYNC_PARENT_ANNO); Assert.equal(orphanAnno, folder1.guid); - } finally { _("Clean up."); await store.wipe(); await engine.finalize(); } }); // Tests Bug 806460, in which query records arrive with empty folder @@ -533,15 +526,14 @@ add_task(async function test_delete_buff await assertDeleted(fxItem.guid); await assertDeleted(folderItem.guid); ok(!store._itemsToDelete.has(folder.id)); ok(!store._itemsToDelete.has(fxRecord.id)); tbItem = await PlacesUtils.bookmarks.fetch(tbRecord.id); equal(tbItem.parentGuid, PlacesUtils.bookmarks.toolbarGuid); - } finally { _("Clean up."); await store.wipe(); await engine.finalize(); } });
--- a/services/sync/tests/unit/test_bookmark_tracker.js +++ b/services/sync/tests/unit/test_bookmark_tracker.js @@ -224,17 +224,16 @@ add_task(async function test_tracking() // changed as well (new child). await verifyTrackedCount(2); Assert.equal(tracker.score, SCORE_INCREMENT_XLARGE); _("Notifying twice won't do any harm."); createBmk(); await verifyTrackedCount(3); Assert.equal(tracker.score, SCORE_INCREMENT_XLARGE * 2); - } finally { _("Clean up."); await cleanup(); } }); add_task(async function test_tracker_sql_batching() { _("Test tracker does the correct thing when it is forced to batch SQL queries");
--- a/services/sync/tests/unit/test_clients_engine.js +++ b/services/sync/tests/unit/test_clients_engine.js @@ -186,17 +186,16 @@ add_task(async function test_bad_hmac() equal(deletedCollections.length, 0); equal(deletedItems.length, 0); await syncClientsEngine(server); equal(deletedItems.length, 1); check_client_deleted(oldLocalID); check_clients_count(1); let newKey = Service.collectionKeys.keyForCollection(); ok(!oldKey.equals(newKey)); - } finally { await cleanup(); await promiseStopServer(server); } }); add_task(async function test_properties() { _("Test lastRecordUpload property"); @@ -290,17 +289,16 @@ add_task(async function test_sync() { await SyncTestingInfrastructure(server); await generateNewKeys(Service.collectionKeys); function clientWBO() { return user.collection("clients").wbo(engine.localID); } try { - _("First sync. Client record is uploaded."); equal(clientWBO(), undefined); equal(engine.lastRecordUpload, 0); ok(engine.isFirstSync); await syncClientsEngine(server); ok(!!clientWBO().payload); ok(engine.lastRecordUpload > 0); ok(!engine.isFirstSync); @@ -320,17 +318,16 @@ add_task(async function test_sync() { _("Time travel one day back, no record uploaded."); engine.lastRecordUpload -= LESS_THAN_CLIENTS_TTL_REFRESH; let yesterday = engine.lastRecordUpload; await syncClientsEngine(server); equal(clientWBO().payload, undefined); equal(engine.lastRecordUpload, yesterday); ok(!engine.isFirstSync); - } finally { await cleanup(); await promiseStopServer(server); } }); add_task(async function test_client_name_change() { _("Ensure client name change incurs a client record update."); @@ -437,17 +434,16 @@ add_task(async function test_last_modifi _("Local record should have updated timestamp"); ok(engine._store._remoteClients[activeID].serverLastModified >= now); _("Record on the server should have new name but not serverLastModified"); let payload = collection.cleartext(activeID); equal(payload.name, "New name"); equal(payload.serverLastModified, undefined); - } finally { await cleanup(); server.deleteCollections("foo"); await promiseStopServer(server); } }); add_task(async function test_send_command() { @@ -547,17 +543,16 @@ add_task(async function test_command_val } else { _("Ensuring command is scrubbed: " + action); equal(clientCommands, undefined); if (store._tracker) { equal(engine._tracker[remoteId], undefined); } } - } await cleanup(); }); add_task(async function test_command_duplication() { _("Ensures duplicate commands are detected and not added"); let store = engine._store; @@ -769,17 +764,16 @@ add_task(async function test_filter_dupl deepEqual(engine.stats, { hasMobile: 1, names: [engine.localName, "My Phone", engine.localName, "My old desktop"], numClients: 4, }); ok(engine.remoteClientExists(dupeID), "recently synced dupe ID should now exist"); equal(engine.remoteClients.length, 3, "recently synced dupe should now be in remoteClients"); - } finally { await cleanup(); try { server.deleteCollections("foo"); } finally { await promiseStopServer(server); } @@ -840,17 +834,16 @@ add_task(async function test_command_syn _("Performing sync on resetted client."); await syncClientsEngine(server); notEqual(engine.localCommands, undefined); equal(engine.localCommands.length, 1); let command = engine.localCommands[0]; equal(command.command, "wipeAll"); equal(command.args.length, 0); - } finally { await cleanup(); try { let collection = server.getCollection("foo", "clients"); collection.remove(remoteId); } finally { await promiseStopServer(server); @@ -900,17 +893,16 @@ add_task(async function test_clients_not }; try { _("Syncing."); await syncClientsEngine(server); ok(!engine._store._remoteClients[remoteId].stale); ok(engine._store._remoteClients[remoteId2].stale); - } finally { engine.fxAccounts = fxAccounts; await cleanup(); try { collection.remove(remoteId); } finally { await promiseStopServer(server); @@ -962,17 +954,16 @@ add_task(async function test_dupe_device }; try { _("Syncing."); await syncClientsEngine(server); ok(engine._store._remoteClients[remoteId].stale); ok(!engine._store._remoteClients[remoteId2].stale); - } finally { engine.fxAccounts = fxAccounts; await cleanup(); try { collection.remove(remoteId); } finally { await promiseStopServer(server); @@ -1697,17 +1688,16 @@ add_task(async function ensureSameFlowID equal(events[0].extra.flowID, flowID); equal(events[1].extra.flowID, flowID); equal(events[0].extra.reason, "testing"); equal(events[1].extra.reason, "testing"); // Wipe remote clients to ensure deduping doesn't prevent us from adding the command. for (let client of Object.values(engine._store._remoteClients)) { client.commands = []; } - } finally { Service.recordTelemetryEvent = origRecordTelemetryEvent; cleanup(); await promiseStopServer(server); } }); add_task(async function test_duplicate_commands_telemetry() {
--- a/services/sync/tests/unit/test_collections_recovery.js +++ b/services/sync/tests/unit/test_collections_recovery.js @@ -63,14 +63,13 @@ add_task(async function test_missing_cry delete johnColls.crypto; await sync_and_validate_telem(); Assert.equal(fresh, 1); fresh = 0; _("Regular sync: no need to freshStart."); await sync_and_validate_telem(); Assert.equal(fresh, 0); - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_forms_tracker.js +++ b/services/sync/tests/unit/test_forms_tracker.js @@ -65,16 +65,13 @@ add_task(async function run_test() { changes = await tracker.getChangedIDs(); do_check_empty(changes); _("Notifying twice won't do any harm."); await tracker.stop(); await removeEntry("email", "john@doe.com"); changes = await tracker.getChangedIDs(); do_check_empty(changes); - - - } finally { _("Clean up."); await engine._store.wipe(); } });
--- a/services/sync/tests/unit/test_history_tracker.js +++ b/services/sync/tests/unit/test_history_tracker.js @@ -4,17 +4,16 @@ const {PlacesDBUtils} = ChromeUtils.import("resource://gre/modules/PlacesDBUtils.jsm"); const {HistoryEngine} = ChromeUtils.import("resource://services-sync/engines/history.js"); const {Service} = ChromeUtils.import("resource://services-sync/service.js"); let engine; let tracker; add_task(async function setup() { - await Service.engineManager.clear(); await Service.engineManager.register(HistoryEngine); engine = Service.engineManager.get("history"); tracker = engine._tracker; // Don't write out by default. tracker.persistChangedIDs = false; });
--- a/services/sync/tests/unit/test_password_engine.js +++ b/services/sync/tests/unit/test_password_engine.js @@ -207,21 +207,19 @@ add_task(async function test_password_du _("Perform sync"); await sync_engine_and_validate_telem(engine, false); let logins = Services.logins.findLogins({}, "https://www.example.com", "", ""); equal(logins.length, 1); equal(logins[0].QueryInterface(Ci.nsILoginMetaInfo).guid, guid2); equal(null, collection.payload(guid1)); - } finally { await cleanup(engine, server); } - }); add_task(async function test_sync_password_validation() { // This test isn't in test_password_validator to avoid duplicating cleanup. _("Ensure that if a password validation happens, it ends up in the ping"); let engine = Service.engineManager.get("passwords"); @@ -229,21 +227,19 @@ add_task(async function test_sync_passwo await SyncTestingInfrastructure(server); Svc.Prefs.set("engine.passwords.validation.interval", 0); Svc.Prefs.set("engine.passwords.validation.percentageChance", 100); Svc.Prefs.set("engine.passwords.validation.maxRecords", -1); Svc.Prefs.set("engine.passwords.validation.enabled", true); try { - let ping = await wait_for_ping(() => Service.sync()); let engineInfo = ping.engines.find(e => e.name == "passwords"); ok(engineInfo, "Engine should be in ping"); let validation = engineInfo.validation; ok(validation, "Engine should have validation info"); - } finally { await cleanup(engine, server); } });
--- a/services/sync/tests/unit/test_password_store.js +++ b/services/sync/tests/unit/test_password_store.js @@ -41,17 +41,16 @@ async function checkRecord(name, record, } return undefined; } async function changePassword(name, hostname, password, expectedCount, timeCreated, expectedTimeCreated, timePasswordChanged, expectedTimePasswordChanged, insert, recordIsUpdated) { - const BOGUS_GUID = "zzzzzz" + hostname; let record = {id: BOGUS_GUID, hostname, formSubmitURL: hostname, username: "john", password, usernameField: "username", @@ -71,17 +70,16 @@ async function changePassword(name, host if (insert) { Assert.equal((await store.applyIncomingBatch([record])).length, 0); } return checkRecord(name, record, expectedCount, timeCreated, expectedTimeCreated, timePasswordChanged, expectedTimePasswordChanged, recordIsUpdated); - } async function test_apply_records_with_times(hostname, timeCreated, timePasswordChanged) { // The following record is going to be inserted in the store and it needs // to be found there. Then its timestamps are going to be compared to // the expected values. await changePassword(" ", hostname, "password", 1, timeCreated, timeCreated, @@ -195,13 +193,12 @@ add_task(async function run_test() { await test_apply_records_with_times("http://afoo.baz.com", undefined, undefined); await test_apply_records_with_times("http://bfoo.baz.com", 1000, undefined); await test_apply_records_with_times("http://cfoo.baz.com", undefined, 2000); await test_apply_records_with_times("http://dfoo.baz.com", 1000, 2000); await test_apply_multiple_records_with_times(); await test_apply_same_record_with_different_times(); - } finally { await store.wipe(); } });
--- a/services/sync/tests/unit/test_password_tracker.js +++ b/services/sync/tests/unit/test_password_tracker.js @@ -71,17 +71,16 @@ add_task(async function test_tracking() Assert.equal(tracker.score, 0); _("Stopping twice won't do any harm."); await tracker.stop(); await createPassword(); changes = await tracker.getChangedIDs(); do_check_empty(changes); Assert.equal(tracker.score, 0); - } finally { _("Clean up."); await store.wipe(); await tracker.clearChangedIDs(); tracker.resetScore(); await tracker.stop(); } });
--- a/services/sync/tests/unit/test_postqueue.js +++ b/services/sync/tests/unit/test_postqueue.js @@ -662,17 +662,16 @@ add_task(async function test_max_records didCommit: true, }]); equal(pq.lastModified, time1 + 200); }); // Test we do the right thing when the limits are met but not exceeded. add_task(async function test_packed_batch() { - let config = { max_post_bytes: 41, max_post_records: 4, max_total_bytes: 81, max_total_records: 8, max_record_payload_bytes: 20 + makeRecord.nonPayloadOverhead + 1,
--- a/services/sync/tests/unit/test_prefs_store.js +++ b/services/sync/tests/unit/test_prefs_store.js @@ -25,17 +25,16 @@ add_task(async function run_test() { _("Test fixtures."); // read our custom prefs file before doing anything. Services.prefs.readDefaultPrefsFromFile(do_get_file("prefs_test_prefs_store.js")); let engine = Service.engineManager.get("prefs"); let store = engine._store; let prefs = new Preferences(); try { - _("The GUID corresponds to XUL App ID."); let allIDs = await store.getAllIDs(); let ids = Object.keys(allIDs); Assert.equal(ids.length, 1); Assert.equal(ids[0], PREFS_GUID); Assert.ok(allIDs[PREFS_GUID]); Assert.ok((await store.itemExists(PREFS_GUID)));
--- a/services/sync/tests/unit/test_prefs_tracker.js +++ b/services/sync/tests/unit/test_prefs_tracker.js @@ -9,17 +9,16 @@ add_task(async function run_test() { let tracker = engine._tracker; // Don't write out by default. tracker.persistChangedIDs = false; let prefs = new Preferences(); try { - _("tracker.modified corresponds to preference."); Assert.equal(Svc.Prefs.get("engine.prefs.modified"), undefined); Assert.ok(!tracker.modified); tracker.modified = true; Assert.equal(Svc.Prefs.get("engine.prefs.modified"), true); Assert.ok(tracker.modified); @@ -76,14 +75,13 @@ add_task(async function run_test() { Assert.equal(tracker.modified, false); await tracker.clearChangedIDs(); _("Changing some other random pref won't do anything."); prefs.set("testing.other", "blergh"); await tracker.asyncObserver.promiseObserversComplete(); Assert.equal(tracker.score, SCORE_INCREMENT_XLARGE * 3); Assert.equal(tracker.modified, false); - } finally { await tracker.stop(); prefs.resetBranch(""); } });
--- a/services/sync/tests/unit/test_records_wbo.js +++ b/services/sync/tests/unit/test_records_wbo.js @@ -61,13 +61,12 @@ add_task(async function test_fetch() { Assert.equal(typeof(rec2.payload), "object"); Assert.equal(rec2.payload.cheese, "gruyere"); Assert.equal(Service.recordManager.response.status, 200); // Testing collection extraction. _("Extracting collection."); let rec3 = new WBORecord("tabs", "foo"); // Create through constructor. Assert.equal(rec3.collection, "tabs"); - } finally { await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_resource_ua.js +++ b/services/sync/tests/unit/test_resource_ua.js @@ -19,34 +19,32 @@ var ua; function uaHandler(f) { return function(request, response) { ua = request.getHeader("User-Agent"); return f(request, response); }; } add_task(async function setup() { - Log.repository.rootLogger.addAppender(new Log.DumpAppender()); meta_global = new ServerWBO("global"); server = httpd_setup({ "/1.1/johndoe/info/collections": uaHandler(collectionsHelper.handler), "/1.1/johndoe/storage/meta/global": uaHandler(meta_global.handler()), }); await configureIdentity({ username: "johndoe" }, server); _("Server URL: " + server.baseURI); // Note this string is missing the trailing ".destkop" as the test // adjusts the "client.type" pref where that portion comes from. expectedUA = Services.appinfo.name + "/" + Services.appinfo.version + " (" + httpProtocolHandler.oscpu + ")" + " FxSync/" + WEAVE_VERSION + "." + Services.appinfo.appBuildID; - }); add_task(async function test_fetchInfo() { _("Testing _fetchInfo."); await Service.login(); await Service._fetchInfo(); _("User-Agent: " + ua); Assert.equal(ua, expectedUA + ".desktop");
--- a/services/sync/tests/unit/test_service_attributes.js +++ b/services/sync/tests/unit/test_service_attributes.js @@ -25,17 +25,16 @@ add_task(async function test_urls() { Assert.equal(Service.userBaseURL, "http://weave.cluster/1.1/johndoe/"); Assert.equal(Service.infoURL, "http://weave.cluster/1.1/johndoe/info/collections"); Assert.equal(Service.storageURL, "http://weave.cluster/1.1/johndoe/storage/"); Assert.equal(Service.metaURL, "http://weave.cluster/1.1/johndoe/storage/meta/global"); - } finally { Svc.Prefs.resetBranch(""); } }); add_test(function test_syncID() { _("Service.syncID is auto-generated, corresponds to preference.");
--- a/services/sync/tests/unit/test_service_cluster.js +++ b/services/sync/tests/unit/test_service_cluster.js @@ -18,17 +18,16 @@ add_task(async function test_findCluster await Assert.rejects(Service.identity._findCluster(), /Connection refused/); Service.identity._ensureValidToken = () => Promise.resolve({ endpoint: "http://weave.user.node" }); _("_findCluster() returns the user's cluster node"); let cluster = await Service.identity._findCluster(); Assert.equal(cluster, "http://weave.user.node/"); - } finally { Svc.Prefs.resetBranch(""); } }); add_task(async function test_setCluster() { syncTestLogging(); _("Test Service._setCluster()");
--- a/services/sync/tests/unit/test_service_detect_upgrade.js +++ b/services/sync/tests/unit/test_service_detect_upgrade.js @@ -30,17 +30,16 @@ add_task(async function v4_upgrade() { "/1.1/johndoe/storage/bookmarks": new ServerCollection().handler(), "/1.1/johndoe/storage/forms": new ServerCollection().handler(), "/1.1/johndoe/storage/history": new ServerCollection().handler(), "/1.1/johndoe/storage/passwords": new ServerCollection().handler(), "/1.1/johndoe/storage/prefs": new ServerCollection().handler(), }); try { - Service.status.resetSync(); _("Logging in."); await configureIdentity({ "username": "johndoe" }, server); await Service.login(); Assert.ok(Service.isLoggedIn); @@ -150,17 +149,16 @@ add_task(async function v4_upgrade() { Assert.ok(collections.clients > oldClientsModified); Assert.ok(collections.tabs > oldTabsModified); _("... and keys will now match."); await retrieve_and_compare_default(true); // Clean up. await Service.startOver(); - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } }); add_task(async function v5_upgrade() { enableValidationPrefs(); @@ -232,17 +230,16 @@ add_task(async function v5_upgrade() { _("Exception: " + e); } _("Status: " + Service.status); Assert.ok(!Service.isLoggedIn); Assert.equal(VERSION_OUT_OF_DATE, Service.status.sync); // Clean up. await Service.startOver(); - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } }); function run_test() { Log.repository.rootLogger.addAppender(new Log.DumpAppender());
--- a/services/sync/tests/unit/test_service_login.js +++ b/services/sync/tests/unit/test_service_login.js @@ -100,17 +100,16 @@ add_task(async function test_login_logou _("Logout."); Service.logout(); Assert.ok(!Service.isLoggedIn); _("Logging out again won't do any harm."); Service.logout(); Assert.ok(!Service.isLoggedIn); - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } }); add_task(async function test_login_on_sync() { enableValidationPrefs(); @@ -197,14 +196,13 @@ add_task(async function test_login_on_sy _("Sync doesn't proceed and clears triggers if MP is still locked."); await Service.sync(); Assert.ok(cSTCalled); Assert.ok(!lockedSyncCalled); // N.B., a bunch of methods are stubbed at this point. Be careful putting // new tests after this point! - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_service_sync_401.js +++ b/services/sync/tests/unit/test_service_sync_401.js @@ -66,14 +66,13 @@ add_task(async function run_test() { Assert.equal(Service.scheduler.globalScore, 0); _("Our next sync will fail appropriately."); try { await Service.sync(); } catch (ex) { } Assert.equal(Service.status.login, LOGIN_FAILED_LOGIN_REJECTED); - } finally { Svc.Prefs.resetBranch(""); await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_service_sync_specified.js +++ b/services/sync/tests/unit/test_service_sync_specified.js @@ -25,17 +25,16 @@ StirlingEngine.prototype = { }, }; // Tracking info/collections. var collectionsHelper = track_collections_helper(); var upd = collectionsHelper.with_updated_collection; function sync_httpd_setup(handlers) { - handlers["/1.1/johndoe/info/collections"] = collectionsHelper.handler; delete collectionsHelper.collections.crypto; delete collectionsHelper.collections.meta; let cr = new ServerWBO("keys"); handlers["/1.1/johndoe/storage/crypto/keys"] = upd("crypto", cr.handler()); @@ -76,82 +75,76 @@ add_task(async function test_noEngines() _("Test: An empty array of engines to sync does nothing."); let server = await setUp(); try { _("Sync with no engines specified."); await Service.sync({engines: []}); deepEqual(syncedEngines, [], "no engines were synced"); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_oneEngine() { enableValidationPrefs(); _("Test: Only one engine is synced."); let server = await setUp(); try { - _("Sync with 1 engine specified."); await Service.sync({engines: ["steam"]}); deepEqual(syncedEngines, ["steam"]); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_bothEnginesSpecified() { enableValidationPrefs(); _("Test: All engines are synced when specified in the correct order (1)."); let server = await setUp(); try { _("Sync with both engines specified."); await Service.sync({engines: ["steam", "stirling"]}); deepEqual(syncedEngines, ["steam", "stirling"]); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_bothEnginesSpecified() { enableValidationPrefs(); _("Test: All engines are synced when specified in the correct order (2)."); let server = await setUp(); try { _("Sync with both engines specified."); await Service.sync({engines: ["stirling", "steam"]}); deepEqual(syncedEngines, ["stirling", "steam"]); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_bothEnginesDefault() { enableValidationPrefs(); _("Test: All engines are synced when nothing is specified."); let server = await setUp(); try { await Service.sync(); deepEqual(syncedEngines, ["steam", "stirling"]); - } finally { await Service.startOver(); await promiseStopServer(server); } });
--- a/services/sync/tests/unit/test_service_sync_updateEnabledEngines.js +++ b/services/sync/tests/unit/test_service_sync_updateEnabledEngines.js @@ -36,17 +36,16 @@ StirlingEngine.prototype = { }, }; // Tracking info/collections. var collectionsHelper = track_collections_helper(); var upd = collectionsHelper.with_updated_collection; function sync_httpd_setup(handlers) { - handlers["/1.1/johndoe/info/collections"] = collectionsHelper.handler; delete collectionsHelper.collections.crypto; delete collectionsHelper.collections.meta; let cr = new ServerWBO("keys"); handlers["/1.1/johndoe/storage/crypto/keys"] = upd("crypto", cr.handler()); @@ -303,17 +302,16 @@ add_task(async function test_disabledRem metaWBO.modified = Date.now() / 1000; _("Add a second client and verify that the local pref is changed."); Service.clientsEngine._store._remoteClients.foobar = {name: "foobar", type: "desktop"}; await Service.sync(); _("Engine is disabled."); Assert.ok(!engine.enabled); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_disabledRemotely() { enableValidationPrefs(); @@ -336,17 +334,16 @@ add_task(async function test_disabledRem engine.enabled = true; Service._ignorePrefObserver = false; _("Sync."); await Service.sync(); _("Engine is not disabled: only one client."); Assert.ok(engine.enabled); - } finally { await Service.startOver(); await promiseStopServer(server); } }); add_task(async function test_dependentEnginesEnabledLocally() { enableValidationPrefs();
--- a/services/sync/tests/unit/test_service_verifyLogin.js +++ b/services/sync/tests/unit/test_service_verifyLogin.js @@ -87,14 +87,13 @@ add_task(async function test_verifyLogin Assert.equal(Service.status.login, LOGIN_FAILED_NETWORK_ERROR); _("Ensure a network error when getting the collection info sets the right Status bits."); Service.status.resetSync(); Service.clusterURL = "http://localhost:12345/"; Assert.equal(false, (await Service.verifyLogin())); Assert.equal(Service.status.service, LOGIN_FAILED); Assert.equal(Service.status.login, LOGIN_FAILED_NETWORK_ERROR); - } finally { Svc.Prefs.resetBranch(""); server.stop(do_test_finished); } });
--- a/services/sync/tests/unit/test_service_wipeServer.js +++ b/services/sync/tests/unit/test_service_wipeServer.js @@ -54,17 +54,16 @@ add_task(async function test_wipeServer_ _("wipeServer() will happily ignore the non-existent collection and use the timestamp of the last DELETE that was successful."); let timestamp = await Service.wipeServer(["steam", "diesel", "petrol"]); Assert.equal(timestamp, diesel_coll.timestamp); _("wipeServer stopped deleting after encountering an error with the 'petrol' collection, thus only 'steam' has been deleted."); Assert.ok(steam_coll.deleted); Assert.ok(diesel_coll.deleted); - } finally { await promiseStopServer(server); Svc.Prefs.resetBranch(""); } }); add_task(async function test_wipeServer_list_503() { _("Service.wipeServer() deletes collections given as argument."); @@ -95,17 +94,16 @@ add_task(async function test_wipeServer_ error = ex; } _("wipeServer() threw this exception: " + error); Assert.equal(error.status, 503); _("wipeServer stopped deleting after encountering an error with the 'petrol' collection, thus only 'steam' has been deleted."); Assert.ok(steam_coll.deleted); Assert.ok(!diesel_coll.deleted); - } finally { await promiseStopServer(server); Svc.Prefs.resetBranch(""); } }); add_task(async function test_wipeServer_all_success() { _("Service.wipeServer() deletes all the things.");
--- a/services/sync/tests/unit/test_status.js +++ b/services/sync/tests/unit/test_status.js @@ -1,12 +1,11 @@ const {Status} = ChromeUtils.import("resource://services-sync/status.js"); function run_test() { - // Check initial states Assert.ok(!Status.enforceBackoff); Assert.equal(Status.backoffInterval, 0); Assert.equal(Status.minimumNextSync, 0); Assert.equal(Status.service, STATUS_OK); Assert.equal(Status.sync, SYNC_SUCCEEDED); Assert.equal(Status.login, LOGIN_SUCCEEDED); @@ -80,10 +79,9 @@ function run_test() { Status.enforceBackoff = true; Status.backOffInterval = 4815162342; Status.backOffInterval = 42; Status.resetBackoff(); Assert.ok(!Status.enforceBackoff); Assert.equal(Status.backoffInterval, 0); Assert.equal(Status.minimumNextSync, 0); - }
--- a/services/sync/tests/unit/test_status_checkSetup.js +++ b/services/sync/tests/unit/test_status_checkSetup.js @@ -14,13 +14,12 @@ add_task(async function test_status_chec Status.resetSync(); _("Let's provide the syncKeyBundle"); await configureIdentity(); _("checkSetup()"); Assert.equal(Status.checkSetup(), STATUS_OK); Status.resetSync(); - } finally { Svc.Prefs.resetBranch(""); } });
--- a/services/sync/tests/unit/test_syncedtabs.js +++ b/services/sync/tests/unit/test_syncedtabs.js @@ -220,17 +220,16 @@ add_task(async function test_filter() { // check it matches the title. clients = await SyncedTabs.getTabClients("test"); equal(clients.length, 1); equal(clients[0].tabs.length, 1); equal(clients[0].tabs[0].url, "http://foo.com/"); }); add_task(async function test_duplicatesTabsAcrossClients() { - await configureClients({ guid_desktop: { clientName: "My Desktop", tabs: [ { urlHistory: ["http://foo.com/"], title: "A test page.", }],
--- a/services/sync/tests/unit/test_syncengine.js +++ b/services/sync/tests/unit/test_syncengine.js @@ -258,17 +258,16 @@ add_task(async function test_wipeServer( await engine.setLastSync(123.45); engine.toFetch = guidSetOfSize(3); _("Wipe server data and reset client."); await engine.wipeServer(); Assert.equal(steamCollection.payload, undefined); Assert.equal(await engine.getLastSync(), 0); Assert.equal(engine.toFetch.size, 0); - } finally { steamServer.stop(do_test_finished); Svc.Prefs.resetBranch(""); } }); add_task(async function finish() { await promiseStopServer(server);
--- a/services/sync/tests/unit/test_syncengine_sync.js +++ b/services/sync/tests/unit/test_syncengine_sync.js @@ -86,17 +86,16 @@ add_task(async function test_syncStartup "/1.1/foo/storage/rotary": collection.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); engine._store.items = {rekolok: "Rekonstruktionslokomotive"}; try { - // Confirm initial environment const changes = await engine._tracker.getChangedIDs(); Assert.equal(changes.rekolok, undefined); let metaGlobal = await Service.recordManager.get(engine.metaURL); Assert.equal(metaGlobal.payload.engines, undefined); Assert.ok(!!collection.payload("flying")); Assert.ok(!!collection.payload("scotsman")); @@ -110,17 +109,16 @@ add_task(async function test_syncStartup let engineData = metaGlobal.payload.engines.rotary; Assert.equal(engineData.version, engine.version); Assert.equal(engineData.syncID, await engine.getSyncID()); // Sync was reset and server data was wiped Assert.equal(await engine.getLastSync(), 0); Assert.equal(collection.payload("flying"), undefined); Assert.equal(collection.payload("scotsman"), undefined); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_syncStartup_serverHasNewerVersion() { _("SyncEngine._syncStartup "); @@ -128,27 +126,25 @@ add_task(async function test_syncStartup let server = httpd_setup({ "/1.1/foo/storage/meta/global": global.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); try { - // The server has a newer version of the data and our engine can // handle. That should give us an exception. let error; try { await engine._syncStartup(); } catch (ex) { error = ex; } Assert.equal(error.failureCode, VERSION_OUT_OF_DATE); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_syncStartup_syncIDMismatchResetsClient() { _("SyncEngine._syncStartup resets sync if syncIDs don't match"); @@ -160,31 +156,29 @@ add_task(async function test_syncStartup // global record with a different syncID than our engine has let engine = makeRotaryEngine(); let global = new ServerWBO("global", {engines: {rotary: {version: engine.version, syncID: "foobar"}}}); server.registerPathHandler("/1.1/foo/storage/meta/global", global.handler()); try { - // Confirm initial environment Assert.equal(await engine.getSyncID(), ""); const changes = await engine._tracker.getChangedIDs(); Assert.equal(changes.rekolok, undefined); await engine.setLastSync(Date.now() / 1000); await engine._syncStartup(); // The engine has assumed the server's syncID Assert.equal(await engine.getSyncID(), "foobar"); // Sync was reset Assert.equal(await engine.getLastSync(), 0); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_processIncoming_emptyServer() { _("SyncEngine._processIncoming working with an empty server backend"); @@ -193,21 +187,19 @@ add_task(async function test_processInco let server = sync_httpd_setup({ "/1.1/foo/storage/rotary": collection.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); try { - // Merely ensure that this code path is run without any errors await engine._processIncoming(); Assert.equal(await engine.getLastSync(), 0); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_processIncoming_createFromServer() { _("SyncEngine._processIncoming creates new records from server data"); @@ -238,17 +230,16 @@ add_task(async function test_processInco let engine = makeRotaryEngine(); let syncID = await engine.resetLocalSyncID(); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); meta_global.payload.engines = {rotary: {version: engine.version, syncID}}; try { - // Confirm initial environment Assert.equal(await engine.getLastSync(), 0); Assert.equal(engine.lastModified, null); Assert.equal(engine._store.items.flying, undefined); Assert.equal(engine._store.items.scotsman, undefined); Assert.equal(engine._store.items["../pathological"], undefined); await engine._syncStartup(); @@ -257,17 +248,16 @@ add_task(async function test_processInco // Timestamps of last sync and last server modification are set. Assert.ok((await engine.getLastSync()) > 0); Assert.ok(engine.lastModified > 0); // Local records have been created from the server data. Assert.equal(engine._store.items.flying, "LNER Class A3 4472"); Assert.equal(engine._store.items.scotsman, "Flying Scotsman"); Assert.equal(engine._store.items["../pathological"], "Pathological Case"); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_processIncoming_reconcile() { _("SyncEngine._processIncoming updates local records"); @@ -331,17 +321,16 @@ add_task(async function test_processInco await engine._tracker.addChangedID("olderidentical", Date.now() / 1000); let syncID = await engine.resetLocalSyncID(); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); meta_global.payload.engines = {rotary: {version: engine.version, syncID}}; try { - // Confirm initial environment Assert.equal(engine._store.items.newrecord, undefined); Assert.equal(engine._store.items.newerserver, "New data, but not as new as server!"); Assert.equal(engine._store.items.olderidentical, "Older but identical"); Assert.equal(engine._store.items.updateclient, "Got data?"); Assert.equal(engine._store.items.nukeme, "Nuke me!"); let changes = await engine._tracker.getChangedIDs(); Assert.ok(changes.olderidentical > 0); @@ -633,17 +622,16 @@ add_task(async function test_processInco await SyncTestingInfrastructure(server); let syncID = await engine.resetLocalSyncID(); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); meta_global.payload.engines = {rotary: {version: engine.version, syncID}}; try { - // Confirm initial environment Assert.equal(engine._store.items.flying, undefined); Assert.equal(engine._store.items.scotsman, undefined); Assert.equal(engine._store.items.rekolok, undefined); await engine._syncStartup(); await engine._processIncoming(); @@ -891,17 +879,16 @@ add_task(async function test_processInco await SyncTestingInfrastructure(server); let syncID = await engine.resetLocalSyncID(); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); meta_global.payload.engines = {rotary: {version: engine.version, syncID}}; try { - // Confirm initial environment Assert.equal(await engine.getLastSync(), 0); Assert.equal(engine.toFetch.size, 0); Assert.equal(engine.previousFailed.size, 0); do_check_empty(engine._store.items); let observerSubject; let observerData; @@ -991,17 +978,16 @@ add_task(async function test_processInco await SyncTestingInfrastructure(server); let syncID = await engine.resetLocalSyncID(); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); meta_global.payload.engines = {rotary: {version: engine.version, syncID}}; try { - // Confirm initial state Assert.equal(engine.toFetch.size, 0); Assert.equal(engine.previousFailed.size, 0); let observerSubject; let observerData; Svc.Obs.add("weave:engine:sync:applied", function onApplied(subject, data) { Svc.Obs.remove("weave:engine:sync:applied", onApplied); @@ -1020,17 +1006,16 @@ add_task(async function test_processInco Assert.ok(engine.previousFailed.has("nojson2")); Assert.ok(engine.previousFailed.has("nodecrypt")); Assert.ok(engine.previousFailed.has("nodecrypt2")); // Ensure the observer was notified Assert.equal(observerData, engine.name); Assert.equal(observerSubject.applied, 2); Assert.equal(observerSubject.failed, 4); - } finally { await promiseClean(engine, server); } }); add_task(async function test_uploadOutgoing_toEmptyServer() { _("SyncEngine._uploadOutgoing uploads new records to server"); @@ -1074,17 +1059,16 @@ add_task(async function test_uploadOutgo Assert.equal(collection.payload("flying"), undefined); Assert.ok(!!collection.payload("scotsman")); Assert.equal(collection.cleartext("scotsman").id, "scotsman"); const changes = await engine._tracker.getChangedIDs(); Assert.equal(changes.scotsman, undefined); // The 'flying' record wasn't marked so it wasn't uploaded Assert.equal(collection.payload("flying"), undefined); - } finally { await cleanAndGo(engine, server); } }); async function test_uploadOutgoing_max_record_payload_bytes(allowSkippedRecord) { _("SyncEngine._uploadOutgoing throws when payload is bigger than max_record_payload_bytes"); let collection = new ServerCollection(); @@ -1128,17 +1112,16 @@ async function test_uploadOutgoing_max_r await engine.trackRemainingChanges(); // Check we uploaded the other record to the server Assert.ok(collection.payload("scotsman")); // And that we won't try to upload the huge record next time. const changes = await engine._tracker.getChangedIDs(); Assert.equal(changes.flying, undefined); - } catch (e) { if (allowSkippedRecord) { do_throw("should not get here"); } await engine.trackRemainingChanges(); // Check that we will try to upload the huge record next time @@ -1210,17 +1193,16 @@ add_task(async function test_uploadOutgo Assert.ok(!!collection.payload("flying")); changes = await engine._tracker.getChangedIDs(); Assert.equal(changes.flying, undefined); // The 'scotsman' and 'peppercorn' records couldn't be uploaded so // they weren't cleared from the tracker. Assert.equal(changes.scotsman, SCOTSMAN_CHANGED); Assert.equal(changes.peppercorn, PEPPERCORN_CHANGED); - } finally { await promiseClean(engine, server); } }); async function createRecordFailTelemetry(allowSkippedRecord) { Service.identity.username = "foo"; let collection = new ServerCollection(); @@ -1376,17 +1358,16 @@ add_task(async function test_syncFinish_ // The 'flying' and 'rekolok' records were deleted while the // 'scotsman' one wasn't. Assert.equal(collection.payload("flying"), undefined); Assert.ok(!!collection.payload("scotsman")); Assert.equal(collection.payload("rekolok"), undefined); // The deletion todo list has been reset. Assert.equal(engine._delete.ids, undefined); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_syncFinish_deleteLotsInBatches() { _("SyncEngine._syncFinish deletes server records in batches of 100 (list of record IDs)."); @@ -1415,17 +1396,16 @@ add_task(async function test_syncFinish_ let server = httpd_setup({ "/1.1/foo/storage/rotary": collection.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); try { - // Confirm initial environment Assert.equal(noOfUploads, 0); // Declare what we want to have deleted: all records no. 100 and // up and all records that are less than 200 mins old (which are // records 0 thru 90). engine._delete = {ids: [], newer: now / 1000 - 60 * 200.5}; @@ -1446,17 +1426,16 @@ add_task(async function test_syncFinish_ } } // The deletion was done in batches Assert.equal(noOfUploads, 2 + 1); // The deletion todo list has been reset. Assert.equal(engine._delete.ids, undefined); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_sync_partialUpload() { _("SyncEngine.sync() keeps changedIDs that couldn't be uploaded."); @@ -1523,17 +1502,16 @@ add_task(async function test_sync_partia // * records after the third batch and higher couldn't be uploaded because // we failed hard on the 3rd upload. if ((i == 23) || (i == 42) || (i >= 200)) { Assert.equal(changes[id], i); } else { Assert.equal(false, id in changes); } } - } finally { Service.serverConfiguration = oldServerConfiguration; await promiseClean(engine, server); } }); add_task(async function test_canDecrypt_noCryptoKeys() { _("SyncEngine.canDecrypt returns false if the engine fails to decrypt items on the server, e.g. due to a missing crypto key collection."); @@ -1548,19 +1526,17 @@ add_task(async function test_canDecrypt_ let server = sync_httpd_setup({ "/1.1/foo/storage/rotary": collection.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); try { - Assert.equal(false, (await engine.canDecrypt())); - } finally { await cleanAndGo(engine, server); } }); add_task(async function test_canDecrypt_true() { _("SyncEngine.canDecrypt returns true if the engine can decrypt the items on the server."); @@ -1573,23 +1549,20 @@ add_task(async function test_canDecrypt_ let server = sync_httpd_setup({ "/1.1/foo/storage/rotary": collection.handler(), }); await SyncTestingInfrastructure(server); let engine = makeRotaryEngine(); try { - Assert.ok((await engine.canDecrypt())); - } finally { await cleanAndGo(engine, server); } - }); add_task(async function test_syncapplied_observer() { const NUMBER_OF_RECORDS = 10; let engine = makeRotaryEngine(); // Create a batch of server side records.
--- a/services/sync/tests/unit/test_syncscheduler.js +++ b/services/sync/tests/unit/test_syncscheduler.js @@ -1051,13 +1051,12 @@ add_task(async function test_link_status Svc.Obs.notify("network:link-status-changed", null, "change"); equal(scheduler.scheduleNextSync.callCount, 0); Svc.Obs.notify("network:link-status-changed", null, "up"); equal(scheduler.scheduleNextSync.callCount, 1); Svc.Obs.notify("network:link-status-changed", null, "change"); equal(scheduler.scheduleNextSync.callCount, 1); - } finally { scheduler.scheduleNextSync.restore(); } });
--- a/services/sync/tests/unit/test_telemetry.js +++ b/services/sync/tests/unit/test_telemetry.js @@ -163,17 +163,16 @@ add_task(async function test_processInco }); equal(pingPayload.engines.length, 1); equal(pingPayload.engines[0].name, "bookmarks"); deepEqual(pingPayload.engines[0].failureReason, { name: "httperror", code: 500, }); - } finally { await store.wipe(); await cleanAndGo(engine, server); } }); add_task(async function test_uploading() { let engine = new BookmarksEngine(Service); @@ -205,17 +204,16 @@ add_task(async function test_uploading() await store.wipe(); await engine.resetClient(); ping = await sync_engine_and_validate_telem(engine, false); equal(ping.engines.length, 1); equal(ping.engines[0].name, "bookmarks"); equal(ping.engines[0].outgoing.length, 1); ok(!!ping.engines[0].incoming); - } finally { // Clean up. await store.wipe(); await cleanAndGo(engine, server); } }); add_task(async function test_upload_failed() { @@ -262,17 +260,16 @@ add_task(async function test_upload_fail changes = await engine._tracker.getChangedIDs(); _(`test_upload_failed: Rotary tracker contents at second sync: ${ JSON.stringify(changes)}`); ping = await sync_engine_and_validate_telem(engine, true); ok(!!ping); equal(ping.engines.length, 1); equal(ping.engines[0].incoming.reconciled, 1); deepEqual(ping.engines[0].outgoing, [{ sent: 2, failed: 2 }]); - } finally { await cleanAndGo(engine, server); await engine.finalize(); } }); add_task(async function test_sync_partialUpload() { let collection = new ServerCollection(); @@ -344,17 +341,16 @@ add_task(async function test_sync_partia equal(ping.engines[0].name, "rotary"); deepEqual(ping.engines[0].incoming, { failed: 1, newFailed: 1, reconciled: 232, }); ok(!ping.engines[0].outgoing); deepEqual(ping.engines[0].failureReason, uploadFailureError); - } finally { await cleanAndGo(engine, server); await engine.finalize(); } }); add_task(async function test_generic_engine_fail() { enableValidationPrefs(); @@ -623,17 +619,16 @@ add_task(async function test_discarding( let upd = helper.with_updated_collection; let telem = get_sync_test_telemetry(); telem.maxPayloadCount = 2; telem.submissionInterval = Infinity; let oldSubmit = telem.submit; let server; try { - let handlers = { "/1.1/johndoe/info/collections": helper.handler, "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()), }; let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"];
--- a/services/sync/tests/unit/test_uistate.js +++ b/services/sync/tests/unit/test_uistate.js @@ -91,17 +91,16 @@ add_task(async function test_refreshStat equal(state.displayName, undefined); equal(state.avatarURL, undefined); equal(state.lastSync, undefined); // only set when STATUS_SIGNED_IN. equal(state.syncing, false); UIStateInternal.fxAccounts = fxAccountsOrig; Services.prefs.clearUserPref("services.sync.lastSync"); Services.prefs.clearUserPref("services.sync.username"); - }); add_task(async function test_refreshState_signedin_profile_unavailable() { UIState.reset(); const fxAccountsOrig = UIStateInternal.fxAccounts; const now = new Date().toString(); Services.prefs.setCharPref("services.sync.lastSync", now);
--- a/services/sync/tps/extensions/tps/resource/tps.jsm +++ b/services/sync/tps/extensions/tps/resource/tps.jsm @@ -242,17 +242,16 @@ var TPS = { break; case "weave:service:tracking-stopped": this._isTracking = false; break; } } catch (e) { this.DumpError("Observer failed", e); - } }, /** * Given that we cannot completely disable the automatic sync operations, we * massively delay the next sync. Sync operations have to only happen when * directly called via TPS.Sync()! */ @@ -634,17 +633,16 @@ var TPS = { Logger.logError("Failed to sign out: " + Log.exceptionStr(e)); } }, /** * Use Sync's bookmark validation code to see if we've corrupted the tree. */ async ValidateBookmarks() { - let getServerBookmarkState = async () => { let bookmarkEngine = Weave.Service.engineManager.get("bookmarks"); let collection = bookmarkEngine.itemSource(); let collectionKey = bookmarkEngine.service.collectionKeys.keyForCollection(bookmarkEngine.name); collection.full = true; let items = []; let resp = await collection.get(); for (let json of resp.obj) {
--- a/taskcluster/docker/periodic-updates/.eslintrc.js +++ b/taskcluster/docker/periodic-updates/.eslintrc.js @@ -65,19 +65,16 @@ module.exports = { "no-unmodified-loop-condition": "error", // No expressions where a statement is expected "no-unused-expressions": "error", // Disallow unnecessary escape usage in strings and regular expressions. "no-useless-escape": "error", - // Disallow blank line padding within blocks. - "padded-blocks": ["error", "never"], - // Enforce spacing after semicolons. "semi-spacing": ["error", { "before": false, "after": true }], // Never use spaces before named function parentheses, but always for async // arrow functions. "space-before-function-paren": ["error", { "anonymous": "ignore", "asyncArrow": "always",
--- a/testing/marionette/accessibility.js +++ b/testing/marionette/accessibility.js @@ -93,17 +93,16 @@ accessibility.get = function(strict = fa /** * Component responsible for interacting with platform accessibility * API. * * Its methods serve as wrappers for testing content and chrome * accessibility as well as accessibility of user interactions. */ accessibility.Checks = class { - /** * @param {boolean} strict * Flag indicating whether the accessibility issue should be logged * or cause an error to be thrown. Default is to log to stdout. */ constructor(strict) { this.strict = strict; } @@ -435,10 +434,9 @@ accessibility.Checks = class { } if (element) { let {id, tagName, className} = element; message += `: id: ${id}, tagName: ${tagName}, className: ${className}`; } throw new ElementNotAccessibleError(message); } - };
--- a/testing/marionette/browser.js +++ b/testing/marionette/browser.js @@ -111,17 +111,16 @@ browser.getTabBrowser = function(window) /** * Creates a browsing context wrapper. * * Browsing contexts handle interactions with the browser, according to * the current environment (Firefox, Fennec). */ browser.Context = class { - /** * @param {ChromeWindow} win * ChromeWindow that contains the top-level browsing context. * @param {GeckoDriver} driver * Reference to driver instance. */ constructor(window, driver) { this.window = window; @@ -525,17 +524,16 @@ browser.Context = class { */ executeWhenReady(cb) { if (this._needsFlushPendingCommands) { this.pendingCommands.push(cb); } else { cb(); } } - }; /** * The window storage is used to save outer window IDs mapped to weak * references of Window objects. * * Usage: * @@ -543,17 +541,16 @@ browser.Context = class { * wins.set(browser.outerWindowID, window); * * ... * * let win = wins.get(browser.outerWindowID); * */ browser.Windows = class extends Map { - /** * Save a weak reference to the Window object. * * @param {string} id * Outer window ID. * @param {Window} win * Window object to save. * @@ -580,17 +577,16 @@ browser.Windows = class extends Map { */ get(id) { let wref = super.get(id); if (!wref) { throw new RangeError(); } return wref.get(); } - }; /** * Marionette representation of the {@link ChromeWindow} window state. * * @enum {string} */ const WindowState = {
--- a/testing/marionette/driver.js +++ b/testing/marionette/driver.js @@ -973,17 +973,16 @@ GeckoDriver.prototype.execute_ = async f args = [], { sandboxName = null, newSandbox = false, file = "", line = 0, async = false, } = {}) { - assert.open(this.getCurrentWindow()); await this._handleUserPrompts(); assert.string(script, pprint`Expected "script" to be a string: ${script}`); assert.array(args, pprint`Expected script args to be an array: ${args}`); if (sandboxName !== null) { assert.string(sandboxName, pprint`Expected sandbox name to be a string: ${sandboxName}`); } @@ -1590,17 +1589,16 @@ GeckoDriver.prototype.setWindowHandle = } this.startBrowser(winProperties.win, false /* isNewSession */); if (registerBrowsers && browserListening) { await registerBrowsers; await browserListening; } - } else { // Otherwise switch to the known chrome window this.curBrowser = this.browsers[winProperties.outerId]; this.mainFrame = this.curBrowser.window; this.curFrame = null; // .. and activate the tab if it's a content browser. if ("tabIndex" in winProperties) { @@ -1809,17 +1807,16 @@ GeckoDriver.prototype.switchToFrame = as if (focus) { this.curFrame.focus(); } checkTimer.initWithCallback( checkLoad.bind(this), 100, Ci.nsITimer.TYPE_ONE_SHOT); } else { throw new NoSuchFrameError(`Unable to locate frame: ${id}`); } - } else if (this.context == Context.Content) { cmd.commandID = cmd.id; await this.listener.switchToFrame(cmd.parameters); } }; GeckoDriver.prototype.getTimeouts = function() { return this.timeouts;
--- a/testing/marionette/element.js +++ b/testing/marionette/element.js @@ -762,17 +762,16 @@ element.isSelected = function(el) { } if (element.isXULElement(el)) { if (XUL_CHECKED_ELS.has(el.tagName)) { return el.checked; } else if (XUL_SELECTED_ELS.has(el.tagName)) { return el.selected; } - } else if (element.isDOMElement(el)) { if (el.localName == "input" && ["checkbox", "radio"].includes(el.type)) { return el.checked; } else if (el.localName == "option") { return el.selected; } } @@ -954,17 +953,16 @@ element.isEditable = function(el) { * @return {Object.<string, number>} * X- and Y coordinates. * * @throws TypeError * If <var>xOffset</var> or <var>yOffset</var> are not numbers. */ element.coordinates = function( node, xOffset = undefined, yOffset = undefined) { - let box = node.getBoundingClientRect(); if (typeof xOffset == "undefined" || xOffset === null) { xOffset = box.width / 2.0; } if (typeof yOffset == "undefined" || yOffset === null) { yOffset = box.height / 2.0; }
--- a/testing/marionette/event.js +++ b/testing/marionette/event.js @@ -774,17 +774,16 @@ function expectEvent_(expectedTarget, ex /* eslint-disable no-restricted-globals */ /** * Check if the event was fired or not. The provided event handler will * be removed. */ function checkExpectedEvent_( expectedTarget, expectedEvent, eventHandler, testName) { - if (eventHandler) { let expectEvent = (expectedEvent.charAt(0) != "!"); let type = expectEvent; if (!type) { type = expectedEvent.substring(1); } expectedTarget.removeEventListener(type, eventHandler); @@ -822,17 +821,16 @@ function checkExpectedEvent_( * @param {string} testName * Test name when outputing results. * @param {Window} win * Window object. */ event.synthesizeMouseExpectEvent = function( target, offsetX, offsetY, ev, expectedTarget, expectedEvent, testName, win) { - let eventHandler = expectEvent_( expectedTarget, expectedEvent, testName); event.synthesizeMouse(target, offsetX, offsetY, ev, win); checkExpectedEvent_( expectedTarget, expectedEvent,
--- a/testing/marionette/interaction.js +++ b/testing/marionette/interaction.js @@ -482,17 +482,16 @@ interaction.isKeyboardInteractable = fun * If `path` doesn't exist. */ interaction.uploadFiles = async function(el, paths) { let files = []; if (el.hasAttribute("multiple")) { // for multiple file uploads new files will be appended files = Array.prototype.slice.call(el.files); - } else if (paths.length > 1) { throw new InvalidArgumentError( pprint`Element ${el} doesn't accept multiple files`); } for (let path of paths) { let file;
--- a/testing/marionette/listener.js +++ b/testing/marionette/listener.js @@ -140,17 +140,16 @@ const loadListener = { if (waitForUnloaded) { addEventListener("beforeunload", this, true); addEventListener("hashchange", this, true); addEventListener("pagehide", this, true); addEventListener("popstate", this, true); addEventListener("unload", this, true); Services.obs.addObserver(this, "outer-window-destroyed"); - } else { // The frame script has been moved to a differnt content process. // Due to the time it takes to re-register the browser in Marionette, // it can happen that page load events are missed before the listeners // are getting attached again. By checking the document readyState the // command can return immediately if the page load is already done. let readyState = content.document.readyState; let documentURI = content.document.documentURI; @@ -264,17 +263,16 @@ const loadListener = { let finished = false; switch (readyState) { case "interactive": if (documentURI.startsWith("about:certerror")) { this.stop(); sendError(new InsecureCertificateError(), this.commandID); finished = true; - } else if (/about:.*(error)\?/.exec(documentURI)) { this.stop(); sendError(new UnknownError(`Reached error page: ${documentURI}`), this.commandID); finished = true; // Return early with a page load strategy of eager, and also // special-case about:blocked pages which should be treated as @@ -391,43 +389,40 @@ const loadListener = { * @param {boolean=} loadEventExpected * Optional flag, which indicates that navigate has to wait for the page * finished loading. * @param {string=} url * Optional URL, which is used to check if a page load is expected. */ navigate(trigger, commandID, timeout, loadEventExpected = true, useUnloadTimer = false) { - // Only wait if the page load strategy is not `none` loadEventExpected = loadEventExpected && (capabilities.get("pageLoadStrategy") !== PageLoadStrategy.None); if (loadEventExpected) { let startTime = new Date().getTime(); this.start(commandID, timeout, startTime, true); } return (async () => { await trigger(); - })().then(() => { if (!loadEventExpected) { sendOk(commandID); return; } // If requested setup a timer to detect a possible page load if (useUnloadTimer) { this.timerPageUnload = Cc["@mozilla.org/timer;1"] .createInstance(Ci.nsITimer); this.timerPageUnload.initWithCallback( this, 200, Ci.nsITimer.TYPE_ONE_SHOT); } - }).catch(err => { if (loadEventExpected) { this.stop(); } sendError(err, commandID); }); }, @@ -1038,17 +1033,16 @@ function get(msg) { // We need to move to the top frame before navigating sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); curContainer.frame = content; loadListener.navigate(() => { curContainer.frame.location = url; }, commandID, pageTimeout, loadEventExpected); - } catch (e) { sendError(e, commandID); } } /** * Cause the browser to traverse one step backward in the joint history * of the current browsing context. @@ -1062,17 +1056,16 @@ function get(msg) { */ function goBack(msg) { let {commandID, pageTimeout} = msg.json; try { loadListener.navigate(() => { curContainer.frame.history.back(); }, commandID, pageTimeout); - } catch (e) { sendError(e, commandID); } } /** * Cause the browser to traverse one step forward in the joint history * of the current browsing context. @@ -1086,17 +1079,16 @@ function goBack(msg) { */ function goForward(msg) { let {commandID, pageTimeout} = msg.json; try { loadListener.navigate(() => { curContainer.frame.history.forward(); }, commandID, pageTimeout); - } catch (e) { sendError(e, commandID); } } /** * Causes the browser to reload the page in in current top-level browsing * context. @@ -1114,17 +1106,16 @@ function refresh(msg) { try { // We need to move to the top frame before navigating sendSyncMessage("Marionette:switchedToFrame", {frameValue: null}); curContainer.frame = content; loadListener.navigate(() => { curContainer.frame.location.reload(true); }, commandID, pageTimeout); - } catch (e) { sendError(e, commandID); } } /** * Get source of the current browsing context's DOM. */
--- a/testing/marionette/packets.js +++ b/testing/marionette/packets.js @@ -154,17 +154,16 @@ Object.defineProperty(JSONPacket.prototy this._object = object; let data = JSON.stringify(object); this._data = unicodeConverter.ConvertFromUnicode(data); this.length = this._data.length; }, }); JSONPacket.prototype.read = function(stream, scriptableStream) { - // Read in more packet data. this._readData(stream, scriptableStream); if (!this.done) { // Don't have a complete packet yet. return; } @@ -187,17 +186,16 @@ JSONPacket.prototype._readData = functio let bytesToRead = Math.min( this.length - this._data.length, stream.available()); this._data += scriptableStream.readBytes(bytesToRead); this._done = this._data.length === this.length; }; JSONPacket.prototype.write = function(stream) { - if (this._outgoing === undefined) { // Format the serialized packet to a buffer this._outgoing = this.length + ":" + this._data; } let written = stream.write(this._outgoing, this._outgoing.length); this._outgoing = this._outgoing.slice(written); this._done = !this._outgoing.length;
--- a/testing/marionette/reftest.js +++ b/testing/marionette/reftest.js @@ -223,17 +223,16 @@ max-width: ${width}px; max-height: ${hei * Test timeout in milliseconds. * * @return {Object} * Result object with fields status, message and extra. */ async run(testUrl, references, expected, timeout, width = DEFAULT_REFTEST_WIDTH, height = DEFAULT_REFTEST_HEIGHT) { - let timeoutHandle; let timeoutPromise = new Promise(resolve => { timeoutHandle = this.parentWindow.setTimeout(() => { resolve({status: STATUS.TIMEOUT, message: null, extra: {}}); }, timeout); }); @@ -345,17 +344,16 @@ max-width: ${width}px; max-height: ${hei let cacheKey = width + "x" + height; let canvasPool = this.canvasCache.get(cacheKey).get(null); [comparison.lhs, comparison.rhs].map(screenshot => { if (screenshot !== null && screenshot.reuseCanvas) { canvasPool.push(screenshot.canvas); } }); logger.debug(`Canvas pool (${cacheKey}) is of length ${canvasPool.length}`); - } if (screenshotData.length) { // For now the tbpl formatter only accepts one screenshot, so just // return the last one we took. let lastScreenshot = screenshotData[screenshotData.length - 1]; // eslint-disable-next-line camelcase result.extra.reftest_screenshots = lastScreenshot; @@ -398,18 +396,16 @@ max-width: ${width}px; max-height: ${hei `maximum difference per channel ${maxDifferences.value}`); } break; case "!=": passed = !passed; break; default: throw new InvalidArgumentError("Reftest operator should be '==' or '!='"); - - } } return {lhs, rhs, passed, error}; } isAcceptableDifference(maxDifference, pixelsDifferent, allowed) { if (!allowed) { logger.info(`No differences allowed`);
--- a/testing/marionette/server.js +++ b/testing/marionette/server.js @@ -87,17 +87,16 @@ class TCPListener { throw new Error(`Could not bind to port ${this.port} (${e.name})`); } this.port = this.socket.port; this.socket.asyncListen(this); logger.info(`Listening on port ${this.port}`); } - } else if (this.socket) { // Note that closing the server socket will not close currently active // connections. this.socket.close(); this.socket = null; logger.info(`Stopped listening on port ${this.port}`); } }
--- a/testing/marionette/sync.js +++ b/testing/marionette/sync.js @@ -155,17 +155,16 @@ function PollPromise(func, {timeout = nu }).catch(reject); }; // the repeating slack timer waits |interval| // before invoking |evalFn| evalFn(); timer.init(evalFn, interval, TYPE_REPEATING_SLACK); - }).then(res => { timer.cancel(); return res; }, err => { timer.cancel(); throw err; }); } @@ -228,17 +227,16 @@ function TimedPromise(fn, timer.initWithCallback({notify: bail}, timeout, TYPE_ONE_SHOT); try { fn(resolve, reject); } catch (e) { reject(e); } - }).then(res => { timer.cancel(); return res; }, err => { timer.cancel(); throw err; }); }
--- a/testing/marionette/test/unit/test_action.js +++ b/testing/marionette/test/unit/test_action.js @@ -181,17 +181,16 @@ add_test(function test_processPointerMov equal(actual.x, expected.x); equal(actual.y, expected.y); let origin = expected.origin; if (typeof origin == "undefined") { origin = action.PointerOrigin.Viewport; } deepEqual(actual.origin, origin); - } run_next_test(); }); add_test(function test_computePointerDestinationViewport() { let act = {type: "pointerMove", x: 100, y: 200, origin: "viewport"}; let inputState = new action.InputState.Pointer(action.PointerType.Mouse); // these values should not affect the outcome
--- a/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm +++ b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm @@ -338,17 +338,16 @@ var BrowserTestUtils = { function isWanted(url) { if (!wantLoad) { return true; } else if (typeof(wantLoad) == "function") { return wantLoad(url); } // It's a string. return wantLoad == url; - } return new Promise(resolve => { let mm = browser.ownerGlobal.messageManager; let eventName = maybeErrorPage ? "browser-test-utils:DOMContentLoadedEvent" : "browser-test-utils:loadEvent"; mm.addMessageListener(eventName, function onLoad(msg) { @@ -1579,17 +1578,16 @@ var BrowserTestUtils = { waitForAttribute(attr, element, value) { let MutationObserver = element.ownerGlobal.MutationObserver; return new Promise(resolve => { let mut = new MutationObserver(mutations => { if ((!value && element.getAttribute(attr)) || (value && element.getAttribute(attr) === value)) { resolve(); mut.disconnect(); - } }); mut.observe(element, {attributeFilter: [attr]}); }); }, /**
--- a/testing/mochitest/browser-test.js +++ b/testing/mochitest/browser-test.js @@ -121,17 +121,16 @@ function testInit() { getService(Ci.nsIEnvironment). get("TEST_SUITE"); if (testSuite == "browser-chrome-instrumentation") { takeInstrumentation(); } } function takeInstrumentation() { - let instrumentData = { elements: {}, }; function pad(str, length) { if (str.length >= length) return str; @@ -1122,17 +1121,16 @@ Tester.prototype = { } currentTest.addResult(new testResult({ name: "Uncaught exception", pass: this.SimpleTest.isExpectingUncaughtException(), ex, stack: (typeof ex == "object" && "stack" in ex) ? ex.stack : null, allowFailure: currentTest.allowFailure, })); - } PromiseTestUtils.assertNoUncaughtRejections(); this.SimpleTest.info("Leaving test " + task.name); } this.finish(); }).call(currentScope); } else if (typeof scope.test == "function") { scope.test();
--- a/testing/mochitest/chrome-harness.js +++ b/testing/mochitest/chrome-harness.js @@ -48,17 +48,16 @@ function getResolvedURI(url) { * the input URI into a nsIFile (actually the directory containing the * file). This can be used for copying or referencing the file or extra files * required by the test. Usually we need to load a secondary html file or library * and this will give us file system access to that. * * resolvedURI: nsIURI (from getResolvedURI) that points to a file:/// url */ function getChromeDir(resolvedURI) { - var fileHandler = Cc["@mozilla.org/network/protocol;1?name=file"]. getService(Ci.nsIFileProtocolHandler); var chromeDir = fileHandler.getFileFromURLSpec(resolvedURI.spec); return chromeDir.parent.QueryInterface(Ci.nsIFile); } // used by tests to determine their directory based off window.location.path function getRootDirectory(path, chromeURI) { @@ -72,17 +71,16 @@ function getRootDirectory(path, chromeUR mydir += "/"; } return chromeURI.prePath + mydir; } // used by tests to determine their directory based off window.location.path function getChromePrePath(path, chromeURI) { - if (chromeURI === undefined) { chromeURI = getChromeURI(path); } return chromeURI.prePath; } /* @@ -246,10 +244,9 @@ function getTestList(params, callback) { } else if (params[p] == 0) { config[p] = false; } else { config[p] = params[p]; } } params = config; getTestManifest("http://mochi.test:8888/" + params.manifestFile, params, callback); - }
--- a/testing/mochitest/server.js +++ b/testing/mochitest/server.js @@ -482,17 +482,16 @@ function linksToListItems(links) { } if ((bug_title == null) || (bug_num == null)) { response += LI({class: classVal}, A({href: link}, link), children); } else { var bug_url = "https://bugzilla.mozilla.org/show_bug.cgi?id=" + bug_num; response += LI({class: classVal}, A({href: link}, link), " - ", A({href: bug_url}, "Bug " + bug_num), children); } - } return response; } /** * Transform nested hashtables of paths to a flat table rows. */ function linksToTableRows(links, recursionLevel) {
--- a/testing/modules/Assert.jsm +++ b/testing/modules/Assert.jsm @@ -62,17 +62,16 @@ function replacer(key, value) { const kTruncateLength = 128; function truncate(text, newLength = kTruncateLength) { if (typeof text == "string") { return text.length < newLength ? text : text.slice(0, newLength); } return text; - } function getMessage(error, prefix = "") { let actual, expected; // Wrap calls to JSON.stringify in try...catch blocks, as they may throw. If // so, fall back to toString(). try { actual = JSON.stringify(error.actual, replacer);
--- a/testing/modules/CoverageUtils.jsm +++ b/testing/modules/CoverageUtils.jsm @@ -58,17 +58,16 @@ CoverageCollector.prototype._getLinesCov let key = [lineNumber, columnNumber, offset].join("#"); if (!currentCoverage[scriptName][key]) { currentCoverage[scriptName][key] = count; } else { currentCoverage[scriptName][key] += count; } }); - }); // Covered lines are determined by comparing every offset mentioned as of the // the completion of a test to the last time we measured coverage. If an // offset in a line is novel as of this test, or a count has increased for // any offset on a particular line, that line must have been covered. for (let scriptName in currentCoverage) { for (let key in currentCoverage[scriptName]) {
--- a/testing/modules/StructuredLog.jsm +++ b/testing/modules/StructuredLog.jsm @@ -35,17 +35,16 @@ var StructuredLogger = function(name, du StructuredLogger.prototype = { testStart(test) { var data = {test: this._testId(test)}; this._logData("test_start", data); }, testStatus(test, subtest, status, expected = "PASS", message = null, stack = null, extra = null) { - if (subtest === null || subtest === undefined) { // Fix for assertions that don't pass in a name subtest = "undefined assertion name"; } var data = { test: this._testId(test), subtest, @@ -237,17 +236,16 @@ StructuredFormatter.prototype = { test_status(message) { var statusInfo = message.test + " | " + message.subtest + (message.message ? " | " + message.message : ""); if (message.expected) { return "TEST-UNEXPECTED-" + message.status + " | " + statusInfo + " - expected: " + message.expected; } return "TEST-" + message.status + " | " + statusInfo; - }, test_end(message) { var startTime = this.testStartTimes[message.test]; delete this.testStartTimes[message.test]; var statusInfo = message.test + (message.message ? " | " + String(message.message) : ""); var result; if (message.expected) {
--- a/testing/mozbase/mozlog/mozlog/formatters/html/main.js +++ b/testing/mozbase/mozlog/mozlog/formatters/html/main.js @@ -58,17 +58,16 @@ addEventListener("DOMContentLoaded", fun elem.addEventListener("click", function(event) { toggle_sort_states(elem); var colIndex = toArray(elem.parentNode.childNodes).indexOf(elem); var key = elem.classList.contains("numeric") ? key_num : key_alpha; sort_table(elem, key(colIndex)); }); }); - }); function sort_table(clicked, key_func) { one_row_for_data(); var rows = find_all(".results-table-row"); var reversed = !clicked.classList.contains("asc"); var sorted_rows = sort(rows, key_func, reversed);
--- a/testing/raptor/webext/raptor/measure.js +++ b/testing/raptor/webext/raptor/measure.js @@ -158,17 +158,16 @@ function measureHero() { obs.observe(el); }); } catch (err) { console.log(err); } } else { console.log("couldn't find hero element"); } - } function measureFNBPaint() { var x = window.performance.timing.timeToNonBlankPaint; if (typeof(x) == "undefined") { console.log("ERROR: timeToNonBlankPaint is undefined; ensure the pref is enabled"); return;
--- a/testing/raptor/webext/raptor/runner.js +++ b/testing/raptor/webext/raptor/runner.js @@ -65,17 +65,16 @@ var results = {"name": "", "type": "", "lower_is_better": true, "alert_threshold": 2.0, "measurements": {}}; function getTestSettings() { console.log("getting test settings from control server"); return new Promise(resolve => { - fetch(settingsURL).then(function(response) { response.text().then(function(text) { console.log(text); settings = JSON.parse(text)["raptor-options"]; // parse the test settings testType = settings.type; pageCycles = settings.page_cycles; @@ -347,17 +346,16 @@ async function nextCycle() { postToControlServer("status", text); // start the profiler if enabled if (geckoProfiling) { await startGeckoProfiling(); } } if (pageCycle <= pageCycles) { setTimeout(function() { - let text = "begin pagecycle " + pageCycle; postToControlServer("status", text); // set page timeout alarm setTimeoutAlarm("raptor-page-timeout", pageTimeout); if (testType == "pageload") { if (getHero) {
--- a/testing/specialpowers/content/MockPermissionPrompt.jsm +++ b/testing/specialpowers/content/MockPermissionPrompt.jsm @@ -59,17 +59,16 @@ var MockPermissionPrompt = { function MockPermissionPromptInstance() { } MockPermissionPromptInstance.prototype = { QueryInterface: ChromeUtils.generateQI([Ci.nsIContentPermissionPrompt]), promptResult: Ci.nsIPermissionManager.UNKNOWN_ACTION, prompt(request) { - let perms = request.types.QueryInterface(Ci.nsIArray); for (let idx = 0; idx < perms.length; idx++) { let perm = perms.queryElementAt(idx, Ci.nsIContentPermissionType); if (Services.perms.testExactPermissionFromPrincipal( request.principal, perm.type) != Ci.nsIPermissionManager.ALLOW_ACTION) { request.cancel(); return; }
--- a/testing/specialpowers/content/specialpowersAPI.js +++ b/testing/specialpowers/content/specialpowersAPI.js @@ -131,17 +131,16 @@ function doApply(fun, invocant, args) { // clamping for Xrayed DOM objects reached from literals, so passing things // like {l : xoWin.location} won't work. Hopefully the rabbit hole doesn't // go that deep. args = args.map(x => isObjectOrArray(x) ? Cu.waiveXrays(x) : x); return Reflect.apply(fun, invocant, args); } function wrapPrivileged(obj) { - // Primitives pass straight through. if (!isWrappable(obj)) return obj; // No double wrapping. if (isWrapper(obj)) throw "Trying to double-wrap object!"; @@ -150,17 +149,16 @@ function wrapPrivileged(obj) { dummy = function() {}; else dummy = Object.create(null); return new Proxy(dummy, new SpecialPowersHandler(obj)); } function unwrapPrivileged(x) { - // We don't wrap primitives, so sometimes we have a primitive where we'd // expect to have a wrapper. The proxy pretends to be the type that it's // emulating, so we can just as easily check isWrappable() on a proxy as // we can on an unwrapped object. if (!isWrappable(x)) return x; // If we have a wrappable type, make sure it's wrapped. @@ -639,17 +637,16 @@ SpecialPowersAPI.prototype = { return this.wrap(chromeScript); }, importInMainProcess(importString) { var message = this._sendSyncMessage("SPImportInMainProcess", importString)[0]; if (message.hadError) { throw "SpecialPowers.importInMainProcess failed with error " + message.errorMessage; } - }, get Services() { return wrapPrivileged(Services); }, /* * A getter for the privileged Components object we have.
--- a/testing/talos/talos/pageloader/chrome/pageloader.js +++ b/testing/talos/talos/pageloader/chrome/pageloader.js @@ -225,17 +225,16 @@ function plInit() { if (useFNBPaint) { content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_fnbpaint.js", false, true); } else if (useMozAfterPaint) { content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_moz.js", false, true); } else if (useHero) { content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_hero.js", false, true); } else { content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/lh_dummy.js", false, true); - } content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/talos-content.js", false); content.selectedBrowser.messageManager.loadFrameScript("resource://talos-powers/TalosContentProfiler.js", false, true); content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/tscroll.js", false, true); content.selectedBrowser.messageManager.loadFrameScript("chrome://pageloader/content/Profiler.js", false, true); // Ensure that any webextensions that need to do setup have a chance // to do so. e.g. the 'tps' talos test registers a about:tabswitch @@ -602,17 +601,16 @@ function plLoadHandler(evt) { return; content.removeEventListener("load", plLoadHandler, true); setTimeout(waitForPainted, 0); } // This is called after we have received a load event, now we wait for painted function waitForPainted() { - var utils = gPaintWindow.windowUtils; if (!utils.isMozAfterPaintPending || !useMozAfterPaint) { _loadHandler(); return; } if (!gPaintListener)
--- a/testing/talos/talos/pageloader/chrome/report.js +++ b/testing/talos/talos/pageloader/chrome/report.js @@ -51,17 +51,16 @@ Report.prototype.pageNames = function() var retval = []; for (var page in this.timeVals) { retval.push(page); } return retval; }; Report.prototype.getReport = function() { - var report; var pages = this.pageNames(); var prefixLen = findCommonPrefixLength(pages); report = "__start_tp_report\n"; report += "_x_x_mozilla_page_load\n"; report += "_x_x_mozilla_page_load_details\n"; report += "|i|pagename|runs|\n"; @@ -86,17 +85,16 @@ Report.prototype.getReport = function() } var now = (new Date()).getTime(); // eslint-disable-line mozilla/avoid-Date-timing report += "__startTimestamp" + now + "__endTimestamp\n"; // timestamp for determning shutdown time, used by talos return report; }; Report.prototype.getReportSummary = function() { - function average(arr) { var sum = 0; for (var i in arr) sum += arr[i]; return sum / (arr.length || 1); } function median(arr) {
--- a/testing/talos/talos/pageloader/chrome/tscroll.js +++ b/testing/talos/talos/pageloader/chrome/tscroll.js @@ -229,17 +229,16 @@ function testScroll(target, stepSize, op var handle = -1; startFrameTimeRecording(function(rv) { handle = rv; }); // Get the measurements after APZ_MEASURE_MS of scrolling setTimeout(function() { - stopFrameTimeRecording(handle, function(intervals) { function average(arr) { var sum = 0; for (var i = 0; i < arr.length; i++) sum += arr[i]; return arr.length ? sum / arr.length : 0; }
--- a/testing/talos/talos/scripts/xpigen.js +++ b/testing/talos/talos/scripts/xpigen.js @@ -6,17 +6,16 @@ /* eslint-disable no-nested-ternary */ // base: relative or absolute path (http[s] or file, untested with ftp) // files: array of file names relative to base to include at the zip // callbacks: object with optional functions: // onsuccess(result), onerror(exception), onprogress(percentage) function createXpiDataUri(base, files, callbacks) { - // Synchronous XHR for http[s]/file (untested ftp), throws on any error // Note that on firefox, file:// XHR can't access files outside base dir function readBinFile(url) { var r = new XMLHttpRequest(); r.open("GET", url, false); r.requestType = "arraybuffer"; r.overrideMimeType("text/plain; charset=x-user-defined"); try { r.send(); } catch (e) { throw "FileNotRetrieved: " + url + " - " + e; } @@ -63,13 +62,12 @@ function createXpiDataUri(base, files, c for (var i = 0; i < files.length; i++) { zip.file(files[i], readBinFile(base + files[i]), {binary: true, compression: "deflate"}); onprogress(100 * (i + 1) / (files.length + 1)); } zip = zip.generate({type: "uint8array"}); onprogress(100); setTimeout(onsuccess, 0, "data:application/x-xpinstall;base64," + base64EncArr(zip)); - } catch (e) { setTimeout(onerror, 0, e); } }
--- a/testing/talos/talos/talos-powers/content/TalosContentProfiler.js +++ b/testing/talos/talos/talos-powers/content/TalosContentProfiler.js @@ -10,17 +10,16 @@ * * This file can be loaded directly into a test page, or can be loaded * as a frame script into a browser by the parent process. */ var TalosContentProfiler; (function() { - // Whether or not this TalosContentProfiler object has had initFromObject // or initFromURLQueryParams called on it. Any functions that will send // events to the parent to change the behaviour of the Gecko Profiler // should only be called after calling either initFromObject or // initFromURLQueryParams. var initted = false; // The subtest name that beginTest() was called with.
--- a/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm +++ b/testing/talos/talos/talos-powers/content/TalosParentProfiler.jsm @@ -136,17 +136,16 @@ const TalosParentProfiler = { if (this.initted) { let profileFile = this.profileDir + "/" + this.currentTest + ".profile"; return this.TalosPowers.profilerFinish(profileFile); } let msg = "You should not call finishTest without having first " + "initted the Profiler"; console.error(msg); return Promise.reject(msg); - }, /** * A start-up test has finished. Callers don't need to run beginTest or * finishTest, but should pause the sampler as soon as possible, and call * this function to dump the profile. * * @returns Promise
--- a/testing/talos/talos/talos-powers/content/TalosPowersContent.js +++ b/testing/talos/talos/talos-powers/content/TalosPowersContent.js @@ -118,10 +118,9 @@ var TalosPowersParent; listeningTo: replyEvent, }, }) ); }, }; // End of possibly embedded code - })();
--- a/testing/talos/talos/tests/tabswitch/api.js +++ b/testing/talos/talos/tests/tabswitch/api.js @@ -53,17 +53,16 @@ function loadTabs(gBrowser, urls) { "nsISupportsWeakReference"]), onStateChange(aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) { let loadedState = Ci.nsIWebProgressListener.STATE_STOP | Ci.nsIWebProgressListener.STATE_IS_NETWORK; if ((aStateFlags & loadedState) == loadedState && !aWebProgress.isLoadingDocument && aWebProgress.isTopLevel && Components.isSuccessCode(aStatus)) { - dump(`Loaded: ${aBrowser.currentURI.spec}\n`); waitingToLoad.delete(aBrowser.currentURI.spec); if (!waitingToLoad.size) { gBrowser.removeTabsProgressListener(listener); dump("Loads complete - starting tab switches\n"); resolve(); }
--- a/testing/talos/talos/tests/tart/addon/content/tart.js +++ b/testing/talos/talos/tests/tart/addon/content/tart.js @@ -245,17 +245,16 @@ Tart.prototype = { Profiler.pause(name); } else { Profiler.mark("End: " + (isReportResult ? name : "[warmup]"), true); } if (self.USE_RECORDING_API) { var paints = {}; return window.windowUtils .stopFrameTimeRecording(recordingHandle, paints); - } _abortRecording = true; return _recording.slice(0); // clone } function addResult(intervals) { @@ -352,17 +351,16 @@ Tart.prototype = { trigger(function() { timeoutId = setTimeout(transEnd, 3000); recordingHandle = startRecord(); triggerFunc(); // also chooses detector detector = self._endDetection; detector.arm(transEnd, self._win); }); }, preWaitMs); - }, _nextCommandIx: 0, _commands: [], _onSequenceComplete: 0, _nextCommand() { if (this._nextCommandIx >= this._commands.length) { @@ -410,17 +408,16 @@ Tart.prototype = { this._win.gBrowser.selectedTab = this._tartTab; if (this._onTestComplete) { this._onTestComplete(JSON.parse(JSON.stringify(this._results))); // Clone results } }, _startTest() { - // Save prefs and states which will change during the test, to get restored when done. var origPreload = Services.prefs.getBoolPref("browser.newtab.preload"); var origDpi = Services.prefs.getCharPref("layout.css.devPixelsPerPx"); var origPinned = this._tartTab.pinned; var self = this; var animate = this._animate.bind(this); var addTab = this.clickNewTab.bind(this);
--- a/testing/talos/talos/tests/tart/tart.html +++ b/testing/talos/talos/tests/tart/tart.html @@ -293,17 +293,16 @@ addEventListener("load", init); Utilities: <a href="blank.icon.html">blank with icon</a> <a href="about:config?filter=/newtab|_rate|devP|offmain|docshell.event_starvation_delay_hint|rce-en/">about:config (already filtered with relevant prefs)</a> <br/><br/> <b>Configure TART</b> (CTRL-F5 to reset to talos defaults) <button type="button" onclick="deselectAll()">Deselect all tests</button><br/> <script> for (var test in defaultConfig.subtests) { - // eslint-disable-next-line no-unsanitized/method document.write('<input type="checkbox" id="subtest-' + test + '" ' + (defaultConfig.subtests[test] ? "" : "un") + "checked>" + test + "</input>" + '<span style="color:grey"> ' + testsInfo[test] + "</span>" + "<br/>"); } $("subtest-simple3open3closeDpiCurrent").checked = false; // Disabled by default for talos </script>
--- a/toolkit/components/aboutmemory/content/aboutMemory.js +++ b/toolkit/components/aboutmemory/content/aboutMemory.js @@ -539,17 +539,16 @@ function updateAboutMemoryFromReporters( let displayReports = function() { updateTitleMainAndFooter("live measurement", "", NO_TIMESTAMP, SHOW_FOOTER); updateAboutMemoryFromCurrentData(); }; gMgr.getReports(handleReport, null, displayReports, null, gAnonymize.checked); - } catch (ex) { handleException(ex); } } // Increment this if the JSON format changes. // let gCurrentFileFormatVersion = 1; @@ -688,17 +687,16 @@ function loadMemoryReportsFromFile(aFile }, null); let file = new nsFile(aFilename); let fileChan = NetUtil.newChannel({ uri: Services.io.newFileURI(file), loadUsingSystemPrincipal: true, }); fileChan.asyncOpen2(converter); - } catch (ex) { handleException(ex); } } /** * Like updateAboutMemoryFromReporters(), but gets its data from a file instead * of the memory reporters. @@ -1351,17 +1349,16 @@ function fillInTree(aRoot) { delete aT._kids; } aT._amount = kidBytes; aT._description = kid._description; if (kid._nMerged !== undefined) { aT._nMerged = kid._nMerged; } assert(!aT._hideKids && !kid._hideKids, "_hideKids set when merging"); - } else { // Non-leaf node with multiple children. Derive its _amount and // _description entirely from its children... let kidsBytes = 0; for (let kid of aT._kids) { kidsBytes += fillInNonLeafNodes(kid); } @@ -1519,23 +1516,21 @@ function appendWarningElements(aP, aHasK // These warnings may not make sense if the reporters they reference have been // filtered out, so just skip them if we have a filter applied. if (!aFiltered && !aHasKnownHeapAllocated && !aHasMozMallocUsableSize) { appendElementWithText(aP, "p", "", "WARNING: the 'heap-allocated' memory reporter and the " + "moz_malloc_usable_size() function do not work for this platform " + "and/or configuration. This means that 'heap-unclassified' is not " + "shown and the 'explicit' tree shows much less memory than it should.\n\n"); - } else if (!aFiltered && !aHasKnownHeapAllocated) { appendElementWithText(aP, "p", "", "WARNING: the 'heap-allocated' memory reporter does not work for this " + "platform and/or configuration. This means that 'heap-unclassified' " + "is not shown and the 'explicit' tree shows less memory than it should.\n\n"); - } else if (!aFiltered && !aHasMozMallocUsableSize) { appendElementWithText(aP, "p", "", "WARNING: the moz_malloc_usable_size() function does not work for " + "this platform and/or configuration. This means that much of the " + "heap-allocated memory is not measured by individual memory reporters " + "and so will fall under 'heap-unclassified'.\n\n"); } @@ -1887,24 +1882,22 @@ function toggle(aEvent) { } } function expandPathToThisElement(aElement) { if (aElement.classList.contains("kids")) { // Unhide the kids. aElement.classList.remove("hidden"); expandPathToThisElement(aElement.previousSibling); // hasKids - } else if (aElement.classList.contains("hasKids")) { // Change the separator to '--'. let sepSpan = aElement.childNodes[2]; assertClassListContains(sepSpan, "mrSep"); sepSpan.textContent = kShowKidsSep; expandPathToThisElement(aElement.parentNode); // kids or pre.entries - } else { assertClassListContains(aElement, "entries"); } } /** * Appends the elements for the tree, including its heading. *
--- a/toolkit/components/aboutperformance/content/aboutPerformance.js +++ b/toolkit/components/aboutperformance/content/aboutPerformance.js @@ -735,17 +735,16 @@ var Control = { // a.name is sometimes an object, so we can't use a.name.localeCompare. return String.prototype.localeCompare.call(a.name, b.name); }); }, }; var go = async function() { - Control.init(); let addons = await AddonManager.getAddonsByTypes(["extension"]); for (let addon of addons) { if (addon.isSystem) { gSystemAddonIds.add(addon.id); } }
--- a/toolkit/components/antitracking/test/browser/3rdPartyWO.html +++ b/toolkit/components/antitracking/test/browser/3rdPartyWO.html @@ -20,17 +20,16 @@ function is(a, b, msg) { } onmessage = function(e) { let runnableStr = `(() => {return (${e.data.blockingCallback});})();`; let runnable = eval(runnableStr); // eslint-disable-line no-eval runnable.call(this, /* Phase */ 2).then(_ => { info("Let's do a window.open()"); return new Promise(resolve => { - if (location.search == "?noopener") { let features = "noopener"; window.open("3rdPartyOpen.html", undefined, features); setTimeout(resolve, 1000); } else { onmessage = resolve; @@ -42,25 +41,23 @@ onmessage = function(e) { // First time storage access should not be granted because the tracker has // not had user interaction yet. let runnableStr = `(() => {return (${e.data.blockingCallback});})();`; let runnable = eval(runnableStr); // eslint-disable-line no-eval return runnable.call(this, /* Phase */ 2); }).then(_ => { info("Let's interact with the tracker"); return new Promise(resolve => { - onmessage = resolve; window.open("3rdPartyOpenUI.html?messageme"); }); }).then(_ => { info("Let's do another window.open()"); return new Promise(resolve => { - if (location.search == "?noopener") { let features = "noopener"; window.open("3rdPartyOpen.html", undefined, features); setTimeout(resolve, 1000); } else { onmessage = resolve;
--- a/toolkit/components/asyncshutdown/AsyncShutdown.jsm +++ b/toolkit/components/asyncshutdown/AsyncShutdown.jsm @@ -236,17 +236,16 @@ function safeGetState(fetchState) { // concatenate the result to a message. if (data && typeof data == "object") { data.toString = function() { return string; }; } return data; } catch (ex) { - // Make sure that this causes test failures Promise.reject(ex); if (string) { return string; } try { return "Error getting state: " + ex + " at " + ex.stack; @@ -828,17 +827,16 @@ Barrier.prototype = Object.freeze({ wait(options = {}) { // This method only implements caching on top of _wait() if (this._promise) { return this._promise; } return this._promise = this._wait(options); }, _wait(options) { - // Sanity checks if (this._isStarted) { throw new TypeError("Internal error: already started " + this._name); } if (!this._waitForMe || !this._conditionToPromise || !this._promiseToBlocker) { throw new TypeError("Internal error: already finished " + this._name); }
--- a/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js +++ b/toolkit/components/asyncshutdown/tests/xpcshell/test_AsyncShutdown.js @@ -81,17 +81,16 @@ add_task(async function test_reentrant() } }); add_task(async function test_phase_removeBlocker() { info("Testing that we can call removeBlocker before, during and after the call to wait()"); for (let kind of ["phase", "barrier", "xpcom-barrier", "xpcom-barrier-unwrapped"]) { - info("Switching to kind " + kind); info("Attempt to add then remove a blocker before wait()"); let lock = makeLock(kind); let blocker = () => { info("This promise will never be resolved"); return PromiseUtils.defer().promise; }; @@ -147,17 +146,16 @@ add_task(async function test_phase_remov blocker = Promise.resolve.bind(Promise); await lock.wait(); do_remove_blocker(lock, blocker, false); info("Attempt to remove non-registered blocker after wait()"); do_remove_blocker(lock, "foo", false); do_remove_blocker(lock, null, false); } - }); add_task(async function test_state() { info("Testing information contained in `state`"); let BLOCKER_NAME = "test_state blocker " + Math.random(); // Set up the barrier. Note that we cannot test `barrier.state`
--- a/toolkit/components/autocomplete/tests/unit/test_378079.js +++ b/toolkit/components/autocomplete/tests/unit/test_378079.js @@ -197,17 +197,16 @@ function unregisterAutoCompleteSearch(aS } /** * Test AutoComplete with multiple AutoCompleteSearch sources. */ function run_test() { - // Make an AutoCompleteSearch that always returns nothing var emptySearch = new AutoCompleteSearch("test-empty-search", new AutoCompleteResult([], [], [])); // Make an AutoCompleteSearch that returns two values var expectedValues = ["test1", "test2"]; var regularSearch = new AutoCompleteSearch("test-regular-search", new AutoCompleteResult(expectedValues, [], [])); @@ -225,17 +224,16 @@ function run_test() { var numSearchesStarted = 0; input.onSearchBegin = function() { numSearchesStarted++; Assert.equal(numSearchesStarted, 1); }; input.onSearchComplete = function() { - Assert.equal(numSearchesStarted, 1); Assert.equal(controller.searchStatus, Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH); Assert.equal(controller.matchCount, 2); // Confirm expected result values for (var i = 0; i < expectedValues.length; i++) {
--- a/toolkit/components/autocomplete/tests/unit/test_393191.js +++ b/toolkit/components/autocomplete/tests/unit/test_393191.js @@ -196,17 +196,16 @@ function unregisterAutoCompleteSearch(aS } /** * Test AutoComplete with a search that returns a null result */ function run_test() { - // Make an AutoCompleteSearch that always returns nothing var emptySearch = new AutoCompleteSearch("test-empty-search", new AutoCompleteResult([], [], [])); // Register search so AutoCompleteController can find them registerAutoCompleteSearch(emptySearch); var controller = Cc["@mozilla.org/autocomplete/controller;1"]. @@ -218,17 +217,16 @@ function run_test() { var numSearchesStarted = 0; input.onSearchBegin = function() { numSearchesStarted++; Assert.equal(numSearchesStarted, 1); }; input.onSearchComplete = function() { - Assert.equal(numSearchesStarted, 1); Assert.equal(controller.searchStatus, Ci.nsIAutoCompleteController.STATUS_COMPLETE_NO_MATCH); Assert.equal(controller.matchCount, 0); // Unregister searches unregisterAutoCompleteSearch(emptySearch);
--- a/toolkit/components/autocomplete/tests/unit/test_440866.js +++ b/toolkit/components/autocomplete/tests/unit/test_440866.js @@ -195,17 +195,16 @@ function unregisterAutoCompleteSearch(aS } /** * Test AutoComplete with multiple AutoCompleteSearch sources. */ function run_test() { - // Make an AutoCompleteSearch that always returns nothing var emptySearch = new AutoCompleteSearch("test-empty-search", new AutoCompleteResult([], [], [])); // Make an AutoCompleteSearch that returns two values var expectedValues = ["test1", "test2"]; var regularSearch = new AutoCompleteSearch("test-regular-search", new AutoCompleteResult(expectedValues, [], []));
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js +++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_multiple.js @@ -222,17 +222,16 @@ function run_test() { var numSearchesStarted = 0; input.onSearchBegin = function() { numSearchesStarted++; Assert.equal(numSearchesStarted, 1); }; input.onSearchComplete = function() { - Assert.equal(numSearchesStarted, 1); Assert.equal(controller.searchStatus, Ci.nsIAutoCompleteController.STATUS_COMPLETE_MATCH); Assert.equal(controller.matchCount, expected1.length + expected2.length); // Unregister searches unregisterAutoCompleteSearch(search1);
--- a/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js +++ b/toolkit/components/autocomplete/tests/unit/test_autocomplete_userContextId.js @@ -33,12 +33,11 @@ function doSearch(aString, aUserContextI registerAutoCompleteSearch(search); let controller = Cc["@mozilla.org/autocomplete/controller;1"]. getService(Ci.nsIAutoCompleteController); let input = new AutoCompleteInput([ search.name ], aUserContextId); controller.input = input; controller.startSearch(aString); - }); }
--- a/toolkit/components/backgroundhangmonitor/tests/test_BHRObserver.js +++ b/toolkit/components/backgroundhangmonitor/tests/test_BHRObserver.js @@ -109,17 +109,16 @@ add_task(async function test_BHRObserver equal(typeof module[1], "string"); }); // hang.annotations equal(typeof hang.annotations, "object"); Object.keys(hang.annotations).forEach(key => { equal(typeof hang.annotations[key], "string"); }); - }); // Check that the telemetry service collected pings which make sense ok(telSvc.payload.hangs.length - beforeLen >= 3); ok(Array.isArray(telSvc.payload.modules)); telSvc.payload.modules.forEach(module => { ok(Array.isArray(module)); equal(module.length, 2);
--- a/toolkit/components/crashes/CrashManager.jsm +++ b/toolkit/components/crashes/CrashManager.jsm @@ -383,17 +383,16 @@ this.CrashManager.prototype = Object.fre try { await OS.File.remove(path); } catch (ex) { this._log.warn("Error removing event file (" + path + ")", ex); } } return unprocessedFiles.length; - } finally { this._aggregatePromise = false; this._storeProtectedCount--; } })(); }, /** @@ -990,17 +989,16 @@ CrashStore.prototype = Object.freeze({ // If we have an OOM size, count the crash as an OOM in addition to // being a main process crash. if (denormalized.metadata && denormalized.metadata.OOMAllocationSize) { let oomKey = key + "-oom"; actualCounts.set(oomKey, (actualCounts.get(oomKey) || 0) + 1); } - } // The validation in this loop is arguably not necessary. We perform // it as a defense against unknown bugs. for (let dayKey in data.countsByDay) { let day = parseInt(dayKey, 10); for (let type in data.countsByDay[day]) { this._ensureCountsForDay(day);
--- a/toolkit/components/crashes/CrashManagerTest.jsm +++ b/toolkit/components/crashes/CrashManagerTest.jsm @@ -33,21 +33,19 @@ var configureLogging = function() { let appender = new Log.DumpAppender(); appender.level = Log.Level.All; log.addAppender(appender); loggingConfigured = true; }; var sleep = function(wait) { return new Promise(resolve => { - setTimeout(() => { resolve(); }, wait); - }); }; var TestingCrashManager = function(options) { CrashManager.call(this, options); }; this.TestingCrashManager.prototype = {
--- a/toolkit/components/crashes/tests/xpcshell/test_crash_service.js +++ b/toolkit/components/crashes/tests/xpcshell/test_crash_service.js @@ -43,17 +43,16 @@ async function setup(crashId) { let minidump = OS.Path.join(cwd, "crash.dmp"); let extra = OS.Path.join(cwd, "crash.extra"); // Make a copy of the files because the .extra file will be modified gDumpFile = OS.Path.join(gMinidumpDir.path, crashId + ".dmp"); await OS.File.copy(minidump, gDumpFile); gExtraFile = OS.Path.join(gMinidumpDir.path, crashId + ".extra"); await OS.File.copy(extra, gExtraFile); - } // Cleans up the fake crash dump and resets the minidump path async function teardown() { await OS.File.remove(gDumpFile); await OS.File.remove(gExtraFile); }
--- a/toolkit/components/crashmonitor/CrashMonitor.jsm +++ b/toolkit/components/crashmonitor/CrashMonitor.jsm @@ -193,17 +193,16 @@ var CrashMonitor = { * thread, for performance reasons. Note that this means * that there's not a 100% guarantee that the file will be * written by the time the notification completes. The * exception is profile-before-change which has a shutdown * blocker. */ await OS.File.writeAtomic( CrashMonitorInternal.path, data, {tmpPath: CrashMonitorInternal.path + ".tmp"}); - } finally { // Resolve promise for blocker if (aTopic == "profile-before-change") { CrashMonitorInternal.profileBeforeChangeDeferred.resolve(); } } })(); }
--- a/toolkit/components/ctypes/tests/unit/test_errno.js +++ b/toolkit/components/ctypes/tests/unit/test_errno.js @@ -36,17 +36,16 @@ function main_test() { let set_last_error, get_last_error; try { // The following test is Windows-specific set_last_error = library.declare("set_last_error", ctypes.default_abi, ctypes.void_t, ctypes.int); get_last_error = library.declare("get_last_error", ctypes.default_abi, ctypes.int); - } catch (x) { Assert.equal(ctypes.winLastError, undefined); } if (set_last_error) { Assert.notEqual(ctypes.winLastError, undefined); for (let i = 0; i < 50; ++i) { set_last_error(i);
--- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js +++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js @@ -1474,17 +1474,16 @@ function run_StructType_tests() { // Test 2: overflow struct size + struct tail padding. // To do this, we use a struct with maximum size and alignment 2. large_t = ctypes.StructType("large_t", [{"a": ctypes.int16_t.array(0xfffffffe / 2)}]); Assert.equal(large_t.size, 0xfffffffe); do_check_throws(function() { ctypes.StructType("large_t", [{"a": large_t}, {"b": ctypes.int8_t}]); }, RangeError); - } else { // Test 1: overflow struct size when converting from size_t to jsdouble. let large_t = ctypes.StructType("large_t", [{"a": ctypes.int8_t.array(0xfffffffffffff800)}]); Assert.equal(large_t.size, 0xfffffffffffff800); do_check_throws(function() { ctypes.StructType("large_t", [{"a": large_t}, {"b": ctypes.int8_t}]); }, RangeError); @@ -2023,17 +2022,16 @@ function run_ArrayType_tests() { ctypes.ArrayType(ctypes.int8_t, 0x100000000); }, TypeError); do_check_throws(function() { ctypes.ArrayType(ctypes.int16_t, 0x80000000); }, RangeError); let large_t = ctypes.int8_t.array(0x80000000); do_check_throws(function() { large_t.array(2); }, RangeError); - } else { do_check_throws(function() { ctypes.ArrayType(ctypes.int8_t, ctypes.UInt64("0xffffffffffffffff")); }, TypeError); do_check_throws(function() { ctypes.ArrayType(ctypes.int16_t, ctypes.UInt64("0x8000000000000000")); }, RangeError);
--- a/toolkit/components/downloads/DownloadCore.jsm +++ b/toolkit/components/downloads/DownloadCore.jsm @@ -896,17 +896,16 @@ this.Download.prototype = { this._notifyChange(); } return; } // Update the current progress from disk if we retained partial data. if ((this.hasPartialData || this.hasBlockedData) && this.target.partFilePath) { - try { let stat = await OS.File.stat(this.target.partFilePath); // Ignore the result if the state has changed meanwhile. if (!this.stopped || this._finalized) { return; } @@ -2454,17 +2453,16 @@ this.DownloadLegacySaver.prototype = { } catch (ex) { if (!(ex instanceof OS.File.Error) || !ex.becauseExists) { throw ex; } } } await this._checkReputationAndMove(aSetPropertiesFn); - } catch (ex) { // In case the operation failed, ensure we stop downloading data. Since // we never re-enter this function, deferCanceled is always available. this.deferCanceled.resolve(); throw ex; } finally { // We don't need the reference to the request anymore. We must also set // deferCanceled to null in order to free any indirect references it
--- a/toolkit/components/downloads/DownloadLegacy.js +++ b/toolkit/components/downloads/DownloadLegacy.js @@ -63,17 +63,16 @@ DownloadLegacyTransfer.prototype = { onStateChange: function DLT_onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) { if (!Components.isSuccessCode(aStatus)) { this._componentFailed = true; } if ((aStateFlags & Ci.nsIWebProgressListener.STATE_START) && (aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK)) { - let blockedByParentalControls = false; // If it is a failed download, aRequest.responseStatus doesn't exist. // (missing file on the server, network failure to download) try { // If the request's response has been blocked by Windows Parental Controls // with an HTTP 450 error code, we must cancel the request synchronously. blockedByParentalControls = aRequest instanceof Ci.nsIHttpChannel && aRequest.responseStatus == 450;
--- a/toolkit/components/downloads/test/unit/common_test_Download.js +++ b/toolkit/components/downloads/test/unit/common_test_Download.js @@ -1764,17 +1764,16 @@ add_task(async function test_cancel_midw resolve(download.cancel()); } }; // Register for the notification, but also call the function directly in // case the download already reached the expected progress. download.onchange = onchange; onchange(); - }); Assert.ok(download.stopped); // The second time, we'll provide the entire interruptible response. continueResponses(); download.onchange = null; await download.start();
--- a/toolkit/components/downloads/test/unit/head.js +++ b/toolkit/components/downloads/test/unit/head.js @@ -252,17 +252,16 @@ function promiseStartLegacyDownload(aSou // Apply decoding if required by the "Content-Encoding" header. persist.persistFlags &= ~Ci.nsIWebBrowserPersist.PERSIST_FLAGS_NO_CONVERSION; persist.persistFlags |= Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION; let transfer = Cc["@mozilla.org/transfer;1"].createInstance(Ci.nsITransfer); return new Promise(resolve => { - Downloads.getList(Downloads.ALL).then(function(aList) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ onDownloadAdded(aDownload) { aList.removeView(this).catch(do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -285,17 +284,16 @@ function promiseStartLegacyDownload(aSou persist.progressListener = transfer; // Start the actual download process. persist.savePrivacyAwareURI( sourceURI, Services.scriptSecurityManager.getSystemPrincipal(), 0, referrer, Ci.nsIHttpChannel.REFERRER_POLICY_UNSAFE_URL, null, null, targetFile, isPrivate); }).catch(do_report_unexpected_exception); - }); } /** * Starts a new download using the nsIHelperAppService interface, and controls * it using the legacy nsITransfer interface. The source of the download will * be "interruptible_resumable.txt" and partially downloaded data will be kept. * @@ -308,17 +306,16 @@ function promiseStartLegacyDownload(aSou * download through the legacy nsITransfer interface. * @rejects Never. The current test fails in case of exceptions. */ function promiseStartExternalHelperAppServiceDownload(aSourceUrl) { let sourceURI = NetUtil.newURI(aSourceUrl || httpUrl("interruptible_resumable.txt")); return new Promise(resolve => { - Downloads.getList(Downloads.PUBLIC).then(function(aList) { // Temporarily register a view that will get notified when the download we // are controlling becomes visible in the list of downloads. aList.addView({ onDownloadAdded(aDownload) { aList.removeView(this).catch(do_report_unexpected_exception); // Remove the download to keep the list empty for the next test. This @@ -353,47 +350,44 @@ function promiseStartExternalHelperAppSe onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount) { this.contentListener.onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount); }, }); }).catch(do_report_unexpected_exception); - }); } /** * Waits for a download to reach half of its progress, in case it has not * reached the expected progress already. * * @param aDownload * The Download object to wait upon. * * @return {Promise} * @resolves When the download has reached half of its progress. * @rejects Never. */ function promiseDownloadMidway(aDownload) { return new Promise(resolve => { - // Wait for the download to reach half of its progress. let onchange = function() { if (!aDownload.stopped && !aDownload.canceled && aDownload.progress == 50) { aDownload.onchange = null; resolve(); } }; // Register for the notification, but also call the function directly in // case the download already reached the expected progress. aDownload.onchange = onchange; onchange(); - }); } /** * Waits for a download to finish, in case it has not finished already. * * @param aDownload * The Download object to wait upon. @@ -475,17 +469,16 @@ function promiseVerifyContents(aPath, aE Assert.equal(contents.length, aExpectedContents.length); Assert.ok(contents == aExpectedContents); } else { // Print the string if it is short and made of printable characters. Assert.equal(contents, aExpectedContents); } resolve(); }); - }); })(); } /** * Starts a socket listener that closes each incoming connection. * * @returns nsIServerSocket that listens for connections. Call its "close"
--- a/toolkit/components/downloads/test/unit/test_PrivateTemp.js +++ b/toolkit/components/downloads/test/unit/test_PrivateTemp.js @@ -5,17 +5,16 @@ "use strict"; /* * The temporary directory downloads saves to, should be only readable * for the current user. */ add_task(async function test_private_temp() { - let download = await promiseStartExternalHelperAppServiceDownload( httpUrl("empty.txt")); await promiseDownloadStopped(download); var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); targetFile.initWithPath(download.target.path);
--- a/toolkit/components/extensions/.eslintrc.js +++ b/toolkit/components/extensions/.eslintrc.js @@ -249,19 +249,16 @@ module.exports = { // Don't require method and property shorthand syntax for object literals. // We use this in the code a lot, but not consistently, and this seems more // like something to check at code review time. "object-shorthand": "off", // Allow more than one variable declaration per function. "one-var": "off", - // Disallow padding within blocks. - "padded-blocks": ["error", "never"], - // Don't require quotes around object literal property names. "quote-props": "off", // Require use of the second argument for parseInt(). "radix": "error", // Enforce spacing after semicolons. "semi-spacing": ["error", {"before": false, "after": true}],
--- a/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js @@ -11,17 +11,16 @@ function run_test() { // Start executing the tests. run_next_test(); } /** * Test for addPath usage with null arguments. */ add_task(async function test_null_args_addPath() { - let watcher = makeWatcher(); let testPath = "someInvalidPath"; // Define a dummy callback function. In this test no callback is // expected to be called. let dummyFunc = function(changed) { do_throw("Not expected in this test."); }; @@ -44,17 +43,16 @@ add_task(async function test_null_args_a info("Initialisation thrown NS_ERROR_NULL_POINTER as expected."); } }); /** * Test for removePath usage with null arguments. */ add_task(async function test_null_args_removePath() { - let watcher = makeWatcher(); let testPath = "someInvalidPath"; // Define a dummy callback function. In this test no callback is // expected to be called. let dummyFunc = function(changed) { do_throw("Not expected in this test."); };
--- a/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Test the component behaves correctly when no error callback is * provided and an error occurs. */ add_task(async function test_error_with_no_error_callback() { - let watcher = makeWatcher(); let testPath = "someInvalidPath"; // Define a dummy callback function. In this test no callback is // expected to be called. let dummyFunc = function(changed) { do_throw("Not expected in this test."); }; @@ -32,17 +31,16 @@ add_task(async function test_error_with_ watcher.addPath(testPath, dummyFunc); }); /** * Test the component behaves correctly when no error callback is * provided (no error should occur). */ add_task(async function test_watch_single_path_file_creation_no_error_cb() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); let tempFileName = "test_filecreation.tmp"; // Instantiate and initialize the native watcher.
--- a/toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_shared_callback.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Test the watcher correctly handles two watches sharing the same * change callback. */ add_task(async function test_watch_with_shared_callback() { - // Create and watch two sub-directories of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDirs = [ OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"), OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground2"), ];
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_creation_single.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Tests that the watcher correctly notifies of a directory creation when watching * a single path. */ add_task(async function test_watch_single_path_directory_creation() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); let tmpDirPath = OS.Path.join(watchedDir, "testdir"); // Instantiate and initialize the native watcher.
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_directory_deletion_single.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Tests that the watcher correctly notifies of a directory deletion when watching * a single path. */ add_task(async function test_watch_single_path_directory_deletion() { - let watchedDir = OS.Constants.Path.profileDir; let tempDirName = "test"; let tmpDirPath = OS.Path.join(watchedDir, tempDirName); // Instantiate and initialize the native watcher. let watcher = makeWatcher(); let deferred = Promise.defer();
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_creation_single.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Test the watcher correctly notifies of a file creation when watching * a single path. */ add_task(async function test_watch_single_path_file_creation() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); let tempFileName = "test_filecreation.tmp"; // Instantiate and initialize the native watcher.
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js @@ -11,17 +11,16 @@ function run_test() { // Start executing the tests. run_next_test(); } /** * Test the watcher correctly notifies of a file deletion when watching * a single path. */ add_task(async function test_watch_single_path_file_deletion() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); let tempFileName = "test_filedeletion.tmp"; // Instantiate and initialize the native watcher.
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_modification_single.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Tests that the watcher correctly notifies of a file modification when watching * a single path. */ add_task(async function test_watch_single_path_file_modification() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); let tempFileName = "test_filemodification.tmp"; // Instantiate and initialize the native watcher.
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_many_changes.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Test that we correctly handle watching directories when hundreds of files * change simultaneously. */ add_task(async function test_fill_notification_buffer() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); // The number of files to create. let numberOfFiles = 100; let fileNameBase = "testFile";
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_multi_paths.js @@ -16,17 +16,16 @@ function run_test() { * Tests the watcher by watching several resources. * This test creates the specified number of directory inside the profile * directory, adds each one of them to the watched list the creates * a file in them in order to trigger the notification. * The test keeps track of the number of times the changes callback is * called in order to verify the success of the test. */ add_task(async function test_watch_multi_paths() { - // The number of resources to watch. We expect changes for // creating a file within each directory. let resourcesToWatch = 5; let watchedDir = OS.Constants.Path.profileDir; // The directories to be watched will be created with. let tempDirNameBase = "FileWatcher_Test_"; let tempFileName = "test.tmp";
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_recursively.js @@ -12,17 +12,16 @@ function run_test() { run_next_test(); } /** * Test the watcher correctly notifies of a file creation in a subdirectory * of the watched sub-directory (recursion). */ add_task(async function test_watch_recursively() { - // Create and watch a sub-directory of the profile directory so we don't // catch notifications we're not interested in (i.e. "startupCache"). let watchedDir = OS.Path.join(OS.Constants.Path.profileDir, "filewatcher_playground"); await OS.File.makeDir(watchedDir); // We need at least 2 levels of directories to test recursion. let subdirectory = OS.Path.join(watchedDir, "level1"); await OS.File.makeDir(subdirectory);
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.js +++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_resource.js @@ -17,16 +17,15 @@ function run_test() { */ add_task(async function test_watching_non_existing() { let notExistingDir = OS.Path.join(OS.Constants.Path.profileDir, "absolutelyNotExisting"); // Instantiate the native watcher. let watcher = makeWatcher(); let error = await new Promise((resolve, reject) => { - // Try watch a path which doesn't exist. watcher.addPath(notExistingDir, reject, resolve); // Wait until the watcher informs us that there was an error. }); Assert.equal(error, Cr.NS_ERROR_FILE_NOT_FOUND); });
--- a/toolkit/components/gfx/content/gfxFrameScript.js +++ b/toolkit/components/gfx/content/gfxFrameScript.js @@ -35,17 +35,16 @@ const gfxFrameScript = { return aUri.endsWith("/sanitytest.html"); }, onStateChange(webProgress, req, flags, status) { if (webProgress.isTopLevel && (flags & Ci.nsIWebProgressListener.STATE_STOP) && this.isSanityTest(req.name)) { - webProgress.removeProgressListener(this); // If no paint is pending, then the test already painted if (this.domUtils.isMozAfterPaintPending) { addEventListener("MozAfterPaint", this); } else { sendAsyncMessage("gfxSanity:ContentLoaded"); }
--- a/toolkit/components/mozintl/mozIntl.js +++ b/toolkit/components/mozintl/mozIntl.js @@ -427,17 +427,16 @@ class MozIntl { } } return MozPluralRules; } get RelativeTimeFormat() { class MozRelativeTimeFormat extends Intl.RelativeTimeFormat { constructor(locales, options = {}, ...args) { - // If someone is asking for MozRelativeTimeFormat, it's likely they'll want // to use `formatBestUnit` which works better with `auto` if (options.numeric === undefined) { options.numeric = "auto"; } super(getLocales(locales), options, ...args); }
--- a/toolkit/components/narrate/.eslintrc.js +++ b/toolkit/components/narrate/.eslintrc.js @@ -20,16 +20,15 @@ module.exports = { "no-inline-comments": "error", "no-mixed-spaces-and-tabs": "error", "no-multi-spaces": "error", "no-multi-str": "error", "no-multiple-empty-lines": ["error", {"max": 1}], "no-return-assign": "error", "no-shadow": "error", "no-throw-literal": "error", - "padded-blocks": ["error", "never"], "quotes": ["error", "double", "avoid-escape"], "semi-spacing": ["error", {"before": false, "after": true}], "space-in-parens": ["error", "never"], "strict": ["error", "global"], "yoda": "error" } };
--- a/toolkit/components/normandy/actions/PreferenceRolloutAction.jsm +++ b/toolkit/components/normandy/actions/PreferenceRolloutAction.jsm @@ -63,17 +63,16 @@ class PreferenceRolloutAction extends Ba } default: { Cu.reportError(new Error(`Updated pref rollout in unexpected state: ${existingRollout.state}`)); } } } else { this.log.debug(`No updates to preference rollout ${args.slug}`); } - } else { // new enrollment // Check if this rollout would be a no-op, which is not allowed. if (newRollout.preferences.every(({value, previousValue}) => value === previousValue)) { TelemetryEvents.sendEvent("enrollFailed", "preference_rollout", args.slug, {reason: "would-be-no-op"}); // Throw so that this recipe execution is marked as a failure throw new Error(`New rollout ${args.slug} does not change any preferences.`); }
--- a/toolkit/components/normandy/lib/ActionsManager.jsm +++ b/toolkit/components/normandy/lib/ActionsManager.jsm @@ -92,17 +92,16 @@ class ActionsManager { async runRecipe(recipe) { let actionName = recipe.action; if (actionName in this.localActions) { log.info(`Executing recipe "${recipe.name}" (action=${recipe.action})`); const action = this.localActions[actionName]; await action.runRecipe(recipe); - } else if (actionName in this.remoteActionSandboxes) { let status; const manager = this.remoteActionSandboxes[recipe.action]; if (manager.disabled) { log.warn( `Skipping recipe ${recipe.name} because ${recipe.action} failed during pre-execution.` ); @@ -114,17 +113,16 @@ class ActionsManager { status = Uptake.RECIPE_SUCCESS; } catch (e) { e.message = `Could not execute recipe ${recipe.name}: ${e.message}`; Cu.reportError(e); status = Uptake.RECIPE_EXECUTION_ERROR; } } Uptake.reportRecipe(recipe.id, status); - } else { log.error( `Could not execute recipe ${recipe.name}:`, `Action ${recipe.action} is either missing or invalid.` ); Uptake.reportRecipe(recipe.id, Uptake.RECIPE_INVALID_ACTION); } }
--- a/toolkit/components/normandy/test/browser/browser_RecipeRunner.js +++ b/toolkit/components/normandy/test/browser/browser_RecipeRunner.js @@ -55,17 +55,16 @@ add_task(async function getFilterContext "environment.recipe drops unrecognized attributes from the recipe", ); // Filter context attributes are cached. await SpecialPowers.pushPrefEnv({set: [["app.normandy.user_id", "some id"]]}); is(context.env.userId, "some id", "User id is read from prefs when accessed"); await SpecialPowers.pushPrefEnv({set: [["app.normandy.user_id", "real id"]]}); is(context.env.userId, "some id", "userId was cached"); - }); add_task(async function checkFilter() { const check = filter => RecipeRunner.checkFilter({filter_expression: filter}); // Errors must result in a false return value. ok(!(await check("invalid ( + 5yntax")), "Invalid filter expressions return false"); @@ -376,14 +375,13 @@ decorate_task( RecipeRunner.enable(); is(registerTimerStub.callCount, 1, "Enable should be idempotent"); RecipeRunner.enabled = true; RecipeRunner.disable(); RecipeRunner.disable(); RecipeRunner.disable(); is(registerTimerStub.callCount, 1, "Disable should be idempotent"); - } finally { RecipeRunner.enabled = originalEnabled; } } );
--- a/toolkit/components/normandy/test/browser/browser_ShieldPreferences.js +++ b/toolkit/components/normandy/test/browser/browser_ShieldPreferences.js @@ -11,17 +11,16 @@ ShieldPreferences.init(); decorate_task( withMockPreferences, AddonStudies.withStudies([ addonStudyFactory({active: true}), addonStudyFactory({active: true}), ]), async function testDisableStudiesWhenOptOutDisabled(mockPreferences, [study1, study2]) { - mockPreferences.set(OPT_OUT_STUDIES_ENABLED_PREF, true); const observers = [ studyEndObserved(study1.recipeId), studyEndObserved(study2.recipeId), ]; Services.prefs.setBoolPref(OPT_OUT_STUDIES_ENABLED_PREF, false); await Promise.all(observers); @@ -37,17 +36,16 @@ decorate_task( decorate_task( withMockPreferences, PreferenceExperiments.withMockExperiments([ preferenceStudyFactory({active: true}), preferenceStudyFactory({active: true}), ]), withStub(PreferenceExperiments, "stop"), async function testDisableExperimentsWhenOptOutDisabled(mockPreferences, [study1, study2], stopStub) { - mockPreferences.set(OPT_OUT_STUDIES_ENABLED_PREF, true); let stopArgs = []; let stoppedBoth = new Promise(resolve => { let calls = 0; stopStub.callsFake(function() { stopArgs.push(Array.from(arguments)); calls++; if (calls == 2) {
--- a/toolkit/components/normandy/test/browser/head.js +++ b/toolkit/components/normandy/test/browser/head.js @@ -342,17 +342,16 @@ this.studyEndObserved = function(recipeI return TestUtils.topicObserved( "shield-study-ended", (subject, endedRecipeId) => Number.parseInt(endedRecipeId) === recipeId, ); }; this.withSendEventStub = function(testFunction) { return async function wrappedTestFunction(...args) { - /* Checks that calls match the event schema. */ function checkEventMatchesSchema(method, object, value, extra) { let match = true; const spec = Array.from(Object.values(TelemetryEvents.eventSchema)) .filter(spec => spec.methods.includes(method))[0]; if (spec) { if (!spec.objects.includes(object)) {
--- a/toolkit/components/osfile/modules/osfile_async_front.jsm +++ b/toolkit/components/osfile/modules/osfile_async_front.jsm @@ -82,17 +82,16 @@ for (let [constProp, dirKey] of [ ["userApplicationDataDir", "UAppData"], ["winAppDataDir", "AppData"], ["winLocalAppDataDir", "LocalAppData"], ["winStartMenuProgsDir", "Progs"], ["tmpDir", "TmpD"], ["homeDir", "Home"], ["macUserLibDir", "ULibDir"], ]) { - if (constProp in SharedAll.Constants.Path) { continue; } LOG("Installing lazy getter for OS.Constants.Path." + constProp + " because it isn't defined and profile may not be loaded."); Object.defineProperty(SharedAll.Constants.Path, constProp, { get: lazyPathGetter(constProp, dirKey), @@ -281,17 +280,16 @@ var Scheduler = this.Scheduler = { // to an obsolete worker (we reactivate it in the `finally`). // This needs to be done right now so that we maintain relative // ordering with calls to post(), etc. let deferred = PromiseUtils.defer(); let savedQueue = this.queue; this.queue = deferred.promise; return this._killQueue = (async () => { - await killQueue; // From this point, and until the end of the Task, we are the // only call to `kill`, regardless of any `yield`. await savedQueue; try { // Enter critical section: no yield in this block @@ -351,24 +349,22 @@ var Scheduler = this.Scheduler = { // Make sure that we do not leave an invalid |worker| around. if (killed || shutdown) { this._worker = null; } this.shutdown = shutdown; return resources; - } finally { // Resume accepting messages. If we have set |shutdown| to |true|, // any pending/future request will be rejected. Otherwise, any // pending/future request will spawn a new worker if necessary. deferred.resolve(); } - })(); }, /** * Push a task at the end of the queue. * * @param {function} code A function returning a Promise. * This function will be executed once all the previously
--- a/toolkit/components/osfile/modules/osfile_shared_allthreads.jsm +++ b/toolkit/components/osfile/modules/osfile_shared_allthreads.jsm @@ -160,17 +160,16 @@ var stringifyArg = function stringifyArg } if (isArrayBuffer(arg)) { return "[" + value.constructor.name + " " + value.byteLength + "]"; } return value; }); } return argToString; - } return arg; }; var LOG = function(...args) { if (!Config.DEBUG) { // If logging is deactivated, don't log return; @@ -552,17 +551,16 @@ function projector(type, signed) { || type == ctypes.uintptr_t || type == ctypes.off_t) { if (signed) { LOG("Projected as a large signed integer"); return projectLargeInt; } LOG("Projected as a large unsigned integer"); return projectLargeUInt; - } LOG("Projected as a regular number"); return projectValue; } exports.projectValue = projectValue; /** * Get the appropriate type for an unsigned int of the given size.
--- a/toolkit/components/osfile/modules/osfile_shared_front.jsm +++ b/toolkit/components/osfile/modules/osfile_shared_front.jsm @@ -11,17 +11,16 @@ /* eslint-env node */ /* global OS */ if (typeof Components != "undefined") { throw new Error("osfile_shared_front.jsm cannot be used from the main thread"); } (function(exports) { - var SharedAll = require("resource://gre/modules/osfile/osfile_shared_allthreads.jsm"); var Path = require("resource://gre/modules/osfile/ospath.jsm"); var Lz4 = require("resource://gre/modules/lz4.js"); SharedAll.LOG.bind(SharedAll, "Shared front-end"); var clone = SharedAll.clone; @@ -81,17 +80,16 @@ AbstractFile.prototype = { break; } pos += chunkSize; } if (pos == bytes) { return buffer; } return buffer.subarray(0, pos); - }, /** * Write bytes from a buffer to this file. * * Note that, by default, this function may perform several I/O * operations to ensure that the buffer is fully written. * @@ -406,17 +404,16 @@ AbstractFile.read = function read(path, * If the process or the operating system freezes or crashes * during the short window between these operations, * the destination file will have been moved to its backup. * * @return {number} The number of bytes actually written. */ AbstractFile.writeAtomic = function writeAtomic(path, buffer, options = {}) { - // Verify that path is defined and of the correct type if (typeof path != "string" || path == "") { throw new TypeError("File path should be a (non-empty) string"); } let noOverwrite = options.noOverwrite; if (noOverwrite && OS.File.exists(path)) { throw OS.File.Error.exists("writeAtomic", path); }
--- a/toolkit/components/osfile/modules/osfile_unix_front.jsm +++ b/toolkit/components/osfile/modules/osfile_unix_front.jsm @@ -76,17 +76,16 @@ } if (result == -1) { this._closeResult = new File.Error("close", ctypes.errno, this._path); } } if (this._closeResult) { throw this._closeResult; } - }; /** * Read some bytes from a file. * * @param {C pointer} buffer A buffer for holding the data * once it is read. * @param {number} nbytes The number of bytes to read. It must not @@ -339,17 +338,16 @@ * * @return {bool} true if the file exists, false otherwise. */ File.exists = function Unix_exists(path) { if (UnixFile.access(path, Const.F_OK) == -1) { return false; } return true; - }; /** * Remove an existing file. * * @param {string} path The name of the file. * @param {*=} options Additional options. * - {bool} ignoreAbsent If |false|, throw an error if the file does
--- a/toolkit/components/osfile/modules/osfile_win_back.jsm +++ b/toolkit/components/osfile/modules/osfile_win_back.jsm @@ -208,30 +208,28 @@ /* return */ctypes.bool, /* handle*/ ctypes.voidptr_t); SysFile.CloseHandle = function(fd) { if (fd == INVALID_HANDLE) { return true; } return fd.dispose(); // Returns the value of |CloseHandle|. - }; libc.declareLazy(SysFile, "_FindClose", "FindClose", ctypes.winapi_abi, /* return */ctypes.bool, /* handle*/ ctypes.voidptr_t); SysFile.FindClose = function(handle) { if (handle == INVALID_HANDLE) { return true; } return handle.dispose(); // Returns the value of |FindClose|. - }; // Declare libc functions as functions of |OS.Win.File| libc.declareLazyFFI(SysFile, "CopyFile", "CopyFileW", ctypes.winapi_abi, /* return*/ Type.zero_or_nothing, /* sourcePath*/ Type.path, Type.path,
--- a/toolkit/components/osfile/modules/osfile_win_front.jsm +++ b/toolkit/components/osfile/modules/osfile_win_front.jsm @@ -94,17 +94,16 @@ } if (result == -1) { this._closeResult = new File.Error("close", ctypes.winLastError, this._path); } } if (this._closeResult) { throw this._closeResult; } - }; /** * Read some bytes from a file. * * @param {C pointer} buffer A buffer for holding the data * once it is read. * @param {number} nbytes The number of bytes to read. It must not @@ -796,18 +795,16 @@ return this._findData; } let error = ctypes.winLastError; this.close(); if (error == Const.ERROR_NO_MORE_FILES) { return null; } throw new File.Error("iter (FindNextFile)", error, this._path); - - }; /** * Return the next entry in the directory, if any such entry is * available. * * Skip special directories "." and "..". *
--- a/toolkit/components/osfile/modules/ospath_win.jsm +++ b/toolkit/components/osfile/modules/ospath_win.jsm @@ -99,17 +99,16 @@ var dirname = function(path, options) { } if (index == 1 && path.charAt(0) == "\\") { // The path is reduced to a UNC drive if (noDrive) { return "."; } return path; - } // Ignore any occurrence of "\\: immediately before that one while (index >= 0 && path[index] == "\\") { --index; } // Compute what is left, removing the drive name if necessary
--- a/toolkit/components/osfile/tests/mochi/main_test_osfile_async.js +++ b/toolkit/components/osfile/tests/mochi/main_test_osfile_async.js @@ -102,17 +102,16 @@ var reference_fetch_file = function refe } stream.close(); if (reject) { reject(reject); } else { resolve(result); } }); - }); }; var reference_dir_contents = function reference_dir_contents(path) { let result = []; let entries = new FileUtils.File(path).directoryEntries; while (entries.hasMoreElements()) { let entry = entries.nextFile;
--- a/toolkit/components/osfile/tests/mochi/worker_handler.js +++ b/toolkit/components/osfile/tests/mochi/worker_handler.js @@ -23,12 +23,11 @@ function worker_handler(worker) { case "info": SimpleTest.info(msg.data.description); return; case "finish": SimpleTest.finish(); return; default: SimpleTest.ok(false, "test_osfile.xul: wrong message " + JSON.stringify(msg.data)); - } }; }
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js +++ b/toolkit/components/osfile/tests/mochi/worker_test_osfile_front.js @@ -251,17 +251,16 @@ function test_iter_dir() { let lastWrite = entry.winLastWriteDate; ok(lastWrite, "test_iter_dir: Windows lastWrite date exists: " + lastWrite); ok(lastWrite.getFullYear() >= 2009 && lastWrite.getFullYear() <= year, "test_iter_dir: consistent lastWrite date"); let lastAccess = entry.winLastAccessDate; ok(lastAccess, "test_iter_dir: Windows lastAccess date exists: " + lastAccess); ok(lastAccess.getFullYear() >= 2009 && lastAccess.getFullYear() <= year, "test_iter_dir: consistent lastAccess date"); } - } ok(encountered_tmp_file, "test_iter_dir: We have found the temporary file"); info("test_iter_dir: Cleaning up"); iterator.close(); // Testing nextBatch() iterator = new OS.File.DirectoryIterator(parent);
--- a/toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js +++ b/toolkit/components/osfile/tests/mochi/worker_test_osfile_win.js @@ -161,17 +161,16 @@ function test_ReadWrite() { // remote file system, I believe. bytes = Math.min(bytes_read.value, bytes_read2.value); pos += bytes; result = OS.Win.File.SetFilePointer(input, pos, null, OS.Constants.Win.FILE_BEGIN); isnot(result, 0, "test_ReadWrite: input seek succeeded"); result = OS.Win.File.SetFilePointer(output, pos, null, OS.Constants.Win.FILE_BEGIN); isnot(result, 0, "test_ReadWrite: output seek succeeded"); - } else { bytes = bytes_read.value; pos += bytes; } for (let i = 0; i < bytes; ++i) { if (array[i] != array2[i]) { ok(false, "Files do not match at position " + i + " (" + array[i] + "/" + array2[i] + ")");
--- a/toolkit/components/osfile/tests/xpcshell/head.js +++ b/toolkit/components/osfile/tests/xpcshell/head.js @@ -66,17 +66,16 @@ function reference_fetch_file(path, test } stream.close(); if (reject) { reject(reject); } else { resolve(result); } }); - }); } /** * Compare asynchronously the contents two files using xpcom. * * Used for comparing xpcom-based results to os.file-based results. *
--- a/toolkit/components/osfile/tests/xpcshell/test_open.js +++ b/toolkit/components/osfile/tests/xpcshell/test_open.js @@ -50,17 +50,16 @@ add_task(async function() { await openedFile.close(); }); /** * Test the error thrown by OS.File.open when attempting to open a directory * that does not exist. */ add_task(async function test_error_attributes() { - let dir = OS.Path.join(do_get_profile().path, "test_osfileErrorAttrs"); let fpath = OS.Path.join(dir, "test_error_attributes.txt"); try { await OS.File.open(fpath, {truncate: true}, {}); Assert.ok(false, "Opening path suceeded (it should fail) " + fpath); } catch (err) { Assert.ok(err instanceof OS.File.Error);
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js +++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_copy.js @@ -42,17 +42,16 @@ var reference_fetch_file = function refe } stream.close(); if (reject) { reject(reject); } else { resolve(result); } }); - }); }; /** * Compare asynchronously the contents two files using xpcom. * * Used for comparing xpcom-based results to os.file-based results. *
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js +++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_largefiles.js @@ -36,17 +36,16 @@ async function test_setPosition(forward, pos += current; Assert.equal((await file.getPosition()), pos); // 3. seek backward from current position info("Moving current backward: " + backward); await file.setPosition(-backward, OS.File.POS_CURRENT); pos -= backward; Assert.equal((await file.getPosition()), pos); - } finally { await file.setPosition(0, OS.File.POS_START); await file.close(); } } catch (ex) { await removeTestFile(path); } } @@ -90,17 +89,16 @@ async function test_setPosition_failures // double. E.g. in js 9007199254740992 + 1 == 9007199254740992 await file.setPosition(9007199254740992, OS.File.POS_START); await file.setPosition(1, OS.File.POS_CURRENT); do_throw("Shouldn't have succeeded"); } catch (ex) { info(ex.toString()); Assert.ok(!!ex); } - } finally { await file.setPosition(0, OS.File.POS_START); await file.close(); await removeTestFile(path); } } catch (ex) { do_throw(ex); }
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js +++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setPermissions.js @@ -18,17 +18,16 @@ * four digits wide. * Sample outputs: 0022, 0644, 04755. */ function format_mode(mode) { if (mode <= 0o777) { return ("0000" + mode.toString(8)).slice(-4); } return "0" + mode.toString(8); - } const _umask = OS.Constants.Sys.umask; info("umask: " + format_mode(_umask)); /** * Compute the mode that a file should have after applying the umask, * whatever it happens to be.
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js +++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_closed.js @@ -36,12 +36,11 @@ add_task(async function test_closed() { await file.read(); } catch (ex) { exn = ex; } info("Ensure that this raises the correct error"); Assert.ok(!!exn); Assert.ok(exn instanceof OS.File.Error); Assert.ok(exn.becauseClosed); - }); add_task(do_test_finished);
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js +++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_win_async_setPermissions.js @@ -42,17 +42,16 @@ add_task(async function test_path_setPer } let stat = await OS.File.stat(path); info("Got stat winAttributes: " + JSON.stringify(stat.winAttributes)); Assert.equal(stat.winAttributes.readOnly, attributesExpected.readOnly); Assert.equal(stat.winAttributes.system, attributesExpected.system); Assert.equal(stat.winAttributes.hidden, attributesExpected.hidden); - } } finally { await OS.File.remove(path); } }); // Test application to open files. add_task(async function test_file_setPermissions() {
--- a/toolkit/components/osfile/tests/xpcshell/test_path_constants.js +++ b/toolkit/components/osfile/tests/xpcshell/test_path_constants.js @@ -21,17 +21,16 @@ function compare_paths(ospath, key) { Assert.ok(!ospath); } } // Test simple paths add_task(async function test_simple_paths() { Assert.ok(!!OS.Constants.Path.tmpDir); compare_paths(OS.Constants.Path.tmpDir, "TmpD"); - }); // Some path constants aren't set up until the profile is available. This // test verifies that behavior. add_task(async function test_before_after_profile() { Assert.equal(null, OS.Constants.Path.profileDir); Assert.equal(null, OS.Constants.Path.localProfileDir); Assert.equal(null, OS.Constants.Path.userApplicationDataDir);
--- a/toolkit/components/osfile/tests/xpcshell/test_shutdown.js +++ b/toolkit/components/osfile/tests/xpcshell/test_shutdown.js @@ -5,17 +5,16 @@ ChromeUtils.import("resource://gre/modul add_task(function init() { do_get_profile(); }); /** * Test logging of file descriptors leaks. */ add_task(async function system_shutdown() { - // Test that unclosed files cause warnings // Test that unclosed directories cause warnings // Test that closed files do not cause warnings // Test that closed directories do not cause warnings function testLeaksOf(resource, topic) { return (async function() { let deferred = Promise.defer();
--- a/toolkit/components/passwordmgr/OSCrypto_win.js +++ b/toolkit/components/passwordmgr/OSCrypto_win.js @@ -25,17 +25,16 @@ function OSCrypto() { this._libs = new Map(); this._structs.DATA_BLOB = new ctypes.StructType("DATA_BLOB", [ {cbData: wintypes.DWORD}, {pbData: wintypes.PVOID}, ]); try { - this._libs.set("crypt32", ctypes.open("Crypt32")); this._libs.set("kernel32", ctypes.open("Kernel32")); this._functions.set("CryptProtectData", this._libs.get("crypt32").declare("CryptProtectData", ctypes.winapi_abi, wintypes.DWORD, this._structs.DATA_BLOB.ptr,
--- a/toolkit/components/passwordmgr/content/passwordManager.js +++ b/toolkit/components/passwordmgr/content/passwordManager.js @@ -209,17 +209,16 @@ let signonsTreeView = { table[row][field] = value; table[row].timePasswordChanged = Date.now(); Services.logins.modifyLogin(existingLogin, table[row]); signonsTree.invalidateRow(row); } if (col.id == "userCol") { _editLogin("username"); - } else if (col.id == "passwordCol") { if (!value) { return; } _editLogin("password"); } }, };
--- a/toolkit/components/passwordmgr/nsLoginManager.js +++ b/toolkit/components/passwordmgr/nsLoginManager.js @@ -75,17 +75,16 @@ LoginManager.prototype = { /** * Initialize the Login Manager. Automatically called when service * is created. * * Note: Service created in /browser/base/content/browser.js, * delayedStartup() */ init() { - // Cache references to current |this| in utility objects this._observer._pwmgr = this; // Preferences. Add observer so we get notified of changes. this._prefBranch = Services.prefs.getBranch("signon."); this._prefBranch.addObserver("rememberSignons", this._observer); this._remember = this._prefBranch.getBoolPref("rememberSignons");
--- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js +++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js @@ -579,17 +579,16 @@ LoginManagerPrompter.prototype = { this._SetAuthInfo(aAuthInfo, selectedLogin.username, selectedLogin.password); // Allow automatic proxy login if (aAuthInfo.flags & Ci.nsIAuthInformation.AUTH_PROXY && !(aAuthInfo.flags & Ci.nsIAuthInformation.PREVIOUS_FAILED) && Services.prefs.getBoolPref("signon.autologin.proxy") && !this._inPrivateBrowsing) { - this.log("Autologin enabled, skipping auth prompt."); canAutologin = true; } checkbox.value = true; } var canRememberLogin = Services.logins.getLoginSavingEnabled(hostname); @@ -1073,17 +1072,16 @@ LoginManagerPrompter.prototype = { var dialogText; if (aLogin.username) { var displayUser = this._sanitizeUsername(aLogin.username); dialogText = this._getLocalizedString("rememberPasswordMsg", [displayUser, displayHost]); } else { dialogText = this._getLocalizedString("rememberPasswordMsgNoUsername", [displayHost]); - } var dialogTitle = this._getLocalizedString("savePasswordTitle"); var neverButtonText = this._getLocalizedString("neverForSiteButtonText"); var rememberButtonText = this._getLocalizedString("rememberButtonText"); var notNowButtonText = this._getLocalizedString("notNowButtonText"); this.log("Prompting user to save/ignore login"); var userChoice = Services.prompt.confirmEx(this._chromeWindow,
--- a/toolkit/components/passwordmgr/storage-mozStorage.js +++ b/toolkit/components/passwordmgr/storage-mozStorage.js @@ -628,17 +628,16 @@ LoginManagerStorage_mozStorage.prototype this.log("_findLogins: returning " + logins.length + " logins"); count.value = logins.length; // needed for XPCOM return logins; }, countLogins(hostname, formSubmitURL, httpRealm) { - let _countLoginsHelper = (hostname, formSubmitURL, httpRealm) => { // Do checks for null and empty strings, adjust conditions and params let [conditions, params] = this._buildConditionsAndParams(hostname, formSubmitURL, httpRealm); let query = "SELECT COUNT(1) AS numLogins FROM moz_logins"; if (conditions.length) { conditions = conditions.map(c => "(" + c + ")");
--- a/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js +++ b/toolkit/components/passwordmgr/test/browser/browser_capture_doorhanger.js @@ -535,17 +535,16 @@ add_task(async function test_recipeCaptu ok(notif, "got notification popup"); // Sanity check, no logins should exist yet. let logins = Services.logins.getAllLogins(); is(logins.length, 0, "Should not have any logins yet"); await checkDoorhangerUsernamePassword("notifyu1", "notifyp1"); clickDoorhangerButton(notif, REMEMBER_BUTTON); - }, "http://example.org"); // The recipe is for example.org let logins = Services.logins.getAllLogins(); is(logins.length, 1, "Should only have 1 login"); let login = logins[0].QueryInterface(Ci.nsILoginMetaInfo); is(login.username, "notifyu1", "Check the username unchanged"); is(login.password, "notifyp1", "Check the password unchanged"); is(login.timesUsed, 1, "Check times used");
--- a/toolkit/components/passwordmgr/test/browser/browser_context_menu.js +++ b/toolkit/components/passwordmgr/test/browser/browser_context_menu.js @@ -178,17 +178,16 @@ add_task(async function test_context_men * username context menu login menuitem is clicked. */ add_task(async function test_context_menu_username_login_fill() { Services.prefs.setBoolPref("signon.schemeUpgrades", true); await BrowserTestUtils.withNewTab({ gBrowser, url: TEST_HOSTNAME + MULTIPLE_FORMS_PAGE_PATH, }, async function(browser) { - let formDescriptions = await ContentTask.spawn(browser, {}, async function() { let forms = Array.from(content.document.getElementsByClassName("test-form")); return forms.map((f) => f.getAttribute("description")); }); for (let description of formDescriptions) { info("Testing form: " + description); let usernameInputIds = await ContentTask
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_fields.js @@ -1,15 +1,14 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.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(async function test() { await new Promise(resolve => { - Services.logins.removeAllLogins(); // add login data let nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init"); let login = new nsLoginInfo("http://example.com/", "http://example.com/", null, "user", "password", "u1", "p1"); Services.logins.addLogin(login); @@ -55,11 +54,10 @@ add_task(async function test() { Services.logins.removeAllLogins(); resolve(); } }); pwmgrdlg.close(); } - }); });
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js @@ -1,14 +1,13 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ add_task(async function test() { await new Promise(resolve => { - const LOGIN_HOST = "http://example.com"; const LOGIN_COUNT = 5; let nsLoginInfo = new Components.Constructor( "@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo, "init"); let pmDialog = window.openDialog( "chrome://passwordmgr/content/passwordManager.xul", "Toolkit:PasswordManager", ""); @@ -121,11 +120,10 @@ add_task(async function test() { case 9: // finish Services.obs.removeObserver( testObserver, "passwordmgr-dialog-updated"); pmDialog.close(); resolve(); break; } } - }); });
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js +++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_switchtab.js @@ -1,17 +1,16 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.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 PROMPT_URL = "chrome://global/content/commonDialog.xul"; add_task(async function test() { await new Promise(resolve => { - let tab = BrowserTestUtils.addTab(gBrowser); isnot(tab, gBrowser.selectedTab, "New tab shouldn't be selected"); let listener = { onOpenWindow(xulWin) { var domwindow = xulWin.docShell.domWindow; waitForFocus(() => { is(domwindow.document.location.href, PROMPT_URL, "Should have seen a prompt window"); @@ -30,11 +29,10 @@ add_task(async function test() { Services.wm.addListener(listener); registerCleanupFunction(() => { Services.wm.removeListener(listener); gBrowser.removeTab(tab); }); BrowserTestUtils.browserLoaded(tab.linkedBrowser).then(() => finish()); BrowserTestUtils.loadURI(tab.linkedBrowser, "http://example.com/browser/toolkit/components/passwordmgr/test/browser/authenticate.sjs"); - }); });
--- a/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html +++ b/toolkit/components/passwordmgr/test/chrome/test_privbrowsing_perwindowpb.html @@ -187,17 +187,16 @@ function checkTest() { gotPass = iframe.contentDocument.getElementById("pass").textContent; is(gotUser, "notifyu1", "Checking submitted username"); is(gotPass, "notifyp1", "Checking submitted password"); Services.logins.removeLogin(login); break; default: ok(false, "Unexpected call to checkTest for test #" + testNum); - } } var mainWindow = window.docShell.rootTreeItem.domWindow; var contentPage = "http://mochi.test:8888/chrome/toolkit/components/passwordmgr/test/chrome/privbrowsing_perwindowpb_iframe.html"; var testWindows = []; function whenDelayedStartupFinished(aWindow, aCallback) {
--- a/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html +++ b/toolkit/components/passwordmgr/test/mochitest/test_basic_form_pwonly.html @@ -177,17 +177,16 @@ password-only, the other is username+pas </div> <pre id="test"> <script class="testbody" type="text/javascript"> /** Test for Login Manager: password-only logins **/ function startTest() { - checkForm(1, "1234"); checkForm(2, "1234", ""); checkForm(3, "1234", "", ""); checkUnmodifiedForm(4); checkForm(5, "", "1234"); checkForm(6, "someuser", "");
--- a/toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js +++ b/toolkit/components/passwordmgr/test/unit/test_OSCrypto_win.js @@ -27,17 +27,16 @@ add_task(function test_getIELoginHash() "6935CF27628830605927F86AB53831016FC8973D1A"); Assert.equal(crypto.getIELoginHash("https://reviewboard.mozilla.org/account/login/"), "09141FD287E2E59A8B1D3BB5671537FD3D6B61337A"); Assert.equal(crypto.getIELoginHash("https://www.facebook.com/"), "EF44D3E034009CB0FD1B1D81A1FF3F3335213BD796"); - }); add_task(function test_decryptData_encryptData() { function decryptEncryptTest(key) { Assert.equal(crypto.decryptData(crypto.encryptData("", key), key), ""); Assert.equal(crypto.decryptData(crypto.encryptData("secret", key), key),
--- a/toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js +++ b/toolkit/components/passwordmgr/test/unit/test_dedupeLogins.js @@ -238,17 +238,16 @@ add_task(async function test_dedupeLogin let description = tc.shift(); let expected = tc.shift(); let actual = LoginHelper.dedupeLogins(...tc); Assert.strictEqual(actual.length, expected.length, `Check: ${description}`); for (let [i, login] of expected.entries()) { Assert.strictEqual(actual[i], login, `Check index ${i}`); } } - }); add_task(async function test_dedupeLogins_preferredOriginMissing() { let testcases = [ [ "resolveBy scheme + timePasswordChanged, missing preferredOrigin", /preferredOrigin/, [DOMAIN1_HTTPS_TO_HTTPS_U1_P1, DOMAIN1_HTTP_TO_HTTP_U1_P1],
--- a/toolkit/components/passwordmgr/test/unit/test_notifications.js +++ b/toolkit/components/passwordmgr/test/unit/test_notifications.js @@ -44,19 +44,17 @@ var TestObserver = { } expectedNotification = null; // ensure a duplicate is flagged as unexpected. expectedData = null; }, }; add_task(function test_notifications() { - try { - var testnum = 0; var testdesc = "Setup of nsLoginInfo test-users"; var testuser1 = new LoginInfo("http://testhost1", "", null, "dummydude", "itsasecret", "put_user_here", "put_pw_here"); var testuser2 = new LoginInfo("http://testhost2", "", null, "dummydude2", "itsasecret2", "put_user2_here", "put_pw2_here"); @@ -158,14 +156,12 @@ add_task(function test_notifications() { expectedData = "http://site.com"; Services.logins.setLoginSavingEnabled("http://site.com", true); Assert.equal(expectedNotification, null); LoginTestUtils.checkLogins([]); Services.obs.removeObserver(TestObserver, "passwordmgr-storage-changed"); LoginTestUtils.clearData(); - } catch (e) { throw new Error("FAILED in test #" + testnum + " -- " + testdesc + ": " + e); } - });
--- a/toolkit/components/passwordmgr/test/unit/test_recipes_add.js +++ b/toolkit/components/passwordmgr/test/unit/test_recipes_add.js @@ -17,17 +17,16 @@ add_task(async function test_init() { Assert.ok(recipesParent instanceof LoginRecipesParent, "Check init return value"); Assert.strictEqual(recipesParent._recipesByHost.size, 0, "Initially 0 recipes"); }); add_task(async function test_get_missing_host() { let recipesParent = await RecipeHelpers.initNewParent(); let exampleRecipes = recipesParent.getRecipesForHost("example.invalid"); Assert.strictEqual(exampleRecipes.size, 0, "Check recipe count for example.invalid"); - }); add_task(async function test_add_get_simple_host() { let recipesParent = await RecipeHelpers.initNewParent(); Assert.strictEqual(recipesParent._recipesByHost.size, 0, "Initially 0 recipes"); recipesParent.add({ hosts: ["example.com"], });
--- a/toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js +++ b/toolkit/components/passwordmgr/test/unit/test_storage_mozStorage.js @@ -78,21 +78,19 @@ function setLoginSavingEnabled(origin, e if (enabled) { Services.perms.remove(uri, PERMISSION_SAVE_LOGINS); } else { Services.perms.add(uri, PERMISSION_SAVE_LOGINS, Services.perms.DENY_ACTION); } } add_task(async function test_execute() { - const OUTDIR = OS.Constants.Path.profileDir; try { - var isGUID = /^\{[0-9a-f\d]{8}-[0-9a-f\d]{4}-[0-9a-f\d]{4}-[0-9a-f\d]{4}-[0-9a-f\d]{12}\}$/; function getGUIDforID(conn, id) { var stmt = conn.createStatement("SELECT guid from moz_logins WHERE id = " + id); stmt.executeStep(); var guid = stmt.getString(0); stmt.finalize(); return guid; } @@ -489,14 +487,12 @@ add_task(async function test_execute() { // check the file exists var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile); file.initWithPath(OS.Constants.Path.profileDir); file.append(filename); Assert.ok(file.exists()); deleteFile(OS.Constants.Path.profileDir, filename + ".corrupt"); deleteFile(OS.Constants.Path.profileDir, filename); - } catch (e) { throw new Error("FAILED in test #" + testnum + " -- " + testdesc + ": " + e); } - });
--- a/toolkit/components/places/Bookmarks.jsm +++ b/toolkit/components/places/Bookmarks.jsm @@ -1713,17 +1713,16 @@ async function updateBookmark(db, info, return mergeIntoNewObject(item, info, additionalParentInfo); } // Insert implementation. function insertBookmark(item, parent) { return PlacesUtils.withConnectionWrapper("Bookmarks.jsm: insertBookmark", async function(db) { - // If a guid was not provided, generate one, so we won't need to fetch the // bookmark just after having created it. let hasExistingGuid = item.hasOwnProperty("guid"); if (!hasExistingGuid) item.guid = PlacesUtils.history.makeGuid(); let isTagging = parent._parentId == PlacesUtils.tagsFolderId; @@ -2262,18 +2261,16 @@ function reorderChildren(parent, ordered if (requestedChildIndices[i - 1] > requestedChildIndices[i]) { needReorder = true; break; } } } if (needReorder) { - - // Reorder the children array according to the specified order, provided // GUIDs come first, others are appended in somehow random order. children.sort((a, b) => { // This works provided fetchBookmarksByParent returns sorted children. if (!guidIndices.has(a.guid) && !guidIndices.has(b.guid)) { return currentIndices.get(a.guid) < currentIndices.get(b.guid) ? -1 : 1; } if (!guidIndices.has(a.guid)) {
--- a/toolkit/components/places/PlacesDBUtils.jsm +++ b/toolkit/components/places/PlacesDBUtils.jsm @@ -944,17 +944,16 @@ var PlacesDBUtils = { await db.execute(query, params, r => { logs.push(`Index ${r.getResultByIndex(0)}`); }); params.type = "trigger"; await db.execute(query, params, r => { logs.push(`Trigger ${r.getResultByIndex(0)}`); }); - } catch (ex) { throw new Error("Unable to collect stats."); } return logs; }, /**
--- a/toolkit/components/places/PlacesUtils.jsm +++ b/toolkit/components/places/PlacesUtils.jsm @@ -2624,17 +2624,16 @@ var GuidHelper = { async getItemGuid(aItemId) { let cached = this.guidsForIds.get(aItemId); if (cached !== undefined) return cached; let guid = await PlacesUtils.withConnectionWrapper("GuidHelper.getItemGuid", async function(db) { - let rows = await db.executeCached( "SELECT b.id, b.guid from moz_bookmarks b WHERE b.id = :id LIMIT 1", { id: aItemId }); if (rows.length == 0) throw new Error("no item found for the given itemId"); return rows[0].getResultByName("guid"); });
--- a/toolkit/components/places/SyncedBookmarksMirror.jsm +++ b/toolkit/components/places/SyncedBookmarksMirror.jsm @@ -1337,17 +1337,16 @@ class SyncedBookmarksMirror { * @param {Object[]} deletions * `{ guid, localLevel, shouldUploadTombstone }` tuples for items to * remove from Places, write tombstones, and flag as merged. */ async updateLocalItemsInPlaces(mergeStatesParams, deletions) { MirrorLog.trace("Setting up merge states table"); for (let chunk of PlacesSyncUtils.chunkArray(mergeStatesParams, Math.floor(SQLITE_MAX_VARIABLE_NUMBER / 3))) { - await this.db.execute(` INSERT INTO mergeStates(localGuid, mergedGuid, parentGuid, level, position, useRemote, shouldUpload) VALUES ${chunk.map(param => `(?, ?, ?, ${param.level}, ${param.position}, ${param.useRemote}, ${param.shouldUpload})` ).join(",")}`, chunk.flatMap(param => [param.localGuid, param.mergedGuid, @@ -1369,17 +1368,16 @@ class SyncedBookmarksMirror { JOIN mergeStates r ON r.mergedGuid = v.guid WHERE r.useRemote`, { queryKind: SyncedBookmarksMirror.KIND.QUERY }); await this.db.execute(`DELETE FROM moz_updateoriginsinsert_temp`); MirrorLog.trace("Setting up deletions table"); for (let chunk of PlacesSyncUtils.chunkArray(deletions, SQLITE_MAX_VARIABLE_NUMBER)) { - // This fires the `noteItemRemoved` trigger, which records observer infos // for deletions. It's important we do this before updating the structure, // so that the trigger captures the old parent and position. await this.db.execute(` INSERT INTO itemsToRemove(guid, localLevel, shouldUploadTombstone) VALUES ${chunk.map(({ localLevel, shouldUploadTombstone }) => `(?, ${localLevel}, ${shouldUploadTombstone})` ).join(",")}`,
--- a/toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js +++ b/toolkit/components/places/tests/bookmarks/test_1017502-bookmarks_foreign_count.js @@ -54,17 +54,16 @@ add_task(async function add_remove_chang // Check foreign count for original URI Assert.equal((await getForeignCountForURL(conn, T_URI)), 0); // Check foreign count for new URI Assert.equal((await getForeignCountForURL(conn, URI2)), 1); // Cleanup - Remove changed bookmark await PlacesUtils.bookmarks.remove(bm1); Assert.equal((await getForeignCountForURL(conn, URI2)), 0); - }); add_task(async function maintenance_foreign_count_test() { let conn = await PlacesUtils.promiseDBConnection(); // Simulate a visit to the url await PlacesTestUtils.addVisits(T_URI);
--- a/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js +++ b/toolkit/components/places/tests/bookmarks/test_424958-json-quoted-folders.js @@ -38,10 +38,9 @@ add_task(async function() { // restore json file await BookmarkJSONUtils.importFromFile(jsonFile, { replace: true }); checkQuotedFolder(); // clean up await OS.File.remove(jsonFile); - });
--- a/toolkit/components/places/tests/bookmarks/test_bmindex.js +++ b/toolkit/components/places/tests/bookmarks/test_bmindex.js @@ -106,12 +106,11 @@ add_task(async function test_bookmarks_i bm.index = newIndex; await PlacesUtils.bookmarks.update(bm); if (newIndex < -1) do_throw("Moving an item to a negative index should throw\n"); } catch (ex) { if (newIndex >= -1) do_throw("Moving an item to a valid index should not throw\n"); } - } await check_contiguous_indexes(bookmarks); });
--- a/toolkit/components/places/tests/favicons/test_setAndFetchFaviconForPage_failures.js +++ b/toolkit/components/places/tests/favicons/test_setAndFetchFaviconForPage_failures.js @@ -88,10 +88,9 @@ add_task(async function() { // This is the only test that should cause the waitForFaviconChanged // callback to be invoked. await PlacesTestUtils.addVisits({ uri: lastPageURI, transition: TRANSITION_TYPED }); PlacesUtils.favicons.setAndFetchFaviconForPage(lastPageURI, SMALLPNG_DATA_URI, true, PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE, null, Services.scriptSecurityManager.getSystemPrincipal()); await promiseIconChanged; - });
--- a/toolkit/components/places/tests/queries/head_queries.js +++ b/toolkit/components/places/tests/queries/head_queries.js @@ -321,17 +321,16 @@ function isInResult(aQueryData, aRoot) { } /** * A nice helper function for debugging things. It prints the contents of a * result set. */ function displayResultSet(aRoot) { - var wasOpen = aRoot.containerOpen; if (!wasOpen) aRoot.containerOpen = true; if (!aRoot.hasChildren) { // Something wrong? Empty result set? info("Result Set Empty"); return;
--- a/toolkit/components/places/tests/unifiedcomplete/test_history_autocomplete_tags.js +++ b/toolkit/components/places/tests/unifiedcomplete/test_history_autocomplete_tags.js @@ -53,17 +53,16 @@ async function ensure_tag_results(uris, // Make an AutoCompleteInput that uses our searches // and confirms results on search complete var input = new AutoCompleteInput(["unifiedcomplete"]); controller.input = input; return new Promise(resolve => { - var numSearchesStarted = 0; input.onSearchBegin = function() { numSearchesStarted++; Assert.equal(numSearchesStarted, 1); }; input.onSearchComplete = function() { Assert.equal(numSearchesStarted, 1);
--- a/toolkit/components/places/tests/unit/test_000_frecency.js +++ b/toolkit/components/places/tests/unit/test_000_frecency.js @@ -243,11 +243,10 @@ add_task(async function test_frecency() "' and '" + expectURL + "'"); Assert.equal(getFrecency(searchURL), getFrecency(expectURL)); } } resolve(); }; controller.startSearch(searchTerm); - }); });
--- a/toolkit/components/places/tests/unit/test_hash.js +++ b/toolkit/components/places/tests/unit/test_hash.js @@ -34,11 +34,10 @@ add_task(async function() { UPDATE moz_places SET url_hash = hash(:url), url = :url WHERE id = :id `, {url, id}); rows = await wdb.execute( "SELECT id FROM moz_places WHERE url_hash = hash(:url) AND url = :url", {url}); Assert.equal(rows.length, 1, "Matched the place from the database"); }); - } });
--- a/toolkit/components/places/tests/unit/test_markpageas.js +++ b/toolkit/components/places/tests/unit/test_markpageas.js @@ -42,10 +42,9 @@ add_task(async function test_execute() { } await PlacesTestUtils.addVisits({ uri: uri(visit.url), transition: visit.transition, }); } await completionPromise; - });
--- a/toolkit/components/printing/content/printPageSetup.js +++ b/toolkit/components/printing/content/printPageSetup.js @@ -54,17 +54,16 @@ function initDialog() { gDialog.enabled = false; gDialog.strings = []; gDialog.strings["marginUnits.inches"] = document.getElementById("marginUnits.inches").childNodes[0].nodeValue; gDialog.strings["marginUnits.metric"] = document.getElementById("marginUnits.metric").childNodes[0].nodeValue; gDialog.strings["customPrompt.title"] = document.getElementById("customPrompt.title").childNodes[0].nodeValue; gDialog.strings["customPrompt.prompt"] = document.getElementById("customPrompt.prompt").childNodes[0].nodeValue; - } // --------------------------------------------------- function isListOfPrinterFeaturesAvailable() { return Services.prefs.getBoolPref("print.tmp.printerfeatures." + gPrintSettings.printerName + ".has_special_printerfeatures", false); } @@ -357,17 +356,16 @@ function convertMarginInchesToUnits(aVal if (aIsMetric) { return aVal * 25.4; } return aVal; } // --------------------------------------------------- function onAccept() { - if (gPrintSettings) { if ( gDialog.orientation.selectedItem == gDialog.portrait ) { gPrintSettings.orientation = gPrintSettingsInterface.kPortraitOrientation; } else { gPrintSettings.orientation = gPrintSettingsInterface.kLandscapeOrientation; } // save these out so they can be picked up by the device spec
--- a/toolkit/components/printing/content/printPreviewToolbar.js +++ b/toolkit/components/printing/content/printPreviewToolbar.js @@ -3,17 +3,16 @@ // -*- tab-width: 2; 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/. */ customElements.define("printpreview-toolbar", class PrintPreviewToolbar extends MozXULElement { - constructor() { super(); this.disconnectedCallback = this.disconnectedCallback.bind(this); } connectedCallback() { window.addEventListener("unload", this.disconnectedCallback, { once: true }); this.appendChild(MozXULElement.parseXULToFragment(` <button id="print-preview-print" label="&print.label;" accesskey="&print.accesskey;" oncommand="this.parentNode.print();"/>
--- a/toolkit/components/printing/content/printProgress.js +++ b/toolkit/components/printing/content/printProgress.js @@ -181,17 +181,16 @@ function loadDialog() { function replaceInsert( text, index, value ) { var result = text; var regExp = new RegExp( "#" + index ); result = result.replace( regExp, value ); return result; } function onLoad() { - // Set global variables. printProgress = window.arguments[0]; if (window.arguments[1]) { progressParams = window.arguments[1].QueryInterface(Ci.nsIPrintProgressParams); if (progressParams) { docTitle = ellipseString(progressParams.docTitle, false); docURL = ellipseString(progressParams.docURL, true); }
--- a/toolkit/components/promiseworker/PromiseWorker.jsm +++ b/toolkit/components/promiseworker/PromiseWorker.jsm @@ -342,17 +342,16 @@ this.BasePromiseWorker.prototype = { let durationMs = Math.max(0, reply.durationMs); // Accumulate (or initialize) outExecutionDuration if (typeof options.outExecutionDuration == "number") { options.outExecutionDuration += durationMs; } else { options.outExecutionDuration = durationMs; } return reply.ok; - }.bind(this))(); }, /** * Terminate the worker, if it has been created at all, and set things up to * be instantiated lazily again on the next `post()`. * If there are pending Promises in the queue, we'll reject them and clear it. */
--- a/toolkit/components/prompts/src/nsPrompter.js +++ b/toolkit/components/prompts/src/nsPrompter.js @@ -669,17 +669,16 @@ ModalPrompter.prototype = { checkValue.value = args.checked; // Did user click Ok or Cancel? return args.ok; }, confirmEx(title, text, flags, button0, button1, button2, checkLabel, checkValue) { - if (!title) title = PromptUtils.getLocalizedString("Confirm"); let args = { promptType: "confirmEx", title, text, checkLabel,
--- a/toolkit/components/prompts/test/chromeScript.js +++ b/toolkit/components/prompts/test/chromeScript.js @@ -43,17 +43,16 @@ function handlePrompt(action, isTabModal if (!doc) { return false; // try again in a bit } if (isSelect) ui = doc; else ui = doc.defaultView.Dialog.ui; - } let promptState; if (isSelect) { promptState = getSelectState(ui); dismissSelect(ui, action); } else { promptState = getPromptState(ui);
--- a/toolkit/components/reader/test/head.js +++ b/toolkit/components/reader/test/head.js @@ -49,15 +49,14 @@ function promiseTabLoadEvent(tab, url) { // if our loaded promise resolves before the timeout, then we resolve the // timeout promise as well, causing the all promise to resolve. return Promise.all([deferred.promise, loaded]); } function is_element_visible(element, msg) { isnot(element, null, "Element should not be null, when checking visibility"); ok(BrowserTestUtils.is_visible(element), msg || "Element should be visible"); - } function is_element_hidden(element, msg) { isnot(element, null, "Element should not be null, when checking visibility"); ok(BrowserTestUtils.is_hidden(element), msg || "Element should be hidden"); }
--- a/toolkit/components/reputationservice/test/unit/test_login_rep.js +++ b/toolkit/components/reputationservice/test/unit/test_login_rep.js @@ -21,17 +21,16 @@ const exampleURI = "http://user:password const LOCAL_WHITELIST_DATA = { tableName: "test-passwordwhite-proto", providerName: "test", updateUrl: "http://localhost:5555/safebrowsing/update?", gethashUrl: "", }; add_task(async function test_setup() { - // Enable login reputation service Services.prefs.setBoolPref("browser.safebrowsing.passwords.enabled", true); gLoginRep.init(); // Setup local whitelist table. Services.prefs.setCharPref("urlclassifier.passwordAllowTable", "test-passwordwhite-proto"); gListManager.registerTable(LOCAL_WHITELIST_DATA.tableName, LOCAL_WHITELIST_DATA.providerName,
--- a/toolkit/components/satchel/.eslintrc.js +++ b/toolkit/components/satchel/.eslintrc.js @@ -41,17 +41,16 @@ module.exports = { "no-unused-expressions": "error", "no-unused-vars": ["error", { args: "none", vars: "all", }], "no-use-before-define": ["error", { functions: false, }], - "padded-blocks": ["error", "never"], radix: "error", semi: ["error", "always"], "semi-spacing": ["error", {"before": false, "after": true}], "space-in-parens": ["error", "never"], "valid-jsdoc": ["error", { prefer: { return: "returns", },
--- a/toolkit/components/search/nsSearchService.js +++ b/toolkit/components/search/nsSearchService.js @@ -1387,17 +1387,16 @@ Engine.prototype = { this._data = responseXML.documentElement; resolve(); }; request.onerror = function(aEvent) { resolve(); }; request.open("GET", aURL, true); request.send(); - }); }, _initFromURISync: function SRCH_ENG_initFromURISync(uri) { ENSURE_WARN(uri instanceof Ci.nsIURI, "Must have URI when calling _initFromURISync!", Cr.NS_ERROR_UNEXPECTED); @@ -1760,17 +1759,16 @@ Engine.prototype = { let element = this._data; if ((element.localName == MOZSEARCH_LOCALNAME && element.namespaceURI == MOZSEARCH_NS_10) || (element.localName == OPENSEARCH_LOCALNAME && OPENSEARCH_NAMESPACES.includes(element.namespaceURI))) { LOG("_init: Initing search plugin from " + this._location); this._parse(); - } else { Cu.reportError("Invalid search plugin due to namespace not matching."); FAIL(this._location + " is not a valid search plugin.", Cr.NS_ERROR_FILE_CORRUPTED); } // No need to keep a ref to our data (which in some cases can be a document // element) past this point this._data = null; }, @@ -2912,17 +2910,16 @@ SearchService.prototype = { let locations; try { locations = getDir(NS_APP_DISTRIBUTION_SEARCH_DIR_LIST, Ci.nsISimpleEnumerator); } catch (e) { // NS_APP_DISTRIBUTION_SEARCH_DIR_LIST is defined by each app // so this throws during unit tests (but not xpcshell tests). locations = []; - } for (let dir of locations) { if (dir.directoryEntries.nextFile) distDirs.push(dir); } function notInCacheVisibleEngines(aEngineName) { return !cache.visibleDefaultEngines.includes(aEngineName); @@ -4656,17 +4653,16 @@ SearchService.prototype = { } LOG(engine.name + " has expired"); engineUpdateService.update(engine); // Schedule the next update engineUpdateService.scheduleNextUpdate(engine); - } // end engine iteration }, _addObservers: function SRCH_SVC_addObservers() { if (this._observersAdded) { // There might be a race between synchronous and asynchronous // initialization for which we try to register the observers twice. return;
--- a/toolkit/components/search/tests/xpcshell/test_location.js +++ b/toolkit/components/search/tests/xpcshell/test_location.js @@ -8,17 +8,16 @@ function run_test() { // check we have "success" recorded in telemetry checkCountryResultTelemetry(TELEMETRY_RESULT_ENUM.SUCCESS); // a false value for each of SEARCH_SERVICE_COUNTRY_TIMEOUT and SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT for (let hid of ["SEARCH_SERVICE_COUNTRY_TIMEOUT", "SEARCH_SERVICE_COUNTRY_FETCH_CAUSED_SYNC_INIT"]) { let histogram = Services.telemetry.getHistogramById(hid); let snapshot = histogram.snapshot(); deepEqual(snapshot.values, {0: 1, 1: 0}); // boolean probe so 3 buckets, expect 1 result for |0|. - } // simple checks for our platform-specific telemetry. We can't influence // what they return (as we can't influence the countryCode the platform // thinks we are in), but we can check the values are correct given reality. let probeUSMismatched, probeNonUSMismatched; switch (Services.appinfo.OS) { case "Darwin":
--- a/toolkit/components/telemetry/pings/TelemetrySession.jsm +++ b/toolkit/components/telemetry/pings/TelemetrySession.jsm @@ -1605,17 +1605,16 @@ var Impl = { for (const [i, histogramName] of prioEncodedHistograms.entries()) { try { if (histogramName in payloadObj.histograms) { const histogram = payloadObj.histograms[histogramName]; prioParams.booleans[i] = Boolean(histogram.sum); } else { prioParams.booleans[i] = false; } - } catch (ex) { this._log.error(ex); } } // Prio encode the data and add to payload. const batchID = Services.appinfo.appBuildID;
--- a/toolkit/components/telemetry/tests/unit/head.js +++ b/toolkit/components/telemetry/tests/unit/head.js @@ -343,17 +343,16 @@ function getSnapshot(histogramId) { return Telemetry.getHistogramById(histogramId).snapshot(); } // Helper for setting an empty list of Environment preferences to watch. function setEmptyPrefWatchlist() { const {TelemetryEnvironment} = ChromeUtils.import("resource://gre/modules/TelemetryEnvironment.jsm"); return TelemetryEnvironment.onInitialized().then(() => { TelemetryEnvironment.testWatchPreferences(new Map()); - }); } if (runningInParent) { // Set logging preferences for all the tests. Services.prefs.setCharPref("toolkit.telemetry.log.level", "Trace"); // Telemetry archiving should be on. Services.prefs.setBoolPref(TelemetryUtils.Preferences.ArchiveEnabled, true);
--- a/toolkit/components/telemetry/tests/unit/test_EventPing.js +++ b/toolkit/components/telemetry/tests/unit/test_EventPing.js @@ -134,17 +134,16 @@ add_task(async function test_eventLimitR Assert.equal(payload.lostEventsCount, 0, "Lost no events"); Assert.ok(!payload.events.parent.some(ev => ev[3] === "object2"), "Should not have included any of the lost two events from the previous bunch."); pingCount++; }); callback(); // Trigger the send immediately }); recordEvents(1); Assert.equal(pingCount, 3, "Should have sent a third ping"); - }); add_task(async function test_timers() { Telemetry.clearEvents(); TelemetryEventPing.testReset(); // Immediately after submitting a MAX ping, we should set the timer for the // next interval. @@ -153,17 +152,16 @@ add_task(async function test_timers() { Assert.equal(delay, TelemetryEventPing.minFrequency, "Timer should be started with the min frequency"); }, pass, pass); recordEvents(1); fakePolicy((callback, delay) => { Assert.ok(delay <= TelemetryEventPing.maxFrequency, "Timer should be at most the max frequency for a subsequent MAX ping."); }, pass, pass); recordEvents(1000); - }); add_task(async function test_periodic() { Telemetry.clearEvents(); TelemetryEventPing.testReset(); fakePolicy((callback, delay) => { Assert.equal(delay, TelemetryEventPing.minFrequency, "Timer should default to the min frequency");
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetryEnvironment.js @@ -1093,17 +1093,16 @@ add_task(async function test_prefInvalid [PREF_TEST_1, {what: TelemetryEnvironment.RECORD_DEFAULTPREF_VALUE}], [PREF_TEST_2, {what: TelemetryEnvironment.RECORD_DEFAULTPREF_STATE}], ]); TelemetryEnvironment.testWatchPreferences(PREFS_TO_WATCH); Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST_1], undefined); Assert.strictEqual(TelemetryEnvironment.currentEnvironment.settings.userPrefs[PREF_TEST_2], undefined); - }); add_task(async function test_addonsWatch_InterestingChange() { const ADDON_INSTALL_URL = gDataRoot + "restartless.xpi"; const ADDON_ID = "tel-restartless-webext@tests.mozilla.org"; // We only expect a single notification for each install, uninstall, enable, disable. const EXPECTED_NOTIFICATIONS = 4;
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetryEvents.js @@ -109,17 +109,16 @@ add_task(async function test_event_summa Telemetry.recordEvent("telemetry.test.dynamic", "testMethod", object); } let snapshot = Telemetry.snapshotEvents(OPTIN, true); Assert.equal(snapshot.dynamic.length, limit + 1, "Should have recorded all events"); let scalarSnapshot = Telemetry.getSnapshotForKeyedScalars("main", true); Assert.equal(Object.keys(scalarSnapshot.dynamic["telemetry.dynamic_event_counts"]).length, limit, "Should not have recorded more than `limit` events"); - }); add_task(async function test_recording_state() { Telemetry.clearEvents(); Telemetry.clearScalars(); const events = [ ["telemetry.test", "test1", "object1"], @@ -293,18 +292,16 @@ add_task(async function test_clear() { Telemetry.recordEvent("telemetry.test", "test1", "object1"); snapshot = Telemetry.snapshotEvents(OPTIN, false, 5); Assert.ok(("parent" in snapshot), "Should have entry for main process."); Assert.equal(snapshot.parent.length, 5, "Should have returned 5 events"); snapshot = Telemetry.snapshotEvents(OPTIN, true); Assert.ok(("parent" in snapshot), "Should have entry for main process."); Assert.equal(snapshot.parent.length, (2 * COUNT) - 5 + 1, `Should have returned ${(2 * COUNT) - 5 + 1} events`); - - }); add_task(async function test_expiry() { Telemetry.clearEvents(); // Recording call with event that is expired by version. Telemetry.recordEvent("telemetry.test", "expired_version", "object1"); checkRecordingFailure(1 /* Expired */);
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_multistore.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_multistore.js @@ -156,17 +156,16 @@ add_task(async function test_multistore_ Assert.equal(syncScalars[MULTIPLE_STORES], 2, `Multi-store scalar ${MULTIPLE_STORES} must manage independently for add operations.`); mainScalars = getParentSnapshot("main"); Assert.equal(mainScalars[MULTIPLE_STORES], 1235, `Multi-store scalar ${MULTIPLE_STORES} must add properly.`); Telemetry.scalarSet(MULTIPLE_STORES, 9876); assertBothEqual(9876); - }); add_task(async function test_empty_absence() { // Current semantics are we don't snapshot empty things. // So no {parent: {}, ...}. Instead {...}. Telemetry.clearScalars(); @@ -214,17 +213,16 @@ add_task(async function test_empty_absen snapshot = getParentSnapshot("sync", true /* keyed */); Assert.ok(MULTIPLE_STORES_KEYED in snapshot, `${MULTIPLE_STORES_KEYED} must be in the sync snapshot.`); Assert.ok(key in snapshot[MULTIPLE_STORES_KEYED], `${MULTIPLE_STORES_KEYED} must have the stored key.`); Assert.equal(snapshot[MULTIPLE_STORES_KEYED][key], 1, `${MULTIPLE_STORES_KEYED}[${key}] should have the correct value.`); - }); add_task(async function test_multistore_default_values() { Telemetry.clearScalars(); const expectedUint = 3785; const expectedKey = "some key"; Telemetry.scalarSet(MAIN_ONLY, expectedUint);
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js @@ -84,17 +84,16 @@ function fakeGenerateUUID(sessionFunc, s } function fakeIdleNotification(topic) { let session = ChromeUtils.import("resource://gre/modules/TelemetrySession.jsm", null); return session.TelemetryScheduler.observe(null, topic, null); } function setupTestData() { - Services.startup.interrupted = true; let h2 = Telemetry.getHistogramById("TELEMETRY_TEST_COUNT"); h2.add(); let k1 = Telemetry.getKeyedHistogramById("TELEMETRY_TEST_KEYED_COUNT"); k1.add("a"); k1.add("a"); k1.add("b"); @@ -481,17 +480,16 @@ add_task(async function test_setup() { add_task(async function asyncSetup() { await TelemetryController.testSetup(); // Load the client ID from the client ID provider to check for pings sanity. gClientID = await ClientID.getClientID(); }); // Ensures that expired histograms are not part of the payload. add_task(async function test_expiredHistogram() { - let dummy = Telemetry.getHistogramById("TELEMETRY_TEST_EXPIRED"); dummy.add(1); Assert.equal(TelemetrySession.getPayload().histograms.TELEMETRY_TEST_EXPIRED, undefined); }); // Sends a ping to a non existing server. If we remove this test, we won't get
--- a/toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js +++ b/toolkit/components/terminator/tests/xpcshell/test_terminator_reload.js @@ -68,10 +68,9 @@ add_task(async function test_reload() { info("Testing histogram " + id); let snapshot = telemetrySnapshots[id]; let count = 0; for (let x of Object.values(snapshot.values)) { count += x; } Assert.equal(count, 1, "We have added one item"); } - });
--- a/toolkit/components/thumbnails/PageThumbs.jsm +++ b/toolkit/components/thumbnails/PageThumbs.jsm @@ -158,24 +158,22 @@ var PageThumbs = { * @resolve {Blob} The thumbnail, as a Blob. */ captureToBlob: function PageThumbs_captureToBlob(aBrowser) { if (!this._prefEnabled()) { return null; } return new Promise(resolve => { - let canvas = this.createCanvas(aBrowser.contentWindow); this.captureToCanvas(aBrowser, canvas, () => { canvas.toBlob(blob => { resolve(blob, this.contentType); }); }); - }); }, /** * Captures a thumbnail from a given window and draws it to the given canvas. * Note, when dealing with remote content, this api draws into the passed * canvas asynchronously. Pass aCallback to receive an async callback after * canvas painting has completed. @@ -279,17 +277,16 @@ var PageThumbs = { * @param aWidth The desired canvas width. * @param aHeight The desired canvas height. * @param aArgs (optional) Additional named parameters: * fullScale - request that a non-downscaled image be returned. * @return a promise */ _captureRemoteThumbnail(aBrowser, aWidth, aHeight, aArgs) { return new Promise(resolve => { - // The index we send with the request so we can identify the // correct response. let index = gRemoteThumbId++; // Thumbnail request response handler let mm = aBrowser.messageManager; // Browser:Thumbnail:Response handler @@ -325,17 +322,16 @@ var PageThumbs = { mm.addMessageListener("Browser:Thumbnail:Response", thumbFunc); mm.sendAsyncMessage("Browser:Thumbnail:Request", { canvasWidth: aWidth, canvasHeight: aHeight, background: PageThumbUtils.THUMBNAIL_BG_COLOR, id: index, additionalArgs: aArgs, }); - }); }, /** * Captures a thumbnail for the given browser and stores it to the cache. * @param aBrowser The browser to capture a thumbnail for. * @param aCallback The function to be called when finished (optional). */
--- a/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js +++ b/toolkit/components/thumbnails/test/browser_thumbnails_bug818225.js @@ -1,29 +1,27 @@ /* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ const URL = "http://mochi.test:8888/browser/toolkit/components/thumbnails/" + "test/background_red.html?" + Date.now(); // Test PageThumbs API function getThumbnailPath function* runTests() { - let path = PageThumbs.getThumbnailPath(URL); yield testIfExists(path, false, "Thumbnail file does not exist"); yield addVisitsAndRepopulateNewTabLinks(URL, next); yield createThumbnail(URL); path = PageThumbs.getThumbnailPath(URL); let expectedPath = PageThumbsStorageService.getFilePathForURL(URL); is(path, expectedPath, "Thumbnail file has correct path"); yield testIfExists(path, true, "Thumbnail file exists"); - } function createThumbnail(aURL) { addTab(aURL, function() { gBrowserThumbnails.clearTopSiteURLCache(); whenFileExists(aURL, function() { gBrowser.removeTab(gBrowser.selectedTab); next();
--- a/toolkit/components/tooltiptext/TooltipTextProvider.js +++ b/toolkit/components/tooltiptext/TooltipTextProvider.js @@ -87,17 +87,16 @@ TooltipTextProvider.prototype = { } // Check texts against null so that title="" can be used to undefine a // title on a child element. let usedTipElement = null; while (tipElement && (titleText == null) && (XLinkTitleText == null) && (SVGTitleText == null) && (XULtooltiptextText == null)) { - if (tipElement.nodeType == defView.Node.ELEMENT_NODE) { if (tipElement.namespaceURI == XULNS) XULtooltiptextText = tipElement.getAttribute("tooltiptext"); else if (!(tipElement instanceof defView.SVGElement)) titleText = tipElement.getAttribute("title"); if ((tipElement instanceof defView.HTMLAnchorElement || tipElement instanceof defView.HTMLAreaElement ||
--- a/toolkit/components/url-classifier/nsUrlClassifierHashCompleter.js +++ b/toolkit/components/url-classifier/nsUrlClassifierHashCompleter.js @@ -398,17 +398,16 @@ HashCompleterRequest.prototype = { let metadata = line.substring(p + 1).split(":"); let stateBase64 = metadata[0]; this.tableNames.set(tableName, stateBase64); } }); aCallback(); }); - }, // This initiates the HTTP request. It can fail due to backoff timings and // will notify all callbacks as necessary. We notify the backoff object on // begin. begin: function HCR_begin() { if (!this._completer.canMakeRequest(this.gethashUrl)) { log("Can't make request to " + this.gethashUrl + "\n");
--- a/toolkit/components/url-classifier/nsUrlClassifierListManager.js +++ b/toolkit/components/url-classifier/nsUrlClassifierListManager.js @@ -115,17 +115,16 @@ PROT_ListManager.prototype.unregisterTab if (!this.updatesNeeded_(table.updateUrl) && this.updateCheckers_[table.updateUrl]) { this.updateCheckers_[table.updateUrl].cancel(); this.updateCheckers_[table.updateUrl] = null; } delete this.needsUpdate_[table.updateUrl][tableName]; } delete this.tablesData[tableName]; - }; /** * Delete all of our data tables which seem to leak otherwise. * Remove observers */ PROT_ListManager.prototype.shutdown_ = function() { this.stopUpdateCheckers();
--- a/toolkit/components/url-classifier/tests/mochitest/gethashFrame.html +++ b/toolkit/components/url-classifier/tests/mochitest/gethashFrame.html @@ -2,17 +2,16 @@ <head> <title></title> <script type="text/javascript"> var scriptItem = "untouched"; function checkLoads() { - var title = document.getElementById("title"); title.textContent = window.parent.shouldLoad ? "The following should be hidden:" : "The following should not be hidden:"; if (window.parent.shouldLoad) { window.parent.is(scriptItem, "loaded malware javascript!", "Should load bad javascript"); } else {
--- a/toolkit/components/url-classifier/tests/mochitest/test_classifier.html +++ b/toolkit/components/url-classifier/tests/mochitest/test_classifier.html @@ -104,17 +104,16 @@ function testService() { `Successful asynchronous local classification of ${test.url}`); } else { let result = results[0].QueryInterface(Ci.nsIUrlClassifierFeatureResult); is(result.list, test.table, `Successful asynchronous local classification of ${test.url}`); } runNextTest(); }); - }); } runNextTest(resolve); }); } SpecialPowers.pushPrefEnv( {"set": [["urlclassifier.malwareTable", "test-malware-simple,test-unwanted-simple,test-harmful-simple"],
--- a/toolkit/components/url-classifier/tests/mochitest/test_gethash.html +++ b/toolkit/components/url-classifier/tests/mochitest/test_gethash.html @@ -28,17 +28,16 @@ const NOTEXIST_URL = "http://mochi.test: var shouldLoad = false; // In this testcase we store prefixes to localdb and send the fullhash to gethash server. // When access the test page gecko should trigger gethash request to server and // get the completion response. function loadTestFrame(id) { return new Promise(function(resolve, reject) { - var iframe = document.getElementById(id); iframe.setAttribute("src", "gethashFrame.html"); iframe.onload = function() { resolve(); }; }); }
--- a/toolkit/components/url-classifier/tests/unit/test_addsub.js +++ b/toolkit/components/url-classifier/tests/unit/test_addsub.js @@ -57,17 +57,16 @@ function testSimpleSub() { var assertions = { "tableData": "test-phish-simple;a:1:s:50", "urlsExist": [ "bar.com/b" ], "urlsDontExist": ["foo.com/a" ], "subsDontExist": [ "foo.com/a" ], }; doTest([addUpdate, subUpdate], assertions); - } // Same as testSimpleSub(), but the sub comes in before the add. function testSubEmptiesAdd() { var subUrls = ["1:foo.com/a"]; var addUrls = ["foo.com/a", "bar.com/b"]; var subUpdate = buildPhishingUpdate(
--- a/toolkit/components/url-classifier/tests/unit/test_hashcompleter_v4.js +++ b/toolkit/components/url-classifier/tests/unit/test_hashcompleter_v4.js @@ -220,17 +220,16 @@ function registerHandlerUpdateV4() { "application/vnd.google.safebrowsing-update", false); response.setStatusLine(request.httpVersion, 200, "OK"); response.bodyOutputStream.write(UPDATE_RESPONSE_CONTENT, UPDATE_RESPONSE_CONTENT.length); waitUntilMetaDataSaved(NEW_CLIENT_STATE, CHECKSUM, () => { run_next_test(); }); - }); } function run_test() { throwOnUpdateErrors(); gHttpServV4 = new HttpServer(); gHttpServV4.registerDirectory("/", do_get_cwd());
--- a/toolkit/components/url-classifier/tests/unit/test_listmanager.js +++ b/toolkit/components/url-classifier/tests/unit/test_listmanager.js @@ -284,17 +284,16 @@ function run_test() { if (gUpdatedCntForTableData === SERVER_INVOLVED_TEST_CASE_LIST.length) { // All tests are done! run_next_test(); return; } info("Wait for all sever-involved tests to be done ..."); }); - }); gHttpServV4.start(5555); registerCleanupFunction(function() { return (async function() { await Promise.all([gHttpServ.stop(), gHttpServV4.stop()]);
--- a/toolkit/components/url-classifier/tests/unit/test_partial.js +++ b/toolkit/components/url-classifier/tests/unit/test_partial.js @@ -220,17 +220,16 @@ function testSpecFragments() { var assertions = { "tableData": "test-phish-simple;a:1", "urlsExist": probeUrls, "completerQueried": [completer, addUrls], }; doTest([update], assertions); - } // Test http://code.google.com/p/google-safe-browsing/wiki/Protocolv2Spec // section 6.2 example 2 function testMoreSpecFragments() { var probeUrls = [ "a.b.c.d.e.f.g/1.html" ]; var addUrls = [ "a.b.c.d.e.f.g/1.html", @@ -255,17 +254,16 @@ function testMoreSpecFragments() { var assertions = { "tableData": "test-phish-simple;a:1", "urlsExist": probeUrls, "completerQueried": [completer, addUrls], }; doTest([update], assertions); - } function testFalsePositives() { var addUrls = [ "foo.com/a", "foo.com/b", "bar.com/c" ]; var update = buildPhishingUpdate( [ { "chunkNum": 1, "urls": addUrls,
--- a/toolkit/components/viewsource/content/viewSource-content.js +++ b/toolkit/components/viewsource/content/viewSource-content.js @@ -500,17 +500,16 @@ var ViewSourceContent = { // The column number of the first character in the current text node. let firstCol = 1; let found = false; for (let textNode = treewalker.firstChild(); textNode && !found; textNode = treewalker.nextNode()) { - // \r is not a valid character in the DOM, so we only check for \n. let lineArray = textNode.data.split(/\n/); let lastLineInNode = curLine + lineArray.length - 1; // Check if we can skip the text node without further inspection. if (node ? (textNode != node) : (lastLineInNode < lineNumber)) { if (lineArray.length > 1) { firstCol = 1; @@ -520,17 +519,16 @@ var ViewSourceContent = { continue; } // curPos is the offset within the current text node of the first // character in the current line. for (var i = 0, curPos = 0; i < lineArray.length; curPos += lineArray[i++].length + 1) { - if (i > 0) { curLine++; } if (node) { if (offset >= curPos && offset <= curPos + lineArray[i].length) { // If we are right after the \n of a line and interlinePosition is // false, the caret looks as if it were at the end of the previous @@ -543,26 +541,24 @@ var ViewSourceContent = { } else { result.line = curLine; result.col = (i == 0 ? firstCol : 1) + offset - curPos; } found = true; break; } - } else if (curLine == lineNumber && !("range" in result)) { result.range = content.document.createRange(); result.range.setStart(textNode, curPos); // This will always be overridden later, except when we look for // the very last line in the file (this is the only line that does // not end with \n). result.range.setEndAfter(pre.lastChild); - } else if (curLine == lineNumber + 1) { result.range.setEnd(textNode, curPos - 1); found = true; break; } } }
--- a/toolkit/components/viewsource/test/browser/browser_contextmenu.js +++ b/toolkit/components/viewsource/test/browser/browser_contextmenu.js @@ -48,17 +48,16 @@ async function onViewSourceWindowOpen(aW }); expectedData.push(["a[href]", true, false, "http://example.com/"]); expectedData.push(["a[href^=mailto]", false, true, "abc@def.ghi"]); expectedData.push(["span", false, false, null]); } async function checkMenuItems(contextMenu, selector, copyLinkExpected, copyEmailExpected, expectedClipboardContent) { - let browser = gBrowser.selectedBrowser; await ContentTask.spawn(browser, { selector }, async function(arg) { content.document.querySelector(arg.selector).scrollIntoView(); }); let popupShownPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown"); await BrowserTestUtils.synthesizeMouseAtCenter(selector, { type: "contextmenu", button: 2}, browser);
--- a/toolkit/components/workerloader/require.js +++ b/toolkit/components/workerloader/require.js @@ -45,17 +45,16 @@ if (exports.require) { // Avoid double-imports return; } // Simple implementation of |require| let require = (function() { - /** * Mapping from module paths to module exports. * * @keys {string} The absolute path to a module. * @values {object} The |exports| objects for that module. */ let modules = new Map();
--- a/toolkit/content/aboutProfiles.js +++ b/toolkit/content/aboutProfiles.js @@ -206,17 +206,16 @@ function CreateProfile(profile) { function createProfileWizard() { // This should be rewritten in HTML eventually. window.openDialog("chrome://mozapps/content/profile/createProfileWizard.xul", "", "centerscreen,chrome,modal,titlebar", ProfileService); } async function renameProfile(profile) { - let newName = { value: profile.name }; let [title, msg] = await document.l10n.formatValues([ { id: "profiles-rename-profile-title" }, { id: "profiles-rename-profile", args: { name: profile.name } }, ]); if (Services.prompt.prompt(window, title, msg, newName, null, { value: 0 })) {
--- a/toolkit/content/aboutTelemetry.js +++ b/toolkit/content/aboutTelemetry.js @@ -2570,12 +2570,11 @@ function displayRichPingData(ping, updat // Show captured stacks. CapturedStacks.render(payload); LateWritesSingleton.renderLateWrites(payload.lateWrites); // Show simple measurements SimpleMeasurements.render(payload); - } window.addEventListener("load", onLoad);
--- a/toolkit/content/contentAreaUtils.js +++ b/toolkit/content/contentAreaUtils.js @@ -855,17 +855,16 @@ function appendFiltersForContentType(aFi } if (!bundleName) { if (aSaveMode != SAVEMODE_FILEONLY) throw "Invalid save mode for type '" + aContentType + "'"; var mimeInfo = getMIMEInfoForType(aContentType, aFileExtension); if (mimeInfo) { - var extString = ""; for (var extension of mimeInfo.getFileExtensions()) { if (extString) extString += "; "; // If adding more than one extension, // separate by semi-colon extString += "*." + extension; }
--- a/toolkit/content/customElements.js +++ b/toolkit/content/customElements.js @@ -6,17 +6,16 @@ // Define them here so that ESLint can find them: /* globals BaseControlMixin, MozElementMixin, MozXULElement, MozElements */ "use strict"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. (() => { - // Handle customElements.js being loaded as a script in addition to the subscriptLoader // from MainProcessSingleton, to handle pages that can open both before and after // MainProcessSingleton starts. See Bug 1501845. if (window.MozXULElement) { return; } const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); @@ -43,17 +42,16 @@ window.addEventListener("DOMContentLoade }, { once: true, capture: true }); const gXULDOMParser = new DOMParser(); gXULDOMParser.forceEnableXULXBL(); const MozElements = {}; const MozElementMixin = Base => class MozElement extends Base { - /* * Implements attribute inheritance by a child element. Uses XBL @inherit * syntax of |to=from|. * * @param {element} child * A child element that inherits an attribute. * @param {string} attr * An attribute to inherit. Optionally in the form of |to=from|, where
--- a/toolkit/content/process-content.js +++ b/toolkit/content/process-content.js @@ -40,17 +40,16 @@ let ProcessObserver = { Services.obs.removeObserver(this, topic); } }, observe(subject, topic, data) { switch (topic) { case "chrome-document-global-created": case "content-document-global-created": { - // Strip the hash from the URL, because it's not part of the origin. let window = subject; let url = window.document.documentURI.replace(/[\#|\?].*$/, ""); let registeredURLs = Services.cpmm.sharedData.get("RemotePageManager:urls"); if (!registeredURLs || !registeredURLs.has(url)) return;
--- a/toolkit/content/tests/browser/browser_audioCompeting_onlyForActiveAgent.js +++ b/toolkit/content/tests/browser/browser_audioCompeting_onlyForActiveAgent.js @@ -152,17 +152,16 @@ async function audio_competing_for_activ await ContentTask.spawn(browser, SuspendedType.NONE_SUSPENDED, check_audio1_suspended); info("- audio2 should still be suspended -"); await ContentTask.spawn(browser, SuspendedType.SUSPENDED_PAUSE_DISPOSABLE, check_audio2_suspended); await ContentTask.spawn(browser, true /* expect for pause */, check_audio2_pause_state); - } add_task(async function setup_test_preference() { await SpecialPowers.pushPrefEnv({"set": [ ["media.useAudioChannelService.testing", true], ["dom.audiochannel.audioCompeting", true], ["dom.audiochannel.audioCompeting.allAgents", true], ]});
--- a/toolkit/content/tests/browser/browser_default_image_filename_redirect.js +++ b/toolkit/content/tests/browser/browser_default_image_filename_redirect.js @@ -20,17 +20,16 @@ add_task(async function() { } WebRequest.onBeforeRequest.addListener(redirect, {urls: new MatchPatternSet(["http://*/*firebird.png"])}, ["blocking"] ); await BrowserTestUtils.withNewTab(URL_FIREBIRD, async function(browser) { - // Click image to show context menu. let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown"); await BrowserTestUtils.synthesizeMouseAtCenter("img", { type: "contextmenu", button: 2 }, browser); await popupShownPromise; // Prepare mock file picker.
--- a/toolkit/content/tests/browser/browser_findbar.js +++ b/toolkit/content/tests/browser/browser_findbar.js @@ -198,17 +198,16 @@ add_task(async function e10sLostKeys() { "findbar is now focused"); is(findBar._findField.value, "abc", "abc fully entered as find query"); BrowserTestUtils.removeTab(tab); }); function promiseFindFinished(searchText, highlightOn) { return new Promise(async (resolve) => { - let findbar = await gBrowser.getFindBar(); findbar.startFind(findbar.FIND_NORMAL); let highlightElement = findbar.getElement("highlight"); if (highlightElement.checked != highlightOn) highlightElement.click(); executeSoon(() => { findbar._findField.value = searchText; @@ -235,17 +234,16 @@ function promiseFindFinished(searchText, onFindResult: foundOrTimedout, onCurrentSelection() {}, onMatchesCountResult() {}, onHighlightFinished() {}, }; findbar.browser.finder.addResultListener(resultListener); findbar._find(); }); - }); } function promiseRemotenessChange(tab, shouldBeRemote) { return new Promise((resolve) => { let browser = gBrowser.getBrowserForTab(tab); tab.addEventListener("TabRemotenessChange", function() { resolve();
--- a/toolkit/content/tests/chrome/RegisterUnregisterChrome.js +++ b/toolkit/content/tests/chrome/RegisterUnregisterChrome.js @@ -39,17 +39,16 @@ function getParent(path) { return ""; } return "/" + path.substring(0, lastSlash).replace(/\\/g, "/"); } return path.substring(0, lastSlash); } function copyDirToTempProfile(path, subdirname) { - if (subdirname === undefined) { subdirname = "mochikit-tmp"; } let tmpdir = Services.dirsvc.get("ProfD", Ci.nsIFile); tmpdir.append(subdirname); tmpdir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o777); @@ -59,17 +58,16 @@ function copyDirToTempProfile(path, subd } // The SimpleTest directory is hidden var files = Array.from(dirIter("file://" + rootDir)); for (let f in files) { files[f].copyTo(tmpdir, ""); } return tmpdir; - } function convertChromeURI(chromeURI) { let uri = Services.io.newURI(chromeURI); return gChromeReg.convertChromeURL(uri); } function chromeURIToFile(chromeURI) {
--- a/toolkit/content/widgets/autocomplete.xml +++ b/toolkit/content/widgets/autocomplete.xml @@ -444,17 +444,16 @@ } } // Handle readline/emacs-style navigation bindings on Mac. if (isMac && this.popup.popupOpen && aEvent.ctrlKey && (aEvent.key === "n" || aEvent.key === "p")) { - const effectiveKey = (aEvent.key === "p") ? KeyEvent.DOM_VK_UP : KeyEvent.DOM_VK_DOWN; cancel = this.mController.handleKeyNavigation(effectiveKey); } // Handle keys we know aren't part of a shortcut, even with Alt or // Ctrl. @@ -1045,17 +1044,16 @@ "autofill-footer", "autofill-clear-button", "autofill-insecureWarning", ]; // Reuse the item when its style is exactly equal to the previous style or // neither of their style are in the UNREUSEABLE_STYLES. reusable = originalType === style || !(UNREUSEABLE_STYLES.includes(style) || UNREUSEABLE_STYLES.includes(originalType)); - } else { // need to create a new item item = document.createXULElement("richlistitem"); } item.setAttribute("dir", this.style.direction); item.setAttribute("ac-image", image); item.setAttribute("ac-value", value); @@ -1068,17 +1066,16 @@ // we are about to replace the currently moused-over item, to // avoid surprising the user. let iface = Ci.nsIAutoCompletePopup; if (reusable && originalText == trimmedSearchString && invalidateReason == iface.INVALIDATE_REASON_NEW_RESULT && (originalValue == value || this.mousedOverIndex === this._currentIndex)) { - // try to re-use the existing item let reused = item._reuseAcItem(); if (reused) { this._currentIndex++; continue; } } else { if (typeof item._cleanup == "function") { @@ -1827,17 +1824,16 @@ // If the item is a searchengine action, then it should // only be reused if the engine name is the same as the // popup's override engine name, if any. if (!action || action.type != "searchengine" || !popup.overrideSearchEngineName || action.params.engineName == popup.overrideSearchEngineName) { - this.collapsed = false; // The popup may have changed size between now and the last // time the item was shown, so always handle over/underflow. let dwu = window.windowUtils; let popupWidth = dwu.getBoundsWithoutFlushing(this.parentNode).width; if (!this._previousPopupWidth || this._previousPopupWidth != popupWidth) { this._previousPopupWidth = popupWidth;
--- a/toolkit/content/widgets/browser-custom-element.js +++ b/toolkit/content/widgets/browser-custom-element.js @@ -146,17 +146,16 @@ class MozBrowser extends MozElementMixin this.addEventListener("dragstart", (event) => { // If we're a remote browser dealing with a dragstart, stop it // from propagating up, since our content process should be dealing // with the mouse movement. if (this.isRemoteBrowser) { event.stopPropagation(); } }); - } resetFields() { if (this.observer) { try { Services.obs.removeObserver(this.observer, "browser:purge-session-history"); } catch (ex) { // It's not clear why this sometimes throws an exception. @@ -653,17 +652,16 @@ class MozBrowser extends MozElementMixin } catch (ex) {} let event = new Event("TextZoomChange", { bubbles: true }); this.dispatchEvent(event); } } else { this.markupDocumentViewer.textZoom = val; } - } get textZoom() { if (this.isRemoteBrowser) { return this._textZoom; } return this.markupDocumentViewer.textZoom; } @@ -1134,17 +1132,16 @@ class MozBrowser extends MozElementMixin this.messageManager.addMessageListener("AudioPlayback:ActiveMediaBlockStop", this); this.messageManager.addMessageListener("UnselectedTabHover:Toggle", this); this.messageManager.addMessageListener("GloballyAutoplayBlocked", this); if (this.hasAttribute("selectmenulist")) { this.messageManager.addMessageListener("Forms:ShowDropDown", this); this.messageManager.addMessageListener("Forms:HideDropDown", this); } - } } /** * This is necessary because the destructor doesn't always get called when * we are removed from a tabbrowser. This will be explicitly called by tabbrowser. */ destroy() { @@ -1346,17 +1343,16 @@ class MozBrowser extends MozElementMixin this.dispatchEvent(event); break; } default: return this._receiveMessage(aMessage); } return undefined; - } enableDisableCommandsRemoteOnly(aAction, aEnabledLength, aEnabledCommands, aDisabledLength, aDisabledCommands) { if (this._controller) { this._controller.enableDisableCommands(aAction, aEnabledLength, aEnabledCommands, aDisabledLength, aDisabledCommands); } @@ -1880,10 +1876,9 @@ class MozBrowser extends MozElementMixin return this.docShell ? this.docShell.getContentBlockingLog() : Promise.reject("docshell isn't available"); } } MozXULElement.implementCustomInterface(MozBrowser, [Ci.nsIBrowser, Ci.nsIFrameLoaderOwner]); customElements.define("browser", MozBrowser); - }
--- a/toolkit/content/widgets/datepicker.js +++ b/toolkit/content/widgets/datepicker.js @@ -223,17 +223,16 @@ function DatePicker(context) { this._update(); } break; } case "mouseup": { if (event.target == this.context.buttonPrev || event.target == this.context.buttonNext) { event.target.classList.remove("active"); } - } } }, /** * Handle postMessage events. * * @param {Event} event
--- a/toolkit/content/widgets/editor.js +++ b/toolkit/content/widgets/editor.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - /* globals XULFrameElement */ class MozEditor extends XULFrameElement { connectedCallback() { this._editorContentListener = { QueryInterface: ChromeUtils.generateQI([ "nsIURIContentListener", "nsISupportsWeakReference", @@ -155,10 +154,9 @@ class MozEditor extends XULFrameElement getHTMLEditor(containingWindow) { var editor = this.editingSession.getEditorForWindow(containingWindow); return editor.QueryInterface(Ci.nsIHTMLEditor); } } customElements.define("editor", MozEditor); - }
--- a/toolkit/content/widgets/findbar.js +++ b/toolkit/content/widgets/findbar.js @@ -3,17 +3,16 @@ * License, v. 2.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"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); class MozFindbar extends XULElement { constructor() { super(); MozXULElement.insertFTLIfNeeded("toolkit/main-window/findbar.ftl"); this.destroy = this.destroy.bind(this); @@ -225,17 +224,16 @@ class MozFindbar extends XULElement { this._finishFAYT(event); } break; case KeyEvent.DOM_VK_TAB: let shouldHandle = !event.altKey && !event.ctrlKey && !event.metaKey; if (shouldHandle && this._findMode != this.FIND_NORMAL) { - this._finishFAYT(event); } break; case KeyEvent.DOM_VK_PAGE_UP: case KeyEvent.DOM_VK_PAGE_DOWN: if (!event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { this.browser.finder.keyPress(event); @@ -1071,17 +1069,16 @@ class MozFindbar extends XULElement { } /* Fetches the currently selected text and sets that as the text to search next. This is a MacOS specific feature. */ onFindSelectionCommand() { let searchString = this.browser.finder.setSearchStringToSelection(); if (searchString) this._findField.value = searchString; - } _onFindFieldFocus() { let prefsvc = this._prefsvc; const kPref = "accessibility.typeaheadfind.prefillwithselection"; if (this.prefillWithSelection && prefsvc.getBoolPref(kPref)) return; @@ -1210,10 +1207,9 @@ class MozFindbar extends XULElement { while (this.lastChild) { this.removeChild(this.lastChild); } this.destroy(); } } customElements.define("findbar", MozFindbar); - }
--- a/toolkit/content/widgets/general.js +++ b/toolkit/content/widgets/general.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - class MozDeck extends MozXULElement { set selectedIndex(val) { if (this.selectedIndex == val) return val; this.setAttribute("selectedIndex", val); var event = document.createEvent("Events"); event.initEvent("select", true, true); this.dispatchEvent(event); return val; @@ -62,10 +61,9 @@ class MozCommandSet extends MozXULElemen disconnectedCallback() { if (this.getAttribute("commandupdater") === "true") { document.commandDispatcher.removeCommandUpdater(this); } } } customElements.define("commandset", MozCommandSet); - }
--- a/toolkit/content/widgets/menulist.js +++ b/toolkit/content/widgets/menulist.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into all XUL windows. Wrap in a block to prevent // leaking to window scope. { - const MozXULMenuElement = MozElementMixin(XULMenuElement); const MenuBaseControl = BaseControlMixin(MozXULMenuElement); class MozMenuList extends MenuBaseControl { constructor() { super(); this.addEventListener("command", (event) => { @@ -50,17 +49,16 @@ class MozMenuList extends MenuBaseContro // Moving relative to an item: start from the currently selected item this.activeChild = this.mSelectedInternal; if (this.handleKeyPress(event)) { this.activeChild.doCommand(); event.preventDefault(); } } }, { mozSystemGroup: true }); - } connectedCallback() { if (this.delayConnectedCallback()) { return; } if (this.getAttribute("popuponly") != "true") { @@ -399,10 +397,9 @@ class MozMenuList extends MenuBaseContro this.inheritAttribute(this._dropmarker, "open"); } } MenuBaseControl.implementCustomInterface(MozMenuList, [Ci.nsIDOMXULMenuListElement, Ci.nsIDOMXULSelectControlElement]); customElements.define("menulist", MozMenuList); - }
--- a/toolkit/content/widgets/radio.js +++ b/toolkit/content/widgets/radio.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into all XUL windows. Wrap in a block to prevent // leaking to window scope. { - class MozRadiogroup extends MozElements.BaseControl { constructor() { super(); this.addEventListener("mousedown", (event) => { if (this.disabled) event.preventDefault(); }); @@ -389,10 +388,9 @@ class MozRadiogroup extends MozElements. } MozXULElement.implementCustomInterface(MozRadiogroup, [ Ci.nsIDOMXULSelectControlElement, Ci.nsIDOMXULRadioGroupElement, ]); customElements.define("radiogroup", MozRadiogroup); - }
--- a/toolkit/content/widgets/spinner.js +++ b/toolkit/content/widgets/spinner.js @@ -13,17 +13,16 @@ */ function Spinner(props, context) { this.context = context; this._init(props); } { - const ITEM_HEIGHT = 2.5, VIEWPORT_SIZE = 7, VIEWPORT_COUNT = 5; Spinner.prototype = { /** * Initializes a spinner. Set the default states and properties, cache * element references, create the HTML markup, and add event listeners.
--- a/toolkit/content/widgets/stringbundle.js +++ b/toolkit/content/widgets/stringbundle.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); class MozStringbundle extends MozXULElement { get stringBundle() { if (!this._bundle) { try { this._bundle = Services.strings.createBundle(this.src); } catch (e) { @@ -54,10 +53,9 @@ class MozStringbundle extends MozXULElem } catch (e) { dump("*** Failed to format string " + aStringKey + " in bundle: " + this.src + "\n"); throw e; } } } customElements.define("stringbundle", MozStringbundle); - }
--- a/toolkit/content/widgets/tabbox.js +++ b/toolkit/content/widgets/tabbox.js @@ -255,10 +255,9 @@ class MozTabpanels extends MozXULElement } return tabElmFromIndex; } } MozXULElement.implementCustomInterface(MozTabpanels, [Ci.nsIDOMXULRelatedElement]); customElements.define("tabpanels", MozTabpanels); - }
--- a/toolkit/content/widgets/text.xml +++ b/toolkit/content/widgets/text.xml @@ -304,17 +304,16 @@ // if the scheme is not an exposed protocol, then opening this link // should be deferred to the system's external protocol handler if (!protocolSvc.isExposedProtocol(uri.scheme)) { protocolSvc.loadURI(uri); aEvent.preventDefault(); return; } - } catch (ex) { Cu.reportError(ex); } aEvent.preventDefault(); href = uri ? uri.spec : href; // Try handing off the link to the host application, e.g. for
--- a/toolkit/content/widgets/textbox.js +++ b/toolkit/content/widgets/textbox.js @@ -2,17 +2,16 @@ * License, v. 2.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"; // This is loaded into chrome windows with the subscript loader. Wrap in // a block to prevent accidentally leaking globals onto `window`. { - const cachedFragments = { get entities() { return [ "chrome://global/locale/textcontext.dtd", ]; }, get editMenuItems() { return ` @@ -193,10 +192,9 @@ class MozInputBox extends MozXULElement doCommand(command) { var controller = document.commandDispatcher.getControllerForCommand(command); controller.doCommand(command); } } customElements.define("moz-input-box", MozInputBox); - }
--- a/toolkit/content/widgets/tree.js +++ b/toolkit/content/widgets/tree.js @@ -141,29 +141,27 @@ if (this.parentNode._editingColumn || !view.isContainer(row)) return; // Cyclers and twisties respond to single clicks, not double clicks if (cell.col && !cell.col.cycler && cell.childElt != "twisty") this.parentNode.changeOpenState(row); }); - } connectedCallback() { if (this.delayConnectedCallback()) { return; } this._lastSelectedRow = -1; if ("_ensureColumnOrder" in this.parentNode) this.parentNode._ensureColumnOrder(); - } } customElements.define("treechildren", MozTreeChildren); class MozTreecolPicker extends MozElements.BaseControl { constructor() { super(); @@ -189,33 +187,31 @@ if (element.getAttribute("hidden") == "true") element.setAttribute("hidden", "false"); else element.setAttribute("hidden", "true"); } } } }); - } connectedCallback() { if (this.delayConnectedCallback()) { return; } this.textContent = ""; this.appendChild(MozXULElement.parseXULToFragment(` <image class="tree-columnpicker-icon"></image> <menupopup anonid="popup"> <menuseparator anonid="menuseparator"></menuseparator> <menuitem anonid="menuitem" label="&restoreColumnOrder.label;"></menuitem> </menupopup> `, ["chrome://global/locale/tree.dtd"])); - } buildPopup(aPopup) { // We no longer cache the picker content, remove the old content. while (aPopup.childNodes.length > 2) aPopup.firstChild.remove(); var refChild = aPopup.firstChild; @@ -303,17 +299,16 @@ if (/Win/.test(navigator.platform) && event.detail % 2 == 0) return; var tree = this.parentNode.parentNode; if (tree.columns) { tree.view.cycleHeader(tree.columns.getColumnFor(this)); } }); - } markTreeDirty() { this.parentNode.parentNode._columnsDirty = true; } connectedCallback() { if (this.delayConnectedCallback()) { @@ -517,10 +512,9 @@ Array.forEach(this.getElementsByTagName("splitter"), function(splitter) { if (!splitter.hasAttribute("resizeafter")) splitter.setAttribute("resizeafter", "farthest"); }); } } customElements.define("treecols", MozTreecols); - }
--- a/toolkit/content/widgets/tree.xml +++ b/toolkit/content/widgets/tree.xml @@ -470,17 +470,16 @@ if (offset > 0) { i += p - 1; if (c >= i) { i = c + p; this.ensureRowIsVisible(i > edge ? edge : i); } i = i > edge ? edge : i; - } else if (c <= i) { i = c <= p ? 0 : c - p; this.ensureRowIsVisible(i); } this.view.selection.timedSelect(i, this._selectDelay); ]]> </body> </method> @@ -518,19 +517,17 @@ if (offset > 0) { i += p - 1; if (c >= i) { i = c + p; this.ensureRowIsVisible(i > edge ? edge : i); } // Extend the selection from the existing pivot, if any this.view.selection.rangedSelect(-1, i > edge ? edge : i, event.getModifierState("Accel")); - } else { - if (c <= i) { i = c <= p ? 0 : c - p; this.ensureRowIsVisible(i); } // Extend the selection from the existing pivot, if any this.view.selection.rangedSelect(-1, i, event.getModifierState("Accel")); }
--- a/toolkit/crashreporter/test/unit/head_win64cfi.js +++ b/toolkit/crashreporter/test/unit/head_win64cfi.js @@ -67,17 +67,16 @@ function stackFrameToString(frameIndex, // Calculate the module offset. let ip = frame.ip; let symbol = ""; let moduleOffset = "unknown_offset"; let filename = "unknown_module"; if (typeof frame.module_index !== "undefined" && (frame.module_index >= 0) && (frame.module_index < gModules.length)) { - let base = gModules[frame.module_index].base_addr; moduleOffset = getModuleOffset(base, ip); filename = gModules[frame.module_index].filename; if (filename === "testcrasher.dll") { let nearestSym = findNearestTestCrasherSymbol(moduleOffset); if (nearestSym !== null) { symbol = nearestSym.symbol + "+" + nearestSym.offset.toString(16); @@ -170,17 +169,16 @@ function assertStack(stack, expected) { // // how: The crash to perform. Constants defined in both CrashTestUtils.jsm // and nsTestCrasher.cpp (i.e. CRASH_X64CFI_PUSH_NONVOL) // expectedStack: An array of {"symbol", "trust"} where trust is "cfi", // "context", "scan", et al. May be null if you don't need to check the stack. // minidumpAnalyzerArgs: An array of additional arguments to pass to // minidump-analyzer.exe. function do_x64CFITest(how, expectedStack, minidumpAnalyzerArgs) { - // Setup is run in the subprocess so we cannot use any closures. let setupFn = "crashType = CrashTestUtils." + how + ";"; let callbackFn = function(minidumpFile, extra, extraFile) { runMinidumpAnalyzer(minidumpFile, minidumpAnalyzerArgs); // Refresh updated extra data extra = parseKeyValuePairsFromFile(extraFile);
--- a/toolkit/crashreporter/test/unit/test_event_files.js +++ b/toolkit/crashreporter/test/unit/test_event_files.js @@ -27,17 +27,16 @@ add_task(async function test_main_proces crashReporter.annotateCrashReport("ShutdownProgress", "event-test"); }, (minidump, extra) => { basename = minidump.leafName; Object.defineProperty(cm, "_eventsDirs", {value: [getEventDir()]}); cm.aggregateEventsFiles().then(resolve, reject); }, true); - }); Assert.equal(count, 1, "A single crash event file was seen."); let crashes = await cm.getCrashes(); Assert.equal(crashes.length, 1); let crash = crashes[0]; Assert.ok(crash.isOfType(cm.PROCESS_TYPE_MAIN, cm.CRASH_TYPE_CRASH)); Assert.equal(crash.id + ".dmp", basename, "ID recorded properly"); Assert.equal(crash.metadata.ShutdownProgress, "event-test");
--- a/toolkit/crashreporter/test/unit/test_oom_annotation_windows.js +++ b/toolkit/crashreporter/test/unit/test_oom_annotation_windows.js @@ -15,12 +15,11 @@ function run_test() { Assert.ok(Number(extra.OOMAllocationSize) > 0); Assert.ok("SystemMemoryUsePercentage" in extra); Assert.ok("TotalVirtualMemory" in extra); Assert.ok("AvailableVirtualMemory" in extra); Assert.ok("TotalPageFile" in extra); Assert.ok("AvailablePageFile" in extra); Assert.ok("TotalPhysicalMemory" in extra); Assert.ok("AvailablePhysicalMemory" in extra); - }, true); }
--- a/toolkit/modules/AutoScrollController.jsm +++ b/toolkit/modules/AutoScrollController.jsm @@ -155,17 +155,16 @@ class AutoScrollController { this.findNearestScrollableElement(this._scrollable.frameElement); } else { this._scrollable = null; // abort scrolling } } } startScroll(event) { - this.findNearestScrollableElement(event.originalTarget); if (!this._scrollable) return; let content = event.originalTarget.ownerGlobal; // In some configurations like Print Preview, content.performance
--- a/toolkit/modules/PopupNotifications.jsm +++ b/toolkit/modules/PopupNotifications.jsm @@ -512,17 +512,16 @@ PopupNotifications.prototype = { let notifications = this._getNotificationsForBrowser(browser); notifications.push(notification); let isActiveBrowser = this._isActiveBrowser(browser); let isActiveWindow = Services.focus.activeWindow == this.window; if (isActiveBrowser) { if (isActiveWindow) { - // Autofocus if the notification requests focus. if (options && !options.dismissed && options.autofocus) { this.panel.removeAttribute("noautofocus"); } else { this.panel.setAttribute("noautofocus", "true"); } // show panel now @@ -531,17 +530,16 @@ PopupNotifications.prototype = { // indicate attention and update the icon if necessary if (!notification.dismissed) { this.window.getAttention(); } this._updateAnchorIcons(notifications, this._getAnchorsForNotifications( notifications, notification.anchorElement)); this._notify("backgroundShow"); } - } else { // Notify observers that we're not showing the popup (useful for testing) this._notify("backgroundShow"); } return notification; }, @@ -1241,17 +1239,16 @@ PopupNotifications.prototype = { for (let notification of aCurrentNotifications) { let anchorElm = notification.anchorElement; if (anchorElm) { anchorElm.setAttribute(ICON_ATTRIBUTE_SHOWING, "true"); if (notification.options.extraAttr) { anchorElm.setAttribute("extraAttr", notification.options.extraAttr); } - } } }, _hideIcons: function PopupNotifications_hideIcons() { let icons = this.iconBox.querySelectorAll(ICON_SELECTOR); for (let icon of icons) { icon.removeAttribute(ICON_ATTRIBUTE_SHOWING);
--- a/toolkit/modules/Promise-backend.js +++ b/toolkit/modules/Promise-backend.js @@ -440,17 +440,16 @@ this.Promise = function Promise(aExecuto */ Promise.prototype.then = function(aOnResolve, aOnReject) { let handler = new Handler(this, aOnResolve, aOnReject); this[N_INTERNALS].handlers.push(handler); // Ensure the handler is scheduled for processing if this promise is already // resolved or rejected. if (this[N_INTERNALS].status != STATUS_PENDING) { - // This promise is not the last in the chain anymore. Remove any watchdog. if (this[N_INTERNALS].witness != null) { let [id, witness] = this[N_INTERNALS].witness; this[N_INTERNALS].witness = null; witness.forget(); PendingErrors.unregister(id); } @@ -923,37 +922,34 @@ Handler.prototype = { if (typeof(this.onResolve) == "function") { nextValue = this.onResolve.call(undefined, nextValue); } } else if (typeof(this.onReject) == "function") { nextValue = this.onReject.call(undefined, nextValue); nextStatus = STATUS_RESOLVED; } } catch (ex) { - // An exception has occurred in the handler. if (ex && typeof ex == "object" && "name" in ex && ERRORS_TO_REPORT.includes(ex.name)) { - // We suspect that the exception is a programmer error, so we now // display it using dump(). Note that we do not use Cu.reportError as // we assume that this is a programming error, so we do not want end // users to see it. Also, if the programmer handles errors correctly, // they will either treat the error or log them somewhere. dump("*************************\n"); dump("A coding exception was thrown in a Promise " + ((nextStatus == STATUS_RESOLVED) ? "resolution" : "rejection") + " callback.\n"); dump("See https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n\n"); dump("Full message: " + ex + "\n"); dump("Full stack: " + (("stack" in ex) ? ex.stack : "not available") + "\n"); dump("*************************\n"); - } // Additionally, reject the next promise. nextStatus = STATUS_REJECTED; nextValue = ex; } // Propagate the newly determined state to the next promise.
--- a/toolkit/modules/SelectParentHelper.jsm +++ b/toolkit/modules/SelectParentHelper.jsm @@ -437,17 +437,16 @@ function populateChildren(menulist, opti } } } // Check if search pref is enabled, if this is the first time iterating through // the dropdown, and if the list is long enough for a search element to be added. if (Services.prefs.getBoolPref("dom.forms.selectSearch") && addSearch && element.childElementCount > SEARCH_MINIMUM_ELEMENTS) { - // Add a search text field as the first element of the dropdown let searchbox = element.ownerDocument.createXULElement("textbox"); searchbox.setAttribute("type", "search"); searchbox.addEventListener("input", onSearchInput); searchbox.addEventListener("focus", onSearchFocus); searchbox.addEventListener("blur", onSearchBlur); searchbox.addEventListener("command", onSearchInput);
--- a/toolkit/modules/ZipUtils.jsm +++ b/toolkit/modules/ZipUtils.jsm @@ -26,17 +26,16 @@ const EXTRACTION_BUFFER = * The name of the file being extracted for logging purposes. * @param aStream * The source nsIInputStream. * @param aFile * The open OS.File instance to write to. */ function saveStreamAsync(aPath, aStream, aFile) { return new Promise((resolve, reject) => { - // Read the input stream on a background thread let sts = Cc["@mozilla.org/network/stream-transport-service;1"]. getService(Ci.nsIStreamTransportService); let transport = sts.createInputTransport(aStream, true); let input = transport.openInputStream(0, 0, 0) .QueryInterface(Ci.nsIAsyncInputStream); let source = Cc["@mozilla.org/binaryinputstream;1"]. createInstance(Ci.nsIBinaryInputStream); @@ -71,17 +70,16 @@ function saveStreamAsync(aPath, aStream, if (e.result == Cr.NS_BASE_STREAM_CLOSED) resolve(aFile.close()); else readFailed(e); } } input.asyncWait(readData, 0, 0, Services.tm.currentThread); - }); } var ZipUtils = { /** * Asynchronously extracts files from a ZIP file into a directory.
--- a/toolkit/modules/sessionstore/SessionHistory.jsm +++ b/toolkit/modules/sessionstore/SessionHistory.jsm @@ -323,17 +323,16 @@ var SessionHistoryInternal = { * Object containing serialized history data for a URL * @param idMap * Hash for ensuring unique frame IDs * @param docIdentMap * Hash to ensure reuse of BFCache entries * @returns nsISHEntry */ deserializeEntry(entry, idMap, docIdentMap) { - var shEntry = Cc["@mozilla.org/browser/session-history-entry;1"]. createInstance(Ci.nsISHEntry); shEntry.URI = Services.io.newURI(entry.url); shEntry.title = entry.title || entry.url; if (entry.subframe) shEntry.isSubFrame = entry.subframe || false; shEntry.setLoadTypeAsHistory();
--- a/toolkit/modules/tests/browser/browser_Finder_offscreen_text.js +++ b/toolkit/modules/tests/browser/browser_Finder_offscreen_text.js @@ -1,13 +1,12 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ add_task(async function test_offscreen_text() { - // Generate URI of a big DOM that contains the target text at several // line positions (to force some targets to be offscreen). const linesToGenerate = 155; const linesToInsertTargetText = [5, 50, 150]; let targetCount = linesToInsertTargetText.length; let t = 0; const TARGET_TEXT = "findthis";
--- a/toolkit/modules/tests/browser/browser_Finder_overflowed_textarea.js +++ b/toolkit/modules/tests/browser/browser_Finder_overflowed_textarea.js @@ -1,14 +1,13 @@ /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ "use strict"; add_task(async function test_offscreen_text() { - // Generate URI of a big DOM that contains the target text // within a textarea at several line positions (to force // some targets to be overflowed). const linesToGenerate = 155; const linesToInsertTargetText = [5, 50, 150]; const targetCount = linesToInsertTargetText.length; let t = 0; const TARGET_TEXT = "findthis";
--- a/toolkit/modules/tests/chrome/test_findCssSelector.html +++ b/toolkit/modules/tests/chrome/test_findCssSelector.html @@ -41,33 +41,31 @@ addTest(function findAllCssSelectors() { is(matches.length, 1, "There is a single match: " + selector); is(matches[0], nodes[i], "The selector matches the correct node: " + selector); } runNextTest(); }); addTest(function findCssSelectorNotContainedInDocument() { - var unattached = document.createElement("div"); unattached.id = "unattached"; is(findCssSelector(unattached), "", "Unattached node returns empty string"); var unattachedChild = document.createElement("div"); unattached.appendChild(unattachedChild); is(findCssSelector(unattachedChild), "", "Unattached child returns empty string"); var unattachedBody = document.createElement("body"); is(findCssSelector(unattachedBody), "", "Unattached body returns empty string"); runNextTest(); }); addTest(function findCssSelectorBasic() { - let data = [ "#one", "#" + CSS.escape("2"), ".three", "." + CSS.escape("4"), "#find-css-selector > div:nth-child(5)", "#find-css-selector > p:nth-child(6)", ".seven",
--- a/toolkit/modules/tests/modules/Task.jsm +++ b/toolkit/modules/tests/modules/Task.jsm @@ -305,17 +305,16 @@ TaskImpl.prototype = { * function regularly (if we were waiting on a promise, it was * resolved). If false, indicates that we should cause an exception to * be thrown into the generator function (if we were waiting on a * promise, it was rejected). * @param aSendValue * Resolution result or rejection exception, if any. */ _run: function TaskImpl_run(aSendResolved, aSendValue) { - try { gCurrentTask = this; if (this._isStarGenerator) { if (Cu.isDeadWrapper(this._iterator)) { this._resolve(undefined); } else { try { @@ -407,27 +406,24 @@ TaskImpl.prototype = { /** * Handle an uncaught exception thrown from a generator. * * @param aException * The uncaught exception to handle. */ _handleException: function TaskImpl_handleException(aException) { - gCurrentTask = this; if (aException && typeof aException == "object" && "stack" in aException) { - let stack = aException.stack; if (gMaintainStack && aException._capturedTaskStack != this._stack && typeof stack == "string") { - // Rewrite the stack for more readability. let bottomStack = this._stack; stack = Task.Debugging.generateReadableStack(stack); aException.stack = stack; @@ -435,17 +431,16 @@ TaskImpl.prototype = { // we don't want to perform the rewrite again. aException._capturedTaskStack = bottomStack; } else if (!stack) { stack = "Not available"; } if ("name" in aException && ERRORS_TO_REPORT.includes(aException.name)) { - // We suspect that the exception is a programmer error, so we now // display it using dump(). Note that we do not use Cu.reportError as // we assume that this is a programming error, so we do not want end // users to see it. Also, if the programmer handles errors correctly, // they will either treat the error or log them somewhere. dump("*************************\n"); dump("A coding exception was thrown and uncaught in a Task.\n\n");
--- a/toolkit/modules/tests/xpcshell/test_servicerequest_xhr.js +++ b/toolkit/modules/tests/xpcshell/test_servicerequest_xhr.js @@ -14,10 +14,9 @@ add_task(async function test_tls_conserv ok(sr_channel.beConservative, "TLS setting in request channel is set to conservative for SR"); const xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com", false); const xhr_channel = xhr.channel.QueryInterface(Ci.nsIHttpChannelInternal); ok(("beConservative" in xhr_channel), "TLS setting is present in XHR channel"); ok(!xhr_channel.beConservative, "TLS setting in request channel is not set to conservative for XHR"); - });
--- a/toolkit/modules/tests/xpcshell/test_sqlite.js +++ b/toolkit/modules/tests/xpcshell/test_sqlite.js @@ -5,26 +5,24 @@ do_get_profile(); const {Promise} = ChromeUtils.import("resource://gre/modules/Promise.jsm"); const {PromiseUtils} = ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm"); const {OS} = ChromeUtils.import("resource://gre/modules/osfile.jsm"); const {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm"); const {Sqlite} = ChromeUtils.import("resource://gre/modules/Sqlite.jsm"); function sleep(ms) { return new Promise(resolve => { - let timer = Cc["@mozilla.org/timer;1"] .createInstance(Ci.nsITimer); timer.initWithCallback({ notify() { resolve(); }, }, ms, timer.TYPE_ONE_SHOT); - }); } // When testing finalization, use this to tell Sqlite.jsm to not throw // an uncatchable `Promise.reject` function failTestsOnAutoClose(enabled) { Sqlite.failTestsOnAutoClose(enabled); } @@ -291,23 +289,21 @@ add_task(async function test_close_cache await c.close(); }); add_task(async function test_execute_invalid_statement() { let c = await getDummyDatabase("invalid_statement"); await new Promise(resolve => { - Assert.equal(c._connectionData._anonymousStatements.size, 0); c.execute("SELECT invalid FROM unknown").then(do_throw, function onError(error) { resolve(); }); - }); // Ensure we don't leak the statement instance. Assert.equal(c._connectionData._anonymousStatements.size, 0); await c.close(); });
--- a/toolkit/modules/tests/xpcshell/test_sqlite_shutdown.js +++ b/toolkit/modules/tests/xpcshell/test_sqlite_shutdown.js @@ -34,26 +34,24 @@ async function getDummyDatabase(name, ex c._initialStatementCount++; } return c; } function sleep(ms) { return new Promise(resolve => { - let timer = Cc["@mozilla.org/timer;1"] .createInstance(Ci.nsITimer); timer.initWithCallback({ notify() { resolve(); }, }, ms, timer.TYPE_ONE_SHOT); - }); } // // ----------- Don't add a test after this one, as it shuts down Sqlite.jsm // add_task(async function test_shutdown_clients() {
--- a/toolkit/mozapps/downloads/nsHelperAppDlg.js +++ b/toolkit/mozapps/downloads/nsHelperAppDlg.js @@ -337,17 +337,16 @@ nsUnknownContentTypeDialog.prototype = { // display an informative error message. // In all cases, download will be stopped. if (ex.result == Cr.NS_ERROR_FILE_ACCESS_DENIED) { this.displayBadPermissionAlert(); aLauncher.saveDestinationAvailable(null); return; } - } } aLauncher.saveDestinationAvailable(result); }); }); })().catch(Cu.reportError); },
--- a/toolkit/mozapps/extensions/Blocklist.jsm +++ b/toolkit/mozapps/extensions/Blocklist.jsm @@ -1152,17 +1152,16 @@ var Blocklist = { * @param {string?} toolkitVersion * The toolkit version to compare to, will use the current version if * null. * @returns {integer} * The blocklist state for the item, one of the STATE constants as * defined in nsIBlocklistService. */ _getPluginBlocklistState(plugin, pluginEntries, appVersion, toolkitVersion) { - let r = this._getPluginBlocklistEntry(plugin, pluginEntries, appVersion, toolkitVersion); if (!r) { return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; } let {version: blockEntryVersion} = r;
--- a/toolkit/mozapps/extensions/content/extensions.js +++ b/toolkit/mozapps/extensions/content/extensions.js @@ -487,17 +487,16 @@ var gEventManager = { if (child.nodeName == "menuitem" && gViewController.isCommandEnabled(child.command)) { countMenuItemsBeforeSep++; } } // Hide the separator if there are no visible menu items before it menuSep.hidden = (countMenuItemsBeforeSep == 0); - }); let addonTooltip = document.getElementById("addonitem-tooltip"); addonTooltip.addEventListener("popupshowing", function() { let addonItem = addonTooltip.triggerNode; // The way the test triggers the tooltip the richlistitem is the // tooltipNode but in normal use it is the anonymous node. This allows // any case @@ -1672,17 +1671,16 @@ function sortElements(aElements, aSortBy return result; } } } // If we got here, then all values of a and b // must have been equal. return 0; - }); } function sortList(aList, aSortBy, aAscending) { var elements = Array.slice(aList.childNodes, 0); sortElements(elements, [aSortBy], aAscending); while (aList.lastChild)
--- a/toolkit/mozapps/extensions/content/extensions.xml +++ b/toolkit/mozapps/extensions/content/extensions.xml @@ -343,17 +343,16 @@ ]]></body> </method> <method name="refreshState"> <body><![CDATA[ var showInstallRemote = false; if (this.mInstall) { - switch (this.mInstall.state) { case AddonManager.STATE_AVAILABLE: if (this.mControl.getAttribute("remote") != "true") break; this._progress.hidden = true; showInstallRemote = true; break; @@ -376,17 +375,16 @@ case AddonManager.STATE_INSTALL_FAILED: // XXXunf expose what error occured (bug 553487) this.showMessage("installFailed", true); break; case AddonManager.STATE_CANCELLED: this.showMessage("installCancelled", true); break; } - } this._installRemote.hidden = !showInstallRemote; if ("refreshInfo" in this.mControl) this.mControl.refreshInfo(); ]]></body> </method>
--- a/toolkit/mozapps/extensions/internal/Content.js +++ b/toolkit/mozapps/extensions/internal/Content.js @@ -2,17 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* globals addMessageListener*/ "use strict"; (function() { - var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const MSG_JAR_FLUSH = "AddonJarFlush"; const MSG_MESSAGE_MANAGER_CACHES_FLUSH = "AddonMessageManagerCachesFlush"; try { if (Services.appinfo.processType !== Services.appinfo.PROCESS_TYPE_DEFAULT) { @@ -23,10 +22,9 @@ try { // Propagate message manager caches flush notifications across processes. addMessageListener(MSG_MESSAGE_MANAGER_CACHES_FLUSH, function() { Services.obs.notifyObservers(null, "message-manager-flush-caches"); }); } } catch (e) { Cu.reportError(e); } - })();
--- a/toolkit/mozapps/extensions/internal/PluginProvider.jsm +++ b/toolkit/mozapps/extensions/internal/PluginProvider.jsm @@ -449,17 +449,16 @@ PluginWrapper.prototype = { get permissions() { let { tags: [tag] } = pluginFor(this); let permissions = 0; if (tag.isEnabledStateLocked) { return permissions; } if (!this.appDisabled) { - if (this.userDisabled !== true) permissions |= AddonManager.PERM_CAN_DISABLE; let blocklistState = this.blocklistState; let isCTPBlocklisted = (blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE || blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE);
--- a/toolkit/mozapps/extensions/internal/ProductAddonChecker.jsm +++ b/toolkit/mozapps/extensions/internal/ProductAddonChecker.jsm @@ -220,25 +220,23 @@ function parseXML(document) { }; } /** * If downloading from the network fails (AUS server is down), * load the sources from local build configuration. */ function downloadLocalConfig() { - if (!GMPPrefs.getBool(GMPPrefs.KEY_UPDATE_ENABLED, true)) { logger.info("Updates are disabled via media.gmp-manager.updateEnabled"); return Promise.resolve({usedFallback: true, gmpAddons: []}); } return Promise.all(LOCAL_GMP_SOURCES.map(conf => { return downloadJSON(conf.src).then(addons => { - let platforms = addons.vendors[conf.id].platforms; let target = Services.appinfo.OS + "_" + UpdateUtils.ABI; let details = null; while (!details) { if (!(target in platforms)) { // There was no matching platform so return false, this addon // will be filtered from the results below @@ -260,17 +258,16 @@ function downloadLocalConfig() { "URL": details.fileUrl, "hashFunction": addons.hashFunction, "hashValue": details.hashValue, "version": addons.vendors[conf.id].version, "size": details.filesize, }; }); })).then(addons => { - // Some filters may not match this platform so // filter those out addons = addons.filter(x => x !== false); return { usedFallback: true, gmpAddons: addons, };
--- a/toolkit/mozapps/extensions/internal/XPIDatabase.jsm +++ b/toolkit/mozapps/extensions/internal/XPIDatabase.jsm @@ -439,17 +439,16 @@ class AddonInternal { else if (app.id == TOOLKIT_ID) version = aPlatformVersion; // Only extensions and dictionaries can be compatible by default; themes // and language packs always use strict compatibility checking. // Dictionaries are compatible by default unless requested by the dictinary. if (!this.strictCompatibility && (!AddonManager.strictCompatibility || this.type == "dictionary")) { - // The repository can specify compatibility overrides. // Note: For now, only blacklisting is supported by overrides. let overrides = AddonRepository.getCompatibilityOverridesSync(this.id); if (overrides) { let override = AddonRepository.findMatchingCompatOverride(this.version, overrides); if (override) { return false;
--- a/toolkit/mozapps/extensions/internal/XPIInstall.jsm +++ b/toolkit/mozapps/extensions/internal/XPIInstall.jsm @@ -1772,17 +1772,16 @@ var LocalAddonInstall = class extends Ad this.state = AddonManager.STATE_DOWNLOADED; this._callInstallListeners("onNewInstall"); resolve(); }, }, AddonManager.UPDATE_WHEN_ADDON_INSTALLED); }); } else { this._callInstallListeners("onNewInstall"); - } } install() { if (this.state == AddonManager.STATE_DOWNLOAD_FAILED) { // For a local install, this state means that verification of the // file failed (e.g., the hash or signature or manifest contents // were invalid). It doesn't make sense to retry anything in this @@ -2985,17 +2984,16 @@ class SystemAddonInstaller extends Direc ignorePermissions: true, }); } else { await OS.File.remove(entry.path, { ignoreAbsent: true, }); } } - } catch (e) { logger.error("Failed to clean updated system add-ons directories.", e); } finally { iterator.close(); } } /**
--- a/toolkit/mozapps/extensions/test/browser/browser_bug562797.js +++ b/toolkit/mozapps/extensions/test/browser/browser_bug562797.js @@ -208,17 +208,16 @@ add_test(async function() { info("Part 7"); is_in_list(aManager, "addons://list/extension", false, true); close_manager(aManager, run_next_test); }); // Tests that browsing to the add-ons manager from a website and going back works add_test(function() { - function promiseManagerLoaded(manager) { return new Promise(resolve => { wait_for_manager_load(manager, resolve); }); } (async function() { info("Part 1"); @@ -265,17 +264,16 @@ add_test(function() { })(); }); // Tests simple forward and back navigation and that the right heading and // category is selected -- Keyboard navigation [Bug 565359] // Only add the test if the backspace key navigates back and addon-manager // loaded in a tab add_test(async function() { - if (Services.prefs.getIntPref("browser.backspace_action") != 0) { run_next_test(); return; } let aManager = await open_manager("addons://list/extension"); info("Part 1"); is_in_list(aManager, "addons://list/extension", false, false); @@ -382,17 +380,16 @@ function wait_for_page_show(browser) { false, false); }); return promise; } // Tests than navigating to a website and then going back returns to the // previous view add_test(async function() { - let aManager = await open_manager("addons://list/plugin"); info("Part 1"); is_in_list(aManager, "addons://list/plugin", false, false); BrowserTestUtils.loadURI(gBrowser, "http://example.com/"); wait_for_page_show(gBrowser.selectedBrowser).then(() => { info("Part 2"); @@ -435,17 +432,16 @@ add_test(async function() { }); }); }); }); }); // Tests that refreshing a list view does not affect the history add_test(async function() { - let aManager = await open_manager("addons://list/extension"); info("Part 1"); is_in_list(aManager, "addons://list/extension", false, false); EventUtils.synthesizeMouseAtCenter(aManager.document.getElementById("category-plugin"), { }, aManager); aManager = await wait_for_view_load(aManager); info("Part 2"); @@ -467,17 +463,16 @@ add_test(async function() { is_in_list(aManager, "addons://list/extension", false, true); close_manager(aManager, run_next_test); }); }); // Tests that refreshing a detail view does not affect the history add_test(async function() { - let aManager = await open_manager(null); info("Part 1"); is_in_list(aManager, "addons://list/extension", false, false); double_click_addon_element(aManager, "test1@tests.mozilla.org"); aManager = await wait_for_view_load(aManager); info("Part 2");
--- a/toolkit/mozapps/extensions/test/browser/browser_bug567137.js +++ b/toolkit/mozapps/extensions/test/browser/browser_bug567137.js @@ -7,27 +7,25 @@ async function test() { waitForExplicitFinish(); let aWindow = await open_manager(null); let utils = new CategoryUtilities(aWindow); // Open the plugins category utils.openType("plugin", async function() { - // Re-open the manager await close_manager(aWindow); aWindow = await open_manager(null); utils = new CategoryUtilities(aWindow); is(utils.selectedCategory, "plugin", "Should have shown the plugins category"); // Open the extensions category utils.openType("extension", async function() { - // Re-open the manager await close_manager(aWindow); aWindow = await open_manager(null); utils = new CategoryUtilities(aWindow); is(utils.selectedCategory, "extension", "Should have shown the extensions category"); close_manager(aWindow, finish); });
--- a/toolkit/mozapps/extensions/test/browser/browser_bug586574.js +++ b/toolkit/mozapps/extensions/test/browser/browser_bug586574.js @@ -229,17 +229,16 @@ add_test(function() { wait_for_hide(run_next_test); }, }; AddonManager.addAddonListener(listener); info("Clicking Reset to Manual menuitem"); EventUtils.synthesizeMouseAtCenter(gResetToManual, { }, gManagerWindow); - }); info("Opening utilities menu"); EventUtils.synthesizeMouseAtCenter(gUtilsBtn, { }, gManagerWindow); }); add_test(function() {
--- a/toolkit/mozapps/extensions/test/browser/browser_bug591465.js +++ b/toolkit/mozapps/extensions/test/browser/browser_bug591465.js @@ -108,17 +108,16 @@ function check_contextmenu(aIsTheme, aIs "'Show More Information' should be visible in list view"); if (aIsSingleItemCase) is_element_hidden(gManagerWindow.document.getElementById("addonitem-menuseparator"), "Menu separator should be hidden with only one menu item"); else is_element_visible(gManagerWindow.document.getElementById("addonitem-menuseparator"), "Menu separator should be visible with multiple menu items"); - } add_test(function() { var el = get_addon_element(gManagerWindow, "addon1@tests.mozilla.org"); isnot(el, null, "Should have found addon element"); gContextMenu.addEventListener("popupshown", function() {
--- a/toolkit/mozapps/extensions/test/browser/browser_extension_sideloading_permission.js +++ b/toolkit/mozapps/extensions/test/browser/browser_extension_sideloading_permission.js @@ -7,17 +7,16 @@ */ const {AddonTestUtils} = ChromeUtils.import("resource://testing-common/AddonTestUtils.jsm"); const ADDON_ID = "addon1@test.mozilla.org"; AddonTestUtils.initMochitest(this); // Loading extension by sideloading method add_task(async function test() { - await SpecialPowers.pushPrefEnv({ set: [ ["xpinstall.signatures.required", false], ["extensions.autoDisableScopes", 15], ["extensions.ui.ignoreUnsigned", true], ], });
--- a/toolkit/mozapps/extensions/test/browser/browser_gmpProvider.js +++ b/toolkit/mozapps/extensions/test/browser/browser_gmpProvider.js @@ -258,17 +258,16 @@ add_task(async function testInstalledGlo } else { Assert.ok(item, "Got add-on element."); } } gPrefs.setBoolPref(GMPScope.GMPPrefs.KEY_EME_ENABLED, true); }); add_task(async function testPreferencesButton() { - let prefValues = [ { enabled: false, version: "" }, { enabled: false, version: "1.2.3.4" }, { enabled: true, version: "" }, { enabled: true, version: "1.2.3.4" }, ]; for (let preferences of prefValues) { @@ -369,14 +368,13 @@ add_task(async function testEmeSupport() } for (let addon of gMockAddons) { gPrefs.setBoolPref(getKey(GMPScope.GMPPrefs.KEY_PLUGIN_VISIBLE, addon.id), true); gPrefs.setBoolPref(getKey(GMPScope.GMPPrefs.KEY_PLUGIN_FORCE_SUPPORTED, addon.id), true); } await GMPScope.GMPProvider.shutdown(); GMPScope.GMPProvider.startup(); - }); add_task(async function test_cleanup() { await close_manager(gManagerWindow); });
--- a/toolkit/mozapps/extensions/test/browser/browser_manualupdates.js +++ b/toolkit/mozapps/extensions/test/browser/browser_manualupdates.js @@ -135,24 +135,21 @@ add_test(function() { info("Re-opening release notes"); item.addEventListener("RelNotesToggle", function() { info("Release notes now open"); is_element_hidden(item._relNotesLoading, "Release notes loading message should be hidden"); is_element_hidden(item._relNotesError, "Release notes error message should be hidden"); isnot(item._relNotes.childElementCount, 0, "Release notes should have been inserted into container"); run_next_test(); - }, {once: true}); EventUtils.synthesizeMouseAtCenter(item._relNotesToggle, { }, gManagerWindow); is_element_visible(item._relNotesLoading, "Release notes loading message should be visible"); - }, {once: true}); EventUtils.synthesizeMouseAtCenter(item._relNotesToggle, { }, gManagerWindow); - }, {once: true}); EventUtils.synthesizeMouseAtCenter(item._relNotesToggle, { }, gManagerWindow); is_element_visible(item._relNotesLoading, "Release notes loading message should be visible"); }); }); add_test(function() {
--- a/toolkit/mozapps/extensions/test/browser/browser_sorting.js +++ b/toolkit/mozapps/extensions/test/browser/browser_sorting.js @@ -209,17 +209,16 @@ function check_order(aExpectedOrder) { node = node.nextSibling; } is(order.toSource(), aExpectedOrder.toSource(), "Should have seen the right order"); } // Tests that ascending name ordering was the default add_test(function() { - check_order([ "test2@tests.mozilla.org", "test4@tests.mozilla.org", "test3@tests.mozilla.org", "test5@tests.mozilla.org", "test1@tests.mozilla.org", "test7@tests.mozilla.org", "test8@tests.mozilla.org",
--- a/toolkit/mozapps/extensions/test/browser/browser_sorting_plugins.js +++ b/toolkit/mozapps/extensions/test/browser/browser_sorting_plugins.js @@ -75,17 +75,16 @@ function check_order(aExpectedOrder) { node = node.nextSibling; } is(order.toSource(), aExpectedOrder.toSource(), "Should have seen the right order"); } // Tests that ascending name ordering was the default add_test(function() { - check_order([ "test5@tests.mozilla.org", "test2@tests.mozilla.org", "test4@tests.mozilla.org", "test1@tests.mozilla.org", "test3@tests.mozilla.org", ]);
--- a/toolkit/mozapps/extensions/test/browser/head.js +++ b/toolkit/mozapps/extensions/test/browser/head.js @@ -365,17 +365,16 @@ function wait_for_manager_load(aManagerW }, {once: true}); }); return log_callback(p, aCallback); } function open_manager(aView, aCallback, aLoadCallback, aLongerTimeout, aWin = window) { let p = new Promise((resolve, reject) => { - async function setup_manager(aManagerWindow) { if (aLoadCallback) log_exceptions(aLoadCallback, aManagerWindow); if (aView) aManagerWindow.loadView(aView); ok(aManagerWindow != null, "Should have an add-ons manager window"); @@ -579,17 +578,16 @@ CategoryUtilities.prototype = { return !is_hidden(aCategory); }, isTypeVisible(aCategoryType) { return this.isVisible(this.get(aCategoryType)); }, open(aCategory, aCallback) { - isnot(this.window, null, "Should not open category when manager window is not loaded"); ok(this.isVisible(aCategory), "Category should be visible if attempting to open it"); EventUtils.synthesizeMouse(aCategory, 2, 2, { }, this.window); let p = new Promise((resolve, reject) => wait_for_view_load(this.window, resolve)); return log_callback(p, aCallback); },
--- a/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository.js @@ -126,17 +126,16 @@ function check_results(aActualAddons, aE // Additional tests aActualAddons.forEach(function check_each_addon(aActualAddon) { // Separately check name so better messages are output when test fails if (aActualAddon.name == "FAIL") do_throw(aActualAddon.id + " - " + aActualAddon.description); if (aActualAddon.name != "PASS") do_throw(aActualAddon.id + " - invalid add-on name " + aActualAddon.name); - }); } add_task(async function setup() { // Setup for test createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "1.9"); let xpis = ADDONS.map(addon => createTempWebExtensionFile(addon));
--- a/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_langpacks.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_langpacks.js @@ -84,10 +84,9 @@ add_task(async function setup() { equal(result.length, 2, "Got 2 results"); deepEqual(result[0], EXPECTED[0], "Got expected result for simple entry"); deepEqual(result[1], EXPECTED[1], "Got expected result for multi-platform entry"); setData("not valid json"); await Assert.rejects(AddonRepository.getAvailableLangpacks(), /SyntaxError/, "Got parse error on invalid JSON"); - });
--- a/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_metadata_filters.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_metadata_filters.js @@ -26,17 +26,16 @@ var WindowWatcher = { var list = args.wrappedJSObject.list; list.forEach(function(aItem) { if (!aItem.blocked) aItem.disable = true; }); // run the code after the blocklist is closed Services.obs.notifyObservers(null, "addon-blocklist-closed"); - }, QueryInterface: ChromeUtils.generateQI(["nsIWindowWatcher"]), }; MockRegistrar.register("@mozilla.org/embedcomp/window-watcher;1", WindowWatcher); function load_blocklist(aFile) {
--- a/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_plugin_outdated.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_plugin_outdated.js @@ -84,17 +84,16 @@ add_task(async function setup() { }); add_task(async function test_part_1() { // update blocklist with data that marks the plugin as outdated await loadBlocklist("test_bug514327_3_outdated_1.xml"); // plugin should now be marked as outdated Assert.equal(await gBlocklist.getPluginBlocklistState(PLUGINS[0], "1", "1.9"), nsIBLS.STATE_OUTDATED); - }); add_task(async function test_part_2() { // update blocklist with data that marks the plugin as outdated await loadBlocklist("test_bug514327_3_outdated_2.xml"); // plugin should still be marked as outdated Assert.equal(await gBlocklist.getPluginBlocklistState(PLUGINS[0], "1", "1.9"), nsIBLS.STATE_OUTDATED);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_prefs.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_blocklist_prefs.js @@ -24,17 +24,16 @@ var WindowWatcher = { var list = args.wrappedJSObject.list; list.forEach(function(aItem) { if (!aItem.blocked) aItem.disable = true; }); // run the code after the blocklist is closed Services.obs.notifyObservers(null, "addon-blocklist-closed"); - }, QueryInterface: ChromeUtils.generateQI(["nsIWindowWatcher"]), }; MockRegistrar.register("@mozilla.org/embedcomp/window-watcher;1", WindowWatcher); function load_blocklist(aFile) {
--- a/toolkit/mozapps/extensions/test/xpcshell/test_blocklistchange.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_blocklistchange.js @@ -54,17 +54,16 @@ var WindowWatcher = { var list = openArgs.wrappedJSObject.list; list.forEach(function(aItem) { if (!aItem.blocked) aItem.disable = true; }); // run the code after the blocklist is closed Services.obs.notifyObservers(null, "addon-blocklist-closed"); - }, QueryInterface: ChromeUtils.generateQI(["nsIWindowWatcher"]), }; MockRegistrar.register("@mozilla.org/embedcomp/window-watcher;1", WindowWatcher); var InstallConfirm = {
--- a/toolkit/mozapps/extensions/test/xpcshell/test_install.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_install.js @@ -855,17 +855,16 @@ add_task(async function test_restart_has promise, promiseWebExtensionStartup("addon1@tests.mozilla.org"), ]); ensure_test_completed(); clearListeners(); await install.addon.uninstall(); - }); // Tests that an install with a bad hash can be restarted after it fails, though // it will only fail again add_task(async function test_restart_badhash() { let url = "http://example.com/addons/test_install1.xpi"; let install = await AddonManager.getInstallForURL(url, "application/x-xpinstall", "sha1:foo"); equal(install.state, AddonManager.STATE_AVAILABLE);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_pluginBlocklistCtp.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_pluginBlocklistCtp.js @@ -95,17 +95,16 @@ add_task(async function basic() { Assert.equal(await blocklist.getPluginBlocklistState(PLUGINS[3], "1", "1.9"), nsIBLS.STATE_BLOCKED); Assert.equal(await blocklist.getPluginBlocklistState(PLUGINS[4], "1", "1.9"), nsIBLS.STATE_SOFTBLOCKED); Assert.equal(await blocklist.getPluginBlocklistState(PLUGINS[5], "1", "1.9"), nsIBLS.STATE_NOT_BLOCKED); - }); function get_test_plugin() { for (var plugin of gPluginHost.getPluginTags()) { if (plugin.name == "Test Plug-in") return plugin; } Assert.ok(false); @@ -133,17 +132,16 @@ add_task(async function test_is_clicktop // But now we've removed that entry from the blocklist (really we've gone back // to the old one), so the plugin shouldn't be click-to-play any more. add_task(async function test_is_not_clicktoplay2() { await updateBlocklist("http://example.com/data/test_pluginBlocklistCtp.xml"); var plugin = get_test_plugin(); var blocklistState = await Blocklist.getPluginBlocklistState(plugin, "1", "1.9"); Assert.notEqual(blocklistState, Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE); Assert.notEqual(blocklistState, Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE); - }); // Test that disabling the blocklist when a plugin is ctp-blocklisted will // result in the plugin not being click-to-play. add_task(async function test_disable_blocklist() { await updateBlocklist("http://example.com/data/test_pluginBlocklistCtpUndo.xml"); var plugin = get_test_plugin(); var blocklistState = await Blocklist.getPluginBlocklistState(plugin, "1", "1.9");
--- a/toolkit/mozapps/extensions/test/xpcshell/test_update_rdf.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_update_rdf.js @@ -52,17 +52,16 @@ add_task(async function test_update_rdf_ "Should have the same keys"); deepEqual(Object.keys(rdfJSON.addons).sort(), Object.keys(json.addons).sort(), "Should have the same add-on IDs"); for (let addon of Object.keys(json.addons)) { deepEqual(rdfJSON.addons[addon], json.addons[addon], `Should have the same entry for add-on ${addon}`); } - } }); add_task(async function test_update_check() { for (let file of ["test_updatecheck.rdf", "test_updatecheck.json"]) { let updates = await checkUpdates("updatecheck1@tests.mozilla.org", file); equal(updates.length, 5);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_upgrade.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_upgrade.js @@ -109,17 +109,16 @@ add_task(async function test_1() { Assert.equal(a2.isActive, true, "Extension 2 is active"); Assert.notEqual(a3, null, "Found extension 3"); Assert.equal(a3.isActive, false, "Extension 3 is not active"); Assert.notEqual(a4, null); Assert.equal(a4.isActive, true); Assert.equal(a4.version, "1.0"); - }); // Test that upgrading the application doesn't disable now incompatible add-ons add_task(async function test_2() { await promiseShutdownManager(); // Upgrade the extension let xpi = createAddon({
--- a/toolkit/mozapps/extensions/test/xpcshell/test_webextension_install_syntax_error.js +++ b/toolkit/mozapps/extensions/test/xpcshell/test_webextension_install_syntax_error.js @@ -1,17 +1,16 @@ const ADDON_ID = "webext-test@tests.mozilla.org"; add_task(async function setup() { createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "1"); await promiseStartupManager(); }); add_task(async function install_xpi() { - // WebExtension with a JSON syntax error in manifest.json let xpi1 = Extension.generateXPI({ files: { "manifest.json": String.raw`{ "manifest_version: 2, "applications": {"gecko": {"id": "${ADDON_ID}"}}, "name": "Temp WebExt with Error", "version": "0.1"
--- a/toolkit/mozapps/preferences/changemp.js +++ b/toolkit/mozapps/preferences/changemp.js @@ -208,10 +208,9 @@ function checkPasswords() { } } if (pw1 == pw2) { ok.setAttribute("disabled", "false"); } else { ok.setAttribute("disabled", "true"); } - }
--- a/toolkit/mozapps/update/tests/browser/head.js +++ b/toolkit/mozapps/update/tests/browser/head.js @@ -85,17 +85,16 @@ async function continueFileHandler(leafN throw new Error("The continue file should not exist, path: " + continueFile.path); } continueFile.create(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE); return BrowserTestUtils.waitForCondition(() => (!continueFile.exists()), "Waiting for file to be deleted, path: " + continueFile.path, undefined, retries); - } /** * Creates and locks the app update write test file so it is possible to test * when the user doesn't have write access to update. Since this is only * possible on Windows the function throws when it is called on other platforms. * This uses registerCleanupFunction to remove the lock and the file when the * test completes. @@ -309,17 +308,16 @@ function runUpdateProcessingTest(updates function processStep(step) { if (typeof(step) == "function") { return step(); } const {notificationId, button, beforeClick, cleanup} = step; return (async function() { - await BrowserTestUtils.waitForEvent(PanelUI.notificationPanel, "popupshown"); const shownNotification = AppMenuNotifications.activeNotification.id; is(shownNotification, notificationId, "The right notification showed up."); if (shownNotification != notificationId) { if (cleanup) { await cleanup(); }
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js @@ -323,16 +323,19 @@ module.exports = { "no-whitespace-before-property": "error", // No using with "no-with": "error", // Require object-literal shorthand with ES6 method syntax "object-shorthand": ["error", "always", { "avoidQuotes": true }], + // Prohibit blank lines at the beginning and end of blocks. + "padded-blocks": ["error", "never"], + // Require double-quotes everywhere, except where quotes are escaped // or template literals are used. "quotes": ["error", "double", { "allowTemplateLiterals": true, "avoidEscape": true, }], // XXX Bug 1487642 - decide if we want to enable this or not.
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/helpers.js @@ -717,17 +717,16 @@ module.exports = { // without any path info (happens in Atom with linter-eslint) return path.join(cwd, fileName); } // Case 1: executed form in a nested directory, e.g. from a text editor: // fileName: a/b/c/d.js // cwd: /path/to/mozilla/repo/a/b/c var dirName = path.dirname(fileName); return cwd.slice(0, cwd.length - dirName.length) + fileName; - }, /** * When ESLint is run from SublimeText, paths retrieved from * context.getFileName contain leading and trailing double-quote characters. * These characters need to be removed. */ cleanUpPath(pathName) {
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/avoid-removeChild.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/avoid-removeChild.js @@ -11,17 +11,16 @@ // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- var helpers = require("../helpers"); module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "CallExpression": function(node) { let callee = node.callee; if (callee.type !== "MemberExpression" ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/import-headjs-globals.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/import-headjs-globals.js @@ -13,17 +13,16 @@ // Rule Definition // ----------------------------------------------------------------------------- var fs = require("fs"); var helpers = require("../helpers"); var globals = require("../globals"); module.exports = function(context) { - function importHead(path, node) { try { let stats = fs.statSync(path); if (!stats.isFile()) { return; } } catch (e) { return;
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-compare-against-boolean-literals.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-compare-against-boolean-literals.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "BinaryExpression": function(node) { if (["==", "!="].includes(node.operator) && (["true", "false"].includes(node.left.raw) ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-define-cc-etc.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-define-cc-etc.js @@ -10,17 +10,16 @@ // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- const componentsBlacklist = ["Cc", "Ci", "Cr", "Cu"]; module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "VariableDeclarator": function(node) { if (node.id.type == "Identifier" && componentsBlacklist.includes(node.id.name)) { context.report(node,
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-useless-removeEventListener.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-useless-removeEventListener.js @@ -9,17 +9,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "CallExpression": function(node) { let callee = node.callee; if (callee.type !== "MemberExpression" ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-useless-run-test.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/no-useless-run-test.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "Program > FunctionDeclaration": function(node) { if (node.id.name === "run_test" && node.body.type === "BlockStatement" &&
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-some-requires.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/reject-some-requires.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- if (typeof(context.options[0]) !== "string") { throw new Error("reject-some-requires expects a regexp"); } const RX = new RegExp(context.options[0]);
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-cc-etc.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-cc-etc.js @@ -15,17 +15,16 @@ const componentsMap = { classes: "Cc", interfaces: "Ci", results: "Cr", utils: "Cu", }; module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "MemberExpression": function(node) { if (node.object.type === "Identifier" && node.object.name === "Components" &&
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-default-preference-values.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-default-preference-values.js @@ -9,17 +9,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "TryStatement": function(node) { let types = ["Bool", "Char", "Float", "Int"]; let methods = types.map(type => "get" + type + "Pref");
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-includes-instead-of-indexOf.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-includes-instead-of-indexOf.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "BinaryExpression": function(node) { if (node.left.type != "CallExpression" || node.left.callee.type != "MemberExpression" ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-ownerGlobal.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-ownerGlobal.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "MemberExpression": function(node) { if (node.property.type != "Identifier" || node.property.name != "defaultView" ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-returnValue.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-returnValue.js @@ -8,17 +8,16 @@ "use strict"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- module.exports = function(context) { - // --------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { "ExpressionStatement": function(node) { if (!node.expression || node.expression.type != "CallExpression" ||
--- a/tools/lint/eslint/eslint-plugin-mozilla/package-lock.json +++ b/tools/lint/eslint/eslint-plugin-mozilla/package-lock.json @@ -1,11 +1,11 @@ { "name": "eslint-plugin-mozilla", - "version": "1.1.0", + "version": "1.1.1", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", "dev": true,
--- a/tools/lint/eslint/eslint-plugin-mozilla/package.json +++ b/tools/lint/eslint/eslint-plugin-mozilla/package.json @@ -1,11 +1,11 @@ { "name": "eslint-plugin-mozilla", - "version": "1.1.0", + "version": "1.1.1", "description": "A collection of rules that help enforce JavaScript coding standard in the Mozilla project.", "keywords": [ "eslint", "eslintplugin", "eslint-plugin", "mozilla", "firefox" ],
--- a/tools/profiler/tests/chrome/profiler_test_utils.js +++ b/tools/profiler/tests/chrome/profiler_test_utils.js @@ -1,12 +1,11 @@ "use strict"; (function() { - const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); function startProfiler(settings) { Services.profiler.StartProfiler( settings.entries, settings.interval, settings.features, settings.features.length, @@ -54,10 +53,9 @@ async function runTest(settings, workloa } catch (e) { // By catching and handling the error, we're being nice to mochitest // runners: instead of waiting for the timeout, we fail right away. await end(e); } } window.runTest = runTest; - })();
--- a/tools/profiler/tests/test_run.js +++ b/tools/profiler/tests/test_run.js @@ -33,11 +33,9 @@ function run_test() { Assert.notEqual(profileObj.threads[0].samples, null); // NOTE: The number of samples will be empty since we // don't have any labels in the xpcshell code Services.profiler.StopProfiler(); Assert.ok(!Services.profiler.IsActive()); do_test_finished(); }); - - }
--- a/xpcom/tests/unit/test_iniParser.js +++ b/xpcom/tests/unit/test_iniParser.js @@ -8,17 +8,16 @@ function parserForFile(filename) { Assert.ok(!!file); parser = factory.createINIParser(file); Assert.ok(!!parser); } catch (e) { dump("INFO | caught error: " + e); // checkParserOutput will handle a null parser when it's expected. } return parser; - } function checkParserOutput(parser, expected) { // If the expected output is null, we expect the parser to have // failed (and vice-versa). if (!parser || !expected) { Assert.equal(parser, null); Assert.equal(expected, null); @@ -54,17 +53,16 @@ function getParserOutput(parser) { output[section][key] = value; } } return output; } function run_test() { try { - var testdata = [ { filename: "data/iniparser01.ini", reference: {} }, { filename: "data/iniparser02.ini", reference: {} }, { filename: "data/iniparser03.ini", reference: {} }, { filename: "data/iniparser04.ini", reference: {} }, { filename: "data/iniparser05.ini", reference: {} }, { filename: "data/iniparser06.ini", reference: {} }, { filename: "data/iniparser07.ini", reference: {} }, @@ -296,13 +294,12 @@ Assert.equal(caughtError.result, Cr.NS_E caughtError = null; try { parser.setString("ok", "ok", "bad\n"); } catch (e) { caughtError = e; } Assert.ok(caughtError); Assert.equal(caughtError.result, Cr.NS_ERROR_INVALID_ARG); caughtError = null; try { parser.setString("ok", "ok", "good="); } catch (e) { caughtError = e; } Assert.ok(!caughtError); caughtError = null; - } catch (e) { throw "FAILED in test #" + testnum + " -- " + e; } }
--- a/xpcom/tests/unit/test_nsIProcess_stress.js +++ b/xpcom/tests/unit/test_nsIProcess_stress.js @@ -16,10 +16,9 @@ function run_test() { process.kill(); } catch (e) { } // We need to ensure that we process any events on the main thread - // this allow threads to clean up properly and avoid out of memory // errors during the test. tm.spinEventLoopUntilEmpty(); } - }
--- a/xpcom/tests/unit/test_seek_multiplex.js +++ b/xpcom/tests/unit/test_seek_multiplex.js @@ -118,17 +118,16 @@ function test_multiplex_streams() { Assert.equal(seekable.tell(), 100); seekable.seek(Ci.nsISeekableStream.NS_SEEK_SET, data.length * count); Assert.equal(seekable.tell(), 100); seekable.seek(Ci.nsISeekableStream.NS_SEEK_CUR, -2 * data.length * count); Assert.equal(seekable.tell(), 0); } function test_multiplex_bug797871() { - var data2 = "1234567890123456789012345678901234567890"; var MultiplexStream = CC("@mozilla.org/io/multiplex-input-stream;1", "nsIMultiplexInputStream"); Assert.equal(1, 1); var multiplex = new MultiplexStream(); let s = Cc["@mozilla.org/io/string-input-stream;1"]
--- a/xpcom/tests/unit/test_windows_registry.js +++ b/xpcom/tests/unit/test_windows_registry.js @@ -122,17 +122,16 @@ function test_invalidread_functions(test try { testKey.readStringValue(TESTDATA_BINARYNAME); do_throw("Reading a string from an Binary registry value should throw."); } catch (e) { if (!(e instanceof Ci.nsIException && e.result == Cr.NS_ERROR_FAILURE)) { throw e; } } - } function test_childkey_functions(testKey) { strictEqual(testKey.childCount, 0); strictEqual(testKey.hasChild(TESTDATA_CHILD_KEY), false); let childKey = testKey.createChild(TESTDATA_CHILD_KEY, nsIWindowsRegKey.ACCESS_ALL); childKey.close();