Debian Codegraph @

pkg/base1/test-http.js

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import cockpit from "cockpit";
3 import QUnit, { mock_info } from "qunit-tests";
4
5 const EXPECT_MOCK_STREAM = "0 1 2 3 4 5 6 7 8 9 ";
6
7 const test_server = {
8 address: window.location.hostname,
9 port: parseInt(window.location.port, 10)
10 };
11
12 /* Normalize header keys to lowercase for comparison (py-ws returns lowercase) */
13 function lc_headers(headers) {
14 return Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
15 }
16
17 /* Case-insensitive check that expected headers are present (ignores extras like date, server) */
18 function assert_headers_contain(assert, actual, expected, message) {
19 const actual_lc = lc_headers(actual);
20 const expected_lc = lc_headers(expected);
21 const filtered = Object.fromEntries(
22 Object.entries(actual_lc).filter(([k]) => k in expected_lc)
23 );
24 assert.deepEqual(filtered, expected_lc, message);
25 }
26
27 QUnit.test("public api", assert => {
28 const client = cockpit.http("/test");
29 assert.equal(typeof client, "object", "http is an object");
30 assert.equal(typeof client.get, "function", "http.get() is a function");
31 assert.equal(typeof client.post, "function", "http.post() is a function");
32 });
33
34 QUnit.test("simple request", async assert => {
35 const data = await cockpit.http(test_server).get("/pkg/playground/manifest.json");
36 assert.deepEqual(JSON.parse(data), {
37 tools: {
38 index: {
39 label: "Development"
40 }
41 },
42
43 playground: {
44 "react-patterns": {
45 label: "React Patterns"
46 },
47 translate: {
48 label: "Translating"
49 },
50 exception: {
51 label: "Exceptions"
52 },
53 pkgs: {
54 label: "Packages"
55 },
56 preloaded: {
57 label: "Preloaded"
58 },
59 "notifications-receiver": {
60 label: "Notifications Receiver"
61 },
62 metrics: {
63 label: "Monitoring"
64 },
65 plot: {
66 label: "Plots"
67 },
68 remote: {
69 label: "Remote channel"
70 },
71 service: {
72 label: "Generic Service Monitor"
73 },
74 speed: {
75 label: "Speed Tests"
76 },
77 terminal: {
78 label: "Terminal"
79 },
80 journal: {
81 label: "Logs Box"
82 },
83 test: {
84 label: "Playground"
85 },
86 packagemanager: {
87 label: "PackageManager (install dialog)"
88 },
89 dialog: {
90 label: "Dialog Implementation Convenience Kit"
91 },
92 },
93 preload: ["preloaded"],
94 "content-security-policy": "img-src 'self' data:"
95 }, "returned right data");
96 });
97
98 QUnit.test("with params", async assert => {
99 const resp = await cockpit.http(test_server)
100 .get("/mock/qs", { key: "value", name: "Scruffy the Janitor" });
101 assert.equal(resp, "key=value&name=Scruffy+the+Janitor", "right query string");
102 });
103
104 QUnit.test("not found", async assert => {
105 let response_status;
106 try {
107 await cockpit.http(test_server)
108 .get("/not/found")
109 .response(status => { response_status = status });
110 assert.ok(false, "should not have succeeded");
111 } catch (ex) {
112 assert.equal(response_status, 404, "status code");
113 assert.strictEqual(ex.problem, null, "mapped to cockpit code");
114 assert.strictEqual(ex.status, 404, "has status code");
115 assert.equal(ex.message, "Not Found", "has reason");
116 }
117 });
118
119 QUnit.test("streaming", async assert => {
120 let num_chunks = 0;
121 let got = "";
122 await cockpit.http(test_server)
123 .get("/mock/stream")
124 .stream(resp => {
125 got += resp;
126 num_chunks++;
127 });
128 assert.true(num_chunks > 1, "got at least two chunks");
129 assert.true(num_chunks <= 10, "got at most 10 chunks");
130 assert.equal(got, EXPECT_MOCK_STREAM, "stream got right data");
131 });
132
133 QUnit.test("split UTF8 frames", async assert => {
134 const resp = await cockpit.http(test_server).get("/mock/split-utf8");
135 assert.equal(resp, "initialfirst half é second halffinal", "correct response");
136 });
137
138 QUnit.test("truncated UTF8 frame", async assert => {
139 let received = "";
140 try {
141 await cockpit.http(test_server)
142 .get("/mock/truncated-utf8")
143 .stream(block => { received += block });
144 assert.ok(false, "should not have succeeded");
145 } catch (ex) {
146 // does not include the first byte of é
147 assert.equal(received, "initialfirst half ", "received expected data");
148 assert.equal(ex.problem, "protocol-error", "error code");
149 assert.ok(ex.message.includes("unexpected end of data"), ex.message);
150 }
151 });
152
153 QUnit.test("binary data", async assert => {
154 const data = await cockpit.http({ ...test_server, binary: true }).get("/mock/binary-data");
155 assert.deepEqual(data, new Uint8Array([255, 1, 255, 2]));
156 });
157
158 QUnit.test("invalid UTF-8", async assert => {
159 await assert.rejects(
160 cockpit.http(test_server).get("/mock/binary-data"),
161 ex => ex.problem == "protocol-error" && ex.message.includes("can't decode byte 0xff"),
162 "rejects non-UTF-8 data on text channel");
163 });
164
165 QUnit.test("close", async assert => {
166 let at = 0;
167 const http = cockpit.http(test_server);
168
169 try {
170 await http.get("/mock/stream")
171 .stream(resp => {
172 at += 1;
173 assert.equal(resp, "0 ", "first stream part");
174 http.close("bad-boy");
175 });
176 assert.ok(false, "should not have succeeded");
177 } catch (ex) {
178 assert.equal(ex.problem, "bad-boy", "right problem");
179 }
180 assert.equal(at, 1, "stream got cancelled");
181 });
182
183 QUnit.test("close all", async assert => {
184 const http = cockpit.http(test_server);
185
186 let at = 0;
187 try {
188 await http.get("/mock/stream")
189 .stream(resp => {
190 at += 1;
191 assert.equal(resp, "0 ", "first stream part");
192 http.close("bad-boy");
193 });
194 assert.ok(false, "should not have succeeded");
195 } catch (ex) {
196 assert.equal(ex.problem, "bad-boy", "right problem");
197 }
198 assert.equal(at, 1, "stream got cancelled");
199 http.close("closed"); // This should be a no-op now
200 });
201
202 QUnit.test("headers", async assert => {
203 let status, headers;
204 await cockpit.http(test_server)
205 .get("/mock/headers", null, { Header1: "booo", Header2: "yay value" })
206 .response((s, h) => { status = s; headers = h });
207 assert.equal(status, 201, "status code");
208 assert_headers_contain(assert, headers, {
209 Header1: "booo",
210 Header2: "yay value",
211 Header3: "three",
212 Header4: "marmalade",
213 "Referrer-Policy": "no-referrer",
214 "X-DNS-Prefetch-Control": "off",
215 "X-Content-Type-Options": "nosniff",
216 "X-Frame-Options": "sameorigin",
217 "Cross-Origin-Resource-Policy": "same-origin",
218 }, "got back headers");
219 });
220
221 QUnit.test("escape host header", async assert => {
222 let status, headers;
223 await cockpit.http(test_server)
224 .get("/mock/host", null, { })
225 .response((s, h) => { status = s; headers = h });
226 assert.equal(status, 201, "status code");
227 assert.deepEqual(lc_headers(headers).host, window.location.host, "got back escaped headers");
228 });
229
230 QUnit.test("connection headers", async assert => {
231 let status, headers;
232 await cockpit.http({ port: test_server.port, headers: { Header1: "booo", Header2: "not this" } })
233 .get("/mock/headers", null, { Header2: "yay value", Header0: "extra" })
234 .response((s, h) => { status = s; headers = h });
235 assert.equal(status, 201, "status code");
236 assert_headers_contain(assert, headers, {
237 Header0: "extra",
238 Header1: "booo",
239 Header2: "yay value",
240 Header3: "three",
241 Header4: "marmalade",
242 "Referrer-Policy": "no-referrer",
243 "X-DNS-Prefetch-Control": "off",
244 "X-Content-Type-Options": "nosniff",
245 "X-Frame-Options": "sameorigin",
246 "Cross-Origin-Resource-Policy": "same-origin",
247 }, "got back combined headers");
248 });
249
250 QUnit.test("http promise recursive", assert => {
251 const promise = cockpit.http(test_server).get("/");
252
253 const target = { };
254 const promise2 = promise.promise(target);
255 assert.strictEqual(promise2, target, "used target");
256 assert.equal(typeof promise2.done, "function", "promise2.done()");
257 assert.equal(typeof promise2.promise, "function", "promise2.promise()");
258 assert.equal(typeof promise2.input, "function", "promise2.input()");
259
260 const promise3 = promise2.promise();
261 assert.equal(typeof promise3.done, "function", "promise3.done()");
262 assert.equal(typeof promise3.promise, "function", "promise3.promise()");
263 assert.equal(typeof promise3.input, "function", "promise3.input()");
264 });
265
266 QUnit.test("no dns address", async assert => {
267 await assert.rejects(cockpit.http({ port: 8080, address: "the-other-host.example.com" }).get("/"),
268 /* Unfortunately we can see either of these errors when running unit tests */
269 ex => { return ex.problem === "timeout" || ex.problem === "not-found" });
270 });
271
272 QUnit.test("address with params", async assert => {
273 const resp = await cockpit.http(test_server)
274 .get("/mock/qs", { key: "value", name: "Scruffy the Janitor" });
275 assert.equal(resp, "key=value&name=Scruffy+the+Janitor", "right query string");
276 });
277
278 QUnit.test("HEAD method", async assert => {
279 await assert.rejects(
280 cockpit.http(test_server).get("/mock/headonly"),
281 ex => ex.status == 400,
282 "rejects GET request on /headonly path");
283
284 const InputData = "some chars";
285
286 let status, headers;
287 const data = await cockpit.http(test_server).request({
288 path: "/mock/headonly",
289 method: "HEAD",
290 headers: { InputData },
291 body: "",
292 })
293 .response((s, h) => { status = s; headers = h });
294 assert.equal(status, 200);
295 assert.equal(lc_headers(headers).inputdatalength, InputData.length);
296 assert.equal(data, "");
297 });
298
299 QUnit.test("wrong options", async assert => {
300 await assert.rejects(
301 cockpit.http({}).get("/"),
302 // unfortunately cockpit.js does not propagate the detailed error message
303 ex => ex.problem == "protocol-error" && ex.status == undefined,
304 "rejects request without port or unix option");
305
306 await assert.rejects(
307 cockpit.http({ port: 1234, unix: "/nonexisting/socket" }).get("/"),
308 ex => ex.problem == "protocol-error" && ex.status == undefined,
309 "rejects request with both port and unix option");
310
311 await assert.rejects(
312 cockpit.http({ unix: "/nonexisting/socket", tls: {} }).get("/"),
313 ex => ex.problem == "protocol-error" && ex.status == undefined,
314 "rejects request with both unix and tls option");
315 });
316
317 QUnit.test("parallel stress test", async assert => {
318 // This is way too slow under valgrind
319 if (await mock_info("skip_slow_tests")) {
320 assert.ok(true, "skipping on python bridge, not implemented");
321 return;
322 }
323
324 assert.timeout(6000);
325
326 const num = 1000;
327
328 const promises = [];
329 for (let i = 0; i < num; ++i)
330 promises.push(cockpit.http(test_server).get("/mock/stream"));
331
332 const results = await Promise.all(promises);
333 assert.equal(results.length, num, "got correct number of responses");
334 for (let i = 0; i < num; ++i)
335 assert.equal(results[i], EXPECT_MOCK_STREAM);
336 });
337
338 QUnit.start();