summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/webidl-api/test_ext_webidl_api.js
blob: 57aed8a7002605eb10089701b5f61f0dcbf5972e (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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";

AddonTestUtils.init(this);
AddonTestUtils.createAppInfo(
  "xpcshell@tests.mozilla.org",
  "XPCShell",
  "1",
  "42"
);

add_task(async function setup() {
  await AddonTestUtils.promiseStartupManager();
});

add_task(async function test_ext_context_does_have_webidl_bindings() {
  await runExtensionAPITest("should have a browser global object", {
    backgroundScript() {
      const { browser, chrome } = self;

      return {
        hasExtensionAPI: !!browser,
        hasExtensionMockAPI: !!browser?.mockExtensionAPI,
        hasChromeCompatGlobal: !!chrome,
        hasChromeMockAPI: !!chrome?.mockExtensionAPI,
      };
    },
    assertResults({ testResult, testError }) {
      Assert.deepEqual(testError, undefined);
      Assert.deepEqual(
        testResult,
        {
          hasExtensionAPI: true,
          hasExtensionMockAPI: true,
          hasChromeCompatGlobal: true,
          hasChromeMockAPI: true,
        },
        "browser and browser.test WebIDL API bindings found"
      );
    },
  });
});

add_task(async function test_propagated_extension_error() {
  await runExtensionAPITest(
    "should throw an extension error on ResultType::EXTENSION_ERROR",
    {
      backgroundScript({ testAsserts }) {
        try {
          const api = self.browser.mockExtensionAPI;
          api.methodSyncWithReturn("arg0", 1, { value: "arg2" });
        } catch (err) {
          testAsserts.isErrorInstance(err);
          throw err;
        }
      },
      mockAPIRequestHandler() {
        return {
          type: Ci.mozIExtensionAPIRequestResult.EXTENSION_ERROR,
          value: new Error("Fake Extension Error"),
        };
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError?.message, "Fake Extension Error");
      },
    }
  );
});

add_task(async function test_system_errors_donot_leak() {
  function assertResults({ testError }) {
    ok(
      testError?.message?.match(/An unexpected error occurred/),
      `Got the general unexpected error as expected: ${testError?.message}`
    );
  }

  function mockAPIRequestHandler() {
    throw new Error("Fake handleAPIRequest exception");
  }

  const msg =
    "should throw an unexpected error occurred if handleAPIRequest throws";

  await runExtensionAPITest(`sync method ${msg}`, {
    backgroundScript({ testAsserts }) {
      try {
        self.browser.mockExtensionAPI.methodSyncWithReturn("arg0");
      } catch (err) {
        testAsserts.isErrorInstance(err);
        throw err;
      }
    },
    mockAPIRequestHandler,
    assertResults,
  });

  await runExtensionAPITest(`async method ${msg}`, {
    backgroundScript({ testAsserts }) {
      try {
        self.browser.mockExtensionAPI.methodAsync("arg0");
      } catch (err) {
        testAsserts.isErrorInstance(err);
        throw err;
      }
    },
    mockAPIRequestHandler,
    assertResults,
  });

  await runExtensionAPITest(`no return method ${msg}`, {
    backgroundScript({ testAsserts }) {
      try {
        self.browser.mockExtensionAPI.methodNoReturn("arg0");
      } catch (err) {
        testAsserts.isErrorInstance(err);
        throw err;
      }
    },
    mockAPIRequestHandler,
    assertResults,
  });
});

add_task(async function test_call_sync_function_result() {
  await runExtensionAPITest(
    "sync API methods should support structured clonable return values",
    {
      backgroundScript({ testAsserts }) {
        const api = self.browser.mockExtensionAPI;
        const results = {
          string: api.methodSyncWithReturn("string-result"),
          nested_prop: api.methodSyncWithReturn({
            string: "123",
            number: 123,
            date: new Date("2020-09-20"),
            map: new Map([
              ["a", 1],
              ["b", 2],
            ]),
          }),
        };

        testAsserts.isInstanceOf(results.nested_prop.date, "Date");
        testAsserts.isInstanceOf(results.nested_prop.map, "Map");
        return results;
      },
      mockAPIRequestHandler(policy, request) {
        if (request.apiName === "methodSyncWithReturn") {
          // Return the first argument unmodified, which will be checked in the
          // resultAssertFn above.
          return {
            type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
            value: request.args[0],
          };
        }
        throw new Error("Unexpected API method");
      },
      assertResults({ testResult, testError }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
        Assert.deepEqual(testResult, {
          string: "string-result",
          nested_prop: {
            string: "123",
            number: 123,
            date: new Date("2020-09-20"),
            map: new Map([
              ["a", 1],
              ["b", 2],
            ]),
          },
        });
      },
    }
  );
});

