summaryrefslogtreecommitdiffstats
path: root/devtools/client/aboutdebugging/test/browser/helper-addons.js
blob: dd299a3c0f9359f628a5c845cbf69c845fd4524b (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

/* import-globals-from head.js */

function _getSupportsFile(path) {
  const cr = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(
    Ci.nsIChromeRegistry
  );
  const uri = Services.io.newURI(CHROME_URL_ROOT + path);
  const fileurl = cr.convertChromeURL(uri);
  return fileurl.QueryInterface(Ci.nsIFileURL);
}

async function enableExtensionDebugging() {
  // Disable security prompt
  await pushPref("devtools.debugger.prompt-connection", false);
}
/* exported enableExtensionDebugging */

/**
 * Install an extension using the AddonManager so it does not show up as temporary.
 */
async function installRegularExtension(pathOrFile) {
  const isFile = typeof pathOrFile.isFile === "function" && pathOrFile.isFile();
  const file = isFile ? pathOrFile : _getSupportsFile(pathOrFile).file;
  const install = await AddonManager.getInstallForFile(file);
  return new Promise((resolve, reject) => {
    if (!install) {
      throw new Error(`An install was not created for ${file.path}`);
    }
    install.addListener({
      onDownloadFailed: reject,
      onDownloadCancelled: reject,
      onInstallFailed: reject,
      onInstallCancelled: reject,
      onInstallEnded: resolve,
    });
    install.install();
  });
}
/* exported installRegularExtension */

/**
 * Install a temporary extension at the provided path, with the provided name.
 * Will use a mock file picker to select the file.
 */
async function installTemporaryExtension(pathOrFile, name, document) {
  const { Management } = ChromeUtils.importESModule(
    "resource://gre/modules/Extension.sys.mjs"
  );

  info("Install temporary extension named " + name);
  // Mock the file picker to select a test addon
  prepareMockFilePicker(pathOrFile);

  const onAddonInstalled = new Promise(done => {
    Management.on("startup", function listener(event, extension) {
      if (extension.name != name) {
        return;
      }

      Management.off("startup", listener);
      done(extension);
    });
  });

  // Trigger the file picker by clicking on the button
  document.querySelector(".qa-temporary-extension-install-button").click();

  info("Wait for addon to be installed");
  return onAddonInstalled;
}
/* exported installTemporaryExtension */

function createTemporaryXPI(xpiData) {
  const { ExtensionTestCommon } = ChromeUtils.importESModule(
    "resource://testing-common/ExtensionTestCommon.sys.mjs"
  );

  const { background, files, id, name, extraProperties } = xpiData;
  info("Generate XPI file for " + id);

  const manifest = Object.assign(
    {},
    {
      browser_specific_settings: { gecko: { id } },
      manifest_version: 2,
      name,
      version: "1.0",
    },
    extraProperties
  );

  const xpiFile = ExtensionTestCommon.generateXPI({
    background,
    files,
    manifest,
  });
  registerCleanupFunction(() => xpiFile.exists() && xpiFile.remove(false));
  return xpiFile;
}
/* exported createTemporaryXPI */

/**
 * Remove the existing temporary XPI file generated by ExtensionTestCommon and create a
 * new one at the same location.
 * @return {File} the temporary extension XPI file created
 */
function updateTemporaryXPI(xpiData, existingXPI) {
  info("Delete and regenerate XPI for " + xpiData.id);

  // Store the current name to check the xpi is correctly replaced.
  const existingName = existingXPI.leafName;
  info("Delete existing XPI named: " + existingName);
  existingXPI.exists() && existingXPI.remove(false);

  const xpiFile = createTemporaryXPI(xpiData);
  // Check that the name of the new file is correct
  if (xpiFile.leafName !== existingName) {
    throw new Error(
      "New XPI created with unexpected name: " + xpiFile.leafName
    );
  }
  return xpiFile;
}
/* exported updateTemporaryXPI */

/**
 * Install a fake temporary extension by creating a temporary in-memory XPI file.
 * @return {File} the temporary extension XPI file created
 */
async function installTemporaryExtensionFromXPI(xpiData, document) {
  const xpiFile = createTemporaryXPI(xpiData);
  const extension = await installTemporaryExtension(
    xpiFile,
    xpiData.name,
    document
  );

  info("Wait until the addon debug target appears");
  await waitUntil(() => findDebugTargetByText(xpiData.name, document));
  return { extension, xpiFile };
}
/* exported installTemporaryExtensionFromXPI */

async function removeTemporaryExtension(name, document) {
  info(`Wait for removable extension with name: '${name}'`);
  const buttonName = ".qa-temporary-extension-remove-button";
  await waitUntil(() => {
    const extension = findDebugTargetByText(name, document);
    return extension && extension.querySelector(buttonName);
  });
  info(`Remove the temporary extension with name: '${name}'`);
  const temporaryExtensionItem = findDebugTargetByText(name, document);
  temporaryExtensionItem.querySelector(buttonName).click();

  info("Wait until the debug target item disappears");
  await waitUntil(() => !findDebugTargetByText(name, document));
}
/* exported removeTemporaryExtension */

async function removeExtension(id, name, document) {
  info(
    "Retrieve the extension instance from the addon manager, and uninstall it"
  );
  const extension = await AddonManager.getAddonByID(id);
  extension.uninstall();

  info("Wait until the addon disappears from about:debugging");
  await waitUntil(() => !findDebugTargetByText(name, document));
}
/* exported removeExtension */

function prepareMockFilePicker(pathOrFile) {
  const isFile = typeof pathOrFile.isFile === "function" && pathOrFile.isFile();
  const file = isFile ? pathOrFile : _getSupportsFile(pathOrFile).file;

  // Mock the file picker to select a test addon
  const MockFilePicker = SpecialPowers.MockFilePicker;
  MockFilePicker.init(window.browsingContext);
  MockFilePicker.setFiles([file]);
}
/* exported prepareMockFilePicker */

function promiseBackgroundContextEvent(extensionId, eventName) {
  const { Management } = ChromeUtils.importESModule(
    "resource://gre/modules/Extension.sys.mjs"
  );

  return new Promise(resolve => {
    Management.on(eventName, function listener(_evtName, context) {
      if (context.extension.id === extensionId) {
        Management.off(eventName, listener);
        resolve();
      }
    });
  });
}

function promiseBackgroundContextLoaded(extensionId) {
  return promiseBackgroundContextEvent(extensionId, "proxy-context-load");
}
/* exported promiseBackgroundContextLoaded */

function promiseBackgroundContextUnloaded(extensionId) {
  return promiseBackgroundContextEvent(extensionId, "proxy-context-unload");
}
/* exported promiseBackgroundContextUnloaded */

async function assertBackgroundStatus(
  extName,
  { document, expectedStatus, targetElement }
) {
  const target = targetElement || findDebugTargetByText(extName, document);
  const getBackgroundStatusElement = () =>
    target.querySelector(".extension-backgroundscript__status");
  await waitFor(
    () =>
      getBackgroundStatusElement()?.classList.contains(
        `extension-backgroundscript__status--${expectedStatus}`
      ),
    `Wait ${extName} Background script status "${expectedStatus}" to be rendered`
  );
}
/* exported assertBackgroundStatus */

function getExtensionInstance(extensionId) {
  const policy = WebExtensionPolicy.getByID(extensionId);
  ok(policy, `Got a WebExtensionPolicy instance for ${extensionId}`);
  ok(policy.extension, `Got an Extension class instance for ${extensionId}`);
  return policy.extension;
}
/* exported getExtensionInstance */

async function triggerExtensionEventPageIdleTimeout(extensionId) {
  await getExtensionInstance(extensionId).terminateBackground();
}
/* exported triggerExtensionEventPageIdleTimeout */

async function wakeupExtensionEventPage(extensionId) {
  await getExtensionInstance(extensionId).wakeupBackground();
}
/* exported wakeupExtensionEventPage */

function promiseTerminateBackgroundScriptIgnored(extensionId) {
  const extension = getExtensionInstance(extensionId);
  return new Promise(resolve => {
    extension.once("background-script-suspend-ignored", resolve);
  });
}
/* exported promiseTerminateBackgroundScriptIgnored */

async function promiseBackgroundStatusUpdate(window) {
  waitForDispatch(
    window.AboutDebugging.store,
    "EXTENSION_BGSCRIPT_STATUS_UPDATED"
  );
}
/* exported promiseBackgroundStatusUpdate */