-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathhttp-client-test.ts
More file actions
650 lines (569 loc) · 20.8 KB
/
Copy pathhttp-client-test.ts
File metadata and controls
650 lines (569 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/********************************************************************************
* Copyright (c) 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the W3C Software Notice and
* Document License (2015-05-13) which is available at
* https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document.
*
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
********************************************************************************/
/**
* Protocol test suite to test protocol implementations
*/
import { suite, test } from "@testdeck/mocha";
import chai, { expect, should } from "chai";
import * as http from "http";
import { Content, DefaultContent, ContentSerdes, createLoggers, ProtocolServer } from "@node-wot/core";
import { Readable } from "stream";
import { text } from "node:stream/consumers";
import HttpClient from "../src/http-client";
import { HttpForm } from "../src/http";
import express from "express";
import serveStatic from "serve-static";
import { DataSchema, DataSchemaValue, Form } from "wot-typescript-definitions";
import SseStream from "ssestream";
import FakeTimers from "@sinonjs/fake-timers";
// Add spies
import spies from "chai-spies";
import { fail } from "assert";
const { debug } = createLoggers("binding-http", "http-client-test");
// should must be called to augment all variables
should();
chai.use(spies);
interface TestVector {
op: Array<string>;
method?: string;
schema?: DataSchema;
payload?: DataSchemaValue;
headers?: Record<string, string>;
form: Form;
}
const port1 = 30001;
const port2 = 30002;
const port3 = 30001;
const port4 = 30003;
class TestHttpServer implements ProtocolServer {
public readonly scheme: string = "test";
private testVector: TestVector | undefined;
private readonly port: number = 60606;
private readonly address: string | undefined = undefined;
private readonly server: http.Server;
constructor(port?: number, address?: string) {
if (port !== undefined) {
this.port = port;
}
if (address !== undefined) {
this.address = address;
}
this.server = http.createServer((req, res) => {
this.checkRequest(req, res);
});
}
public async start(): Promise<void> {
return new Promise<void>((resolve) => {
this.server.listen(this.port, this.address, resolve);
});
}
public async stop(): Promise<void> {
return new Promise<void>((resolve) => {
this.server.close(() => {
resolve();
});
});
}
/** returns server port number and indicates that server is running when larger than -1 */
public getPort(): number {
const address = this.server?.address();
if (typeof address === "object") {
return address?.port ?? -1;
}
const port = parseInt(address);
if (isNaN(port)) {
return -1;
}
return port;
}
public async expose(thing: unknown): Promise<void> {}
public async destroy(thingId: string): Promise<boolean> {
return false;
}
public setTestVector(vector: TestVector) {
if (vector.op == null) {
throw new Error("No vector op given");
}
if (vector.form["htv:methodName"] == null) {
// TODO also check all array entries
switch (vector.op[0]) {
case "readproperty":
vector.method = "GET";
break;
case "writeproperty":
vector.method = "PUT";
break;
case "observeproperty":
vector.method = "GET";
break;
case "invokeaction":
vector.method = "POST";
break;
case "subscribeevent":
vector.method = "GET";
break;
default:
throw new Error("Unknown op " + vector.op);
}
} else {
vector.method = vector.form["htv:methodName"];
}
this.testVector = vector;
}
private checkRequest(req: http.IncomingMessage, res: http.ServerResponse) {
if (!this.testVector) throw new Error("No test vector given");
expect(req.method).to.equal(this.testVector.method);
expect(req.url).to.equal(new URL(this.testVector.form.href).pathname);
if (this.testVector.headers) {
expect(req.headers).to.include(this.testVector.headers);
}
if (this.testVector.payload !== undefined) {
// load payload
const body: Array<Uint8Array> = [];
req.on("data", (data) => {
body.push(data);
});
req.on("end", () => {
if (!this.testVector) {
chai.assert.fail("No test vector given");
}
let value;
try {
value = ContentSerdes.get().contentToValue(
{ type: ContentSerdes.DEFAULT, body: Buffer.concat(body) },
this.testVector.schema ?? { type: "string" }
);
} catch (err) {
throw new Error("Cannot deserialize client payload");
}
expect(value).to.equal(this.testVector?.payload);
res.end();
});
} else {
res.end();
}
}
}
@suite("HTTP client basic operations")
class HttpClientTest1 {
static httpServer: TestHttpServer;
static async before(): Promise<void> {
HttpClientTest1.httpServer = new TestHttpServer(port1);
await HttpClientTest1.httpServer.start();
expect(HttpClientTest1.httpServer.getPort()).to.equal(port1);
}
static async after(): Promise<void> {
HttpClientTest1.httpServer.stop();
}
private client!: HttpClient;
before() {
this.client = new HttpClient();
}
async after() {
await this.client.stop();
}
@test async "should apply defaults : read with default"() {
// read with defaults
const inputVector1 = {
op: ["readproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
},
headers: {
accept: "application/json",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector1);
const resource = await this.client.readResource(inputVector1.form);
const body = await resource.toBuffer();
body.toString("ascii").should.eql("");
}
@test async "should apply defaults - write with default"() {
// write with defaults
const inputVector2 = {
op: ["writeproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
},
headers: {
"content-type": "application/json",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector2);
await this.client.writeResource(inputVector2.form, new DefaultContent(Readable.from(inputVector2.payload)));
}
@test async "should apply defaults - invoke with default"() {
// invoke with defaults
const inputVector3 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
},
headers: {
"content-type": "application/json",
accept: "application/json",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector3);
const resource = await this.client.invokeResource(
inputVector3.form,
new DefaultContent(Readable.from(inputVector3.payload))
);
expect(resource.type).eql(ContentSerdes.DEFAULT);
const body = await resource.toBuffer();
body.toString("ascii").should.eql("");
}
@test async "should apply form information - read with POST instead of GET"() {
// read with POST instead of GET
const inputVector1 = {
op: ["readproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
"htv:methodName": "POST",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector1);
const resource = await this.client.readResource(inputVector1.form);
expect(resource.type).eql(ContentSerdes.DEFAULT);
const body = await resource.toBuffer();
body.toString("ascii").should.eql("");
}
@test async "should apply form information - read with not default content-type"() {
// read with defaults
const inputVector1 = {
op: ["readproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
contentType: "text/plain",
},
headers: {
accept: "text/plain",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector1);
const resource = await this.client.readResource(inputVector1.form);
const body = await resource.toBuffer();
body.toString("ascii").should.eql("");
}
@test async "should apply form information - read with header override"() {
// read with defaults
const inputVector1 = {
op: ["readproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
"htv:headers": {
"htv:fieldName": "accept",
"htv:fieldValue": "text/plain",
},
},
headers: {
accept: "text/plain",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector1);
const resource = await this.client.readResource(inputVector1.form);
const body = await resource.toBuffer();
body.toString("ascii").should.eql("");
}
@test async "should apply form information - write with POST instead of PUT"() {
// write with POST instead of PUT
const inputVector2 = {
op: ["writeproperty"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
"htv:methodName": "POST",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector2);
await this.client.writeResource(inputVector2.form, new DefaultContent(Readable.from(inputVector2.payload)));
}
@test async "should apply form information - invoke with PUT instead of GET"() {
// invoke with PUT instead of POST
const inputVector3 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
"htv:methodName": "PUT",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector3);
await this.client.invokeResource(inputVector3.form, new DefaultContent(Readable.from(inputVector3.payload)));
}
@test async "should apply form information - invoke with DELETE instead of POST"() {
// invoke with DELETE instead of POST
const inputVector4 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
"htv:methodName": "DELETE",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector4);
await this.client.invokeResource(inputVector4.form);
}
@test async "should apply form information - invoke with not default content-type and no inputs"() {
// invoke with DELETE instead of POST
const inputVector4 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
contentType: "text/plain",
},
headers: {
accept: "text/plain",
},
};
HttpClientTest1.httpServer.setTestVector(inputVector4);
await this.client.invokeResource(inputVector4.form);
}
@test async "should apply form information - invoke with not default content-type"() {
// invoke with DELETE instead of POST
const inputVector4 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
contentType: "text/plain",
},
headers: {
"content-type": "text/plain",
accept: "text/plain",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector4);
await this.client.invokeResource(
inputVector4.form,
new Content("text/plain", Readable.from(inputVector4.payload))
);
}
@test async "should apply form information - invoke with default content-type and response content-type"() {
// invoke with DELETE instead of POST
const inputVector4 = {
op: ["invokeaction"],
form: <HttpForm>{
href: `http://localhost:${port1}/`,
response: {
contentType: "text/plain",
},
},
headers: {
"content-type": "application/json",
accept: "text/plain",
},
payload: "test",
};
HttpClientTest1.httpServer.setTestVector(inputVector4);
await this.client.invokeResource(inputVector4.form, new DefaultContent(Readable.from(inputVector4.payload)));
}
}
@suite("HTTP client subscriptions")
class HttpClientTest2 {
@test "should register to sse server and get server sent event"(done: Mocha.Done) {
let dataCheckError: string | undefined;
// create sse server
const clock = FakeTimers.install();
const app = express();
app.use(serveStatic(__dirname));
app.get("/sse", function (req: express.Request, res: express.Response) {
debug("new connection");
const sseStream = new SseStream(req);
sseStream.pipe(res);
const pusher = setInterval(() => {
sseStream.write({
data: "Test event",
});
}, 300);
res.on("close", () => {
debug("lost connection");
clearInterval(pusher);
sseStream.unpipe(res);
done();
if (dataCheckError !== undefined) {
fail(dataCheckError);
}
});
});
const server = app.listen(port1, () => {
debug(`server ready on http://localhost:${port1}`);
});
debug("client created");
const client = new HttpClient();
// Subscribe to a resource with sse
const form: HttpForm = {
op: ["observeproperty"],
subprotocol: "sse",
contentType: "application/json",
href: `http://localhost:${port1}/sse`,
};
client
.subscribeResource(form, async (data) => {
if ((await text(data.body)) !== "Test event") {
dataCheckError = "Data should report 'Test event'";
}
client.unlinkResource(form);
server.close();
clock.uninstall();
})
.then(() => {
// subscription is active we can tick the clock
clock.tick(400);
});
}
@test.skip "should call error() and complete() on subscription with no connection"(done: () => void) {
const client = new HttpClient();
// Subscribe to an event
const form: HttpForm = {
op: ["subscribeevent"],
href: "http://404.localhost",
};
const errorSpy = chai.spy();
const completeSpy = chai.spy(() => {
// eslint-disable-next-line no-unused-expressions
errorSpy.should.have.been.called.once;
// eslint-disable-next-line no-unused-expressions
completeSpy.should.have.been.called.once;
done();
});
client.subscribeResource(
form,
(data) => {
/** */
},
errorSpy,
completeSpy
);
// Note: fails with
// Uncaught FetchError: request to http://404.localhost/ failed, reason: getaddrinfo ENOTFOUND 404.localhost
}
@test.skip "should call error() and complete() on subscription with wrong URL"(done: Mocha.Done) {
const client = new HttpClient();
// Subscribe to an event
const form: HttpForm = {
op: ["subscribeevent"],
href: `http://localhost:${port2}/`,
};
const server = http.createServer((req, res) => {
res.writeHead(404);
res.end();
});
const errorSpy = chai.spy();
const completeSpy = chai.spy(function () {
// eslint-disable-next-line no-unused-expressions
errorSpy.should.have.been.called.once;
// eslint-disable-next-line no-unused-expressions
completeSpy.should.have.been.called.once;
done();
server.close();
});
server.listen(port2, "0.0.0.0");
server.once("listening", () => {
client.subscribeResource(
form,
(data) => {
/** */
},
errorSpy,
completeSpy
);
});
// Note: fails with
// Uncaught Error: Client error: Not Found
// at HttpClient.checkFetchResponse (src\http-client-impl.ts:430:19)
// at LongPollingSubscription.<anonymous> (src\subscription-protocols.ts:65:54)
}
@test "should subscribe successfully"(done: Mocha.Done) {
const client = new HttpClient();
// Subscribe to an event
const form: HttpForm = {
op: ["subscribeevent"],
href: `http://localhost:${port3}/`,
};
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end();
});
const subscribeSpy = chai.spy();
const eventSpy = chai.spy(async function (data: Content) {
// eslint-disable-next-line no-unused-expressions
eventSpy.should.have.been.called.once;
// eslint-disable-next-line no-unused-expressions
subscribeSpy.should.have.been.called.once;
server.close();
done();
});
server.listen(port3, "0.0.0.0");
server.once("listening", () => {
client
.subscribeResource(
form,
eventSpy,
() => {
/** */
},
() => {
/** */
}
)
.then(subscribeSpy);
});
}
@test "should unsubscribe successfully"(done: Mocha.Done) {
const client = new HttpClient();
// Subscribe to an event
const form: HttpForm = {
op: ["subscribeevent"],
href: `http://localhost:${port4}/`,
};
const app = express();
const server = http.createServer({}, app);
app.get("/", async (req, res) => {
res.send("Emitted Event!");
});
const eventSpy = chai.spy();
server.listen(port4, "0.0.0.0");
server.once("listening", async () => {
let counter = 0;
const sub = await client.subscribeResource(
form,
async () => {
counter++;
eventSpy();
if (counter === 2) {
sub.unsubscribe();
// wait 100 ms, so that tests fail if unsubscribe didn't work
await new Promise((resolve) => setTimeout(resolve, 100));
// eslint-disable-next-line no-unused-expressions
eventSpy.should.have.been.called.twice;
server.close();
done();
} else if (counter > 2) {
server.close();
done(new Error("unsubscribe didn't work as expected"));
}
},
() => {
/** */
},
() => {
/** */
}
);
});
}
}