add_task(async function test_call_sync_fn_missing_return() {
  await runExtensionAPITest(
    "should throw an unexpected error occurred on missing return value",
    {
      backgroundScript() {
        self.browser.mockExtensionAPI.methodSyncWithReturn("arg0");
      },
      mockAPIRequestHandler() {
        return undefined;
      },
      assertResults({ testError }) {
        ok(
          testError?.message?.match(/An unexpected error occurred/),
          `Got the general unexpected error as expected: ${testError?.message}`
        );
      },
    }
  );
});

add_task(async function test_call_async_throw_extension_error() {
  await runExtensionAPITest(
    "an async function can throw an error occurred for param validation errors",
    {
      backgroundScript({ testAsserts }) {
        try {
          self.browser.mockExtensionAPI.methodAsync("arg0");
        } catch (err) {
          testAsserts.isErrorInstance(err);
          throw err;
        }
      },
      mockAPIRequestHandler() {
        return {
          type: Ci.mozIExtensionAPIRequestResult.EXTENSION_ERROR,
          value: new Error("Fake Param Validation Error"),
        };
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError?.message, "Fake Param Validation Error");
      },
    }
  );
});

add_task(async function test_call_async_reject_error() {
  await runExtensionAPITest(
    "an async function rejected promise should propagate extension errors",
    {
      async backgroundScript({ testAsserts }) {
        try {
          await self.browser.mockExtensionAPI.methodAsync("arg0");
        } catch (err) {
          testAsserts.isErrorInstance(err);
          throw err;
        }
      },
      mockAPIRequestHandler() {
        return {
          type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
          value: Promise.reject(new Error("Fake API rejected error object")),
        };
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError?.message, "Fake API rejected error object");
      },
    }
  );
});

add_task(async function test_call_async_function_result() {
  await runExtensionAPITest(
    "async API methods should support structured clonable resolved values",
    {
      async backgroundScript({ testAsserts }) {
        const api = self.browser.mockExtensionAPI;
        const results = {
          string: await api.methodAsync("string-result"),
          nested_prop: await api.methodAsync({
            string: "123",
            number: 123,
            date: new Date("2020-09-20"),
            map: new Map([
              ["a", 1],
              ["b", 2],
            ]),
          }),
        };

        testAsserts.isInstanceOf(results.nested_prop.date, "Date");
        testAsserts.isInstanceOf(results.nested_prop.map, "Map");
        return results;
      },
      mockAPIRequestHandler(policy, request) {
        if (request.apiName === "methodAsync") {
          // Return the first argument unmodified, which will be checked in the
          // resultAssertFn above.
          return {
            type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
            value: Promise.resolve(request.args[0]),
          };
        }
        throw new Error("Unexpected API method");
      },
      assertResults({ testResult, testError }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
        Assert.deepEqual(testResult, {
          string: "string-result",
          nested_prop: {
            string: "123",
            number: 123,
            date: new Date("2020-09-20"),
            map: new Map([
              ["a", 1],
              ["b", 2],
            ]),
          },
        });
      },
    }
  );
});

add_task(async function test_call_no_return_throw_extension_error() {
  await runExtensionAPITest(
    "no return function call throw an error occurred for param validation errors",
    {
      backgroundScript({ testAsserts }) {
        try {
          self.browser.mockExtensionAPI.methodNoReturn("arg0");
        } catch (err) {
          testAsserts.isErrorInstance(err);
          throw err;
        }
      },
      mockAPIRequestHandler() {
        return {
          type: Ci.mozIExtensionAPIRequestResult.EXTENSION_ERROR,
          value: new Error("Fake Param Validation Error"),
        };
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError?.message, "Fake Param Validation Error");
      },
    }
  );
});

