summaryrefslogtreecommitdiffstats
path: root/remote/cdp/test/browser/head.js
blob: 4a7fcbdd7893f8eb44799e036ee4c453d380f5f6 (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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

const { OS } = ChromeUtils.import("resource://gre/modules/osfile.jsm");

const { RemoteAgent } = ChromeUtils.importESModule(
  "chrome://remote/content/components/RemoteAgent.sys.mjs"
);
const { RemoteAgentError } = ChromeUtils.importESModule(
  "chrome://remote/content/cdp/Error.sys.mjs"
);
const { TabManager } = ChromeUtils.importESModule(
  "chrome://remote/content/shared/TabManager.sys.mjs"
);

const TIMEOUT_MULTIPLIER = SpecialPowers.isDebugBuild ? 4 : 1;
const TIMEOUT_EVENTS = 1000 * TIMEOUT_MULTIPLIER;

/*
add_task() is overriden to setup and teardown a test environment
making it easier to  write browser-chrome tests for the remote
debugger.

Before the task is run, the nsIRemoteAgent listener is started and
a CDP client is connected to it.  A new tab is also added.  These
three things are exposed to the provided task like this:

	add_task(async function testName(client, CDP, tab) {
	  // client is an instance of the CDP class
	  // CDP is ./chrome-remote-interface.js
	  // tab is a fresh tab, destroyed after the test
	});

Also target discovery is getting enabled, which means that targetCreated,
targetDestroyed, and targetInfoChanged events will be received by the client.

add_plain_task() may be used to write test tasks without the implicit
setup and teardown described above.
*/

const add_plain_task = add_task.bind(this);

this.add_task = function(taskFn, opts = {}) {
  const {
    createTab = true, // By default run each test in its own tab
  } = opts;

  const fn = async function() {
    let client, tab, target;

    try {
      const CDP = await getCDP();

      if (createTab) {
        tab = await BrowserTestUtils.openNewForegroundTab(gBrowser);
        const tabId = TabManager.getIdForBrowser(tab.linkedBrowser);

        const targets = await CDP.List();
        target = targets.find(target => target.id === tabId);
      }

      client = await CDP({ target });
      info("CDP client instantiated");

      // Bug 1605722 - Workaround to not hang when waiting for Target events
      await getDiscoveredTargets(client.Target);

      await taskFn({ client, CDP, tab });

      if (createTab) {
        // taskFn may resolve within a tick after opening a new tab.
        // We shouldn't remove the newly opened tab in the same tick.
        // Wait for the next tick here.
        await TestUtils.waitForTick();
        BrowserTestUtils.removeTab(tab);
      }
    } catch (e) {
      // Display better error message with the server side stacktrace
      // if an error happened on the server side:
      if (e.response) {
        throw RemoteAgentError.fromJSON(e.response);
      } else {
        throw e;
      }
    } finally {
      if (client) {
        await client.close();
        info("CDP client closed");
      }

      // Close any additional tabs, so that only a single tab remains open
      while (gBrowser.tabs.length > 1) {
        gBrowser.removeCurrentTab();
      }
    }
  };

  Object.defineProperty(fn, "name", { value: taskFn.name, writable: false });
  add_plain_task(fn);
};

/**
 * Create a test document in an invisible window.
 * This window will be automatically closed on test teardown.
 */
function createTestDocument() {
  const browser = Services.appShell.createWindowlessBrowser(true);
  registerCleanupFunction(() => browser.close());

  // Create a system principal content viewer to ensure there is a valid
  // empty document using system principal and avoid any wrapper issues
  // when using document's JS Objects.
  const webNavigation = browser.docShell.QueryInterface(Ci.nsIWebNavigation);
  const system = Services.scriptSecurityManager.getSystemPrincipal();
  webNavigation.createAboutBlankContentViewer(system, system);

  return webNavigation.document;
}

/**
 * Retrieve an intance of CDP object from chrome-remote-interface library
 */
async function getCDP() {
  // Instantiate a background test document in order to load the library
  // as in a web page
  const document = createTestDocument();

  const window = document.defaultView.wrappedJSObject;
  Services.scriptloader.loadSubScript(
    "chrome://mochitests/content/browser/remote/cdp/test/browser/chrome-remote-interface.js",
    window
  );

  // Implements `criRequest` to be called by chrome-remote-interface
  // library in order to do the cross-domain http request, which,
  // in a regular Web page, is impossible.
  window.criRequest = (options, callback) => {
    const { path } = options;
    const url = `http://${RemoteAgent.host}:${RemoteAgent.port}${path}`;
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);

    // Prevent "XML Parsing Error: syntax error" error messages
    xhr.overrideMimeType("text/plain");

    xhr.send(null);
    xhr.onload = () => callback(null, xhr.responseText);
    xhr.onerror = e => callback(e, null);
  };

  return window.CDP;
}

