summaryrefslogtreecommitdiffstats
path: root/devtools/client/framework/browser-toolbox/test/helpers-browser-toolbox.js
blob: bc97c20c0132635f8ce5e7316d40cc26e659c6cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */
/* eslint-disable no-unused-vars, no-undef */

"use strict";

const { BrowserToolboxLauncher } = ChromeUtils.importESModule(
  "resource://devtools/client/framework/browser-toolbox/Launcher.sys.mjs"
);
const {
  DevToolsClient,
} = require("resource://devtools/client/devtools-client.js");

/**
 * Open up a browser toolbox and return a ToolboxTask object for interacting
 * with it. ToolboxTask has the following methods:
 *
 * importFunctions(object)
 *
 *   The object contains functions from this process which should be defined in
 *   the global evaluation scope of the toolbox. The toolbox cannot load testing
 *   files directly.
 *
 * destroy()
 *
 *   Destroy the browser toolbox and make sure it exits cleanly.
 *
 * @param {Object}:
 *        - {Function} existingProcessClose: if truth-y, connect to an existing
 *          browser toolbox process rather than launching a new one and
 *          connecting to it.  The given function is expected to return an
 *          object containing an `exitCode`, like `{exitCode}`, and will be
 *          awaited in the returned `destroy()` function.  `exitCode` is
 *          asserted to be 0 (success).
 */
async function initBrowserToolboxTask({ existingProcessClose } = {}) {
  if (AppConstants.ASAN) {
    ok(
      false,
      "ToolboxTask cannot be used on ASAN builds. This test should be skipped (Bug 1591064)."
    );
  }

  await pushPref("devtools.chrome.enabled", true);
  await pushPref("devtools.debugger.remote-enabled", true);
  await pushPref("devtools.browsertoolbox.enable-test-server", true);
  await pushPref("devtools.debugger.prompt-connection", false);

  // This rejection seems to affect all tests using the browser toolbox.
  ChromeUtils.importESModule(
    "resource://testing-common/PromiseTestUtils.sys.mjs"
  ).PromiseTestUtils.allowMatchingRejectionsGlobally(/File closed/);

  let process;
  let dbgProcess;
  if (!existingProcessClose) {
    [process, dbgProcess] = await new Promise(resolve => {
      BrowserToolboxLauncher.init({
        onRun: (_process, _dbgProcess) => resolve([_process, _dbgProcess]),
        overwritePreferences: true,
      });
    });
    ok(true, "Browser toolbox started");
    is(
      BrowserToolboxLauncher.getBrowserToolboxSessionState(),
      true,
      "Has session state"
    );
  } else {
    ok(true, "Connecting to existing browser toolbox");
  }

  // The port of the DevToolsServer installed in the toolbox process is fixed.
  // See browser-toolbox/window.js
  let transport;
  while (true) {
    try {
      transport = await DevToolsClient.socketConnect({
        host: "localhost",
        port: 6001,
        webSocket: false,
      });
      break;
    } catch (e) {
      await waitForTime(100);
    }
  }
  ok(true, "Got transport");

  const client = new DevToolsClient(transport);
  await client.connect();

  const commands = await CommandsFactory.forMainProcess({ client });
  const target = await commands.descriptorFront.getTarget();
  const consoleFront = await target.getFront("console");

  ok(true, "Connected");

  await importFunctions({
    info: msg => dump(msg + "\n"),
    is: (a, b, description) => {
      let msg =
        "'" + JSON.stringify(a) + "' is equal to '" + JSON.stringify(b) + "'";
      if (description) {
        msg += " - " + description;
      }
      if (a !== b) {
        msg = "FAILURE: " + msg;
        dump(msg + "\n");
        throw new Error(msg);
      } else {
        msg = "SUCCESS: " + msg;
        dump(msg + "\n");
      }
    },
    ok: (a, description) => {
      let msg = "'" + JSON.stringify(a) + "' is true";
      if (description) {
        msg += " - " + description;
      }
      if (!a) {
        msg = "FAILURE: " + msg;
        dump(msg + "\n");
        throw new Error(msg);
      } else {
        msg = "SUCCESS: " + msg;
        dump(msg + "\n");
      }
    },
  });

  async function evaluateExpression(expression, options = {}) {
    const onEvaluationResult = consoleFront.once("evaluationResult");
    await consoleFront.evaluateJSAsync({ text: expression, ...options });
    return onEvaluationResult;
  }

  /**
   * Invoke the given function and argument(s) within the global evaluation scope
   * of the toolbox. The evaluation scope predefines the name "gToolbox" for the
   * toolbox itself.
   *
   * @param {value|Array<value>} arg
   *        If an Array is passed, we will consider it as the list of arguments
   *        to pass to `fn`. Otherwise we will consider it as the unique argument
   *        to pass to it.
   * @param {Function} fn
   *        Function to call in the global scope within the browser toolbox process.
   *        This function will be stringified and passed to the process via RDP.
   * @return {Promise<Value>}
   *        Return the primitive value returned by `fn`.
   */
  async function spawn(arg, fn) {
    // Use JSON.stringify to ensure that we can pass strings
    // as well as any JSON-able object.
    const argString = JSON.stringify(Array.isArray(arg) ? arg : [arg]);
    const rv = await evaluateExpression(`(${fn}).apply(null,${argString})`, {
      // Use the following argument in order to ensure waiting for the completion
      // of the promise returned by `fn` (in case this is an async method).
      mapped: { await: true },
    });
    if (rv.exceptionMessage) {
      throw new Error(`ToolboxTask.spawn failure: ${rv.exceptionMessage}`);
    } else if (rv.topLevelAwaitRejected) {
      throw new Error(`ToolboxTask.spawn await rejected`);
    }
    return rv.result;
  }

  async function importFunctions(functions) {
    for (const [key, fn] of Object.entries(functions)) {
      await evaluateExpression(`this.${key} = ${fn}`);
    }
  }

  async function importScript(script) {
    const response = await evaluateExpression(script);
    if (response.hasException) {
      ok(
        false,
        "ToolboxTask.spawn exception while importing script: " +
          response.exceptionMessage
      );
    }
  }

  let destroyed = false;
  async function destroy() {
    // No need to do anything if `destroy` was already called.
    if (destroyed) {
      return;
    }

    const closePromise = existingProcessClose
      ? existingProcessClose()
      : dbgProcess.wait();
    evaluateExpression("gToolbox.destroy()").catch(e => {
      // Ignore connection close as the toolbox destroy may destroy
      // everything quickly enough so that evaluate request is still pending
      if (!e.message.includes("Connection closed")) {
        throw e;
      }
    });

    const { exitCode } = await closePromise;
    ok(true, "Browser toolbox process closed");

    is(exitCode, 0, "The remote debugger process died cleanly");

    if (!existingProcessClose) {
      is(
        BrowserToolboxLauncher.getBrowserToolboxSessionState(),
        false,
        "No session state after closing"
      );
    }

    await commands.destroy();
    destroyed = true;
  }

  // When tests involving using this task fail, the spawned Browser Toolbox is not
  // destroyed and might impact the next tests (e.g. pausing the content process before
  // the debugger from the content toolbox does). So make sure to cleanup everything.
  registerCleanupFunction(destroy);

  return {
    importFunctions,
    importScript,
    spawn,
    destroy,
  };
}