| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
import { Channel, ChannelPayload } from "../lib/cockpit/channel"; |
| 3 |
import QUnit from "qunit-tests"; |
| 4 |
|
| 5 |
const QS_REQUEST = "HEAD /mock/qs HTTP/1.0\r\nHOST: localhost\r\n\r\n"; |
| 6 |
|
| 7 |
const test_server = { |
| 8 |
address: window.location.hostname, |
| 9 |
port: parseInt(window.location.port, 10) |
| 10 |
}; |
| 11 |
|
| 12 |
function read_data<P extends ChannelPayload>(channel: Channel<P>): Promise<P> { |
| 13 |
return new Promise(resolve => { |
| 14 |
const disconnect = channel.on('data', data => { |
| 15 |
disconnect(); |
| 16 |
resolve(data); |
| 17 |
}); |
| 18 |
}); |
| 19 |
} |
| 20 |
|
| 21 |
QUnit.test("TCP stream port without a service", async assert => { |
| 22 |
const channel = new Channel({ payload: "stream", address: "127.0.0.99", port: 2222 }); |
| 23 |
|
| 24 |
await assert.rejects( |
| 25 |
channel.wait(), |
| 26 |
{ problem: "not-found", message: "[Errno 111] Connect call failed ('127.0.0.99', 2222)" }, |
| 27 |
"channel should have failed with not-found" |
| 28 |
); |
| 29 |
}); |
| 30 |
|
| 31 |
QUnit.test("TCP stream address without a port", async assert => { |
| 32 |
const channel = new Channel({ payload: "stream", address: "127.0.0.99" }); |
| 33 |
|
| 34 |
await assert.rejects( |
| 35 |
channel.wait(), |
| 36 |
{ problem: "protocol-error", message: 'no "port" or "unix" or other address option for channel' }, |
| 37 |
"channel should have failed with protocol-error" |
| 38 |
); |
| 39 |
}); |
| 40 |
|
| 41 |
QUnit.test("TCP text stream", async assert => { |
| 42 |
const channel = new Channel({ |
| 43 |
payload: "stream", |
| 44 |
address: test_server.address, |
| 45 |
port: test_server.port |
| 46 |
}); |
| 47 |
|
| 48 |
channel.send_data(QS_REQUEST); |
| 49 |
|
| 50 |
const data = await read_data(channel); |
| 51 |
assert.ok(data.startsWith("HTTP/1.1 200 OK"), "got successful HTTP response"); |
| 52 |
|
| 53 |
channel.close(); |
| 54 |
await channel.wait(); |
| 55 |
}); |
| 56 |
|
| 57 |
QUnit.test("TCP binary stream", async assert => { |
| 58 |
const channel = new Channel<Uint8Array>({ |
| 59 |
payload: "stream", |
| 60 |
binary: true, |
| 61 |
address: test_server.address, |
| 62 |
port: test_server.port |
| 63 |
}); |
| 64 |
|
| 65 |
channel.send_data(new TextEncoder().encode(QS_REQUEST)); |
| 66 |
|
| 67 |
const data = await read_data(channel); |
| 68 |
const text = new TextDecoder().decode(data); |
| 69 |
assert.ok(text.startsWith("HTTP/1.1 200 OK"), "got successful HTTP response"); |
| 70 |
|
| 71 |
channel.close(); |
| 72 |
await channel.wait(); |
| 73 |
}); |
| 74 |
|
| 75 |
QUnit.start(); |