| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
import cockpit from "cockpit"; |
| 3 |
import QUnit from "qunit-tests"; |
| 4 |
|
| 5 |
QUnit.test("basic", function (assert) { |
| 6 |
const done = assert.async(); |
| 7 |
assert.expect(4); |
| 8 |
|
| 9 |
const channel = cockpit.channel({ payload: "echo" }); |
| 10 |
let pass = 0; |
| 11 |
|
| 12 |
const onControl = (ev, options) => { |
| 13 |
if (pass === 0) { |
| 14 |
assert.equal(options.command, "ready", "got ready"); |
| 15 |
pass += 1; |
| 16 |
} else { |
| 17 |
assert.equal(options.command, "done", "got done"); |
| 18 |
channel.close(); |
| 19 |
channel.removeEventListener("control", onControl); |
| 20 |
done(); |
| 21 |
} |
| 22 |
}; |
| 23 |
channel.addEventListener("control", onControl); |
| 24 |
|
| 25 |
channel.addEventListener("message", (ev, payload) => { |
| 26 |
assert.strictEqual(payload, "the payload", "got the right payload"); |
| 27 |
channel.control({ command: "done" }); |
| 28 |
}); |
| 29 |
|
| 30 |
assert.strictEqual(channel.binary, false, "not binary"); |
| 31 |
channel.send("the payload"); |
| 32 |
}); |
| 33 |
|
| 34 |
QUnit.test("binary empty", function (assert) { |
| 35 |
const done = assert.async(); |
| 36 |
assert.expect(2); |
| 37 |
|
| 38 |
const channel = cockpit.channel({ |
| 39 |
payload: "echo", |
| 40 |
binary: true |
| 41 |
}); |
| 42 |
|
| 43 |
const onMessage = (ev, payload) => { |
| 44 |
assert.ok(payload instanceof Uint8Array, "got a byte array"); |
| 45 |
assert.strictEqual(payload.length, 0, "got the right payload"); |
| 46 |
channel.removeEventListener("message", onMessage); |
| 47 |
done(); |
| 48 |
}; |
| 49 |
channel.addEventListener("message", onMessage); |
| 50 |
|
| 51 |
channel.send(""); |
| 52 |
}); |
| 53 |
|
| 54 |
QUnit.test("binary", function (assert) { |
| 55 |
const done = assert.async(); |
| 56 |
assert.expect(3); |
| 57 |
|
| 58 |
const channel = cockpit.channel({ payload: "echo", binary: true }); |
| 59 |
|
| 60 |
const onMessage = (ev, payload) => { |
| 61 |
assert.ok(payload instanceof Uint8Array, "got a byte array"); |
| 62 |
|
| 63 |
const array = []; |
| 64 |
for (let i = 0; i < payload.length; i++) |
| 65 |
array.push(payload[i]); |
| 66 |
assert.deepEqual(array, [0, 1, 2, 3, 4, 5, 6, 7], "got back right data"); |
| 67 |
|
| 68 |
channel.close(); |
| 69 |
channel.removeEventListener("message", onMessage); |
| 70 |
done(); |
| 71 |
}; |
| 72 |
channel.addEventListener("message", onMessage); |
| 73 |
|
| 74 |
const buffer = new ArrayBuffer(8); |
| 75 |
const view = new Uint8Array(buffer); |
| 76 |
for (let i = 0; i < 8; i++) |
| 77 |
view[i] = i; |
| 78 |
|
| 79 |
assert.strictEqual(channel.binary, true, "binary set"); |
| 80 |
channel.send(buffer); |
| 81 |
}); |
| 82 |
|
| 83 |
QUnit.start(); |