--- a/devtools/shared/async-utils.js
+++ b/devtools/shared/async-utils.js
@@ -8,18 +8,16 @@
* Helpers for async functions. Async functions are generator functions that are
* run by Tasks. An async function returns a Promise for the resolution of the
* function. When the function returns, the promise is resolved with the
* returned value. If it throws the promise rejects with the thrown error.
*
* See Task documentation at https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Task.jsm.
*/
-var {Task} = require("devtools/shared/task");
-
/**
* Adds an event listener to the given element, and then removes its event
* listener once the event is called, returning the event object as a promise.
* @param nsIDOMElement element
* The DOM element to listen on
* @param String event
* The name of the event type to listen for
* @param Boolean useCapture
--- a/devtools/shared/client/connection-manager.js
+++ b/devtools/shared/client/connection-manager.js
@@ -6,17 +6,16 @@
"use strict";
const {Cc, Ci, Cr} = require("chrome");
const EventEmitter = require("devtools/shared/old-event-emitter");
const { DebuggerServer } = require("devtools/server/main");
const { DebuggerClient } = require("devtools/shared/client/debugger-client");
const Services = require("Services");
-const { Task } = require("devtools/shared/task");
const REMOTE_TIMEOUT = "devtools.debugger.remote-timeout";
/**
* Connection Manager.
*
* To use this module:
* const {ConnectionManager} = require("devtools/shared/client/connection-manager");
@@ -292,27 +291,27 @@ Connection.prototype = {
this.keepConnecting = false;
if (this._client) {
this._client.close();
this._client = null;
}
this._setStatus(Connection.Status.DESTROYED);
},
- _getTransport: Task.async(function* () {
+ async _getTransport() {
if (this._customTransport) {
return this._customTransport;
}
if (!this.host) {
return DebuggerServer.connectPipe();
}
let settings = this.socketSettings;
- let transport = yield DebuggerClient.socketConnect(settings);
+ let transport = await DebuggerClient.socketConnect(settings);
return transport;
- }),
+ },
_clientConnect: function () {
this._getTransport().then(transport => {
if (!transport) {
return;
}
this._client = new DebuggerClient(transport);
this._client.addOneTimeListener("closed", this._onDisconnected);
--- a/devtools/shared/css/parsing-utils.js
+++ b/devtools/shared/css/parsing-utils.js
@@ -14,17 +14,16 @@
"use strict";
loader.lazyRequireGetter(this, "CSS_ANGLEUNIT",
"devtools/shared/css/properties-db", true);
const promise = require("promise");
const {getCSSLexer} = require("devtools/shared/css/lexer");
-const {Task} = require("devtools/shared/task");
const SELECTOR_ATTRIBUTE = exports.SELECTOR_ATTRIBUTE = 1;
const SELECTOR_ELEMENT = exports.SELECTOR_ELEMENT = 2;
const SELECTOR_PSEUDO_CLASS = exports.SELECTOR_PSEUDO_CLASS = 3;
// Used to test whether a newline appears anywhere in some text.
const NEWLINE_RX = /[\r\n]/;
// Used to test whether a bit of text starts an empty comment, either
@@ -897,27 +896,27 @@ RuleRewriter.prototype = {
* @param {String} value value of the new property
* @param {String} priority priority of the new property; either
* the empty string or "important"
* @param {Boolean} enabled True if the new property should be
* enabled, false if disabled
* @return {Promise} a promise that is resolved when the edit has
* completed
*/
- internalCreateProperty: Task.async(function* (index, name, value, priority, enabled) {
+ async internalCreateProperty(index, name, value, priority, enabled) {
this.completeInitialization(index);
let newIndentation = "";
if (this.hasNewLine) {
if (this.declarations.length > 0) {
newIndentation = this.getIndentation(this.inputString,
this.declarations[0].offsets[0]);
} else if (this.defaultIndentation) {
newIndentation = this.defaultIndentation;
} else {
- newIndentation = yield this.getDefaultIndentation();
+ newIndentation = await this.getDefaultIndentation();
}
}
this.maybeTerminateDecl(index - 1);
// If we generally have newlines, and if skipping whitespace
// backward stops at a newline, then insert our text before that
// whitespace. This ensures the indentation we computed is what
@@ -949,17 +948,17 @@ RuleRewriter.prototype = {
}
this.result += savedWhitespace;
if (this.decl) {
// Still want to copy in the declaration previously at this
// index.
this.completeCopying(this.decl.offsets[0]);
}
- }),
+ },
/**
* Create a new declaration.
*
* @param {Number} index index of the property in the rule.
* @param {String} name name of the new property
* @param {String} value value of the new property
* @param {String} priority priority of the new property; either
--- a/devtools/shared/discovery/tests/unit/test_discovery.js
+++ b/devtools/shared/discovery/tests/unit/test_discovery.js
@@ -69,66 +69,66 @@ discovery._factories.Transport = TestTra
// Ignore name generation on b2g and force a fixed value
Object.defineProperty(discovery.device, "name", {
get: function () {
return "test-device";
}
});
-add_task(function* () {
+add_task(async function () {
// At startup, no remote devices are known
deepEqual(discovery.getRemoteDevicesWithService("devtools"), []);
deepEqual(discovery.getRemoteDevicesWithService("penguins"), []);
discovery.scan();
// No services added yet, still empty
deepEqual(discovery.getRemoteDevicesWithService("devtools"), []);
deepEqual(discovery.getRemoteDevicesWithService("penguins"), []);
discovery.addService("devtools", { port: 1234 });
// Changes not visible until next scan
deepEqual(discovery.getRemoteDevicesWithService("devtools"), []);
deepEqual(discovery.getRemoteDevicesWithService("penguins"), []);
- yield scanForChange("devtools", "added");
+ await scanForChange("devtools", "added");
// Now we see the new service
deepEqual(discovery.getRemoteDevicesWithService("devtools"), ["test-device"]);
deepEqual(discovery.getRemoteDevicesWithService("penguins"), []);
discovery.addService("penguins", { tux: true });
- yield scanForChange("penguins", "added");
+ await scanForChange("penguins", "added");
deepEqual(discovery.getRemoteDevicesWithService("devtools"), ["test-device"]);
deepEqual(discovery.getRemoteDevicesWithService("penguins"), ["test-device"]);
deepEqual(discovery.getRemoteDevices(), ["test-device"]);
deepEqual(discovery.getRemoteService("devtools", "test-device"),
{ port: 1234, host: "localhost" });
deepEqual(discovery.getRemoteService("penguins", "test-device"),
{ tux: true, host: "localhost" });
discovery.removeService("devtools");
- yield scanForChange("devtools", "removed");
+ await scanForChange("devtools", "removed");
discovery.addService("penguins", { tux: false });
- yield scanForChange("penguins", "updated");
+ await scanForChange("penguins", "updated");
// Scan again, but nothing should be removed
- yield scanForNoChange("penguins", "removed");
+ await scanForNoChange("penguins", "removed");
// Split the scanning side from the service side to simulate the machine with
// the service becoming unreachable
gTestTransports = {};
discovery.removeService("penguins");
- yield scanForChange("penguins", "removed");
+ await scanForChange("penguins", "removed");
});
function scanForChange(service, changeType) {
let deferred = defer();
let timer = setTimeout(() => {
deferred.reject(new Error("Reply never arrived"));
}, discovery.replyTimeout + 500);
discovery.on(service + "-device-" + changeType, function onChange() {
--- a/devtools/shared/fronts/animation.js
+++ b/devtools/shared/fronts/animation.js
@@ -8,17 +8,16 @@ const {
FrontClassWithSpec,
custom,
preEvent
} = require("devtools/shared/protocol");
const {
animationPlayerSpec,
animationsSpec
} = require("devtools/shared/specs/animation");
-const { Task } = require("devtools/shared/task");
const AnimationPlayerFront = FrontClassWithSpec(animationPlayerSpec, {
initialize: function (conn, form, detail, ctx) {
Front.prototype.initialize.call(this, conn, form, detail, ctx);
this.state = {};
},
@@ -83,22 +82,22 @@ const AnimationPlayerFront = FrontClassW
let {state} = this.reconstructState(partialState);
this.state = state;
}),
/**
* Refresh the current state of this animation on the client from information
* found on the server. Doesn't return anything, just stores the new state.
*/
- refreshState: Task.async(function* () {
- let data = yield this.getCurrentState();
+ async refreshState() {
+ let data = await this.getCurrentState();
if (this.currentStateHasChanged) {
this.state = data;
}
- }),
+ },
/**
* getCurrentState interceptor re-constructs incomplete states since the actor
* only sends the values that have changed.
*/
getCurrentState: custom(function () {
this.currentStateHasChanged = false;
return this._getCurrentState().then(partialData => {
--- a/devtools/shared/fronts/inspector.js
+++ b/devtools/shared/fronts/inspector.js
@@ -10,17 +10,16 @@ const {
preEvent,
types
} = require("devtools/shared/protocol.js");
const {
inspectorSpec,
walkerSpec
} = require("devtools/shared/specs/inspector");
const defer = require("devtools/shared/defer");
-const { Task } = require("devtools/shared/task");
loader.lazyRequireGetter(this, "nodeConstants",
"devtools/shared/dom-node-constants");
loader.lazyRequireGetter(this, "CommandUtils",
"devtools/client/shared/developer-toolbar", true);
/**
* Client side of the DOM walker.
*/
@@ -202,28 +201,28 @@ const WalkerFront = FrontClassWithSpec(w
* query will send the next result. When there are no more results to be sent
* back, null is sent.
* @param {String} query
* @param {Object} options
* - "reverse": search backwards
* - "selectorOnly": treat input as a selector string (don't search text
* tags, attributes, etc)
*/
- search: custom(Task.async(function* (query, options = { }) {
+ search: custom(async function (query, options = { }) {
let nodeList;
let searchType;
let searchData = this.searchData = this.searchData || { };
let selectorOnly = !!options.selectorOnly;
if (selectorOnly) {
searchType = "selector";
- nodeList = yield this.multiFrameQuerySelectorAll(query);
+ nodeList = await this.multiFrameQuerySelectorAll(query);
} else {
searchType = "search";
- let result = yield this._search(query, options);
+ let result = await this._search(query, options);
nodeList = result.list;
}
// If this is a new search, start at the beginning.
if (searchData.query !== query ||
searchData.selectorOnly !== selectorOnly) {
searchData.selectorOnly = selectorOnly;
searchData.query = query;
@@ -240,24 +239,24 @@ const WalkerFront = FrontClassWithSpec(w
if (searchData.index >= nodeList.length) {
searchData.index = 0;
}
if (searchData.index < 0) {
searchData.index = nodeList.length - 1;
}
// Send back the single node, along with any relevant search data
- let node = yield nodeList.item(searchData.index);
+ let node = await nodeList.item(searchData.index);
return {
type: searchType,
node: node,
resultsLength: nodeList.length,
resultsIndex: searchData.index,
};
- }), {
+ }, {
impl: "_search"
}),
_releaseFront: function (node, force) {
if (node.retained && !force) {
node.reparent(null);
this._retainedOrphans.add(node);
return;
@@ -432,24 +431,24 @@ const WalkerFront = FrontClassWithSpec(w
// Fetch and process the mutations.
this.getMutations({cleanup: this.autoCleanup}).catch(() => {});
}),
isLocal: function () {
return !!this.conn._transport._serverConnection;
},
- removeNode: custom(Task.async(function* (node) {
- let previousSibling = yield this.previousSibling(node);
- let nextSibling = yield this._removeNode(node);
+ removeNode: custom(async function (node) {
+ let previousSibling = await this.previousSibling(node);
+ let nextSibling = await this._removeNode(node);
return {
previousSibling: previousSibling,
nextSibling: nextSibling,
};
- }), {
+ }, {
impl: "_removeNode"
}),
});
exports.WalkerFront = WalkerFront;
/**
* Client side of the inspector actor, which is used to create
@@ -489,22 +488,22 @@ var InspectorFront = FrontClassWithSpec(
return this.getWalker().then(() => {
return pageStyle;
});
});
}, {
impl: "_getPageStyle"
}),
- pickColorFromPage: custom(Task.async(function* (toolbox, options) {
+ pickColorFromPage: custom(async function (toolbox, options) {
if (toolbox) {
// If the eyedropper was already started using the gcli command, hide it so we don't
// end up with 2 instances of the eyedropper on the page.
CommandUtils.executeOnTarget(toolbox.target, "eyedropper --hide");
}
- yield this._pickColorFromPage(options);
- }), {
+ await this._pickColorFromPage(options);
+ }, {
impl: "_pickColorFromPage"
})
});
exports.InspectorFront = InspectorFront;
--- a/devtools/shared/fronts/memory.js
+++ b/devtools/shared/fronts/memory.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/. */
"use strict";
const { memorySpec } = require("devtools/shared/specs/memory");
-const { Task } = require("devtools/shared/task");
const protocol = require("devtools/shared/protocol");
loader.lazyRequireGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm", true);
loader.lazyRequireGetter(this, "HeapSnapshotFileUtils",
"devtools/shared/heapsnapshot/HeapSnapshotFileUtils");
const MemoryFront = protocol.FrontClassWithSpec(memorySpec, {
@@ -36,26 +35,26 @@ const MemoryFront = protocol.FrontClassW
* the server and client share a file system.
*
* @params {Object|undefined} options.boundaries
* The boundaries for the heap snapshot. See
* ChromeUtils.webidl for more details.
*
* @returns Promise<String>
*/
- saveHeapSnapshot: protocol.custom(Task.async(function* (options = {}) {
- const snapshotId = yield this._saveHeapSnapshotImpl(options.boundaries);
+ saveHeapSnapshot: protocol.custom(async function (options = {}) {
+ const snapshotId = await this._saveHeapSnapshotImpl(options.boundaries);
if (!options.forceCopy &&
- (yield HeapSnapshotFileUtils.haveHeapSnapshotTempFile(snapshotId))) {
+ (await HeapSnapshotFileUtils.haveHeapSnapshotTempFile(snapshotId))) {
return HeapSnapshotFileUtils.getHeapSnapshotTempFilePath(snapshotId);
}
- return yield this.transferHeapSnapshot(snapshotId);
- }), {
+ return this.transferHeapSnapshot(snapshotId);
+ }, {
impl: "_saveHeapSnapshotImpl"
}),
/**
* Given that we have taken a heap snapshot with the given id, transfer the
* heap snapshot file to the client. The path to the client's local file is
* returned.
*
@@ -75,18 +74,18 @@ const MemoryFront = protocol.FrontClassW
});
return new Promise((resolve, reject) => {
const outFilePath =
HeapSnapshotFileUtils.getNewUniqueHeapSnapshotTempFilePath();
const outFile = new FileUtils.File(outFilePath);
const outFileStream = FileUtils.openSafeFileOutputStream(outFile);
- request.on("bulk-reply", Task.async(function* ({ copyTo }) {
- yield copyTo(outFileStream);
+ request.on("bulk-reply", async function ({ copyTo }) {
+ await copyTo(outFileStream);
FileUtils.closeSafeFileOutputStream(outFileStream);
resolve(outFilePath);
- }));
+ });
});
})
});
exports.MemoryFront = MemoryFront;
--- a/devtools/shared/fronts/performance.js
+++ b/devtools/shared/fronts/performance.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";
const { Cu } = require("chrome");
const { Front, FrontClassWithSpec, custom, preEvent } = require("devtools/shared/protocol");
const { PerformanceRecordingFront } = require("devtools/shared/fronts/performance-recording");
const { performanceSpec } = require("devtools/shared/specs/performance");
-const { Task } = require("devtools/shared/task");
loader.lazyRequireGetter(this, "PerformanceIO",
"devtools/client/performance/modules/io");
loader.lazyRequireGetter(this, "getSystemInfo",
"devtools/shared/system", true);
const PerformanceFront = FrontClassWithSpec(performanceSpec, {
initialize: function (client, form) {
@@ -24,23 +23,23 @@ const PerformanceFront = FrontClassWithS
destroy: function () {
Front.prototype.destroy.call(this);
},
/**
* Conenct to the server, and handle once-off tasks like storing traits
* or system info.
*/
- connect: custom(Task.async(function* () {
- let systemClient = yield getSystemInfo();
- let { traits } = yield this._connect({ systemClient });
+ connect: custom(async function () {
+ let systemClient = await getSystemInfo();
+ let { traits } = await this._connect({ systemClient });
this._traits = traits;
return this._traits;
- }), {
+ }, {
impl: "_connect"
}),
get traits() {
if (!this._traits) {
Cu.reportError("Cannot access traits of PerformanceFront before " +
"calling `connect()`.");
}
--- a/devtools/shared/fronts/styles.js
+++ b/devtools/shared/fronts/styles.js
@@ -9,17 +9,16 @@ const {
custom,
preEvent
} = require("devtools/shared/protocol");
const {
pageStyleSpec,
styleRuleSpec
} = require("devtools/shared/specs/styles");
const promise = require("promise");
-const { Task } = require("devtools/shared/task");
loader.lazyRequireGetter(this, "RuleRewriter",
"devtools/shared/css/parsing-utils", true);
/**
* PageStyleFront, the front object for the PageStyleActor
*/
const PageStyleFront = FrontClassWithSpec(pageStyleSpec, {
@@ -51,27 +50,27 @@ const PageStyleFront = FrontClassWithSpe
getMatchedSelectors: custom(function (node, property, options) {
return this._getMatchedSelectors(node, property, options).then(ret => {
return ret.matched;
});
}, {
impl: "_getMatchedSelectors"
}),
- getApplied: custom(Task.async(function* (node, options = {}) {
+ getApplied: custom(async function (node, options = {}) {
// If the getApplied method doesn't recreate the style cache itself, this
// means a call to cssLogic.highlight is required before trying to access
// the applied rules. Issue a request to getLayout if this is the case.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1103993#c16.
if (!this._form.traits || !this._form.traits.getAppliedCreatesStyleCache) {
- yield this.getLayout(node);
+ await this.getLayout(node);
}
- let ret = yield this._getApplied(node, options);
+ let ret = await this._getApplied(node, options);
return ret.entries;
- }), {
+ }, {
impl: "_getApplied"
}),
addNewRule: custom(function (node, pseudoClasses) {
let addPromise;
if (this.supportsAuthoredStyles) {
addPromise = this._addNewRule(node, pseudoClasses, true);
} else {
@@ -248,34 +247,34 @@ const StyleRuleFront = FrontClassWithSpe
if (!source) {
location.href = this.href;
}
this._originalLocation = location;
return location;
});
},
- modifySelector: custom(Task.async(function* (node, value) {
+ modifySelector: custom(async function (node, value) {
let response;
if (this.supportsModifySelectorUnmatched) {
// If the debugee supports adding unmatched rules (post FF41)
if (this.canSetRuleText) {
- response = yield this.modifySelector2(node, value, true);
+ response = await this.modifySelector2(node, value, true);
} else {
- response = yield this.modifySelector2(node, value);
+ response = await this.modifySelector2(node, value);
}
} else {
- response = yield this._modifySelector(value);
+ response = await this._modifySelector(value);
}
if (response.ruleProps) {
response.ruleProps = response.ruleProps.entries[0];
}
return response;
- }), {
+ }, {
impl: "_modifySelector"
}),
setRuleText: custom(function (newText) {
this._form.authoredText = newText;
return this._setRuleText(newText);
}, {
impl: "_setRuleText"
--- a/devtools/shared/fronts/stylesheets.js
+++ b/devtools/shared/fronts/stylesheets.js
@@ -5,17 +5,16 @@
const { Front, FrontClassWithSpec } = require("devtools/shared/protocol");
const {
mediaRuleSpec,
styleSheetSpec,
styleSheetsSpec
} = require("devtools/shared/specs/stylesheets");
const promise = require("promise");
-const { Task } = require("devtools/shared/task");
loader.lazyRequireGetter(this, "getIndentationFromPrefs",
"devtools/shared/indentation", true);
loader.lazyRequireGetter(this, "getIndentationFromString",
"devtools/shared/indentation", true);
/**
* Corresponding client-side front for a MediaRuleActor.
@@ -125,24 +124,24 @@ const StyleSheetFront = FrontClassWithSp
*/
guessIndentation: function () {
let prefIndent = getIndentationFromPrefs();
if (prefIndent) {
let {indentUnit, indentWithTabs} = prefIndent;
return promise.resolve(indentWithTabs ? "\t" : " ".repeat(indentUnit));
}
- return Task.spawn(function* () {
- let longStr = yield this.getText();
- let source = yield longStr.string();
+ return (async function () {
+ let longStr = await this.getText();
+ let source = await longStr.string();
let {indentUnit, indentWithTabs} = getIndentationFromString(source);
return indentWithTabs ? "\t" : " ".repeat(indentUnit);
- }.bind(this));
+ }.bind(this))();
}
});
exports.StyleSheetFront = StyleSheetFront;
/**
* The corresponding Front object for the StyleSheetsActor.
*/
--- a/devtools/shared/heapsnapshot/tests/unit/test_DominatorTree_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_DominatorTree_02.js
@@ -1,29 +1,29 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that we can compute dominator trees from a snapshot in a worker.
-add_task(function* () {
+add_task(async function () {
const worker = new ChromeWorker("resource://test/dominator-tree-worker.js");
worker.postMessage({});
let assertionCount = 0;
worker.onmessage = e => {
if (e.data.type !== "assertion") {
return;
}
ok(e.data.passed, e.data.msg + "\n" + e.data.stack);
assertionCount++;
};
- yield waitForDone(worker);
+ await waitForDone(worker);
ok(assertionCount > 0);
worker.terminate();
});
function waitForDone(w) {
return new Promise((resolve, reject) => {
w.onerror = e => {
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_computeDominatorTree_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_computeDominatorTree_01.js
@@ -1,19 +1,19 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test the HeapAnalyses{Client,Worker} "computeDominatorTree" request.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ const dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
equal(typeof dominatorTreeId, "number",
"should get a dominator tree id, and it should be a number");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_computeDominatorTree_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_computeDominatorTree_02.js
@@ -1,20 +1,20 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test the HeapAnalyses{Client,Worker} "computeDominatorTree" request with bad
// file paths.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
let threw = false;
try {
- yield client.computeDominatorTree("/etc/passwd");
+ await client.computeDominatorTree("/etc/passwd");
} catch (_) {
threw = true;
}
ok(threw, "should throw when given a bad path");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_01.js
@@ -7,50 +7,50 @@
const breakdown = {
by: "coarseType",
objects: { by: "count", count: true, bytes: true },
scripts: { by: "count", count: true, bytes: true },
strings: { by: "count", count: true, bytes: true },
other: { by: "count", count: true, bytes: true },
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- let dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ let dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
ok(true, "Should have computed the dominator tree");
- yield client.deleteHeapSnapshot(snapshotFilePath);
+ await client.deleteHeapSnapshot(snapshotFilePath);
ok(true, "Should have deleted the snapshot");
let threw = false;
try {
- yield client.getDominatorTree({
+ await client.getDominatorTree({
dominatorTreeId: dominatorTreeId,
breakdown
});
} catch (_) {
threw = true;
}
ok(threw, "getDominatorTree on deleted tree should throw an error");
threw = false;
try {
- yield client.computeDominatorTree(snapshotFilePath);
+ await client.computeDominatorTree(snapshotFilePath);
} catch (_) {
threw = true;
}
ok(threw, "computeDominatorTree on deleted snapshot should throw an error");
threw = false;
try {
- yield client.takeCensus(snapshotFilePath);
+ await client.takeCensus(snapshotFilePath);
} catch (_) {
threw = true;
}
ok(threw, "takeCensus on deleted tree should throw an error");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_02.js
@@ -1,19 +1,19 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test deleteHeapSnapshot is a noop if the provided path matches no snapshot
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
let threw = false;
try {
- yield client.deleteHeapSnapshot("path-does-not-exist");
+ await client.deleteHeapSnapshot("path-does-not-exist");
} catch (_) {
threw = true;
}
ok(threw, "deleteHeapSnapshot on non-existant path should throw an error");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_03.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_deleteHeapSnapshot_03.js
@@ -7,53 +7,53 @@
const breakdown = {
by: "coarseType",
objects: { by: "count", count: true, bytes: true },
scripts: { by: "count", count: true, bytes: true },
strings: { by: "count", count: true, bytes: true },
other: { by: "count", count: true, bytes: true },
};
-function* createSnapshotAndDominatorTree(client) {
+async function createSnapshotAndDominatorTree(client) {
let snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
- let dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
+ let dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
return { dominatorTreeId, snapshotFilePath };
}
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
let savedSnapshots = [
- yield createSnapshotAndDominatorTree(client),
- yield createSnapshotAndDominatorTree(client),
- yield createSnapshotAndDominatorTree(client)
+ await createSnapshotAndDominatorTree(client),
+ await createSnapshotAndDominatorTree(client),
+ await createSnapshotAndDominatorTree(client)
];
ok(true, "Create 3 snapshots and dominator trees");
- yield client.deleteHeapSnapshot(savedSnapshots[1].snapshotFilePath);
+ await client.deleteHeapSnapshot(savedSnapshots[1].snapshotFilePath);
ok(true, "Snapshot deleted");
- let tree = yield client.getDominatorTree({
+ let tree = await client.getDominatorTree({
dominatorTreeId: savedSnapshots[0].dominatorTreeId,
breakdown
});
ok(tree, "Should get a valid tree for first snapshot");
let threw = false;
try {
- yield client.getDominatorTree({
+ await client.getDominatorTree({
dominatorTreeId: savedSnapshots[1].dominatorTreeId,
breakdown
});
} catch (_) {
threw = true;
}
ok(threw, "getDominatorTree on a deleted snapshot should throw an error");
- tree = yield client.getDominatorTree({
+ tree = await client.getDominatorTree({
dominatorTreeId: savedSnapshots[2].dominatorTreeId,
breakdown
});
ok(tree, "Should get a valid tree for third snapshot");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getCensusIndividuals_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getCensusIndividuals_01.js
@@ -16,38 +16,38 @@ const CENSUS_BREAKDOWN = {
const LABEL_BREAKDOWN = {
by: "internalType",
then: COUNT,
};
const MAX_INDIVIDUALS = 10;
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ const dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
ok(true, "Should have computed dominator tree");
- const { report } = yield client.takeCensus(snapshotFilePath,
+ const { report } = await client.takeCensus(snapshotFilePath,
{ breakdown: CENSUS_BREAKDOWN },
{ asTreeNode: true });
ok(report, "Should get a report");
let nodesWithLeafIndicesFound = 0;
- yield* (function* assertCanGetIndividuals(censusNode) {
+ await (async function assertCanGetIndividuals(censusNode) {
if (censusNode.reportLeafIndex !== undefined) {
nodesWithLeafIndicesFound++;
- const response = yield client.getCensusIndividuals({
+ const response = await client.getCensusIndividuals({
dominatorTreeId,
indices: DevToolsUtils.isSet(censusNode.reportLeafIndex)
? censusNode.reportLeafIndex
: new Set([censusNode.reportLeafIndex]),
censusBreakdown: CENSUS_BREAKDOWN,
labelBreakdown: LABEL_BREAKDOWN,
maxRetainingPaths: 1,
maxIndividuals: MAX_INDIVIDUALS,
@@ -70,17 +70,17 @@ add_task(function* () {
ok(individual.shortestPaths.nodes, "individual.shortestPaths.nodes should exist");
ok(individual.shortestPaths.edges, "individual.shortestPaths.edges should exist");
ok(individual.label, "individual.label should exist");
}
}
if (censusNode.children) {
for (let child of censusNode.children) {
- yield* assertCanGetIndividuals(child);
+ await assertCanGetIndividuals(child);
}
}
}(report));
equal(nodesWithLeafIndicesFound, 4, "Should have found a leaf for each coarse type");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getCreationTime_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getCreationTime_01.js
@@ -12,42 +12,42 @@ function waitForThirtyMilliseconds() {
}
}
const BREAKDOWN = {
by: "internalType",
then: { by: "count", count: true, bytes: true }
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const start = Date.now() * 1000;
// Because Date.now() is less precise than the snapshot's time stamp, give it
// a little bit of head room. Additionally, WinXP's timers have a granularity
// of only +/-15 ms.
waitForThirtyMilliseconds();
const snapshotFilePath = saveNewHeapSnapshot();
waitForThirtyMilliseconds();
const end = Date.now() * 1000;
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
let threw = false;
try {
- yield client.getCreationTime("/not/a/real/path", {
+ await client.getCreationTime("/not/a/real/path", {
breakdown: BREAKDOWN
});
} catch (_) {
threw = true;
}
ok(threw, "getCreationTime should throw when snapshot does not exist");
- let time = yield client.getCreationTime(snapshotFilePath, {
+ let time = await client.getCreationTime(snapshotFilePath, {
breakdown: BREAKDOWN
});
dumpn("Start = " + start);
dumpn("End = " + end);
dumpn("Time = " + time);
ok(time >= start, "creation time occurred after start");
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getDominatorTree_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getDominatorTree_01.js
@@ -7,28 +7,28 @@
const breakdown = {
by: "coarseType",
objects: { by: "count", count: true, bytes: true },
scripts: { by: "count", count: true, bytes: true },
strings: { by: "count", count: true, bytes: true },
other: { by: "count", count: true, bytes: true },
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ const dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
equal(typeof dominatorTreeId, "number",
"should get a dominator tree id, and it should be a number");
- const partialTree = yield client.getDominatorTree({
+ const partialTree = await client.getDominatorTree({
dominatorTreeId,
breakdown
});
ok(partialTree, "Should get a partial tree");
equal(typeof partialTree, "object",
"partialTree should be an object");
function checkTree(node) {
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getDominatorTree_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getDominatorTree_02.js
@@ -8,21 +8,21 @@
const breakdown = {
by: "coarseType",
objects: { by: "count", count: true, bytes: true },
scripts: { by: "count", count: true, bytes: true },
strings: { by: "count", count: true, bytes: true },
other: { by: "count", count: true, bytes: true },
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
let threw = false;
try {
- yield client.getDominatorTree({ dominatorTreeId: 42, breakdown });
+ await client.getDominatorTree({ dominatorTreeId: 42, breakdown });
} catch (_) {
threw = true;
}
ok(threw, "should throw when given a bad id");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getImmediatelyDominated_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_getImmediatelyDominated_01.js
@@ -7,32 +7,32 @@
const breakdown = {
by: "coarseType",
objects: { by: "count", count: true, bytes: true },
scripts: { by: "count", count: true, bytes: true },
strings: { by: "count", count: true, bytes: true },
other: { by: "count", count: true, bytes: true },
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
- const dominatorTreeId = yield client.computeDominatorTree(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
+ const dominatorTreeId = await client.computeDominatorTree(snapshotFilePath);
- const partialTree = yield client.getDominatorTree({
+ const partialTree = await client.getDominatorTree({
dominatorTreeId,
breakdown
});
ok(partialTree.children.length > 0,
"root should immediately dominate some nodes");
// First, test getting a subset of children available.
- const response = yield client.getImmediatelyDominated({
+ const response = await client.getImmediatelyDominated({
dominatorTreeId,
breakdown,
nodeId: partialTree.nodeId,
startIndex: 0,
maxCount: partialTree.children.length - 1
});
ok(Array.isArray(response.nodes));
@@ -46,17 +46,17 @@ add_task(function* () {
"Should have shortest paths");
equal(typeof node.shortestPaths.nodes, "object",
"Should have shortest paths' nodes");
equal(typeof node.shortestPaths.edges, "object",
"Should have shortest paths' edges");
}
// Next, test getting a subset of children available.
- const secondResponse = yield client.getImmediatelyDominated({
+ const secondResponse = await client.getImmediatelyDominated({
dominatorTreeId,
breakdown,
nodeId: partialTree.nodeId,
startIndex: 0,
maxCount: Infinity
});
ok(Array.isArray(secondResponse.nodes));
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_readHeapSnapshot_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_readHeapSnapshot_01.js
@@ -1,15 +1,15 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that the HeapAnalyses{Client,Worker} can read heap snapshots.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
client.destroy();
});
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensusDiff_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensusDiff_01.js
@@ -5,41 +5,41 @@
// Test that the HeapAnalyses{Client,Worker} can take diffs between censuses.
const BREAKDOWN = {
by: "objectClass",
then: { by: "count", count: true, bytes: false },
other: { by: "count", count: true, bytes: false },
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const markers = [allocationMarker()];
const firstSnapshotFilePath = saveNewHeapSnapshot();
// Allocate and hold an additional AllocationMarker object so we can see it in
// the next heap snapshot.
markers.push(allocationMarker());
const secondSnapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(firstSnapshotFilePath);
- yield client.readHeapSnapshot(secondSnapshotFilePath);
+ await client.readHeapSnapshot(firstSnapshotFilePath);
+ await client.readHeapSnapshot(secondSnapshotFilePath);
ok(true, "Should have read both heap snapshot files");
- const { delta } = yield client.takeCensusDiff(firstSnapshotFilePath,
+ const { delta } = await client.takeCensusDiff(firstSnapshotFilePath,
secondSnapshotFilePath,
{ breakdown: BREAKDOWN });
equal(delta.AllocationMarker.count, 1,
"There exists one new AllocationMarker in the second heap snapshot");
- const { delta: deltaTreeNode } = yield client.takeCensusDiff(firstSnapshotFilePath,
+ const { delta: deltaTreeNode } = await client.takeCensusDiff(firstSnapshotFilePath,
secondSnapshotFilePath,
{ breakdown: BREAKDOWN },
{ asTreeNode: true });
// Have to manually set these because symbol properties aren't structured
// cloned.
delta[CensusUtils.basisTotalBytes] = deltaTreeNode.totalBytes;
delta[CensusUtils.basisTotalCount] = deltaTreeNode.totalCount;
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensusDiff_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensusDiff_02.js
@@ -21,32 +21,32 @@ const BREAKDOWN = {
then: { by: "count", count: true, bytes: true },
},
other: {
by: "internalType",
then: { by: "count", count: true, bytes: true },
},
};
-add_task(function* () {
+add_task(async function () {
const firstSnapshotFilePath = saveNewHeapSnapshot();
const secondSnapshotFilePath = saveNewHeapSnapshot();
const client = new HeapAnalysesClient();
- yield client.readHeapSnapshot(firstSnapshotFilePath);
- yield client.readHeapSnapshot(secondSnapshotFilePath);
+ await client.readHeapSnapshot(firstSnapshotFilePath);
+ await client.readHeapSnapshot(secondSnapshotFilePath);
ok(true, "Should have read both heap snapshot files");
- const { delta } = yield client.takeCensusDiff(firstSnapshotFilePath,
+ const { delta } = await client.takeCensusDiff(firstSnapshotFilePath,
secondSnapshotFilePath,
{ breakdown: BREAKDOWN });
const { delta: deltaTreeNode }
- = yield client.takeCensusDiff(firstSnapshotFilePath,
+ = await client.takeCensusDiff(firstSnapshotFilePath,
secondSnapshotFilePath,
{ breakdown: BREAKDOWN },
{ asInvertedTreeNode: true });
// Have to manually set these because symbol properties aren't structured
// cloned.
delta[CensusUtils.basisTotalBytes] = deltaTreeNode.totalBytes;
delta[CensusUtils.basisTotalCount] = deltaTreeNode.totalCount;
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_01.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_01.js
@@ -1,22 +1,22 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that the HeapAnalyses{Client,Worker} can take censuses.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const { report } = yield client.takeCensus(snapshotFilePath);
+ const { report } = await client.takeCensus(snapshotFilePath);
ok(report, "Should get a report");
equal(typeof report, "object", "report should be an object");
ok(report.objects);
ok(report.scripts);
ok(report.strings);
ok(report.other);
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_02.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_02.js
@@ -1,23 +1,23 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that the HeapAnalyses{Client,Worker} can take censuses with breakdown
// options.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const { report } = yield client.takeCensus(snapshotFilePath, {
+ const { report } = await client.takeCensus(snapshotFilePath, {
breakdown: { by: "count", count: true, bytes: true }
});
ok(report, "Should get a report");
equal(typeof report, "object", "report should be an object");
ok(report.count);
ok(report.bytes);
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_03.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_03.js
@@ -1,45 +1,45 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test that the HeapAnalyses{Client,Worker} bubbles errors properly when things
// go wrong.
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
// Snapshot file path to a file that doesn't exist.
let failed = false;
try {
- yield client.readHeapSnapshot(getFilePath("foo-bar-baz" + Math.random(), true));
+ await client.readHeapSnapshot(getFilePath("foo-bar-baz" + Math.random(), true));
} catch (e) {
failed = true;
}
ok(failed, "should not read heap snapshots that do not exist");
// Snapshot file path to a file that is not a heap snapshot.
failed = false;
try {
- yield client.readHeapSnapshot(getFilePath("test_HeapAnalyses_takeCensus_03.js"));
+ await client.readHeapSnapshot(getFilePath("test_HeapAnalyses_takeCensus_03.js"));
} catch (e) {
failed = true;
}
ok(failed, "should not be able to read a file "
+ "that is not a heap snapshot as a heap snapshot");
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
// Bad census breakdown options.
failed = false;
try {
- yield client.takeCensus(snapshotFilePath, {
+ await client.takeCensus(snapshotFilePath, {
breakdown: { by: "some classification that we do not have" }
});
} catch (e) {
failed = true;
}
ok(failed, "should not be able to breakdown by an unknown classification");
client.destroy();
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_05.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_05.js
@@ -5,28 +5,28 @@
// Test that the HeapAnalyses{Client,Worker} can take censuses and return
// a CensusTreeNode.
const BREAKDOWN = {
by: "internalType",
then: { by: "count", count: true, bytes: true }
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const { report } = yield client.takeCensus(snapshotFilePath, {
+ const { report } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
});
- const { report: treeNode } = yield client.takeCensus(snapshotFilePath, {
+ const { report: treeNode } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
}, {
asTreeNode: true
});
ok(treeNode.children.length > 0, "treeNode has children");
ok(treeNode.children.every(type => {
return "name" in type &&
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_06.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_06.js
@@ -10,17 +10,17 @@ const BREAKDOWN = {
then: {
by: "allocationStack",
then: { by: "count", count: true, bytes: true },
noStack: { by: "count", count: true, bytes: true }
},
other: { by: "count", count: true, bytes: true }
};
-add_task(function* () {
+add_task(async function () {
const g = newGlobal();
const dbg = new Debugger(g);
// 5 allocation markers with no stack.
g.eval(`
this.markers = [];
for (var i = 0; i < 5; i++) {
markers.push(allocationMarker());
@@ -48,24 +48,24 @@ add_task(function* () {
markers.push(allocationMarker());
}
}());
`);
const snapshotFilePath = saveNewHeapSnapshot({ debugger: dbg });
const client = new HeapAnalysesClient();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const { report } = yield client.takeCensus(snapshotFilePath, {
+ const { report } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
});
- const { report: treeNode } = yield client.takeCensus(snapshotFilePath, {
+ const { report: treeNode } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
}, {
asTreeNode: true
});
const markers = treeNode.children.find(c => c.name === "AllocationMarker");
ok(markers);
--- a/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_07.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_HeapAnalyses_takeCensus_07.js
@@ -21,28 +21,28 @@ const BREAKDOWN = {
then: { by: "count", count: true, bytes: true },
},
other: {
by: "internalType",
then: { by: "count", count: true, bytes: true },
},
};
-add_task(function* () {
+add_task(async function () {
const client = new HeapAnalysesClient();
const snapshotFilePath = saveNewHeapSnapshot();
- yield client.readHeapSnapshot(snapshotFilePath);
+ await client.readHeapSnapshot(snapshotFilePath);
ok(true, "Should have read the heap snapshot");
- const { report } = yield client.takeCensus(snapshotFilePath, {
+ const { report } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
});
- const { report: treeNode } = yield client.takeCensus(snapshotFilePath, {
+ const { report: treeNode } = await client.takeCensus(snapshotFilePath, {
breakdown: BREAKDOWN
}, {
asInvertedTreeNode: true
});
compareCensusViewData(BREAKDOWN, report, treeNode, { invert: true });
client.destroy();
--- a/devtools/shared/heapsnapshot/tests/unit/test_ReadHeapSnapshot_worker.js
+++ b/devtools/shared/heapsnapshot/tests/unit/test_ReadHeapSnapshot_worker.js
@@ -1,28 +1,28 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// Test that we can read core dumps into HeapSnapshot instances in a worker.
// eslint-disable-next-line
-add_task(function* () {
+add_task(async function () {
const worker = new ChromeWorker("resource://test/heap-snapshot-worker.js");
worker.postMessage({});
let assertionCount = 0;
worker.onmessage = e => {
if (e.data.type !== "assertion") {
return;
}
ok(e.data.passed, e.data.msg + "\n" + e.data.stack);
assertionCount++;
};
- yield waitForDone(worker);
+ await waitForDone(worker);
ok(assertionCount > 0);
worker.terminate();
});
function waitForDone(w) {
return new Promise((resolve, reject) => {
w.onerror = e => {
--- a/devtools/shared/qrcode/tests/mochitest/test_decode.html
+++ b/devtools/shared/qrcode/tests/mochitest/test_decode.html
@@ -22,17 +22,17 @@ window.onload = function() {
"/4yPqcvtD6OctNqLs968+w+G4gKU5nkaKKquLuW+QVy2tAkDTj3rfQts8CRDko" +
"+HPPoYRUgy9YsyldDm44mLWhHYZM6W7WaDqyCRGkZDySxpRGw2sqvLt1q5w/fo" +
"XyE6vnUQOJUHBlinMGh046V1F5PDqNcoqcgBOWKBKbK2N+aY+Ih49VkmqMcl2l" +
"dkhZUK1umE6jZXJ2ZJaujZaRqH4bpb2uZrJxvIt4Ebe9qoYYrJOsw8apz2bCut" +
"m9kqDcw52uuImyr5Oh1KXH1jrn2anuunywtODU/o2c6teceW39ZcLFg/fNMo1b" +
"t3jVw2dwTPwJq1KYG3gAklCgu37yGxeScYKyiCc+7DR34hPVQiuQ7UhJMagyEb" +
"lymmzJk0a9q8iTOnzp0NCgAAOw==";
- (async function() {
+ (async function () {
let result = await QR.decodeFromURI(testImage);
is(result, "HELLO", "Decoded data URI result matches");
let canvas = await drawToCanvas(testImage);
result = QR.decodeFromCanvas(canvas);
is(result, "HELLO", "Decoded canvas result matches");
})().then(SimpleTest.finish, ok.bind(null, false));
function drawToCanvas(src) {
--- a/devtools/shared/security/auth.js
+++ b/devtools/shared/security/auth.js
@@ -12,17 +12,16 @@ var defer = require("devtools/shared/def
var DevToolsUtils = require("devtools/shared/DevToolsUtils");
var { dumpn, dumpv } = DevToolsUtils;
loader.lazyRequireGetter(this, "prompt",
"devtools/shared/security/prompt");
loader.lazyRequireGetter(this, "cert",
"devtools/shared/security/cert");
loader.lazyRequireGetter(this, "asyncStorage",
"devtools/shared/async-storage");
-const { Task } = require("devtools/shared/task");
/**
* A simple enum-like object with keys mirrored to values.
* This makes comparison to a specfic value simpler without having to repeat and
* mis-type the value.
*/
function createEnum(obj) {
for (let key in obj) {
@@ -338,24 +337,24 @@ OOBCert.Client.prototype = {
// authentication steps
if (activeSendDialog && activeSendDialog.close) {
activeSendDialog.close();
activeSendDialog = null;
}
};
transport.hooks = {
- onPacket: Task.async(function* (packet) {
+ onPacket: async (packet) => {
closeDialog();
let { authResult } = packet;
switch (authResult) {
case AuthenticationResult.PENDING:
// Step B.8
// Client creates hash(ClientCert) + K(random 128-bit number)
- oobData = yield this._createOOB();
+ oobData = await this._createOOB();
activeSendDialog = this.sendOOB({
host,
port,
cert,
authResult,
oob: oobData
});
break;
@@ -377,39 +376,39 @@ OOBCert.Client.prototype = {
// Debugging begins
transport.hooks = null;
deferred.resolve(transport);
break;
default:
transport.close(new Error("Invalid auth result: " + authResult));
break;
}
- }.bind(this)),
+ },
onClosed(reason) {
closeDialog();
// Transport died before auth completed
transport.hooks = null;
deferred.reject(reason);
}
};
transport.ready();
return deferred.promise;
},
/**
* Create the package of data that needs to be transferred across the OOB
* channel.
*/
- _createOOB: Task.async(function* () {
- let clientCert = yield cert.local.getOrCreate();
+ async _createOOB() {
+ let clientCert = await cert.local.getOrCreate();
return {
sha256: clientCert.sha256Fingerprint,
k: this._createRandom()
};
- }),
+ },
_createRandom() {
// 16 bytes / 128 bits
const length = 16;
let rng = Cc["@mozilla.org/security/random-generator;1"]
.createInstance(Ci.nsIRandomGenerator);
let bytes = rng.generateRandomBytes(length);
return bytes.map(byte => byte.toString(16)).join("");
@@ -506,21 +505,21 @@ OOBCert.Server.prototype = {
* sha256
* }
* },
* transport
* }
* @return An AuthenticationResult value.
* A promise that will be resolved to the above is also allowed.
*/
- authenticate: Task.async(function* ({ client, server, transport }) {
+ async authenticate({ client, server, transport }) {
// Step B.3 / C.3
// TLS connection established, authentication begins
const storageKey = `devtools.auth.${this.mode}.approved-clients`;
- let approvedClients = (yield asyncStorage.getItem(storageKey)) || {};
+ let approvedClients = (await asyncStorage.getItem(storageKey)) || {};
// Step C.4
// Server sees that ClientCert is from a known client via hash(ClientCert)
if (approvedClients[client.cert.sha256]) {
let authResult = AuthenticationResult.ALLOW_PERSIST;
transport.send({ authResult });
// Step C.5
// Debugging begins
return authResult;
@@ -531,34 +530,34 @@ OOBCert.Server.prototype = {
// Tell client they are unknown and should display OOB client UX
transport.send({
authResult: AuthenticationResult.PENDING
});
// Step B.5
// User is shown a Allow / Deny / Always Allow prompt on the Server
// with Client name and hash(ClientCert)
- let authResult = yield this.allowConnection({
+ let authResult = await this.allowConnection({
authentication: this.mode,
client,
server
});
switch (authResult) {
case AuthenticationResult.ALLOW_PERSIST:
case AuthenticationResult.ALLOW:
// Further processing
break;
default:
// Abort for any negative results
return authResult;
}
// Examine additional data for authentication
- let oob = yield this.receiveOOB();
+ let oob = await this.receiveOOB();
if (!oob) {
dumpn("Invalid OOB data received");
return AuthenticationResult.DENY;
}
let { sha256, k } = oob;
// The OOB auth prompt should have transferred:
// hash(ClientCert) + K(random 128-bit number)
@@ -578,26 +577,26 @@ OOBCert.Server.prototype = {
// Step B.11
// Server sends K to Client over TLS connection
transport.send({ authResult, k });
// Persist Client if we want to always allow in the future
if (authResult === AuthenticationResult.ALLOW_PERSIST) {
approvedClients[client.cert.sha256] = true;
- yield asyncStorage.setItem(storageKey, approvedClients);
+ await asyncStorage.setItem(storageKey, approvedClients);
}
// Client may decide to abort if K does not match.
// Server's portion of authentication is now complete.
// Step B.13
// Debugging begins
return authResult;
- }),
+ },
/**
* Prompt the user to accept or decline the incoming connection. The default
* implementation is used unless this is overridden on a particular
* authenticator instance.
*
* It is expected that the implementation of |allowConnection| will show a
* prompt to the user so that they can allow or deny the connection.
--- a/devtools/shared/security/socket.js
+++ b/devtools/shared/security/socket.js
@@ -47,18 +47,16 @@ DevToolsUtils.defineLazyGetter(this, "ce
.getService(Ci.nsICertOverrideService);
});
DevToolsUtils.defineLazyGetter(this, "nssErrorsService", () => {
return Cc["@mozilla.org/nss_errors_service;1"]
.getService(Ci.nsINSSErrorsService);
});
-const { Task } = require("devtools/shared/task");
-
var DebuggerSocket = {};
/**
* Connects to a debugger server socket.
*
* @param host string
* The host name or IP address of the debugger server.
* @param port number
@@ -70,34 +68,34 @@ var DebuggerSocket = {};
* @param authenticator Authenticator (optional)
* |Authenticator| instance matching the mode in use by the server.
* Defaults to a PROMPT instance if not supplied.
* @param cert object (optional)
* The server's cert details. Used with OOB_CERT authentication.
* @return promise
* Resolved to a DebuggerTransport instance.
*/
-DebuggerSocket.connect = Task.async(function* (settings) {
+DebuggerSocket.connect = async function (settings) {
// Default to PROMPT |Authenticator| instance if not supplied
if (!settings.authenticator) {
settings.authenticator = new (Authenticators.get().Client)();
}
_validateSettings(settings);
let { host, port, encryption, authenticator, cert } = settings;
- let transport = yield _getTransport(settings);
- yield authenticator.authenticate({
+ let transport = await _getTransport(settings);
+ await authenticator.authenticate({
host,
port,
encryption,
cert,
transport
});
transport.connectionSettings = settings;
return transport;
-});
+};
/**
* Validate that the connection settings have been set to a supported configuration.
*/
function _validateSettings(settings) {
let { encryption, webSocket, authenticator } = settings;
if (webSocket && encryption) {
@@ -122,52 +120,52 @@ function _validateSettings(settings) {
* |Authenticator| instance matching the mode in use by the server.
* Defaults to a PROMPT instance if not supplied.
* @param cert object (optional)
* The server's cert details. Used with OOB_CERT authentication.
* @return transport DebuggerTransport
* A possible DevTools transport (if connection succeeded and streams
* are actually alive and working)
*/
-var _getTransport = Task.async(function* (settings) {
+var _getTransport = async function (settings) {
let { host, port, encryption, webSocket } = settings;
if (webSocket) {
// Establish a connection and wait until the WebSocket is ready to send and receive
- let socket = yield new Promise((resolve, reject) => {
+ let socket = await new Promise((resolve, reject) => {
let s = new WebSocket(`ws://${host}:${port}`);
s.onopen = () => resolve(s);
s.onerror = err => reject(err);
});
return new WebSocketDebuggerTransport(socket);
}
- let attempt = yield _attemptTransport(settings);
+ let attempt = await _attemptTransport(settings);
if (attempt.transport) {
// Success
return attempt.transport;
}
// If the server cert failed validation, store a temporary override and make
// a second attempt.
if (encryption && attempt.certError) {
_storeCertOverride(attempt.s, host, port);
} else {
throw new Error("Connection failed");
}
- attempt = yield _attemptTransport(settings);
+ attempt = await _attemptTransport(settings);
if (attempt.transport) {
// Success
return attempt.transport;
}
throw new Error("Connection failed even after cert override");
-});
+};
/**
* Make a single attempt to connect and create a DevTools transport. This could
* fail if the remote host is unreachable, for example. If there is security
* error due to the use of self-signed certs, you should make another attempt
* after storing a cert override.
*
* @param host string
@@ -184,27 +182,27 @@ var _getTransport = Task.async(function*
* @return transport DebuggerTransport
* A possible DevTools transport (if connection succeeded and streams
* are actually alive and working)
* @return certError boolean
* Flag noting if cert trouble caused the streams to fail
* @return s nsISocketTransport
* Underlying socket transport, in case more details are needed.
*/
-var _attemptTransport = Task.async(function* (settings) {
+var _attemptTransport = async function (settings) {
let { authenticator } = settings;
// _attemptConnect only opens the streams. Any failures at that stage
// aborts the connection process immedidately.
- let { s, input, output } = yield _attemptConnect(settings);
+ let { s, input, output } = await _attemptConnect(settings);
// Check if the input stream is alive. If encryption is enabled, we need to
// watch out for cert errors by testing the input stream.
let alive, certError;
try {
- let results = yield _isInputAlive(input);
+ let results = await _isInputAlive(input);
alive = results.alive;
certError = results.certError;
} catch (e) {
// For other unexpected errors, like NS_ERROR_CONNECTION_REFUSED, we reach
// this block.
input.close();
output.close();
throw e;
@@ -226,49 +224,49 @@ var _attemptTransport = Task.async(funct
transport = new DebuggerTransport(input, output);
} else {
// Something went wrong, close the streams.
input.close();
output.close();
}
return { transport, certError, s };
-});
+};
/**
* Try to connect to a remote server socket.
*
* If successsful, the socket transport and its opened streams are returned.
* Typically, this will only fail if the host / port is unreachable. Other
* problems, such as security errors, will allow this stage to succeed, but then
* fail later when the streams are actually used.
* @return s nsISocketTransport
* Underlying socket transport, in case more details are needed.
* @return input nsIAsyncInputStream
* The socket's input stream.
* @return output nsIAsyncOutputStream
* The socket's output stream.
*/
-var _attemptConnect = Task.async(function* ({ host, port, encryption }) {
+var _attemptConnect = async function ({ host, port, encryption }) {
let s;
if (encryption) {
s = socketTransportService.createTransport(["ssl"], 1, host, port, null);
} else {
s = socketTransportService.createTransport(null, 0, host, port, null);
}
// By default the CONNECT socket timeout is very long, 65535 seconds,
// so that if we race to be in CONNECT state while the server socket is still
// initializing, the connection is stuck in connecting state for 18.20 hours!
s.setTimeout(Ci.nsISocketTransport.TIMEOUT_CONNECT, 2);
// If encrypting, load the client cert now, so we can deliver it at just the
// right time.
let clientCert;
if (encryption) {
- clientCert = yield cert.local.getOrCreate();
+ clientCert = await cert.local.getOrCreate();
}
let deferred = defer();
let input;
let output;
// Delay opening the input stream until the transport has fully connected.
// The goal is to avoid showing the user a client cert UI prompt when
// encryption is used. This prompt is shown when the client opens the input
@@ -310,17 +308,17 @@ var _attemptConnect = Task.async(functio
}
if (output) {
output.close();
}
DevToolsUtils.reportException("_attemptConnect", e);
});
return deferred.promise;
-});
+};
/**
* Check if the input stream is alive. For an encrypted connection, it may not
* be if the client refuses the server's cert. A cert error is expected on
* first connection to a new host because the cert is self-signed.
*/
function _isInputAlive(input) {
let deferred = defer();
@@ -425,33 +423,33 @@ SocketListener.prototype = {
let flags = Ci.nsIServerSocket.KeepWhenOffline;
// A preference setting can force binding on the loopback interface.
if (Services.prefs.getBoolPref("devtools.debugger.force-local")) {
flags |= Ci.nsIServerSocket.LoopbackOnly;
}
let self = this;
- return Task.spawn(function* () {
+ return (async function () {
let backlog = 4;
self._socket = self._createSocketInstance();
if (self.isPortBased) {
let port = Number(self.portOrPath);
self._socket.initSpecialConnection(port, flags, backlog);
} else {
let file = nsFile(self.portOrPath);
if (file.exists()) {
file.remove(false);
}
self._socket.initWithFilename(file, parseInt("666", 8), backlog);
}
- yield self._setAdditionalSocketOptions();
+ await self._setAdditionalSocketOptions();
self._socket.asyncListen(self);
dumpn("Socket listening on: " + (self.port || self.portOrPath));
- }).then(() => {
+ })().then(() => {
this._advertise();
}).catch(e => {
dumpn("Could not start debugging listener on '" + this.portOrPath +
"': " + e);
this.close();
});
},
@@ -474,26 +472,26 @@ SocketListener.prototype = {
if (this.encryption) {
return Cc["@mozilla.org/network/tls-server-socket;1"]
.createInstance(Ci.nsITLSServerSocket);
}
return Cc["@mozilla.org/network/server-socket;1"]
.createInstance(Ci.nsIServerSocket);
},
- _setAdditionalSocketOptions: Task.async(function* () {
+ async _setAdditionalSocketOptions() {
if (this.encryption) {
- this._socket.serverCert = yield cert.local.getOrCreate();
+ this._socket.serverCert = await cert.local.getOrCreate();
this._socket.setSessionCache(false);
this._socket.setSessionTickets(false);
let requestCert = Ci.nsITLSServerSocket.REQUEST_NEVER;
this._socket.setRequestClientCertificate(requestCert);
}
this.authenticator.augmentSocketOptions(this, this._socket);
- }),
+ },
/**
* Closes the SocketListener. Notifies the server to remove the listener from
* the set of active SocketListeners.
*/
close: function () {
if (this.discoverable && this.port) {
discovery.removeService("devtools");
@@ -624,48 +622,48 @@ ServerSocketConnection.prototype = {
/**
* This is the main authentication workflow. If any pieces reject a promise,
* the connection is denied. If the entire process resolves successfully,
* the connection is finally handed off to the |DebuggerServer|.
*/
_handle() {
dumpn("Debugging connection starting authentication on " + this.address);
let self = this;
- Task.spawn(function* () {
+ (async function () {
self._listenForTLSHandshake();
- yield self._createTransport();
- yield self._awaitTLSHandshake();
- yield self._authenticate();
- }).then(() => this.allow()).catch(e => this.deny(e));
+ await self._createTransport();
+ await self._awaitTLSHandshake();
+ await self._authenticate();
+ })().then(() => this.allow()).catch(e => this.deny(e));
},
/**
* We need to open the streams early on, as that is required in the case of
* TLS sockets to keep the handshake moving.
*/
- _createTransport: Task.async(function* () {
+ async _createTransport() {
let input = this._socketTransport.openInputStream(0, 0, 0);
let output = this._socketTransport.openOutputStream(0, 0, 0);
if (this._listener.webSocket) {
- let socket = yield WebSocketServer.accept(this._socketTransport, input, output);
+ let socket = await WebSocketServer.accept(this._socketTransport, input, output);
this._transport = new WebSocketDebuggerTransport(socket);
} else {
this._transport = new DebuggerTransport(input, output);
}
// Start up the transport to observe the streams in case they are closed
// early. This allows us to clean up our state as well.
this._transport.hooks = {
onClosed: reason => {
this.deny(reason);
}
};
this._transport.ready();
- }),
+ },
/**
* Set the socket's security observer, which receives an event via the
* |onHandshakeDone| callback when the TLS handshake completes.
*/
_setSecurityObserver(observer) {
if (!this._socketTransport || !this._socketTransport.securityInfo) {
return;
@@ -720,18 +718,18 @@ ServerSocketConnection.prototype = {
if (clientStatus.tlsVersionUsed < Ci.nsITLSClientStatus.TLS_VERSION_1_2) {
this._handshakeDeferred.reject(Cr.NS_ERROR_CONNECTION_REFUSED);
return;
}
this._handshakeDeferred.resolve();
},
- _authenticate: Task.async(function* () {
- let result = yield this._listener.authenticator.authenticate({
+ async _authenticate() {
+ let result = await this._listener.authenticator.authenticate({
client: this.client,
server: this.server,
transport: this._transport
});
switch (result) {
case AuthenticationResult.DISABLE_ALL:
DebuggerServer.closeAllListeners();
Services.prefs.setBoolPref("devtools.debugger.remote-enabled", false);
@@ -739,17 +737,17 @@ ServerSocketConnection.prototype = {
case AuthenticationResult.DENY:
return promise.reject(Cr.NS_ERROR_CONNECTION_REFUSED);
case AuthenticationResult.ALLOW:
case AuthenticationResult.ALLOW_PERSIST:
return promise.resolve();
default:
return promise.reject(Cr.NS_ERROR_CONNECTION_REFUSED);
}
- }),
+ },
deny(result) {
if (this._destroyed) {
return;
}
let errorName = result;
for (let name in Cr) {
if (Cr[name] === result) {
--- a/devtools/shared/security/tests/chrome/test_websocket-transport.html
+++ b/devtools/shared/security/tests/chrome/test_websocket-transport.html
@@ -20,48 +20,48 @@ window.onload = function () {
Services.prefs.setBoolPref("devtools.debugger.remote-enabled", true);
Services.prefs.setBoolPref("devtools.debugger.prompt-connection", false);
SimpleTest.registerCleanupFunction(() => {
Services.prefs.clearUserPref("devtools.debugger.remote-enabled");
Services.prefs.clearUserPref("devtools.debugger.prompt-connection");
});
- add_task(function* () {
+ add_task(async function () {
DebuggerServer.init();
DebuggerServer.registerAllActors();
is(DebuggerServer.listeningSockets, 0, "0 listening sockets");
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.webSocket = true;
- yield listener.open();
+ await listener.open();
is(DebuggerServer.listeningSockets, 1, "1 listening socket");
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
webSocket: true
});
ok(transport, "Client transport created");
let client = new DebuggerClient(transport);
let onUnexpectedClose = () => {
ok(false, "Closed unexpectedly");
};
client.addListener("closed", onUnexpectedClose);
- yield client.connect();
- yield client.listTabs();
+ await client.connect();
+ await client.listTabs();
// Send a message the server that will echo back
let message = "message";
- let reply = yield client.request({
+ let reply = await client.request({
to: "root",
type: "echo",
message
});
is(reply.message, message, "Echo message matches");
client.removeListener("closed", onUnexpectedClose);
transport.close();
--- a/devtools/shared/security/tests/unit/test_encryption.js
+++ b/devtools/shared/security/tests/unit/test_encryption.js
@@ -11,96 +11,96 @@ function run_test() {
Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports);
run_next_test();
}
function connectClient(client) {
return client.connect(() => client.listTabs());
}
-add_task(function* () {
+add_task(async function () {
initTestDebuggerServer();
});
// Client w/ encryption connects successfully to server w/ encryption
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.authenticator = authenticator;
listener.encryption = true;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
encryption: true
});
ok(transport, "Client transport created");
let client = new DebuggerClient(transport);
let onUnexpectedClose = () => {
do_throw("Closed unexpectedly");
};
client.addListener("closed", onUnexpectedClose);
- yield connectClient(client);
+ await connectClient(client);
// Send a message the server will echo back
let message = "secrets";
- let reply = yield client.request({
+ let reply = await client.request({
to: "root",
type: "echo",
message
});
equal(reply.message, message, "Encrypted echo matches");
client.removeListener("closed", onUnexpectedClose);
transport.close();
listener.close();
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
});
// Client w/o encryption fails to connect to server w/ encryption
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.authenticator = authenticator;
listener.encryption = true;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
try {
- yield DebuggerClient.socketConnect({
+ await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port
// encryption: false is the default
});
} catch (e) {
ok(true, "Client failed to connect as expected");
listener.close();
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
return;
}
do_throw("Connection unexpectedly succeeded");
});
-add_task(function* () {
+add_task(async function () {
DebuggerServer.destroy();
});
--- a/devtools/shared/security/tests/unit/test_oob_cert_auth.js
+++ b/devtools/shared/security/tests/unit/test_oob_cert_auth.js
@@ -16,151 +16,151 @@ function run_test() {
}
function connectClient(client) {
return client.connect(() => {
return client.listTabs();
});
}
-add_task(function* () {
+add_task(async function () {
initTestDebuggerServer();
});
// Client w/ OOB_CERT auth connects successfully to server w/ OOB_CERT auth
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
// Grab our cert, instead of relying on a discovery advertisement
- let serverCert = yield cert.local.getOrCreate();
+ let serverCert = await cert.local.getOrCreate();
let oobData = defer();
let AuthenticatorType = DebuggerServer.Authenticators.get("OOB_CERT");
let serverAuth = new AuthenticatorType.Server();
serverAuth.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
// Skip prompt for tests
serverAuth.receiveOOB = () => oobData.promise;
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.encryption = true;
listener.authenticator = serverAuth;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
let clientAuth = new AuthenticatorType.Client();
clientAuth.sendOOB = ({ oob }) => {
info(oob);
// Pass to server, skipping prompt for tests
oobData.resolve(oob);
};
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
encryption: true,
authenticator: clientAuth,
cert: {
sha256: serverCert.sha256Fingerprint
}
});
ok(transport, "Client transport created");
let client = new DebuggerClient(transport);
let onUnexpectedClose = () => {
do_throw("Closed unexpectedly");
};
client.addListener("closed", onUnexpectedClose);
- yield connectClient(client);
+ await connectClient(client);
// Send a message the server will echo back
let message = "secrets";
- let reply = yield client.request({
+ let reply = await client.request({
to: "root",
type: "echo",
message
});
equal(reply.message, message, "Encrypted echo matches");
client.removeListener("closed", onUnexpectedClose);
transport.close();
listener.close();
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
});
// Client w/o OOB_CERT auth fails to connect to server w/ OOB_CERT auth
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
let oobData = defer();
let AuthenticatorType = DebuggerServer.Authenticators.get("OOB_CERT");
let serverAuth = new AuthenticatorType.Server();
serverAuth.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
// Skip prompt for tests
serverAuth.receiveOOB = () => oobData.promise;
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.encryption = true;
listener.authenticator = serverAuth;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
// This will succeed, but leaves the client in confused state, and no data is
// actually accessible
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
encryption: true
// authenticator: PROMPT is the default
});
// Attempt to use the transport
let deferred = defer();
let client = new DebuggerClient(transport);
client.onPacket = packet => {
// Client did not authenticate, so it ends up seeing the server's auth data
// which is effectively malformed data from the client's perspective
ok(!packet.from && packet.authResult, "Got auth packet instead of data");
deferred.resolve();
};
client.connect();
- yield deferred.promise;
+ await deferred.promise;
// Try to send a message the server will echo back
let message = "secrets";
try {
- yield client.request({
+ await client.request({
to: "root",
type: "echo",
message
});
} catch (e) {
ok(true, "Sending a message failed");
transport.close();
listener.close();
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
return;
}
do_throw("Connection unexpectedly succeeded");
});
// Client w/ invalid K value fails to connect
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
// Grab our cert, instead of relying on a discovery advertisement
- let serverCert = yield cert.local.getOrCreate();
+ let serverCert = await cert.local.getOrCreate();
let oobData = defer();
let AuthenticatorType = DebuggerServer.Authenticators.get("OOB_CERT");
let serverAuth = new AuthenticatorType.Server();
serverAuth.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
// Skip prompt for tests
@@ -177,21 +177,21 @@ add_task(function* () {
});
};
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.encryption = true;
listener.authenticator = serverAuth;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
try {
- yield DebuggerClient.socketConnect({
+ await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
encryption: true,
authenticator: clientAuth,
cert: {
sha256: serverCert.sha256Fingerprint
}
});
@@ -201,21 +201,21 @@ add_task(function* () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
return;
}
do_throw("Connection unexpectedly succeeded");
});
// Client w/ invalid cert hash fails to connect
-add_task(function* () {
+add_task(async function () {
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
// Grab our cert, instead of relying on a discovery advertisement
- let serverCert = yield cert.local.getOrCreate();
+ let serverCert = await cert.local.getOrCreate();
let oobData = defer();
let AuthenticatorType = DebuggerServer.Authenticators.get("OOB_CERT");
let serverAuth = new AuthenticatorType.Server();
serverAuth.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
// Skip prompt for tests
@@ -232,21 +232,21 @@ add_task(function* () {
});
};
let listener = DebuggerServer.createListener();
ok(listener, "Socket listener created");
listener.portOrPath = -1;
listener.encryption = true;
listener.authenticator = serverAuth;
- yield listener.open();
+ await listener.open();
equal(DebuggerServer.listeningSockets, 1, "1 listening socket");
try {
- yield DebuggerClient.socketConnect({
+ await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port,
encryption: true,
authenticator: clientAuth,
cert: {
sha256: serverCert.sha256Fingerprint
}
});
@@ -255,11 +255,11 @@ add_task(function* () {
listener.close();
equal(DebuggerServer.listeningSockets, 0, "0 listening sockets");
return;
}
do_throw("Connection unexpectedly succeeded");
});
-add_task(function* () {
+add_task(async function () {
DebuggerServer.destroy();
});
--- a/devtools/shared/system.js
+++ b/devtools/shared/system.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/. */
"use strict";
const { Cc, Ci } = require("chrome");
-const { Task } = require("devtools/shared/task");
loader.lazyRequireGetter(this, "Services");
loader.lazyRequireGetter(this, "promise");
loader.lazyRequireGetter(this, "defer", "devtools/shared/defer");
loader.lazyRequireGetter(this, "DebuggerServer", "devtools/server/main", true);
loader.lazyRequireGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm", true);
loader.lazyGetter(this, "screenManager", () => {
@@ -42,17 +41,17 @@ const APP_MAP = {
"{718e30fb-e89b-41dd-9da7-e25a45638b28}": "sunbird",
"{3c2e2abc-06d4-11e1-ac3b-374f68613e61}": "b2g",
"{aa3c5121-dab2-40e2-81ca-7ea25febc110}": "mobile/android",
"{a23983c0-fd0e-11dc-95ff-0800200c9a66}": "mobile/xul"
};
var CACHED_INFO = null;
-function* getSystemInfo() {
+async function getSystemInfo() {
if (CACHED_INFO) {
return CACHED_INFO;
}
let appInfo = Services.appinfo;
let win = Services.wm.getMostRecentWindow(DebuggerServer.chromeWindowType);
let [processor, compiler] = appInfo.XPCOMABI.split("-");
let dpi,
@@ -70,18 +69,18 @@ function* getSystemInfo() {
let version = "unknown";
// B2G specific
if (apptype === "b2g") {
os = "B2G";
// `getSetting` does not work in child processes on b2g.
// TODO bug 1205797, make this work in child processes.
try {
- hardware = yield exports.getSetting("deviceinfo.hardware");
- version = yield exports.getSetting("deviceinfo.os");
+ hardware = await exports.getSetting("deviceinfo.hardware");
+ version = await exports.getSetting("deviceinfo.os");
} catch (e) {
// Ignore.
}
} else {
// Not B2G
os = appInfo.OS;
version = appInfo.version;
}
@@ -319,13 +318,13 @@ function getSetting(name) {
handleError: (error) => deferred.reject(error),
});
} else {
deferred.reject(new Error("No settings service"));
}
return deferred.promise;
}
-exports.getSystemInfo = Task.async(getSystemInfo);
+exports.getSystemInfo = getSystemInfo;
exports.getSetting = getSetting;
exports.getScreenDimensions = getScreenDimensions;
exports.getOSCPU = getOSCPU;
exports.constants = AppConstants;
--- a/devtools/shared/tests/browser/browser_async_storage.js
+++ b/devtools/shared/tests/browser/browser_async_storage.js
@@ -3,75 +3,75 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Test the basic functionality of async-storage.
// Adapted from https://github.com/mozilla-b2g/gaia/blob/f09993563fb5fec4393eb71816ce76cb00463190/apps/sharedtest/test/unit/async_storage_test.js.
const asyncStorage = require("devtools/shared/async-storage");
-add_task(function* () {
+add_task(async function () {
is(typeof asyncStorage.length, "function", "API exists.");
is(typeof asyncStorage.key, "function", "API exists.");
is(typeof asyncStorage.getItem, "function", "API exists.");
is(typeof asyncStorage.setItem, "function", "API exists.");
is(typeof asyncStorage.removeItem, "function", "API exists.");
is(typeof asyncStorage.clear, "function", "API exists.");
});
-add_task(function* () {
- yield asyncStorage.setItem("foo", "bar");
- let value = yield asyncStorage.getItem("foo");
+add_task(async function () {
+ await asyncStorage.setItem("foo", "bar");
+ let value = await asyncStorage.getItem("foo");
is(value, "bar", "value is correct");
- yield asyncStorage.setItem("foo", "overwritten");
- value = yield asyncStorage.getItem("foo");
+ await asyncStorage.setItem("foo", "overwritten");
+ value = await asyncStorage.getItem("foo");
is(value, "overwritten", "value is correct");
- yield asyncStorage.removeItem("foo");
- value = yield asyncStorage.getItem("foo");
+ await asyncStorage.removeItem("foo");
+ value = await asyncStorage.getItem("foo");
is(value, null, "value is correct");
});
-add_task(function* () {
+add_task(async function () {
let object = {
x: 1,
y: "foo",
z: true
};
- yield asyncStorage.setItem("myobj", object);
- let value = yield asyncStorage.getItem("myobj");
+ await asyncStorage.setItem("myobj", object);
+ let value = await asyncStorage.getItem("myobj");
is(object.x, value.x, "value is correct");
is(object.y, value.y, "value is correct");
is(object.z, value.z, "value is correct");
- yield asyncStorage.removeItem("myobj");
- value = yield asyncStorage.getItem("myobj");
+ await asyncStorage.removeItem("myobj");
+ value = await asyncStorage.getItem("myobj");
is(value, null, "value is correct");
});
-add_task(function* () {
- yield asyncStorage.clear();
- let len = yield asyncStorage.length();
+add_task(async function () {
+ await asyncStorage.clear();
+ let len = await asyncStorage.length();
is(len, 0, "length is correct");
- yield asyncStorage.setItem("key1", "value1");
- len = yield asyncStorage.length();
+ await asyncStorage.setItem("key1", "value1");
+ len = await asyncStorage.length();
is(len, 1, "length is correct");
- yield asyncStorage.setItem("key2", "value2");
- len = yield asyncStorage.length();
+ await asyncStorage.setItem("key2", "value2");
+ len = await asyncStorage.length();
is(len, 2, "length is correct");
- yield asyncStorage.setItem("key3", "value3");
- len = yield asyncStorage.length();
+ await asyncStorage.setItem("key3", "value3");
+ len = await asyncStorage.length();
is(len, 3, "length is correct");
- let key = yield asyncStorage.key(0);
+ let key = await asyncStorage.key(0);
is(key, "key1", "key is correct");
- key = yield asyncStorage.key(1);
+ key = await asyncStorage.key(1);
is(key, "key2", "key is correct");
- key = yield asyncStorage.key(2);
+ key = await asyncStorage.key(2);
is(key, "key3", "key is correct");
- key = yield asyncStorage.key(3);
+ key = await asyncStorage.key(3);
is(key, null, "key is correct");
- yield asyncStorage.clear();
- key = yield asyncStorage.key(0);
+ await asyncStorage.clear();
+ key = await asyncStorage.key(0);
is(key, null, "key is correct");
- len = yield asyncStorage.length();
+ len = await asyncStorage.length();
is(len, 0, "length is correct");
});
--- a/devtools/shared/tests/mochitest/test_eventemitter_basic.html
+++ b/devtools/shared/tests/mochitest/test_eventemitter_basic.html
@@ -19,24 +19,23 @@
<body>
<script type="application/javascript">
"use strict";
const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm", {});
const promise = require("promise");
const EventEmitter = require("devtools/shared/old-event-emitter");
- const { Task } = require("devtools/shared/task");
SimpleTest.waitForExplicitFinish();
testEmitter();
testEmitter({});
- Task.spawn(testPromise)
+ testPromise()
.catch(ok.bind(null, false))
.then(SimpleTest.finish);
function testEmitter(aObject) {
let emitter;
if (aObject) {
emitter = aObject;
--- a/devtools/shared/tests/unit/test_defer.js
+++ b/devtools/shared/tests/unit/test_defer.js
@@ -12,21 +12,21 @@ function testResolve() {
}
function testReject() {
const deferred = defer();
deferred.reject("error");
return deferred.promise;
}
-add_task(function* () {
- const success = yield testResolve();
+add_task(async function () {
+ const success = await testResolve();
equal(success, "success");
let error;
try {
- yield testReject();
+ await testReject();
} catch (e) {
error = e;
}
equal(error, "error");
});
--- a/devtools/shared/tests/unit/test_executeSoon.js
+++ b/devtools/shared/tests/unit/test_executeSoon.js
@@ -16,20 +16,20 @@ var defer = require("devtools/shared/def
var asyncStackEnabled =
Services.prefs.getBoolPref("javascript.options.asyncstack");
registerCleanupFunction(() => {
Services.prefs.setBoolPref("javascript.options.asyncstack",
asyncStackEnabled);
});
-add_task(function* () {
+add_task(async function () {
Services.prefs.setBoolPref("javascript.options.asyncstack", true);
- yield waitForTick();
+ await waitForTick();
let stack = Components.stack;
while (stack) {
info(stack.name);
if (stack.name == "waitForTick") {
// Reached back to outer function before executeSoon
ok(true, "Complete stack");
return;
--- a/devtools/shared/tests/unit/test_fetch-bom.js
+++ b/devtools/shared/tests/unit/test_fetch-bom.js
@@ -56,21 +56,21 @@ server.start(-1);
const port = server.identity.primaryPort;
const serverURL = "http://localhost:" + port;
registerCleanupFunction(() => {
return new Promise(resolve => server.stop(resolve));
});
-add_task(function* () {
- yield test_one(serverURL + "/u8", "UTF-8");
- yield test_one(serverURL + "/u16be", "UTF-16BE");
- yield test_one(serverURL + "/u16le", "UTF-16LE");
+add_task(async function () {
+ await test_one(serverURL + "/u8", "UTF-8");
+ await test_one(serverURL + "/u16be", "UTF-16BE");
+ await test_one(serverURL + "/u16le", "UTF-16LE");
});
-function* test_one(url, encoding) {
+async function test_one(url, encoding) {
// Be sure to set the encoding to something that will yield an
// invalid result if BOM sniffing is not done.
- yield DevToolsUtils.fetch(url, { charset: "ISO-8859-1" }).then(({content}) => {
+ await DevToolsUtils.fetch(url, { charset: "ISO-8859-1" }).then(({content}) => {
Assert.equal(content, "hı", "The content looks correct for " + encoding);
});
}
--- a/devtools/shared/tests/unit/test_fetch-chrome.js
+++ b/devtools/shared/tests/unit/test_fetch-chrome.js
@@ -6,26 +6,26 @@
// Tests for DevToolsUtils.fetch on chrome:// URI's.
const URL_FOUND = "chrome://devtools-shared/locale/debugger.properties";
const URL_NOT_FOUND = "chrome://this/is/not/here.js";
/**
* Test that non-existent files are handled correctly.
*/
-add_task(function* test_missing() {
- yield DevToolsUtils.fetch(URL_NOT_FOUND).then(result => {
+add_task(async function test_missing() {
+ await DevToolsUtils.fetch(URL_NOT_FOUND).then(result => {
info(result);
ok(false, "fetch resolved unexpectedly for non-existent chrome:// URI");
}, () => {
ok(true, "fetch rejected as the chrome:// URI was non-existent.");
});
});
/**
* Tests that existing files are handled correctly.
*/
-add_task(function* test_normal() {
- yield DevToolsUtils.fetch(URL_FOUND).then(result => {
+add_task(async function test_normal() {
+ await DevToolsUtils.fetch(URL_FOUND).then(result => {
notDeepEqual(result.content, "",
"chrome:// URI seems to be read correctly.");
});
});
--- a/devtools/shared/tests/unit/test_fetch-file.js
+++ b/devtools/shared/tests/unit/test_fetch-file.js
@@ -16,80 +16,80 @@ const UTF8_TEST_BUFFER = new Uint8Array(
// The TEST_CONTENT encoded as ISO 8859-1.
const ISO_8859_1_BUFFER = new Uint8Array([0x61, 0xe9, 0x64]);
/**
* Tests that URLs with arrows pointing to an actual source are handled properly
* (bug 808960). For example 'resource://gre/modules/XPIProvider.jsm ->
* file://l10n.js' should load 'file://l10n.js'.
*/
-add_task(function* test_arrow_urls() {
+add_task(async function test_arrow_urls() {
let { path } = createTemporaryFile(".js");
let url = "resource://gre/modules/XPIProvider.jsm -> file://" + path;
- yield OS.File.writeAtomic(path, TEST_CONTENT, { encoding: "utf-8" });
- let { content } = yield DevToolsUtils.fetch(url);
+ await OS.File.writeAtomic(path, TEST_CONTENT, { encoding: "utf-8" });
+ let { content } = await DevToolsUtils.fetch(url);
deepEqual(content, TEST_CONTENT, "The file contents were correctly read.");
});
/**
* Tests that empty files are read correctly.
*/
-add_task(function* test_empty() {
+add_task(async function test_empty() {
let { path } = createTemporaryFile();
- let { content } = yield DevToolsUtils.fetch("file://" + path);
+ let { content } = await DevToolsUtils.fetch("file://" + path);
deepEqual(content, "", "The empty file was read correctly.");
});
/**
* Tests that UTF-8 encoded files are correctly read.
*/
-add_task(function* test_encoding_utf8() {
+add_task(async function test_encoding_utf8() {
let { path } = createTemporaryFile();
- yield OS.File.writeAtomic(path, UTF8_TEST_BUFFER);
+ await OS.File.writeAtomic(path, UTF8_TEST_BUFFER);
- let { content } = yield DevToolsUtils.fetch(path);
+ let { content } = await DevToolsUtils.fetch(path);
deepEqual(content, TEST_CONTENT,
"The UTF-8 encoded file was correctly read.");
});
/**
* Tests that ISO 8859-1 (Latin-1) encoded files are correctly read.
*/
-add_task(function* test_encoding_iso_8859_1() {
+add_task(async function test_encoding_iso_8859_1() {
let { path } = createTemporaryFile();
- yield OS.File.writeAtomic(path, ISO_8859_1_BUFFER);
+ await OS.File.writeAtomic(path, ISO_8859_1_BUFFER);
- let { content } = yield DevToolsUtils.fetch(path);
+ let { content } = await DevToolsUtils.fetch(path);
deepEqual(content, TEST_CONTENT,
"The ISO 8859-1 encoded file was correctly read.");
});
/**
* Test that non-existent files are handled correctly.
*/
-add_task(function* test_missing() {
- yield DevToolsUtils.fetch("file:///file/not/found.right").then(result => {
+add_task(async function test_missing() {
+ await DevToolsUtils.fetch("file:///file/not/found.right").then(result => {
info(result);
ok(false, "Fetch resolved unexpectedly when the file was not found.");
}, () => {
ok(true, "Fetch rejected as expected because the file was not found.");
});
});
/**
* Test that URLs without file:// scheme work.
*/
-add_task(function* test_schemeless_files() {
+add_task(async function test_schemeless_files() {
let { path } = createTemporaryFile();
- yield OS.File.writeAtomic(path, TEST_CONTENT, { encoding: "utf-8" });
+ await OS.File.writeAtomic(path, TEST_CONTENT, { encoding: "utf-8" });
- let { content } = yield DevToolsUtils.fetch(path);
+ let { content } = await DevToolsUtils.fetch(path);
deepEqual(content, TEST_CONTENT, "The content was correct.");
});
/**
* Creates a temporary file that is removed after the test completes.
*/
function createTemporaryFile(extension) {
let name = "test_fetch-file-" + Math.random() + (extension || "");
--- a/devtools/shared/tests/unit/test_fetch-http.js
+++ b/devtools/shared/tests/unit/test_fetch-http.js
@@ -26,36 +26,36 @@ function cacheRequestHandler(request, re
let body = "[" + Math.random() + "]";
response.bodyOutputStream.write(body, body.length);
}
registerCleanupFunction(() => {
return new Promise(resolve => server.stop(resolve));
});
-add_task(function* test_normal() {
- yield DevToolsUtils.fetch(NORMAL_URL).then(({content}) => {
+add_task(async function test_normal() {
+ await DevToolsUtils.fetch(NORMAL_URL).then(({content}) => {
ok(content.includes("The content looks correct."),
"The content looks correct.");
});
});
-add_task(function* test_caching() {
+add_task(async function test_caching() {
let initialContent = null;
info("Performing the first request.");
- yield DevToolsUtils.fetch(CACHED_URL).then(({content}) => {
+ await DevToolsUtils.fetch(CACHED_URL).then(({content}) => {
info("Got the first response: " + content);
initialContent = content;
});
info("Performing another request, expecting to get cached response.");
- yield DevToolsUtils.fetch(CACHED_URL).then(({content}) => {
+ await DevToolsUtils.fetch(CACHED_URL).then(({content}) => {
deepEqual(content, initialContent, "The content was loaded from cache.");
});
info("Performing a third request with cache bypassed.");
let opts = { loadFromCache: false };
- yield DevToolsUtils.fetch(CACHED_URL, opts).then(({content}) => {
+ await DevToolsUtils.fetch(CACHED_URL, opts).then(({content}) => {
notDeepEqual(content, initialContent,
"The URL wasn't loaded from cache with loadFromCache: false.");
});
});
--- a/devtools/shared/tests/unit/test_fetch-resource.js
+++ b/devtools/shared/tests/unit/test_fetch-resource.js
@@ -6,26 +6,26 @@
// Tests for DevToolsUtils.fetch on resource:// URI's.
const URL_FOUND = "resource://devtools/shared/DevToolsUtils.js";
const URL_NOT_FOUND = "resource://devtools/this/is/not/here.js";
/**
* Test that non-existent files are handled correctly.
*/
-add_task(function* test_missing() {
- yield DevToolsUtils.fetch(URL_NOT_FOUND).then(result => {
+add_task(async function test_missing() {
+ await DevToolsUtils.fetch(URL_NOT_FOUND).then(result => {
info(result);
ok(false, "fetch resolved unexpectedly for non-existent resource:// URI");
}, () => {
ok(true, "fetch rejected as the resource:// URI was non-existent.");
});
});
/**
* Tests that existing files are handled correctly.
*/
-add_task(function* test_normal() {
- yield DevToolsUtils.fetch(URL_FOUND).then(result => {
+add_task(async function test_normal() {
+ await DevToolsUtils.fetch(URL_FOUND).then(result => {
notDeepEqual(result.content, "",
"resource:// URI seems to be read correctly.");
});
});
--- a/devtools/shared/transport/tests/unit/head_dbg.js
+++ b/devtools/shared/transport/tests/unit/head_dbg.js
@@ -9,17 +9,16 @@
var CC = Components.Constructor;
const { require } =
ChromeUtils.import("resource://devtools/shared/Loader.jsm", {});
const { NetUtil } = require("resource://gre/modules/NetUtil.jsm");
const promise = require("promise");
const defer = require("devtools/shared/defer");
-const { Task } = require("devtools/shared/task");
const Services = require("Services");
// We do not want to log packets by default, because in some tests,
// we can be sending large amounts of data. The test harness has
// trouble dealing with logging all the data, and we end up with
// intermittent time outs (e.g. bug 775924).
// Services.prefs.setBoolPref("devtools.debugger.log", true);
@@ -125,32 +124,32 @@ function writeTestTempFile(fileName, con
} while (content.length > 0);
} finally {
stream.close();
}
}
/** * Transport Factories ***/
-var socket_transport = Task.async(function* () {
+var socket_transport = async function () {
if (!DebuggerServer.listeningSockets) {
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let debuggerListener = DebuggerServer.createListener();
debuggerListener.portOrPath = -1;
debuggerListener.authenticator = authenticator;
- yield debuggerListener.open();
+ await debuggerListener.open();
}
let port = DebuggerServer._listeners[0].port;
info("Debugger server port is " + port);
return DebuggerClient.socketConnect({ host: "127.0.0.1", port });
-});
+};
function local_transport() {
return promise.resolve(DebuggerServer.connectPipe());
}
/** * Sample Data ***/
var gReallyLong;
--- a/devtools/shared/transport/tests/unit/test_bulk_error.js
+++ b/devtools/shared/transport/tests/unit/test_bulk_error.js
@@ -2,19 +2,19 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
function run_test() {
initTestDebuggerServer();
add_test_bulk_actor();
- add_task(function* () {
- yield test_string_error(socket_transport, json_reply);
- yield test_string_error(local_transport, json_reply);
+ add_task(async function () {
+ await test_string_error(socket_transport, json_reply);
+ await test_string_error(local_transport, json_reply);
DebuggerServer.destroy();
});
run_next_test();
}
/** * Sample Bulk Actor ***/
@@ -39,30 +39,30 @@ TestBulkActor.prototype.requestTypes = {
};
function add_test_bulk_actor() {
DebuggerServer.addGlobalActor(TestBulkActor);
}
/** * Tests ***/
-var test_string_error = Task.async(function* (transportFactory, onReady) {
- let transport = yield transportFactory();
+var test_string_error = async function (transportFactory, onReady) {
+ let transport = await transportFactory();
let client = new DebuggerClient(transport);
return client.connect().then(([app, traits]) => {
Assert.equal(traits.bulk, true);
return client.listTabs();
}).then(response => {
return onReady(client, response);
}).then(() => {
client.close();
transport.close();
});
-});
+};
/** * Reply Types ***/
function json_reply(client, response) {
let reallyLong = really_long();
let request = client.startBulkRequest({
actor: response.testBulk,
--- a/devtools/shared/transport/tests/unit/test_client_server_bulk.js
+++ b/devtools/shared/transport/tests/unit/test_client_server_bulk.js
@@ -5,23 +5,23 @@
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm", {});
var Pipe = CC("@mozilla.org/pipe;1", "nsIPipe", "init");
function run_test() {
initTestDebuggerServer();
add_test_bulk_actor();
- add_task(function* () {
- yield test_bulk_request_cs(socket_transport, "jsonReply", "json");
- yield test_bulk_request_cs(local_transport, "jsonReply", "json");
- yield test_bulk_request_cs(socket_transport, "bulkEcho", "bulk");
- yield test_bulk_request_cs(local_transport, "bulkEcho", "bulk");
- yield test_json_request_cs(socket_transport, "bulkReply", "bulk");
- yield test_json_request_cs(local_transport, "bulkReply", "bulk");
+ add_task(async function () {
+ await test_bulk_request_cs(socket_transport, "jsonReply", "json");
+ await test_bulk_request_cs(local_transport, "jsonReply", "json");
+ await test_bulk_request_cs(socket_transport, "bulkEcho", "bulk");
+ await test_bulk_request_cs(local_transport, "bulkEcho", "bulk");
+ await test_json_request_cs(socket_transport, "bulkReply", "bulk");
+ await test_json_request_cs(local_transport, "bulkReply", "bulk");
DebuggerServer.destroy();
});
run_next_test();
}
/** * Sample Bulk Actor ***/
@@ -128,26 +128,26 @@ var replyHandlers = {
});
return replyDeferred.promise;
}
};
/** * Tests ***/
-var test_bulk_request_cs = Task.async(function* (transportFactory, actorType, replyType) {
+var test_bulk_request_cs = async function (transportFactory, actorType, replyType) {
// Ensure test files are not present from a failed run
cleanup_files();
writeTestTempFile("bulk-input", really_long());
let clientDeferred = defer();
let serverDeferred = defer();
let bulkCopyDeferred = defer();
- let transport = yield transportFactory();
+ let transport = await transportFactory();
let client = new DebuggerClient(transport);
client.connect().then(([app, traits]) => {
Assert.equal(traits.bulk, true);
client.listTabs().then(clientDeferred.resolve);
});
function bulkSendReadyCallback({copyFrom}) {
@@ -185,27 +185,27 @@ var test_bulk_request_cs = Task.async(fu
}
});
return promise.all([
clientDeferred.promise,
bulkCopyDeferred.promise,
serverDeferred.promise
]);
-});
+};
-var test_json_request_cs = Task.async(function* (transportFactory, actorType, replyType) {
+var test_json_request_cs = async function (transportFactory, actorType, replyType) {
// Ensure test files are not present from a failed run
cleanup_files();
writeTestTempFile("bulk-input", really_long());
let clientDeferred = defer();
let serverDeferred = defer();
- let transport = yield transportFactory();
+ let transport = await transportFactory();
let client = new DebuggerClient(transport);
client.connect((app, traits) => {
Assert.equal(traits.bulk, true);
client.listTabs().then(clientDeferred.resolve);
});
clientDeferred.promise.then(response => {
@@ -226,17 +226,17 @@ var test_json_request_cs = Task.async(fu
serverDeferred.resolve();
}
});
return promise.all([
clientDeferred.promise,
serverDeferred.promise
]);
-});
+};
/** * Test Utils ***/
function verify_files() {
let reallyLong = really_long();
let inputFile = getTestTempFile("bulk-input");
let outputFile = getTestTempFile("bulk-output");
--- a/devtools/shared/transport/tests/unit/test_dbgsocket.js
+++ b/devtools/shared/transport/tests/unit/test_dbgsocket.js
@@ -11,17 +11,17 @@ function run_test() {
add_task(test_socket_conn);
add_task(test_socket_shutdown);
add_test(test_pipe_conn);
run_next_test();
}
-function* test_socket_conn() {
+async function test_socket_conn() {
Assert.equal(DebuggerServer.listeningSockets, 0);
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let listener = DebuggerServer.createListener();
Assert.ok(listener);
@@ -35,17 +35,17 @@ function* test_socket_conn() {
gExtraListener = DebuggerServer.createListener();
gExtraListener.portOrPath = -1;
gExtraListener.authenticator = authenticator;
gExtraListener.open();
Assert.equal(DebuggerServer.listeningSockets, 2);
info("Starting long and unicode tests at " + new Date().toTimeString());
let unicodeString = "(╯°□°)╯︵ ┻━┻";
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: gPort
});
// Assert that connection settings are available on transport object
let settings = transport.connectionSettings;
Assert.equal(settings.host, "127.0.0.1");
Assert.equal(settings.port, gPort);
@@ -68,29 +68,29 @@ function* test_socket_conn() {
onClosed: function (status) {
closedDeferred.resolve();
},
};
transport.ready();
return closedDeferred.promise;
}
-function* test_socket_shutdown() {
+async function test_socket_shutdown() {
Assert.equal(DebuggerServer.listeningSockets, 2);
gExtraListener.close();
Assert.equal(DebuggerServer.listeningSockets, 1);
Assert.ok(DebuggerServer.closeAllListeners());
Assert.equal(DebuggerServer.listeningSockets, 0);
// Make sure closing the listener twice does nothing.
Assert.ok(!DebuggerServer.closeAllListeners());
Assert.equal(DebuggerServer.listeningSockets, 0);
info("Connecting to a server socket at " + new Date().toTimeString());
try {
- yield DebuggerClient.socketConnect({
+ await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: gPort
});
} catch (e) {
if (e.result == Cr.NS_ERROR_CONNECTION_REFUSED ||
e.result == Cr.NS_ERROR_NET_TIMEOUT) {
// The connection should be refused here, but on slow or overloaded
// machines it may just time out.
--- a/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js
+++ b/devtools/shared/transport/tests/unit/test_dbgsocket_connection_drop.js
@@ -39,29 +39,29 @@ function test_socket_conn_drops_after_to
// The packet header is currently limited to no more than 200 bytes
let rawPacket = "4305724038957487634549823475894325";
for (let i = 0; i < 8; i++) {
rawPacket += rawPacket;
}
return test_helper(rawPacket + ":");
}
-var test_helper = Task.async(function* (payload) {
+var test_helper = async function (payload) {
let AuthenticatorType = DebuggerServer.Authenticators.get("PROMPT");
let authenticator = new AuthenticatorType.Server();
authenticator.allowConnection = () => {
return DebuggerServer.AuthenticationResult.ALLOW;
};
let listener = DebuggerServer.createListener();
listener.portOrPath = -1;
listener.authenticator = authenticator;
listener.open();
- let transport = yield DebuggerClient.socketConnect({
+ let transport = await DebuggerClient.socketConnect({
host: "127.0.0.1",
port: listener.port
});
let closedDeferred = defer();
transport.hooks = {
onPacket: function (packet) {
this.onPacket = function () {
do_throw(new Error("This connection should be dropped."));
@@ -74,9 +74,9 @@ var test_helper = Task.async(function* (
},
onClosed: function (status) {
Assert.ok(true);
closedDeferred.resolve();
},
};
transport.ready();
return closedDeferred.promise;
-});
+};
--- a/devtools/shared/transport/tests/unit/test_delimited_read.js
+++ b/devtools/shared/transport/tests/unit/test_delimited_read.js
@@ -3,21 +3,21 @@
"use strict";
const StreamUtils = require("devtools/shared/transport/stream-utils");
const StringInputStream = CC("@mozilla.org/io/string-input-stream;1",
"nsIStringInputStream", "setData");
function run_test() {
- add_task(function* () {
- yield test_delimited_read("0123:", "0123:");
- yield test_delimited_read("0123:4567:", "0123:");
- yield test_delimited_read("012345678901:", "0123456789");
- yield test_delimited_read("0123/0123", "0123/0123");
+ add_task(async function () {
+ await test_delimited_read("0123:", "0123:");
+ await test_delimited_read("0123:4567:", "0123:");
+ await test_delimited_read("012345678901:", "0123456789");
+ await test_delimited_read("0123/0123", "0123/0123");
});
run_next_test();
}
/** * Tests ***/
function test_delimited_read(input, expected) {
--- a/devtools/shared/transport/tests/unit/test_no_bulk.js
+++ b/devtools/shared/transport/tests/unit/test_no_bulk.js
@@ -3,34 +3,34 @@
"use strict";
function run_test() {
DebuggerServer.registerModule("xpcshell-test/testactors-no-bulk");
// Allow incoming connections.
DebuggerServer.init();
- add_task(function* () {
- yield test_bulk_send_error(socket_transport);
- yield test_bulk_send_error(local_transport);
+ add_task(async function () {
+ await test_bulk_send_error(socket_transport);
+ await test_bulk_send_error(local_transport);
DebuggerServer.destroy();
});
run_next_test();
}
/** * Tests ***/
-var test_bulk_send_error = Task.async(function* (transportFactory) {
- let transport = yield transportFactory();
+var test_bulk_send_error = async function (transportFactory) {
+ let transport = await transportFactory();
let client = new DebuggerClient(transport);
return client.connect().then(([app, traits]) => {
Assert.ok(!traits.bulk);
try {
client.startBulkRequest();
do_throw(new Error("Can't use bulk since server doesn't support it"));
} catch (e) {
Assert.ok(true);
}
});
-});
+};
--- a/devtools/shared/transport/tests/unit/test_queue.js
+++ b/devtools/shared/transport/tests/unit/test_queue.js
@@ -8,39 +8,39 @@
* packets are scheduled simultaneously.
*/
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm", {});
function run_test() {
initTestDebuggerServer();
- add_task(function* () {
- yield test_transport(socket_transport);
- yield test_transport(local_transport);
+ add_task(async function () {
+ await test_transport(socket_transport);
+ await test_transport(local_transport);
DebuggerServer.destroy();
});
run_next_test();
}
/** * Tests ***/
-var test_transport = Task.async(function* (transportFactory) {
+var test_transport = async function (transportFactory) {
let clientDeferred = defer();
let serverDeferred = defer();
// Ensure test files are not present from a failed run
cleanup_files();
let reallyLong = really_long();
writeTestTempFile("bulk-input", reallyLong);
Assert.equal(Object.keys(DebuggerServer._connections).length, 0);
- let transport = yield transportFactory();
+ let transport = await transportFactory();
// Sending from client to server
function write_data({copyFrom}) {
NetUtil.asyncFetch({
uri: NetUtil.newURI(getTestTempFile("bulk-input")),
loadUsingSystemPrincipal: true
}, function (input, status) {
copyFrom(input).then(() => {
@@ -130,17 +130,17 @@ var test_transport = Task.async(function
onClosed: function () {
do_throw("Transport closed before we expected");
}
};
transport.ready();
return promise.all([clientDeferred.promise, serverDeferred.promise]);
-});
+};
/** * Test Utils ***/
function verify() {
let reallyLong = really_long();
let inputFile = getTestTempFile("bulk-input");
let outputFile = getTestTempFile("bulk-output");
--- a/devtools/shared/transport/tests/unit/test_transport_bulk.js
+++ b/devtools/shared/transport/tests/unit/test_transport_bulk.js
@@ -3,44 +3,44 @@
"use strict";
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm", {});
function run_test() {
initTestDebuggerServer();
- add_task(function* () {
- yield test_bulk_transfer_transport(socket_transport);
- yield test_bulk_transfer_transport(local_transport);
+ add_task(async function () {
+ await test_bulk_transfer_transport(socket_transport);
+ await test_bulk_transfer_transport(local_transport);
DebuggerServer.destroy();
});
run_next_test();
}
/** * Tests ***/
/**
* This tests a one-way bulk transfer at the transport layer.
*/
-var test_bulk_transfer_transport = Task.async(function* (transportFactory) {
+var test_bulk_transfer_transport = async function (transportFactory) {
info("Starting bulk transfer test at " + new Date().toTimeString());
let clientDeferred = defer();
let serverDeferred = defer();
// Ensure test files are not present from a failed run
cleanup_files();
let reallyLong = really_long();
writeTestTempFile("bulk-input", reallyLong);
Assert.equal(Object.keys(DebuggerServer._connections).length, 0);
- let transport = yield transportFactory();
+ let transport = await transportFactory();
// Sending from client to server
function write_data({copyFrom}) {
NetUtil.asyncFetch({
uri: NetUtil.newURI(getTestTempFile("bulk-input")),
loadUsingSystemPrincipal: true
}, function (input, status) {
copyFrom(input).then(() => {
@@ -101,17 +101,17 @@ var test_bulk_transfer_transport = Task.
onClosed: function () {
do_throw("Transport closed before we expected");
}
};
transport.ready();
return promise.all([clientDeferred.promise, serverDeferred.promise]);
-});
+};
/** * Test Utils ***/
function verify() {
let reallyLong = really_long();
let inputFile = getTestTempFile("bulk-input");
let outputFile = getTestTempFile("bulk-output");
--- a/devtools/shared/transport/tests/unit/test_transport_events.js
+++ b/devtools/shared/transport/tests/unit/test_transport_events.js
@@ -1,75 +1,75 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
function run_test() {
initTestDebuggerServer();
- add_task(function* () {
- yield test_transport_events("socket", socket_transport);
- yield test_transport_events("local", local_transport);
+ add_task(async function () {
+ await test_transport_events("socket", socket_transport);
+ await test_transport_events("local", local_transport);
DebuggerServer.destroy();
});
run_next_test();
}
-function* test_transport_events(name, transportFactory) {
+async function test_transport_events(name, transportFactory) {
info(`Started testing of transport: ${name}`);
Assert.equal(Object.keys(DebuggerServer._connections).length, 0);
- let transport = yield transportFactory();
+ let transport = await transportFactory();
// Transport expects the hooks to be not null
transport.hooks = {
onPacket: () => {},
onClosed: () => {},
};
let rootReceived = transport.once("packet", (event, packet) => {
info(`Packet event: ${event} ${JSON.stringify(packet)}`);
Assert.equal(event, "packet");
Assert.equal(packet.from, "root");
});
transport.ready();
- yield rootReceived;
+ await rootReceived;
let echoSent = transport.once("send", (event, packet) => {
info(`Send event: ${event} ${JSON.stringify(packet)}`);
Assert.equal(event, "send");
Assert.equal(packet.to, "root");
Assert.equal(packet.type, "echo");
});
let echoReceived = transport.once("packet", (event, packet) => {
info(`Packet event: ${event} ${JSON.stringify(packet)}`);
Assert.equal(event, "packet");
Assert.equal(packet.from, "root");
Assert.equal(packet.type, "echo");
});
transport.send({ to: "root", type: "echo" });
- yield echoSent;
- yield echoReceived;
+ await echoSent;
+ await echoReceived;
let clientClosed = transport.once("close", (event) => {
info(`Close event: ${event}`);
Assert.equal(event, "close");
});
let serverClosed = DebuggerServer.once("connectionchange", (event, type) => {
info(`Server closed`);
Assert.equal(event, "connectionchange");
Assert.equal(type, "closed");
});
transport.close();
- yield clientClosed;
- yield serverClosed;
+ await clientClosed;
+ await serverClosed;
info(`Finished testing of transport: ${name}`);
}
--- a/devtools/shared/webconsole/test/common.js
+++ b/devtools/shared/webconsole/test/common.js
@@ -8,17 +8,16 @@
/* exported ObjectClient, attachConsole, attachConsoleToTab, attachConsoleToWorker,
closeDebugger, checkConsoleAPICalls, checkRawHeaders, runTests, nextTest, Ci, Cc,
withActiveServiceWorker, Services */
// This gives logging to stdout for tests
const {console} = ChromeUtils.import("resource://gre/modules/Console.jsm", {});
const {require} = ChromeUtils.import("resource://devtools/shared/Loader.jsm", {});
-const {Task} = require("devtools/shared/task");
const {DebuggerServer} = require("devtools/server/main");
const {DebuggerClient} = require("devtools/shared/client/debugger-client");
const ObjectClient = require("devtools/shared/client/object-client");
const Services = require("Services");
function initCommon() {
// Services.prefs.setBoolPref("devtools.debugger.log", true);
}
@@ -47,17 +46,17 @@ function attachConsole(listeners, callba
}
function attachConsoleToTab(listeners, callback) {
_attachConsole(listeners, callback, true);
}
function attachConsoleToWorker(listeners, callback) {
_attachConsole(listeners, callback, true, true);
}
-var _attachConsole = Task.async(function* (
+var _attachConsole = async function (
listeners, callback, attachToTab, attachToWorker
) {
function _onAttachConsole(state, response, webConsoleClient) {
if (response.error) {
console.error("attachConsole failed: " + response.error + " " +
response.message);
}
@@ -67,74 +66,74 @@ var _attachConsole = Task.async(function
}
function waitForMessage(target) {
return new Promise(resolve => {
target.addEventListener("message", resolve, { once: true });
});
}
- let [state, response] = yield connectToDebugger();
+ let [state, response] = await connectToDebugger();
if (response.error) {
console.error("client.connect() failed: " + response.error + " " +
response.message);
callback(state, response);
return;
}
if (!attachToTab) {
- response = yield state.dbgClient.getProcess();
- yield state.dbgClient.attachTab(response.form.actor);
+ response = await state.dbgClient.getProcess();
+ await state.dbgClient.attachTab(response.form.actor);
let consoleActor = response.form.consoleActor;
state.actor = consoleActor;
state.dbgClient.attachConsole(consoleActor, listeners,
_onAttachConsole.bind(null, state));
return;
}
- response = yield state.dbgClient.listTabs();
+ response = await state.dbgClient.listTabs();
if (response.error) {
console.error("listTabs failed: " + response.error + " " +
response.message);
callback(state, response);
return;
}
let tab = response.tabs[response.selected];
- let [, tabClient] = yield state.dbgClient.attachTab(tab.actor);
+ let [, tabClient] = await state.dbgClient.attachTab(tab.actor);
if (attachToWorker) {
let workerName = "console-test-worker.js#" + new Date().getTime();
let worker = new Worker(workerName);
// Keep a strong reference to the Worker to avoid it being
// GCd during the test (bug 1237492).
// eslint-disable-next-line camelcase
state._worker_ref = worker;
- yield waitForMessage(worker);
+ await waitForMessage(worker);
- let { workers } = yield tabClient.listWorkers();
+ let { workers } = await tabClient.listWorkers();
let workerActor = workers.filter(w => w.url == workerName)[0].actor;
if (!workerActor) {
console.error("listWorkers failed. Unable to find the " +
"worker actor\n");
return;
}
- let [workerResponse, workerClient] = yield tabClient.attachWorker(workerActor);
+ let [workerResponse, workerClient] = await tabClient.attachWorker(workerActor);
if (!workerClient || workerResponse.error) {
console.error("attachWorker failed. No worker client or " +
" error: " + workerResponse.error);
return;
}
- yield workerClient.attachThread({});
+ await workerClient.attachThread({});
state.actor = workerClient.consoleActor;
state.dbgClient.attachConsole(workerClient.consoleActor, listeners,
_onAttachConsole.bind(null, state));
} else {
state.actor = tab.consoleActor;
state.dbgClient.attachConsole(tab.consoleActor, listeners,
_onAttachConsole.bind(null, state));
}
-});
+};
function closeDebugger(state, callback) {
state.dbgClient.close().then(callback);
state.dbgClient = null;
state.client = null;
}
function checkConsoleAPICalls(consoleCalls, expectedConsoleCalls) {
--- a/devtools/shared/webconsole/test/test_commands_other.html
+++ b/devtools/shared/webconsole/test/test_commands_other.html
@@ -30,64 +30,64 @@ function startTest() {
attachConsoleToTab([], state => {
gState = state;
runTests(tests, testEnd);
});
}
tests = [
- Task.async(function* keys() {
- let response = yield evaluateJS("keys({foo: 'bar'})");
+ async function keys() {
+ let response = await evaluateJS("keys({foo: 'bar'})");
checkObject(response, {
from: gState.actor,
result: {
class: "Array",
preview: {
items: ["foo"]
}
}
});
nextTest();
- }),
- Task.async(function* values() {
- let response = yield evaluateJS("values({foo: 'bar'})");
+ },
+ async function values() {
+ let response = await evaluateJS("values({foo: 'bar'})");
checkObject(response, {
from: gState.actor,
result: {
class: "Array",
preview: {
items: ["bar"]
}
}
});
nextTest();
- }),
+ },
];
function testEnd() {
gWin.close();
gWin = null;
closeDebugger(gState, function() {
gState = null;
SimpleTest.finish();
});
}
-let load = Task.async(function*() {
+let load = async function () {
removeEventListener("load", load);
- yield new Promise(resolve => {
+ await new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": [
["security.data_uri.unique_opaque_origin", false],
]}, resolve);
});
// Open a content window to test XRay functionality on built in functions.
gWin = window.open("data:text/html,");
info ("Waiting for content window to load");
gWin.onload = startTest;
-});
+};
addEventListener("load", load);
</script>
</body>
</html>
--- a/devtools/shared/webconsole/test/test_commands_registration.html
+++ b/devtools/shared/webconsole/test/test_commands_registration.html
@@ -19,18 +19,18 @@ let gState;
let tests;
let {WebConsoleCommands} = require("devtools/server/actors/webconsole/utils");
function evaluateJS(input) {
return new Promise((resolve) => gState.client.evaluateJS(input, resolve));
}
-function* evaluateJSAndCheckResult(input, result) {
- let response = yield evaluateJS(input);
+async function evaluateJSAndCheckResult(input, result) {
+ let response = await evaluateJS(input);
checkObject(response, {result});
}
function startTest()
{
removeEventListener("load", startTest);
attachConsoleToTab(["PageError"], onAttach);
@@ -39,143 +39,143 @@ function startTest()
function onAttach(aState, aResponse)
{
gState = aState;
runTests(tests, testEnd);
}
tests = [
- Task.async(function* registerNewCommand() {
+ async function registerNewCommand() {
let win;
WebConsoleCommands.register("setFoo", (owner, value) => {
owner.window.foo = value;
return "ok";
});
ok(WebConsoleCommands.hasCommand("setFoo"),
"The command should be registered");
let command = "setFoo('bar')";
- let response = yield evaluateJS(command);
+ let response = await evaluateJS(command);
checkObject(response, {
from: gState.actor,
input: command,
result: "ok"
});
is(top.foo, "bar", "top.foo should equal to 'bar'");
nextTest();
- }),
+ },
- Task.async(function* wrapCommand() {
+ async function wrapCommand() {
let origKeys = WebConsoleCommands.getCommand("keys");
let newKeys = (...args) => {
let [owner, arg0] = args;
if (arg0 === ">o_/") {
return "bang!";
}
else {
return origKeys(...args);
}
};
WebConsoleCommands.register("keys", newKeys);
is(WebConsoleCommands.getCommand("keys"), newKeys,
"the keys() command should have been replaced");
- let response = yield evaluateJS("keys('>o_/')");
+ let response = await evaluateJS("keys('>o_/')");
checkObject(response, {
from: gState.actor,
result: "bang!"
});
- response = yield evaluateJS("keys({foo: 'bar'})");
+ response = await evaluateJS("keys({foo: 'bar'})");
checkObject(response, {
from: gState.actor,
result: {
class: "Array",
preview: {
items: ["foo"]
}
}
});
WebConsoleCommands.register("keys", origKeys);
is(WebConsoleCommands.getCommand("keys"), origKeys,
"the keys() command should be restored");
nextTest();
- }),
+ },
- Task.async(function* unregisterCommand() {
+ async function unregisterCommand() {
WebConsoleCommands.unregister("setFoo");
- let response = yield evaluateJS("setFoo");
+ let response = await evaluateJS("setFoo");
checkObject(response, {
from: gState.actor,
input: "setFoo",
result: {
type: "undefined"
},
exceptionMessage: /setFoo is not defined/
});
nextTest();
- }),
+ },
- Task.async(function* registerAccessor() {
+ async function registerAccessor() {
WebConsoleCommands.register("$foo", {
get(owner) {
let foo = owner.window.frames[0].window.document.getElementById("quack");
return owner.makeDebuggeeValue(foo);
}
});
let command = "$foo.textContent = '>o_/'";
- let response = yield evaluateJS(command);
+ let response = await evaluateJS(command);
checkObject(response, {
from: gState.actor,
input: command,
result: ">o_/"
});
is(document.getElementById("quack").textContent, ">o_/",
"#foo textContent should equal to \">o_/\"");
WebConsoleCommands.unregister("$foo");
ok(!WebConsoleCommands.hasCommand("$foo"), "$foo should be unregistered");
nextTest();
- }),
+ },
- Task.async(function* unregisterAfterOverridingTwice() {
+ async function unregisterAfterOverridingTwice() {
WebConsoleCommands.register("keys", (owner, obj) => "command 1");
info("checking the value of the first override");
- yield evaluateJSAndCheckResult("keys('foo');", "command 1");
+ await evaluateJSAndCheckResult("keys('foo');", "command 1");
let orig = WebConsoleCommands.getCommand("keys");
WebConsoleCommands.register("keys", (owner, obj) => {
if (obj === "quack")
return "bang!";
return orig(owner, obj);
});
info("checking the values after the second override");
- yield evaluateJSAndCheckResult("keys({});", "command 1");
- yield evaluateJSAndCheckResult("keys('quack');", "bang!");
+ await evaluateJSAndCheckResult("keys({});", "command 1");
+ await evaluateJSAndCheckResult("keys('quack');", "bang!");
WebConsoleCommands.unregister("keys");
info("checking the value after unregistration (should restore " +
"the original command)");
- yield evaluateJSAndCheckResult("keys({});", {
+ await evaluateJSAndCheckResult("keys({});", {
class: "Array",
preview: {items: []}
});
nextTest();
- })
+ }
];
function testEnd()
{
// If this is the first run, reload the page and do it again.
// Otherwise, end the test.
delete top.foo;
closeDebugger(gState, function() {
--- a/devtools/shared/webconsole/test/test_console_serviceworker.html
+++ b/devtools/shared/webconsole/test/test_console_serviceworker.html
@@ -95,105 +95,105 @@ let expectedConsoleCalls = [
{
level: "log",
filename: /helper_serviceworker/,
arguments: ['fetch event: ' + SCOPE_FRAME_URL2],
},
];
let consoleCalls = [];
-let startTest = Task.async(function*() {
+let startTest = async function () {
removeEventListener("load", startTest);
- yield new Promise(resolve => {
+ await new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": [
["dom.serviceWorkers.enabled", true],
["devtools.webconsole.filter.serviceworkers", true]
]}, resolve);
});
attachConsoleToTab(["ConsoleAPI"], onAttach);
-});
+};
addEventListener("load", startTest);
-let onAttach = Task.async(function*(state, response) {
+let onAttach = async function (state, response) {
onConsoleAPICall = onConsoleAPICall.bind(null, state);
state.dbgClient.addListener("consoleAPICall", onConsoleAPICall);
let currentFrame;
try {
// First, we need a frame from which to register our script. This
// will not trigger any console calls.
info("Loading a non-scope frame from which to register a service worker.");
- currentFrame = yield withFrame(NONSCOPE_FRAME_URL);
+ currentFrame = await withFrame(NONSCOPE_FRAME_URL);
// Now register the service worker and wait for it to become
// activate. This should trigger 3 console calls; 1 for script
// evaluation, 1 for the install event, and 1 for the activate
// event. These console calls are received because we called
// register(), not because we are in scope for the worker.
info("Registering the service worker");
- yield withActiveServiceWorker(currentFrame.contentWindow,
+ await withActiveServiceWorker(currentFrame.contentWindow,
SERVICE_WORKER_URL, SCOPE);
ok(!currentFrame.contentWindow.navigator.serviceWorker.controller,
'current frame should not be controlled');
// Now that the service worker is activate, lets navigate our frame.
// This will trigger 1 more console call for the fetch event.
info("Service worker registered. Navigating frame.");
- yield navigateFrame(currentFrame, SCOPE_FRAME_URL);
+ await navigateFrame(currentFrame, SCOPE_FRAME_URL);
ok(currentFrame.contentWindow.navigator.serviceWorker.controller,
'navigated frame should be controlled');
// We now have a controlled frame. Lets perform a non-navigation fetch.
// This should produce another console call for the fetch event.
info("Frame navigated. Calling fetch().");
- yield currentFrame.contentWindow.fetch(SCOPE_FRAME_URL2);
+ await currentFrame.contentWindow.fetch(SCOPE_FRAME_URL2);
// Now force refresh our controlled frame. This will cause the frame
// to bypass the service worker and become an uncontrolled frame. It
// also happens to make the frame display a 404 message because the URL
// does not resolve to a real resource. This is ok, as we really only
// care about the frame being non-controlled, but still having a location
// that matches our service worker scope so we can provide its not
// incorrectly getting console calls.
info("Completed fetch(). Force refreshing to get uncontrolled frame.");
- yield forceReloadFrame(currentFrame);
+ await forceReloadFrame(currentFrame);
ok(!currentFrame.contentWindow.navigator.serviceWorker.controller,
'current frame should not be controlled after force refresh');
is(currentFrame.contentWindow.location.toString(), SCOPE_FRAME_URL,
'current frame should still have in-scope location URL even though it got 404');
// Now postMessage() the service worker to trigger its message event
// handler. This will generate 1 or 2 to console.log() statements
// depending on if the worker thread needs to spin up again. In either
// case, though, we should not get any console calls because we don't
// have a controlled or registering document.
info("Completed force refresh. Messaging service worker.");
- yield messageServiceWorker(currentFrame.contentWindow, SCOPE, MESSAGE);
+ await messageServiceWorker(currentFrame.contentWindow, SCOPE, MESSAGE);
info("Done messaging service worker. Unregistering service worker.");
- yield unregisterServiceWorker(currentFrame.contentWindow);
+ await unregisterServiceWorker(currentFrame.contentWindow);
info('Service worker unregistered. Checking console calls.');
state.dbgClient.removeListener("consoleAPICall", onConsoleAPICall);
checkConsoleAPICalls(consoleCalls, expectedConsoleCalls);
} catch(error) {
ok(false, 'unexpected error: ' + error);
} finally {
if (currentFrame) {
currentFrame.remove();
currentFrame = null;
}
consoleCalls = [];
closeDebugger(state, function() {
SimpleTest.finish();
});
}
-});
+};
function onConsoleAPICall(state, type, packet) {
info("received message level: " + packet.message.level);
is(packet.from, state.actor, "console API call actor");
consoleCalls.push(packet.message);
}
</script>
</body>
--- a/devtools/shared/webconsole/test/test_console_serviceworker_cached.html
+++ b/devtools/shared/webconsole/test/test_console_serviceworker_cached.html
@@ -39,60 +39,60 @@ let firstTabExpectedCalls = [
let secondTabExpectedCalls = [
{
level: "log",
filename: /helper_serviceworker/,
arguments: ['fetch event: ' + FRAME_URL],
}
];
-let startTest = Task.async(function*() {
+let startTest = async function () {
removeEventListener("load", startTest);
- yield new Promise(resolve => {
+ await new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": [
["dom.serviceWorkers.enabled", true],
["devtools.webconsole.filter.serviceworkers", true]
]}, resolve);
});
info("Adding a tab and attaching a service worker");
- let tab1 = yield addTab(FRAME_URL);
- let swr = yield withActiveServiceWorker(tab1.linkedBrowser.contentWindow,
+ let tab1 = await addTab(FRAME_URL);
+ let swr = await withActiveServiceWorker(tab1.linkedBrowser.contentWindow,
SERVICE_WORKER_URL);
- yield new Promise(resolve => {
+ await new Promise(resolve => {
info("Attaching console to tab 1");
attachConsoleToTab(["ConsoleAPI"], function(state) {
state.client.getCachedMessages(["ConsoleAPI"], function(calls) {
checkConsoleAPICalls(calls.messages, firstTabExpectedCalls);
closeDebugger(state, resolve);
});
});
});
// Because this tab is being added after the original messages happened,
// they shouldn't show up in a call to getCachedMessages.
// However, there is a fetch event which is logged due to loading the tab.
info("Adding a new tab at the same URL");
- let tab2 = yield addTab(FRAME_URL);
- yield new Promise(resolve => {
+ let tab2 = await addTab(FRAME_URL);
+ await new Promise(resolve => {
info("Attaching console to tab 2");
attachConsoleToTab(["ConsoleAPI"], function(state) {
state.client.getCachedMessages(["ConsoleAPI"], function(calls) {
checkConsoleAPICalls(calls.messages, secondTabExpectedCalls);
closeDebugger(state, resolve);
});
});
});
- yield swr.unregister();
+ await swr.unregister();
SimpleTest.finish();
-});
+};
addEventListener("load", startTest);
// This test needs to add tabs that are controlled by a service worker
// so use some special powers to dig around and find gBrowser
let {gBrowser} = SpecialPowers._getTopChromeWindow(SpecialPowers.window.get());
SimpleTest.registerCleanupFunction(() => {
while (gBrowser.tabs.length > 1) {
--- a/devtools/shared/webconsole/test/test_console_worker.html
+++ b/devtools/shared/webconsole/test/test_console_worker.html
@@ -24,59 +24,59 @@ let expectedCachedConsoleCalls = [
let expectedConsoleAPICalls = [
{
level: "log",
arguments: ['Log was requested from worker'],
},
];
-window.onload = Task.async(function*() {
- let {state,response} = yield new Promise(resolve => {
+window.onload = async function () {
+ let {state,response} = await new Promise(resolve => {
attachConsoleToWorker(["ConsoleAPI"], (state, response) => {
resolve({state,response})
});
});
- yield testCachedMessages(state);
- yield testConsoleAPI(state);
+ await testCachedMessages(state);
+ await testConsoleAPI(state);
closeDebugger(state, function() {
SimpleTest.finish();
});
-});
+};
-let testCachedMessages = Task.async(function*(state) {
+let testCachedMessages = async function (state) {
info("testCachedMessages entered");
return new Promise(resolve => {
let onCachedConsoleAPI = (response) => {
let consoleCalls = response.messages;
info('Received cached response. Checking console calls.');
checkConsoleAPICalls(consoleCalls, expectedCachedConsoleCalls);
resolve();
};
state.client.getCachedMessages(["ConsoleAPI"], onCachedConsoleAPI);
})
-});
+};
-let testConsoleAPI = Task.async(function*(state) {
+let testConsoleAPI = async function (state) {
info("testConsoleAPI entered");
return new Promise(resolve => {
let onConsoleAPICall = (type, packet) => {
info("received message level: " + packet.message.level);
is(packet.from, state.actor, "console API call actor");
checkConsoleAPICalls([packet.message], expectedConsoleAPICalls);
state.dbgClient.removeListener("consoleAPICall", onConsoleAPICall);
resolve();
}
info("testConsoleAPI: adding listener for consoleAPICall");
state.dbgClient.addListener("consoleAPICall", onConsoleAPICall);
state.client.evaluateJS("console.log('Log was requested from worker')",
() => { });
});
-});
+};
</script>
</body>
</html>
--- a/devtools/shared/webconsole/test/test_jsterm.html
+++ b/devtools/shared/webconsole/test/test_jsterm.html
@@ -60,174 +60,172 @@ function onAttach(aState, aResponse)
top.largeObject2['a' + i] = i;
}
gState = aState;
let tests = [doSimpleEval, doWindowEval, doEvalWithException,
doEvalWithHelper, doEvalString, doEvalLongString,
doEvalWithBinding, doEvalWithBindingFrame,
- forceLexicalInit].map(t => {
- return Task.async(t);
- });
+ forceLexicalInit];
runTests(tests, testEnd);
}
-function* doSimpleEval() {
+async function doSimpleEval() {
info("test eval '2+2'");
- let response = yield evaluateJS("2+2");
+ let response = await evaluateJS("2+2");
checkObject(response, {
from: gState.actor,
input: "2+2",
result: 4,
});
ok(!response.exception, "no eval exception");
ok(!response.helperResult, "no helper result");
nextTest();
}
-function* doWindowEval() {
+async function doWindowEval() {
info("test eval 'document'");
- let response = yield evaluateJS("document");
+ let response = await evaluateJS("document");
checkObject(response, {
from: gState.actor,
input: "document",
result: {
type: "object",
class: "XULDocument",
actor: /[a-z]/,
},
});
ok(!response.exception, "no eval exception");
ok(!response.helperResult, "no helper result");
nextTest();
}
-function* doEvalWithException() {
+async function doEvalWithException() {
info("test eval with exception");
- let response = yield evaluateJS("window.doTheImpossible()");
+ let response = await evaluateJS("window.doTheImpossible()");
checkObject(response, {
from: gState.actor,
input: "window.doTheImpossible()",
result: {
type: "undefined",
},
exceptionMessage: /doTheImpossible/,
});
ok(response.exception, "js eval exception");
ok(!response.helperResult, "no helper result");
nextTest();
}
-function* doEvalWithHelper() {
+async function doEvalWithHelper() {
info("test eval with helper");
- let response = yield evaluateJS("clear()");
+ let response = await evaluateJS("clear()");
checkObject(response, {
from: gState.actor,
input: "clear()",
result: {
type: "undefined",
},
helperResult: { type: "clearOutput" },
});
ok(!response.exception, "no eval exception");
nextTest();
}
-function* doEvalString() {
- let response = yield evaluateJS("window.foobarObject.strfoo");
+async function doEvalString() {
+ let response = await evaluateJS("window.foobarObject.strfoo");
checkObject(response, {
from: gState.actor,
input: "window.foobarObject.strfoo",
result: "foobarz",
});
nextTest();
}
-function* doEvalLongString() {
- let response = yield evaluateJS("window.foobarObject.omgstr");
+async function doEvalLongString() {
+ let response = await evaluateJS("window.foobarObject.omgstr");
let str = top.foobarObject.omgstr;
let initial = str.substring(0, DebuggerServer.LONG_STRING_INITIAL_LENGTH);
checkObject(response, {
from: gState.actor,
input: "window.foobarObject.omgstr",
result: {
type: "longString",
initial: initial,
length: str.length,
},
});
nextTest();
}
-function* doEvalWithBinding() {
- let response = yield evaluateJS("document;");
+async function doEvalWithBinding() {
+ let response = await evaluateJS("document;");
let documentActor = response.result.actor;
info("running a command with _self as document using bindObjectActor");
- let bindObjectSame = yield evaluateJS("_self === document", {
+ let bindObjectSame = await evaluateJS("_self === document", {
bindObjectActor: documentActor
});
checkObject(bindObjectSame, {
result: true
});
info("running a command with _self as document using selectedObjectActor");
- let selectedObjectSame = yield evaluateJS("_self === document", {
+ let selectedObjectSame = await evaluateJS("_self === document", {
selectedObjectActor: documentActor
});
checkObject(selectedObjectSame, {
result: true
});
nextTest();
}
-function* doEvalWithBindingFrame() {
+async function doEvalWithBindingFrame() {
let frameWin = top.document.querySelector("iframe").contentWindow;
frameWin.fooFrame = { bar: 1 };
- let response = yield evaluateJS(
+ let response = await evaluateJS(
"document.querySelector('iframe').contentWindow.fooFrame"
);
let iframeObjectActor = response.result.actor;
ok(iframeObjectActor, "There is an actor associated with the response");
- let bindObjectGlobal = yield evaluateJS("this.temp0 = _self;", {
+ let bindObjectGlobal = await evaluateJS("this.temp0 = _self;", {
bindObjectActor: iframeObjectActor
});
ok(!top.temp0,
"Global doesn't match the top global with bindObjectActor");
ok(frameWin.temp0 && frameWin.temp0.bar === 1,
"Global matches the object's global with bindObjectActor");
- let selectedObjectGlobal = yield evaluateJS("this.temp1 = _self;", {
+ let selectedObjectGlobal = await evaluateJS("this.temp1 = _self;", {
selectedObjectActor: iframeObjectActor
});
ok(top.temp1 && top.temp1.bar === 1,
"Global matches the top global with bindObjectActor");
ok(!frameWin.temp1,
"Global doesn't match the object's global with bindObjectActor");
nextTest()
}
-function* forceLexicalInit() {
+async function forceLexicalInit() {
info("test that failed let/const bindings are initialized to undefined");
const testData = [
{
stmt: "let foopie = wubbalubadubdub",
vars: ["foopie"]
},
{
@@ -260,25 +258,25 @@ function* forceLexicalInit() {
},
{
stmt: "let {c3pdoh=101} = null",
vars: ["c3pdoh"]
}
];
for (let data of testData) {
- let response = yield evaluateJS(data.stmt);
+ let response = await evaluateJS(data.stmt);
checkObject(response, {
from: gState.actor,
input: data.stmt,
result: undefined,
});
ok(response.exception, "expected exception");
for (let varName of data.vars) {
- let response2 = yield evaluateJS(varName);
+ let response2 = await evaluateJS(varName);
checkObject(response2, {
from: gState.actor,
input: varName,
result: undefined,
});
ok(!response2.exception, "unexpected exception");
}
}
--- a/devtools/shared/webconsole/test/test_jsterm_autocomplete.html
+++ b/devtools/shared/webconsole/test/test_jsterm_autocomplete.html
@@ -35,17 +35,17 @@ let runningInTab = true;
function startTest({worker}) {
if (worker) {
attachConsoleToWorker(["PageError"], onAttach);
} else {
attachConsoleToTab(["PageError"], onAttach);
}
};
-let onAttach = Task.async(function*(aState, response) {
+let onAttach = async function (aState, response) {
gState = aState;
let longStrLength = DebuggerServer.LONG_STRING_LENGTH;
// Set up the global variables needed to test autocompletion
// in the target.
let script = `
// This is for workers so autocomplete acts the same
@@ -68,93 +68,91 @@ let onAttach = Task.async(function*(aSta
}
window.largeObject2 = Object.create(null);
for (let i = 0; i < ${MAX_AUTOCOMPLETIONS * 2}; i++) {
window.largeObject2['a' + i] = i;
}
`;
- yield evaluateJS(script);
+ await evaluateJS(script);
let tests = [doAutocomplete1, doAutocomplete2, doAutocomplete3,
doAutocomplete4, doAutocompleteLarge1,
- doAutocompleteLarge2].map(t => {
- return Task.async(t);
- });
+ doAutocompleteLarge2];
runTests(tests, testEnd);
-});
+};
-function* doAutocomplete1() {
+async function doAutocomplete1() {
info("test autocomplete for 'window.foo'");
- let response = yield autocompletePromise("window.foo", 10);
+ let response = await autocompletePromise("window.foo", 10);
let matches = response.matches;
is(response.matchProp, "foo", "matchProp");
is(matches.length, 1, "matches.length");
is(matches[0], "foobarObject", "matches[0]");
nextTest();
}
-function* doAutocomplete2() {
+async function doAutocomplete2() {
info("test autocomplete for 'window.foobarObject.'");
- let response = yield autocompletePromise("window.foobarObject.", 20);
+ let response = await autocompletePromise("window.foobarObject.", 20);
let matches = response.matches;
ok(!response.matchProp, "matchProp");
is(matches.length, 7, "matches.length");
checkObject(matches,
["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]);
nextTest();
}
-function* doAutocomplete3() {
+async function doAutocomplete3() {
// Check that completion suggestions are offered inside the string.
info("test autocomplete for 'dump(window.foobarObject.)'");
- let response = yield autocompletePromise("dump(window.foobarObject.)", 25);
+ let response = await autocompletePromise("dump(window.foobarObject.)", 25);
let matches = response.matches;
ok(!response.matchProp, "matchProp");
is(matches.length, 7, "matches.length");
checkObject(matches,
["foo", "foobar", "foobaz", "omg", "omgfoo", "omgstr", "strfoo"]);
nextTest();
}
-function* doAutocomplete4() {
+async function doAutocomplete4() {
// Check that completion requests can have no suggestions.
info("test autocomplete for 'dump(window.foobarObject.)'");
- let response = yield autocompletePromise("dump(window.foobarObject.)", 26);
+ let response = await autocompletePromise("dump(window.foobarObject.)", 26);
ok(!response.matchProp, "matchProp");
is(response.matches.length, 0, "matches.length");
nextTest();
}
-function* doAutocompleteLarge1() {
+async function doAutocompleteLarge1() {
// Check that completion requests with too large objects will
// have no suggestions.
info("test autocomplete for 'window.largeObject1.'");
- let response = yield autocompletePromise("window.largeObject1.", 20);
+ let response = await autocompletePromise("window.largeObject1.", 20);
ok(!response.matchProp, "matchProp");
info (response.matches.join("|"));
is(response.matches.length, 0, "Bailed out with too many properties");
nextTest();
}
-function* doAutocompleteLarge2() {
+async function doAutocompleteLarge2() {
// Check that completion requests with pretty large objects will
// have MAX_AUTOCOMPLETIONS suggestions
info("test autocomplete for 'window.largeObject2.'");
- let response = yield autocompletePromise("window.largeObject2.", 20);
+ let response = await autocompletePromise("window.largeObject2.", 20);
ok(!response.matchProp, "matchProp");
is(response.matches.length, MAX_AUTOCOMPLETIONS, "matches.length is MAX_AUTOCOMPLETIONS");
nextTest();
}
function testEnd()
{
--- a/devtools/shared/webconsole/test/test_jsterm_last_result.html
+++ b/devtools/shared/webconsole/test/test_jsterm_last_result.html
@@ -33,83 +33,83 @@ function startTest()
removeEventListener("load", startTest);
attachConsoleToTab([], state => {
gState = state;
let tests = [checkUndefinedResult,checkAdditionResult,checkObjectResult];
runTests(tests, testEnd);
});
}
-let checkUndefinedResult = Task.async(function*() {
+let checkUndefinedResult = async function () {
info ("$_ returns undefined if nothing has evaluated yet");
- let response = yield evaluateJS("$_");
+ let response = await evaluateJS("$_");
basicResultCheck(response, "$_", undefined);
nextTest();
-});
+};
-let checkAdditionResult = Task.async(function*() {
+let checkAdditionResult = async function () {
info ("$_ returns last value and performs basic arithmetic");
- let response = yield evaluateJS("2+2");
+ let response = await evaluateJS("2+2");
basicResultCheck(response, "2+2", 4);
- response = yield evaluateJS("$_");
+ response = await evaluateJS("$_");
basicResultCheck(response, "$_", 4);
- response = yield evaluateJS("$_ + 2");
+ response = await evaluateJS("$_ + 2");
basicResultCheck(response, "$_ + 2", 6);
- response = yield evaluateJS("$_ + 4");
+ response = await evaluateJS("$_ + 4");
basicResultCheck(response, "$_ + 4", 10);
nextTest();
-});
+};
-let checkObjectResult = Task.async(function*() {
+let checkObjectResult = async function () {
info ("$_ has correct references to objects");
- let response = yield evaluateJS("var foo = {bar:1}; foo;");
+ let response = await evaluateJS("var foo = {bar:1}; foo;");
basicResultCheck(response, "var foo = {bar:1}; foo;", {
type: "object",
class: "Object",
actor: /[a-z]/,
});
checkObject(response.result.preview.ownProperties, {
bar: {
value: 1
}
});
- response = yield evaluateJS("$_");
+ response = await evaluateJS("$_");
basicResultCheck(response, "$_", {
type: "object",
class: "Object",
actor: /[a-z]/,
});
checkObject(response.result.preview.ownProperties, {
bar: {
value: 1
}
});
top.foo.bar = 2;
- response = yield evaluateJS("$_");
+ response = await evaluateJS("$_");
basicResultCheck(response, "$_", {
type: "object",
class: "Object",
actor: /[a-z]/,
});
checkObject(response.result.preview.ownProperties, {
bar: {
value: 2
}
});
nextTest();
-});
+};
function basicResultCheck(response, input, output) {
checkObject(response, {
from: gState.actor,
input: input,
result: output,
});
ok(!response.exception, "no eval exception");
--- a/devtools/shared/webconsole/test/test_jsterm_queryselector.html
+++ b/devtools/shared/webconsole/test/test_jsterm_queryselector.html
@@ -36,100 +36,100 @@ function startTest() {
checkQuerySelectorAllNotExist,
checkQuerySelectorException,
checkQuerySelectorAllException
];
runTests(tests, testEnd);
});
}
-let setupWindow = Task.async(function*() {
+let setupWindow = async function () {
info ("Shimming window functions for the content privileged tab");
- yield evaluateJS("document.querySelector = function() { throw 'should not call qS'; }");
- yield evaluateJS("document.querySelectorAll = function() { throw 'should not call qSA'; }");
+ await evaluateJS("document.querySelector = function() { throw 'should not call qS'; }");
+ await evaluateJS("document.querySelectorAll = function() { throw 'should not call qSA'; }");
nextTest();
-});
+};
-let checkQuerySelector = Task.async(function*() {
+let checkQuerySelector = async function () {
info ("$ returns an DOMNode");
- let response = yield evaluateJS("$('body')");
+ let response = await evaluateJS("$('body')");
basicResultCheck(response, "$('body')", {
type: "object",
class: "HTMLBodyElement",
preview: {
kind: "DOMNode",
nodeName: "body"
}
});
nextTest();
-});
+};
-let checkQuerySelectorAll = Task.async(function*() {
+let checkQuerySelectorAll = async function () {
info ("$$ returns an array");
- let response = yield evaluateJS("$$('body')");
+ let response = await evaluateJS("$$('body')");
basicResultCheck(response, "$$('body')", {
type: "object",
class: "Array",
preview: {
length: 1
}
});
nextTest();
-});
+};
-let checkQuerySelectorAllNotExist = Task.async(function*() {
+let checkQuerySelectorAllNotExist = async function () {
info ("$$ returns an array even if query yields no results");
- let response = yield evaluateJS("$$('foobar')");
+ let response = await evaluateJS("$$('foobar')");
basicResultCheck(response, "$$('foobar')", {
type: "object",
class: "Array",
preview: {
length: 0
}
});
nextTest();
-});
+};
-let checkQuerySelectorException = Task.async(function*() {
+let checkQuerySelectorException = async function () {
info ("$ returns an exception if an invalid selector was provided");
- let response = yield evaluateJS("$(':foo')");
+ let response = await evaluateJS("$(':foo')");
checkObject(response, {
input: "$(':foo')",
exceptionMessage: "SyntaxError: ':foo' is not a valid selector",
exception: {
type: "object",
class: "DOMException",
preview: {
kind: "DOMException",
name: "SyntaxError",
message: "':foo' is not a valid selector"
}
}
});
nextTest();
-});
+};
-let checkQuerySelectorAllException = Task.async(function*() {
+let checkQuerySelectorAllException = async function () {
info ("$$ returns an exception if an invalid selector was provided");
- let response = yield evaluateJS("$$(':foo')");
+ let response = await evaluateJS("$$(':foo')");
checkObject(response, {
input: "$$(':foo')",
exceptionMessage: "SyntaxError: ':foo' is not a valid selector",
exception: {
type: "object",
class: "DOMException",
preview: {
kind: "DOMException",
name: "SyntaxError",
message: "':foo' is not a valid selector"
}
}
});
nextTest();
-});
+};
function basicResultCheck(response, input, output) {
checkObject(response, {
from: gState.actor,
input: input,
result: output,
});
ok(!response.exception, "no eval exception");
@@ -140,27 +140,27 @@ function testEnd() {
gWin.close();
gWin = null;
closeDebugger(gState, function() {
gState = null;
SimpleTest.finish();
});
}
-let load = Task.async(function*() {
+let load = async function () {
removeEventListener("load", load);
- yield new Promise(resolve => {
+ await new Promise(resolve => {
SpecialPowers.pushPrefEnv({"set": [
["security.data_uri.unique_opaque_origin", false],
]}, resolve);
});
// Open a content window to test XRay functionality on built in functions.
gWin = window.open("data:text/html,");
info ("Waiting for content window to load");
gWin.onload = startTest;
-});
+};
addEventListener("load", load);
</script>
</body>
</html>
--- a/devtools/shared/webconsole/test/unit/test_throttle.js
+++ b/devtools/shared/webconsole/test/unit/test_throttle.js
@@ -66,17 +66,17 @@ TestChannel.prototype = {
setNewListener: function (listener) {
this.listener = listener;
this.state = "listener";
return this.testListener;
},
};
-add_task(function* () {
+add_task(async function () {
let throttler = new NetworkThrottleManager({
latencyMean: 1,
latencyMax: 1,
downloadBPSMean: 500,
downloadBPSMax: 500,
uploadBPSMean: 500,
uploadBPSMax: 500,
});
@@ -124,18 +124,18 @@ add_task(function* () {
// onDataAvailable is required to immediately read the data.
listener.onDataAvailable(null, null, testInputStream, 0, 6);
equal(testInputStream.available(), 0, "no more data should be available");
equal(testListener.state, "start",
"test listener should not have received data");
equal(activitySeen, false, "activity not distributed yet");
- let newState = yield testListener.onStateChanged();
+ let newState = await testListener.onStateChanged();
equal(newState, "data", "test listener received data");
equal(testListener.data, TEST_INPUT, "test listener received all the data");
equal(activitySeen, true, "activity has been distributed");
let onChange = testListener.onStateChanged();
listener.onStopRequest(null, null, null);
- newState = yield onChange;
+ newState = await onChange;
equal(newState, "stop", "onStateChanged reported");
});
--- a/devtools/shared/worker/tests/browser/browser_worker-01.js
+++ b/devtools/shared/worker/tests/browser/browser_worker-01.js
@@ -15,33 +15,33 @@ const WORKER_DATA = (function () {
for (let i = 0; i < count; i++) {
timestamps.push(i);
}
return timestamps;
})();
const INTERVAL = 100;
const DURATION = 1000;
-add_task(function* () {
+add_task(async function () {
// Test both CJS and JSM versions
- yield testWorker("JSM", () => ChromeUtils.import("resource://devtools/shared/worker/worker.js", {}));
- yield testWorker("CommonJS", () => require("devtools/shared/worker/worker"));
+ await testWorker("JSM", () => ChromeUtils.import("resource://devtools/shared/worker/worker.js", {}));
+ await testWorker("CommonJS", () => require("devtools/shared/worker/worker"));
});
-function* testWorker(context, workerFactory) {
+async function testWorker(context, workerFactory) {
let { DevToolsWorker, workerify } = workerFactory();
let worker = new DevToolsWorker(WORKER_URL);
- let results = yield worker.performTask("plotTimestampsGraph", {
+ let results = await worker.performTask("plotTimestampsGraph", {
timestamps: WORKER_DATA,
interval: INTERVAL,
duration: DURATION
});
ok(results.plottedData.length,
`worker should have returned an object with array properties in ${context}`);
let fn = workerify(x => x * x);
- is((yield fn(5)), 25, `workerify works in ${context}`);
+ is((await fn(5)), 25, `workerify works in ${context}`);
fn.destroy();
worker.destroy();
}
--- a/devtools/shared/worker/tests/browser/browser_worker-02.js
+++ b/devtools/shared/worker/tests/browser/browser_worker-02.js
@@ -4,46 +4,46 @@
"use strict";
// Tests errors are handled properly by the DevToolsWorker.
const { DevToolsWorker } = require("devtools/shared/worker/worker");
const WORKER_URL =
"resource://devtools/client/shared/widgets/GraphsWorker.js";
-add_task(function* () {
+add_task(async function () {
try {
new DevToolsWorker("resource://i/dont/exist.js");
ok(false, "Creating a DevToolsWorker with an invalid URL throws");
} catch (e) {
ok(true, "Creating a DevToolsWorker with an invalid URL throws");
}
let worker = new DevToolsWorker(WORKER_URL);
try {
// plotTimestampsGraph requires timestamp, interval an duration props on the object
// passed in so there should be an error thrown in the worker
- yield worker.performTask("plotTimestampsGraph", {});
+ await worker.performTask("plotTimestampsGraph", {});
ok(false,
"DevToolsWorker returns a rejected promise when an error occurs in the worker");
} catch (e) {
ok(true,
"DevToolsWorker returns a rejected promise when an error occurs in the worker");
}
try {
- yield worker.performTask("not a real task");
+ await worker.performTask("not a real task");
ok(false, "DevToolsWorker returns a rejected promise when task does not exist");
} catch (e) {
ok(true, "DevToolsWorker returns a rejected promise when task does not exist");
}
worker.destroy();
try {
- yield worker.performTask("plotTimestampsGraph", {
+ await worker.performTask("plotTimestampsGraph", {
timestamps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
interval: 1,
duration: 1
});
ok(false, "DevToolsWorker rejects when performing a task on a destroyed worker");
} catch (e) {
ok(true, "DevToolsWorker rejects when performing a task on a destroyed worker");
}
--- a/devtools/shared/worker/tests/browser/browser_worker-03.js
+++ b/devtools/shared/worker/tests/browser/browser_worker-03.js
@@ -20,35 +20,35 @@ function squarePromise(x) {
function squareError(x) {
return new Error("Nope");
}
function squarePromiseReject(x) {
return new Promise((_, reject) => reject("Nope"));
}
-add_task(function* () {
+add_task(async function () {
let fn = workerify(square);
- is((yield fn(5)), 25, "return primitives successful");
+ is((await fn(5)), 25, "return primitives successful");
fn.destroy();
fn = workerify(squarePromise);
- is((yield fn(5)), 25, "promise primitives successful");
+ is((await fn(5)), 25, "promise primitives successful");
fn.destroy();
fn = workerify(squareError);
try {
- yield fn(5);
+ await fn(5);
ok(false, "return error should reject");
} catch (e) {
ok(true, "return error should reject");
}
fn.destroy();
fn = workerify(squarePromiseReject);
try {
- yield fn(5);
+ await fn(5);
ok(false, "returned rejected promise rejects");
} catch (e) {
ok(true, "returned rejected promise rejects");
}
fn.destroy();
});