add_task(async function test_call_no_return_without_errors() {
  await runExtensionAPITest(
    "handleAPIHandler can return undefined on api calls to methods with no return",
    {
      backgroundScript() {
        self.browser.mockExtensionAPI.methodNoReturn("arg0");
      },
      mockAPIRequestHandler() {
        return undefined;
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
      },
    }
  );
});

add_task(async function test_async_method_chrome_compatible_callback() {
  function mockAPIRequestHandler(policy, request) {
    if (request.args[0] === "fake-async-method-failure") {
      return {
        type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
        value: Promise.reject("this-should-not-be-passed-to-cb-as-parameter"),
      };
    }

    return {
      type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
      value: Promise.resolve(request.args),
    };
  }

  await runExtensionAPITest(
    "async method should support an optional chrome-compatible callback",
    {
      mockAPIRequestHandler,
      async backgroundScript({ testAsserts }) {
        const api = self.browser.mockExtensionAPI;
        const success_cb_params = await new Promise(resolve => {
          const res = api.methodAsync(
            { prop: "fake-async-method-success" },
            (...results) => {
              resolve(results);
            }
          );
          testAsserts.equal(res, undefined, "no promise should be returned");
        });
        const error_cb_params = await new Promise(resolve => {
          const res = api.methodAsync(
            "fake-async-method-failure",
            (...results) => {
              resolve(results);
            }
          );
          testAsserts.equal(res, undefined, "no promise should be returned");
        });
        return { success_cb_params, error_cb_params };
      },
      assertResults({ testError, testResult }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
        Assert.deepEqual(
          testResult,
          {
            success_cb_params: [[{ prop: "fake-async-method-success" }]],
            error_cb_params: [],
          },
          "Got the expected results from the chrome compatible callbacks"
        );
      },
    }
  );

  await runExtensionAPITest(
    "async method with ambiguous args called with a chrome-compatible callback",
    {
      mockAPIRequestHandler,
      async backgroundScript({ testAsserts }) {
        const api = self.browser.mockExtensionAPI;
        const success_cb_params = await new Promise(resolve => {
          const res = api.methodAmbiguousArgsAsync(
            "arg0",
            { prop: "arg1" },
            3,
            (...results) => {
              resolve(results);
            }
          );
          testAsserts.equal(res, undefined, "no promise should be returned");
        });
        const error_cb_params = await new Promise(resolve => {
          const res = api.methodAmbiguousArgsAsync(
            "fake-async-method-failure",
            (...results) => {
              resolve(results);
            }
          );
          testAsserts.equal(res, undefined, "no promise should be returned");
        });
        return { success_cb_params, error_cb_params };
      },
      assertResults({ testError, testResult }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
        Assert.deepEqual(
          testResult,
          {
            success_cb_params: [["arg0", { prop: "arg1" }, 3]],
            error_cb_params: [],
          },
          "Got the expected results from the chrome compatible callbacks"
        );
      },
    }
  );
});

add_task(async function test_get_property() {
  await runExtensionAPITest(
    "getProperty API request does return a value synchrously",
    {
      backgroundScript() {
        return self.browser.mockExtensionAPI.propertyAsString;
      },
      mockAPIRequestHandler() {
        return {
          type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
          value: "property-value",
        };
      },
      assertResults({ testError, testResult }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
        Assert.deepEqual(
          testResult,
          "property-value",
          "Got the expected result"
        );
      },
    }
  );

  await runExtensionAPITest(
    "getProperty API request can return an error object",
    {
      backgroundScript({ testAsserts }) {
        const errObj = self.browser.mockExtensionAPI.propertyAsErrorObject;
        testAsserts.isErrorInstance(errObj);
        testAsserts.equal(errObj.message, "fake extension error");
      },
      mockAPIRequestHandler(policy, request) {
        let savedFrame = request.calledSavedFrame;
        return {
          type: Ci.mozIExtensionAPIRequestResult.RETURN_VALUE,
          value: ChromeUtils.createError("fake extension error", savedFrame),
        };
      },
      assertResults({ testError }) {
        Assert.deepEqual(testError, null, "Got no error as expected");
      },
    }
  );
});