async function getScrollbarSize() {
  return SpecialPowers.spawn(gBrowser.selectedBrowser, [], () => {
    const scrollbarHeight = {};
    const scrollbarWidth = {};

    content.windowUtils.getScrollbarSize(
      false,
      scrollbarWidth,
      scrollbarHeight
    );
    return {
      width: scrollbarWidth.value,
      height: scrollbarHeight.value,
    };
  });
}

function getTargets(CDP) {
  return new Promise((resolve, reject) => {
    CDP.List(null, (err, targets) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(targets);
    });
  });
}

// Wait for all Target.targetCreated events. One for each tab, plus the one
// for the main process target.
async function getDiscoveredTargets(Target) {
  return new Promise(resolve => {
    const targets = [];

    const unsubscribe = Target.targetCreated(target => {
      targets.push(target);

      if (targets.length >= gBrowser.tabs.length + 1) {
        unsubscribe();
        resolve(targets);
      }
    });

    Target.setDiscoverTargets({ discover: true });
  });
}

async function openTab(Target, options = {}) {
  const { activate = false } = options;

  info("Create a new tab and wait for the target to be created");
  const targetCreated = Target.targetCreated();
  const newTab = await BrowserTestUtils.openNewForegroundTab(gBrowser);
  const { targetInfo } = await targetCreated;

  is(targetInfo.type, "page");

  if (activate) {
    await Target.activateTarget({
      targetId: targetInfo.targetId,
    });
    info(`New tab with target id ${targetInfo.targetId} created and activated`);
  } else {
    info(`New tab with target id ${targetInfo.targetId} created`);
  }

  return { targetInfo, newTab };
}

async function openWindow(Target, options = {}) {
  const { activate = false } = options;

  info("Create a new window and wait for the target to be created");
  const targetCreated = Target.targetCreated();
  const newWindow = await BrowserTestUtils.openNewBrowserWindow();
  const newTab = newWindow.gBrowser.selectedTab;
  const { targetInfo } = await targetCreated;
  is(targetInfo.type, "page");

  if (activate) {
    await Target.activateTarget({
      targetId: targetInfo.targetId,
    });
    info(
      `New window with target id ${targetInfo.targetId} created and activated`
    );
  } else {
    info(`New window with target id ${targetInfo.targetId} created`);
  }

  return { targetInfo, newWindow, newTab };
}

/** Creates a data URL for the given source document. */
function toDataURL(src, doctype = "html") {
  let doc, mime;
  switch (doctype) {
    case "html":
      mime = "text/html;charset=utf-8";
      doc = `<!doctype html>\n<meta charset=utf-8>\n${src}`;
      break;
    default:
      throw new Error("Unexpected doctype: " + doctype);
  }

  return `data:${mime},${encodeURIComponent(doc)}`;
}

function convertArgument(arg) {
  if (typeof arg === "bigint") {
    return { unserializableValue: `${arg.toString()}n` };
  }
  if (Object.is(arg, -0)) {
    return { unserializableValue: "-0" };
  }
  if (Object.is(arg, Infinity)) {
    return { unserializableValue: "Infinity" };
  }
  if (Object.is(arg, -Infinity)) {
    return { unserializableValue: "-Infinity" };
  }
  if (Object.is(arg, NaN)) {
    return { unserializableValue: "NaN" };
  }

  return { value: arg };
}

async function evaluate(client, contextId, pageFunction, ...args) {
  const { Runtime } = client;

  if (typeof pageFunction === "string") {
    return Runtime.evaluate({
      expression: pageFunction,
      contextId,
      returnByValue: true,
      awaitPromise: true,
    });
  } else if (typeof pageFunction === "function") {
    return Runtime.callFunctionOn({
      functionDeclaration: pageFunction.toString(),
      executionContextId: contextId,
      arguments: args.map(convertArgument),
      returnByValue: true,
      awaitPromise: true,
    });
  }
  throw new Error("pageFunction: expected 'string' or 'function'");
}

