Debian Codegraph @

pkg/base1/test-framed-cache.js

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import cockpit from "cockpit";
3 import QUnit from "qunit-tests";
4
5 /* Top level window */
6 function parent_window(assert) {
7 const done = assert.async();
8 assert.expect(12);
9 window.assert = assert; // for the child frame
10
11 document.getElementById("qunit-header").textContent = "Cockpit Parent Frame";
12 let count = 0;
13 let child_done = false;
14
15 function maybe_done () {
16 if (child_done && count == 2) {
17 child_done = null;
18 done();
19 }
20 }
21
22 window.addEventListener("message", event => {
23 if (event.data == "child-done") {
24 child_done = true;
25 window.setTimeout(maybe_done, 0);
26 }
27 });
28
29 function provider(result, key) {
30 assert.equal(key, "cross-frame-cache", "parent provider got right key");
31 assert.equal(typeof result, "function", "parent provider got result function");
32 result({ myobject: "value" });
33 return {
34 close: function() {}
35 };
36 }
37
38 function consumer(value, key) {
39 count++;
40 assert.equal(key, "cross-frame-cache", "parent consumer got right key");
41 if (count === 1) {
42 assert.equal(value.myobject, "value", "parent consumer got parent value");
43 } else if (count === 2) {
44 assert.equal(value.myobject, "value2", "parent consumer got child value");
45 }
46 maybe_done();
47 }
48
49 cockpit.cache("cross-frame-cache", provider, consumer, 'parent');
50 const iframe = document.createElement("iframe");
51 iframe.setAttribute("name", "cockpit1:blah");
52 iframe.setAttribute("src", window.location.href + "?sub");
53 document.body.appendChild(iframe);
54 }
55
56 function child_frame() {
57 const assert = window.parent.assert;
58
59 let count = 0;
60
61 function provider(result, key) {
62 assert.equal(key, "cross-frame-cache", "child provider got right key");
63 assert.equal(typeof result, "function", "child provider got result function");
64 const timer = window.setTimeout(() => {
65 result({ myobject: "value2" });
66 window.clearTimeout(timer);
67 }, 1000);
68 return {
69 close: () => undefined,
70 };
71 }
72
73 function consumer(value, key) {
74 count++;
75 assert.equal(key, "cross-frame-cache", "child consumer got right key");
76 if (count === 1) {
77 assert.equal(value.myobject, "value", "child consumer got parent value");
78 cache.claim();
79 } else if (count == 2) {
80 assert.equal(value.myobject, "value2", "child consumer got child value");
81 window.parent.postMessage("child-done", "*");
82 }
83 }
84
85 const cache = cockpit.cache("cross-frame-cache", provider, consumer, 'child');
86 }
87
88 if (window.parent === window) {
89 QUnit.test("framed cache", parent_window);
90 QUnit.start();
91 } else {
92 child_frame();
93 }