summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/androidTest/assets/web_extensions/test-support/test-api.js
blob: 1868d25c84e86850af919409faddf8705c4deff7 (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
/* 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";

/* globals Services */

const { E10SUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/E10SUtils.sys.mjs"
);
const { Preferences } = ChromeUtils.importESModule(
  "resource://gre/modules/Preferences.sys.mjs"
);

// eslint-disable-next-line mozilla/reject-importGlobalProperties
Cu.importGlobalProperties(["PathUtils"]);

this.test = class extends ExtensionAPI {
  onStartup() {
    ChromeUtils.registerWindowActor("TestSupport", {
      child: {
        esModuleURI:
          "resource://android/assets/web_extensions/test-support/TestSupportChild.sys.mjs",
      },
      allFrames: true,
    });
    ChromeUtils.registerProcessActor("TestSupportProcess", {
      child: {
        esModuleURI:
          "resource://android/assets/web_extensions/test-support/TestSupportProcessChild.sys.mjs",
      },
    });
  }

  onShutdown(isAppShutdown) {
    if (isAppShutdown) {
      return;
    }
    ChromeUtils.unregisterWindowActor("TestSupport");
    ChromeUtils.unregisterProcessActor("TestSupportProcess");
  }

  getAPI(context) {
    /**
     * Helper function for getting window or process actors.
     *
     * @param tabId - id of the tab; required
     * @param actorName - a string; the name of the actor
     *   Default: "TestSupport" which is our test framework actor
     *   (you can still pass the second parameter when getting the TestSupport actor, for readability)
     *
     * @returns actor
     */
    function getActorForTab(tabId, actorName = "TestSupport") {
      const tab = context.extension.tabManager.get(tabId);
      const { browsingContext } = tab.browser;
      return browsingContext.currentWindowGlobal.getActor(actorName);
    }

    return {
      test: {
        /* Set prefs and returns set of saved prefs */
        async setPrefs(oldPrefs, newPrefs) {
          // Save old prefs
          Object.assign(
            oldPrefs,
            ...Object.keys(newPrefs)
              .filter(key => !(key in oldPrefs))
              .map(key => ({ [key]: Preferences.get(key, null) }))
          );

          // Set new prefs
          Preferences.set(newPrefs);
          return oldPrefs;
        },

        /* Restore prefs to old value. */
        async restorePrefs(oldPrefs) {
          for (const [name, value] of Object.entries(oldPrefs)) {
            if (value === null) {
              Preferences.reset(name);
            } else {
              Preferences.set(name, value);
            }
          }
        },

        /* Get pref values. */
        async getPrefs(prefs) {
          return Preferences.get(prefs);
        },

        /* Gets link color for a given selector. */
        async getLinkColor(tabId, selector) {
          return getActorForTab(tabId, "TestSupport").sendQuery(
            "GetLinkColor",
            { selector }
          );
        },

        async getRequestedLocales() {
          return Services.locale.requestedLocales;
        },

        async getPidForTab(tabId) {
          const tab = context.extension.tabManager.get(tabId);
          const pids = E10SUtils.getBrowserPids(tab.browser);
          return pids[0];
        },

        async waitForContentTransformsReceived(tabId) {
          return getActorForTab(tabId).sendQuery(
            "WaitForContentTransformsReceived"
          );
        },

        async getAllBrowserPids() {
          const pids = [];
          const processes = ChromeUtils.getAllDOMProcesses();
          for (const process of processes) {
            if (process.remoteType && process.remoteType.startsWith("web")) {
              pids.push(process.osPid);
            }
          }
          return pids;
        },

        async killContentProcess(pid) {
          const procs = ChromeUtils.getAllDOMProcesses();
          for (const proc of procs) {
            if (pid === proc.osPid) {
              proc
                .getActor("TestSupportProcess")
                .sendAsyncMessage("KillContentProcess");
            }
          }
        },

        async addHistogram(id, value) {
          return Services.telemetry.getHistogramById(id).add(value);
        },

        removeAllCertOverrides() {
          const overrideService = Cc[
            "@mozilla.org/security/certoverride;1"
          ].getService(Ci.nsICertOverrideService);
          overrideService.clearAllOverrides();
        },

        async setScalar(id, value) {
          return Services.telemetry.scalarSet(id, value);
        },

        async setResolutionAndScaleTo(tabId, resolution) {
          return getActorForTab(tabId, "TestSupport").sendQuery(
            "SetResolutionAndScaleTo",
            {
              resolution,
            }
          );
        },

        async getActive(tabId) {
          const tab = context.extension.tabManager.get(tabId);
          return tab.browser.docShellIsActive;
        },

        async getProfilePath() {
          return PathUtils.profileDir;
        },

        async flushApzRepaints(tabId) {
          // TODO: Note that `waitUntilApzStable` in apz_test_utils.js does
          // flush APZ repaints in the parent process (i.e. calling
          // nsIDOMWindowUtils.flushApzRepaints for the parent process) before
          // flushApzRepaints is called for the target content document, if we
          // still meet intermittent failures, we might want to do it here as
          // well.
          await getActorForTab(tabId, "TestSupport").sendQuery(
            "FlushApzRepaints"
          );
        },

        async promiseAllPaintsDone(tabId) {
          await getActorForTab(tabId, "TestSupport").sendQuery(
            "PromiseAllPaintsDone"
          );
        },

        async usingGpuProcess() {
          const gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(
            Ci.nsIGfxInfo
          );
          return gfxInfo.usingGPUProcess;
        },

        async killGpuProcess() {
          const gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(
            Ci.nsIGfxInfo
          );
          return gfxInfo.killGPUProcessForTests();
        },

        async crashGpuProcess() {
          const gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(
            Ci.nsIGfxInfo
          );
          return gfxInfo.crashGPUProcessForTests();
        },

        async clearHSTSState() {
          const sss = Cc["@mozilla.org/ssservice;1"].getService(
            Ci.nsISiteSecurityService
          );
          return sss.clearAll();
        },

        async triggerCookieBannerDetected(tabId) {
          const actor = getActorForTab(tabId, "CookieBanner");
          return actor.receiveMessage({
            name: "CookieBanner::DetectedBanner",
          });
        },

        async triggerCookieBannerHandled(tabId) {
          const actor = getActorForTab(tabId, "CookieBanner");
          return actor.receiveMessage({
            name: "CookieBanner::HandledBanner",
          });
        },

        async triggerTranslationsOffer(tabId) {
          const browser = context.extension.tabManager.get(tabId).browser;
          const { CustomEvent } = browser.ownerGlobal;
          return browser.dispatchEvent(
            new CustomEvent("TranslationsParent:OfferTranslation", {
              bubbles: true,
            })
          );
        },

        async triggerLanguageStateChange(tabId, languageState) {
          const browser = context.extension.tabManager.get(tabId).browser;
          const { CustomEvent } = browser.ownerGlobal;
          return browser.dispatchEvent(
            new CustomEvent("TranslationsParent:LanguageState", {
              bubbles: true,
              detail: languageState,
            })
          );
        },
      },
    };
  }
};