/**
 * Load a given URL in the currently selected tab
 */
async function loadURL(url, expectedURL = undefined) {
  expectedURL = expectedURL || url;

  const browser = gBrowser.selectedTab.linkedBrowser;
  const loaded = BrowserTestUtils.browserLoaded(browser, true, expectedURL);

  BrowserTestUtils.loadURI(browser, url);
  await loaded;
}

/**
 * Enable the Runtime domain
 */
async function enableRuntime(client) {
  const { Runtime } = client;

  // Enable watching for new execution context
  await Runtime.enable();
  info("Runtime domain has been enabled");

  // Calling Runtime.enable will emit executionContextCreated for the existing contexts
  const { context } = await Runtime.executionContextCreated();
  ok(!!context.id, "The execution context has an id");
  ok(context.auxData.isDefault, "The execution context is the default one");
  ok(!!context.auxData.frameId, "The execution context has a frame id set");

  return context;
}

/**
 * Retrieve the value of a property on the content window.
 */
function getContentProperty(prop) {
  info(`Retrieve ${prop} on the content window`);
  return SpecialPowers.spawn(
    gBrowser.selectedBrowser,
    [prop],
    _prop => content[_prop]
  );
}

/**
 * Retrieve all frames for the current tab as flattened list.
 *
 * @return {Map<number, Frame>}
 *     Flattened list of frames as Map
 */
async function getFlattenedFrameTree(client) {
  const { Page } = client;

  function flatten(frames) {
    return frames.reduce((result, current) => {
      result.set(current.frame.id, current.frame);
      if (current.childFrames) {
        const frames = flatten(current.childFrames);
        result = new Map([...result, ...frames]);
      }
      return result;
    }, new Map());
  }

  const { frameTree } = await Page.getFrameTree();
  return flatten(Array(frameTree));
}

/**
 * Return a new promise, which resolves after ms have been elapsed
 */
function timeoutPromise(ms) {
  return new Promise(resolve => {
    window.setTimeout(resolve, ms);
  });
}

/** Fail a test. */
function fail(message) {
  ok(false, message);
}

/**
 * Create a file with the specified contents.
 *
 * @param {string} contents
 *     Contents of the file.
 * @param {Object} options
 * @param {string=} options.path
 *     Path of the file. Defaults to the temporary directory.
 * @param {boolean=} options.remove
 *     If true, automatically remove the file after the test. Defaults to true.
 *
 * @return {Promise}
 * @resolves {string}
 *     Returns the final path of the created file.
 */
async function createFile(contents, options = {}) {
  let { path = null, remove = true } = options;

  if (!path) {
    const basePath = OS.Path.join(OS.Constants.Path.tmpDir, "remote-agent.txt");
    const { file, path: tmpPath } = await OS.File.openUnique(basePath, {
      humanReadable: true,
    });
    await file.close();
    path = tmpPath;
  }

  let encoder = new TextEncoder();
  let array = encoder.encode(contents);

  const count = await OS.File.writeAtomic(path, array, {
    encoding: "utf-8",
    tmpPath: path + ".tmp",
  });
  is(count, contents.length, "All data has been written to file");

  const file = await OS.File.open(path);

  // Automatically remove the file once the test has finished
  if (remove) {
    registerCleanupFunction(async () => {
      await file.close();
      await OS.File.remove(path, { ignoreAbsent: true });
    });
  }

  return { file, path };
}

async function throwScriptError(options = {}) {
  const { inContent = true } = options;

  const addScriptErrorInternal = ({ options }) => {
    const {
      flag = Ci.nsIScriptError.errorFlag,
      innerWindowId = content.windowGlobalChild.innerWindowId,
    } = options;

    const scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(
      Ci.nsIScriptError
    );
    scriptError.initWithWindowID(
      options.text,
      options.sourceName || "sourceName",
      null,
      options.lineNumber || 0,
      options.columnNumber || 0,
      flag,
      options.category || "javascript",
      innerWindowId
    );
    Services.console.logMessage(scriptError);
  };

  if (inContent) {
    ContentTask.spawn(
      gBrowser.selectedBrowser,
      { options },
      addScriptErrorInternal
    );
  } else {
    options.innerWindowId = window.windowGlobalChild.innerWindowId;
    addScriptErrorInternal({ options });
  }
}

