summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/service-workers/service-worker/tentative/static-router/resources/static-router-helpers.sub.js
blob: cf34e98635fb68f9cbc8ccf842f16a71e63e5173 (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
// Helper functions for ServiceWorker static routing API.
//
// test-helpers.sub.js must be loaded before using this.

// Get a dictionary of information recorded inside ServiceWorker.
// It includes:
// - request URL and mode.
// - errors.
//
// See: static-router-sw.js for details.
const get_info_from_worker =
    async worker => {
  const promise = new Promise(function(resolve) {
      var channel = new MessageChannel();
      channel.port1.onmessage = function(msg) { resolve(msg); };
      worker.postMessage({port: channel.port2}, [channel.port2]);
    });
  const message = await promise;

  return message.data;
}

// Reset information stored inside ServiceWorker.
const reset_info_in_worker =
    async worker => {
  const promise = new Promise(function(resolve) {
      var channel = new MessageChannel();
      channel.port1.onmessage = function(msg) { resolve(msg); };
      worker.postMessage({port: channel.port2, reset: true}, [channel.port2]);
    });
  await promise;
}

// Register the ServiceWorker and wait until activated.
// {ruleKey} represents the key of routerRules defined in router-rules.js.
// {swScript} represents the service worker source URL.
const registerAndActivate = async (test, ruleKey, swScript) => {
  if (!swScript) {
    swScript = 'resources/static-router-sw.js'
  }
  const swURL = `${swScript}?key=${ruleKey}`;
  const swScope = 'resources/';
  const reg = await service_worker_unregister_and_register(
    test, swURL, swScope, { type: 'module' });
  add_completion_callback(() => reg.unregister());
  const worker = reg.installing;
  await wait_for_state(test, worker, 'activated');

  return worker;
};

// Create iframe with the given url. This automatically removes the iframe in a
// cleanup.
const createIframe = async (t, url) => {
  const iframe = await with_iframe(url);
  t.add_cleanup(() => iframe.remove());

  return iframe;
};

// Register a service worker, then create an iframe at url.
function iframeTest(url, ruleKey, callback, name) {
  return promise_test(async t => {
    const worker = await registerAndActivate(t, ruleKey);
    const iframe = await createIframe(t, url);
    await callback(t, iframe.contentWindow, worker);
  }, name);
};

function randomString() {
  let result = "";
  for (let i = 0; i < 5; i++) {
    result += String.fromCharCode(97 + Math.floor(Math.random() * 26));
  }
  return result;
}