Debian Codegraph @

pkg/base1/test-websocket.js

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import cockpit from "cockpit";
3 import QUnit from "qunit-tests";
4
5 QUnit.test("external channel websocket", function (assert) {
6 const done = assert.async();
7 assert.expect(3);
8
9 const query = window.btoa(JSON.stringify({
10 payload: "websocket-stream1",
11 address: "localhost",
12 port: parseInt(window.location.port, 10),
13 path: "/cockpit/echosocket/",
14 }));
15
16 let count = 0;
17 const ws = new WebSocket("ws://" + window.location.host + "/cockpit/channel/" +
18 cockpit.transport.csrf_token + '?' + query);
19 ws.onopen = function() {
20 assert.ok(true, "websocket is open");
21 ws.send("oh marmalade");
22 };
23 ws.onerror = function() {
24 assert.ok(false, "websocket error");
25 };
26 ws.onmessage = function(ev) {
27 if (count === 0) {
28 assert.equal(ev.data, "OH MARMALADE", "got payload");
29 ws.send("another test");
30 count += 1;
31 } else {
32 assert.equal(ev.data, "ANOTHER TEST", "got payload again");
33 ws.close(1000);
34 }
35 };
36 ws.onclose = function(ev) {
37 done();
38 };
39 });
40
41 QUnit.test("bad channel options websocket", function (assert) {
42 const done = assert.async();
43 const payloads = [
44 window.btoa(JSON.stringify({
45 payload: "websocket-stream1",
46 address: "localhost",
47 port: 'bad',
48 path: "/cockpit/echosocket/",
49 })),
50 window.btoa(JSON.stringify({
51 payload: "websocket-stream1",
52 address: "localhost",
53 port: parseInt(window.location.port, 10),
54 }))
55 ];
56 assert.expect(payloads.length * 3);
57 function step() {
58 const query = payloads.shift();
59 const url = "ws://" + window.location.host + "/cockpit/channel/" +
60 cockpit.transport.csrf_token + '?' + query;
61 console.log(url);
62 let ws = new WebSocket(url);
63 ws.onopen = function() {
64 assert.ok(true, "websocket opened");
65 };
66 ws.onclose = function(ev) {
67 console.log(ev);
68 assert.ok(ev.wasClean, url + "websocket unclean shutdown");
69 assert.notEqual(ev.code, 0, url + "websocket error code");
70 ws = null;
71 if (payloads.length === 0)
72 done();
73 else
74 step();
75 };
76 }
77 step();
78 });
79
80 cockpit.transport.wait(function() {
81 QUnit.start();
82 });