class RecordEvents {
  /**
   * A timeline of events chosen by calls to `addRecorder`.
   * Call `configure`` for each client event you want to record.
   * Then `await record(someTimeout)` to record a timeline that you
   * can make assertions about.
   *
   * const history = new RecordEvents(expectedNumberOfEvents);
   *
   * history.addRecorder({
   *  event: Runtime.executionContextDestroyed,
   *  eventName: "Runtime.executionContextDestroyed",
   *  messageFn: payload => {
   *    return `Received Runtime.executionContextDestroyed for id ${payload.executionContextId}`;
   *  },
   * });
   *
   *
   * @param {number} total
   *     Number of expected events. Stop recording when this number is exceeded.
   *
   */
  constructor(total) {
    this.events = [];
    this.promises = new Set();
    this.subscriptions = new Set();
    this.total = total;
  }

  /**
   * Configure an event to be recorded and logged.
   * The recording stops once we accumulate more than the expected
   * total of all configured events.
   *
   * @param {Object} options
   * @param {CDPEvent} options.event
   *     https://github.com/cyrus-and/chrome-remote-interface#clientdomaineventcallback
   * @param {string} options.eventName
   *     Name to use for reporting.
   * @param {Function=} options.callback
   *     ({ eventName, payload }) => {} to be called when each event is received
   * @param {function(payload):string=} options.messageFn
   */
  addRecorder(options = {}) {
    const {
      event,
      eventName,
      messageFn = () => `Recorded ${eventName}`,
      callback,
    } = options;

    const promise = new Promise(resolve => {
      const unsubscribe = event(payload => {
        info(messageFn(payload));
        this.events.push({ eventName, payload, index: this.events.length });
        callback?.({ eventName, payload, index: this.events.length - 1 });
        if (this.events.length > this.total) {
          this.subscriptions.delete(unsubscribe);
          unsubscribe();
          resolve(this.events);
        }
      });
      this.subscriptions.add(unsubscribe);
    });

    this.promises.add(promise);
  }

  /**
   * Register a promise to await while recording the timeline. The returned
   * callback resolves the registered promise and adds `step`
   * to the timeline, along with an associated payload, if provided.
   *
   * @param {string} step
   * @return {Function} callback
   */
  addPromise(step) {
    let callback;
    const promise = new Promise(resolve => {
      callback = value => {
        resolve();
        info(`Recorded ${step}`);
        this.events.push({
          eventName: step,
          payload: value,
          index: this.events.length,
        });
        return value;
      };
    });

    this.promises.add(promise);
    return callback;
  }

  /**
   * Record events until we hit the timeout or the expected total is exceeded.
   *
   * @param {number=} timeout
   *     Timeout in milliseconds. Defaults to 1000.
   *
   * @return {Array<{ eventName, payload, index }>} Recorded events
   */
  async record(timeout = TIMEOUT_EVENTS) {
    await Promise.race([Promise.all(this.promises), timeoutPromise(timeout)]);
    for (const unsubscribe of this.subscriptions) {
      unsubscribe();
    }
    return this.events;
  }

  /**
   * Filter events based on predicate
   *
   * @param {Function} predicate
   *
   * @return {Array<{ eventName, payload, index }>}
   *     The list of events matching the filter.
   */
  filter(predicate) {
    return this.events.filter(predicate);
  }

  /**
   * Find first occurrence of the given event.
   *
   * @param {string} eventName
   *
   * @return {{ eventName, payload, index }} The event, if any.
   */
  findEvent(eventName) {
    const event = this.events.find(el => el.eventName == eventName);
    if (event) {
      return event;
    }
    return {};
  }

  /**
   * Find given events.
   *
   * @param {string} eventName
   *
   * @return {Array<{ eventName, payload, index }>}
   *     The events, if any.
   */
  findEvents(eventName) {
    return this.events.filter(event => event.eventName == eventName);
  }

  /**
   * Find index of first occurrence of the given event.
   *
   * @param {string} eventName
   *
   * @return {number} The event index, -1 if not found.
   */
  indexOf(eventName) {
    const event = this.events.find(el => el.eventName == eventName);
    if (event) {
      return event.index;
    }
    return -1;
  }
}