deno.land / std@0.166.0 / streams / conversion_test.ts

conversion_test.ts
نووسراو ببینە
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { assert, assertEquals, assertRejects } from "../testing/asserts.ts";import { delay } from "../async/delay.ts";import { copy, iterateReader, iterateReaderSync, readableStreamFromIterable, readableStreamFromReader, readAll, readAllSync, readerFromIterable, readerFromStreamReader, toTransformStream, writableStreamFromWriter, writeAll, writeAllSync, writerFromStreamWriter,} from "./conversion.ts";import { Buffer } from "../io/buffer.ts";import { concat, copy as copyBytes } from "../bytes/mod.ts";
function repeat(c: string, bytes: number): Uint8Array { assertEquals(c.length, 1); const ui8 = new Uint8Array(bytes); ui8.fill(c.charCodeAt(0)); return ui8;}
Deno.test("[streams] readerFromIterable()", async function () { const reader = readerFromIterable((function* () { const encoder = new TextEncoder(); for (const string of ["hello", "deno", "foo"]) { yield encoder.encode(string); } })());
const readStrings = []; const decoder = new TextDecoder(); const p = new Uint8Array(4); while (true) { const n = await reader.read(p); if (n == null) { break; } readStrings.push(decoder.decode(p.slice(0, n))); } assertEquals(readStrings, ["hell", "o", "deno", "foo"]);});
Deno.test("[streams] writerFromStreamWriter()", async function () { const written: string[] = []; const chunks: string[] = ["hello", "deno", "land"]; const writableStream = new WritableStream({ write(chunk) { const decoder = new TextDecoder(); written.push(decoder.decode(chunk)); }, });
const encoder = new TextEncoder(); const writer = writerFromStreamWriter(writableStream.getWriter());
for (const chunk of chunks) { const n = await writer.write(encoder.encode(chunk)); // stream writers always write all the bytes assertEquals(n, chunk.length); }
assertEquals(written, chunks);});
Deno.test("[streams] readerFromStreamReader()", async function () { const chunks: string[] = ["hello", "deno", "land"]; const expected = chunks.slice(); const readChunks: Uint8Array[] = []; const readableStream = new ReadableStream({ pull(controller) { const encoder = new TextEncoder(); const chunk = chunks.shift(); if (!chunk) return controller.close(); controller.enqueue(encoder.encode(chunk)); }, });
const decoder = new TextDecoder(); const reader = readerFromStreamReader(readableStream.getReader());
let i = 0;
while (true) { const b = new Uint8Array(1024); const n = await reader.read(b);
if (n === null) break;
readChunks.push(b.subarray(0, n)); assert(i < expected.length);
i++; }
assertEquals( expected, readChunks.map((chunk) => decoder.decode(chunk)), );});
Deno.test("[streams] readerFromStreamReader() big chunks", async function () { const bufSize = 1024; const chunkSize = 3 * bufSize; const writer = new Buffer();
// A readable stream can enqueue chunks bigger than Copy bufSize // Reader returned by toReader should enqueue exceeding bytes const chunks: string[] = [ "a".repeat(chunkSize), "b".repeat(chunkSize), "c".repeat(chunkSize), ]; const expected = chunks.slice(); const readableStream = new ReadableStream({ pull(controller) { const encoder = new TextEncoder(); const chunk = chunks.shift(); if (!chunk) return controller.close();
controller.enqueue(encoder.encode(chunk)); }, });
const reader = readerFromStreamReader(readableStream.getReader()); const n = await copy(reader, writer, { bufSize });
const expectedWritten = chunkSize * expected.length; assertEquals(n, chunkSize * expected.length); assertEquals(writer.length, expectedWritten);});
Deno.test("[streams] readerFromStreamReader() irregular chunks", async function () { const bufSize = 1024; const chunkSize = 3 * bufSize; const writer = new Buffer();
// A readable stream can enqueue chunks bigger than Copy bufSize // Reader returned by toReader should enqueue exceeding bytes const chunks: Uint8Array[] = [ repeat("a", chunkSize), repeat("b", chunkSize + 253), repeat("c", chunkSize + 8), ]; const expected = new Uint8Array( chunks .slice() .map((chunk) => [...chunk]) .flat(), ); const readableStream = new ReadableStream({ pull(controller) { const chunk = chunks.shift(); if (!chunk) return controller.close();
controller.enqueue(chunk); }, });
const reader = readerFromStreamReader(readableStream.getReader());
const n = await copy(reader, writer, { bufSize }); assertEquals(n, expected.length); assertEquals(expected, writer.bytes());});
class MockWriterCloser implements Deno.Writer, Deno.Closer { chunks: Uint8Array[] = []; closeCall = 0;
write(p: Uint8Array): Promise<number> { if (this.closeCall) { throw new Error("already closed"); } if (p.length) { this.chunks.push(p); } return Promise.resolve(p.length); }
close() { this.closeCall++; }}
Deno.test("[streams] writableStreamFromWriter()", async function () { const written: string[] = []; const chunks: string[] = ["hello", "deno", "land"]; const decoder = new TextDecoder();
// deno-lint-ignore require-await async function write(p: Uint8Array): Promise<number> { written.push(decoder.decode(p)); return p.length; }
const writableStream = writableStreamFromWriter({ write });
const encoder = new TextEncoder(); const streamWriter = writableStream.getWriter(); for (const chunk of chunks) { await streamWriter.write(encoder.encode(chunk)); }
assertEquals(written, chunks);});
Deno.test("[streams] writableStreamFromWriter() - calls close on close", async function () { const written: string[] = []; const chunks: string[] = ["hello", "deno", "land"]; const decoder = new TextDecoder();
const writer = new MockWriterCloser(); const writableStream = writableStreamFromWriter(writer);
const encoder = new TextEncoder(); const streamWriter = writableStream.getWriter(); for (const chunk of chunks) { await streamWriter.write(encoder.encode(chunk)); } await streamWriter.close();
for (const chunk of writer.chunks) { written.push(decoder.decode(chunk)); }
assertEquals(written, chunks); assertEquals(writer.closeCall, 1);});
Deno.test("[streams] writableStreamFromWriter() - calls close on abort", async function () { const written: string[] = []; const chunks: string[] = ["hello", "deno", "land"]; const decoder = new TextDecoder();
const writer = new MockWriterCloser(); const writableStream = writableStreamFromWriter(writer);
const encoder = new TextEncoder(); const streamWriter = writableStream.getWriter(); for (const chunk of chunks) { await streamWriter.write(encoder.encode(chunk)); } await streamWriter.abort();
for (const chunk of writer.chunks) { written.push(decoder.decode(chunk)); }
assertEquals(written, chunks); assertEquals(writer.closeCall, 1);});
Deno.test("[streams] writableStreamFromWriter() - doesn't call close with autoClose false", async function () { const written: string[] = []; const chunks: string[] = ["hello", "deno", "land"]; const decoder = new TextDecoder();
const writer = new MockWriterCloser(); const writableStream = writableStreamFromWriter(writer, { autoClose: false });
const encoder = new TextEncoder(); const streamWriter = writableStream.getWriter(); for (const chunk of chunks) { await streamWriter.write(encoder.encode(chunk)); } await streamWriter.close();
for (const chunk of writer.chunks) { written.push(decoder.decode(chunk)); }
assertEquals(written, chunks); assertEquals(writer.closeCall, 0);});
Deno.test("[streams] readableStreamFromIterable() array", async function () { const strings: string[] = ["hello", "deno", "land"]; const encoder = new TextEncoder(); const readableStream = readableStreamFromIterable( strings.map((s) => encoder.encode(s)), );
const readStrings = []; const decoder = new TextDecoder(); for await (const chunk of readableStream) { readStrings.push(decoder.decode(chunk)); }
assertEquals(readStrings, strings);});
Deno.test("[streams] readableStreamFromIterable() generator", async function () { const strings: string[] = ["hello", "deno", "land"]; const readableStream = readableStreamFromIterable((function* () { const encoder = new TextEncoder(); for (const string of strings) { yield encoder.encode(string); } })());
const readStrings = []; const decoder = new TextDecoder(); for await (const chunk of readableStream) { readStrings.push(decoder.decode(chunk)); }
assertEquals(readStrings, strings);});
Deno.test("[streams] readableStreamFromIterable() cancel", async function () { let generatorError = null; const readable = readableStreamFromIterable(async function* () { try { yield "foo"; } catch (error) { generatorError = error; } }()); const reader = readable.getReader(); assertEquals(await reader.read(), { value: "foo", done: false }); const cancelReason = new Error("Cancelled by consumer."); await reader.cancel(cancelReason); assertEquals(generatorError, cancelReason);});
Deno.test({ name: "[streams] toTransformStream()", async fn() { const readable = readableStreamFromIterable([0, 1, 2]) .pipeThrough(toTransformStream(async function* (src) { for await (const i of src) { yield i * 100; } }));
const res = []; for await (const i of readable) { res.push(i); } assertEquals(res, [0, 100, 200]); },});
Deno.test({ name: "[streams] toTransformStream() Pass iterable instead of asyncIterable", async fn() { const readable = readableStreamFromIterable([0, 1, 2]) .pipeThrough(toTransformStream(function* (_src) { yield 0; yield 100; yield 200; }));
const res = []; for await (const i of readable) { res.push(i); } assertEquals(res, [0, 100, 200]); },});
Deno.test({ name: "[streams] toTransformStream() Propagate the error from readable 1", async fn(t) { // When data is pipelined in the order of readable1 → generator → readable2, // Propagate the error that occurred in readable1 to generator and readable2. const expectedError = new Error("Error from readable1"); await t.step({ name: "to readable 2", async fn() { // Propagate the error that occurred in readable1 to readable2. let actualError = null;
const readable1 = new ReadableStream({ start(controller) { controller.error(expectedError); // error from readable1 }, }); const readable2 = readable1.pipeThrough( toTransformStream(async function* (src) { for await (const i of src) { yield i; } }), );
try { await readable2.getReader().read(); } catch (error) { actualError = error; // catch error in readable2 }
assertEquals(actualError, expectedError); }, }); await t.step({ name: "to generator", async fn() { // Propagate the error that occurred in readable1 to generator. let actualError = null;
const readable1 = new ReadableStream({ start(controller) { controller.error(expectedError); // error from readable1 }, }); const readable2 = readable1.pipeThrough( toTransformStream(async function* (src) { try { await src.getReader().read(); } catch (error) { actualError = error; // catch error in generator } yield 0; }), );
await readable2.getReader().read(); assertEquals(actualError, expectedError); }, }); },});
Deno.test({ name: "[streams] toTransformStream() Propagate the error from generator", async fn(t) { // When data is pipelined in the order of readable1 → generator → readable2, // Propagate the error that occurred in generator to readable2 and readable1. const expectedError = new Error("Error from generator"); let actualError1: unknown = null; let actualError2: unknown = null;
const readable1 = new ReadableStream({ cancel(reason) { actualError1 = reason; // catch error in readable1 }, }); const readable2 = readable1.pipeThrough( // deno-lint-ignore require-yield toTransformStream(function* () { throw expectedError; // error from generator }), );
try { await readable2.getReader().read(); } catch (error) { actualError2 = error; // catch error in readable2 }
await t.step({ name: "to readable 1", fn() { assertEquals(actualError1, expectedError); }, }); await t.step({ name: "to readable 2", fn() { assertEquals(actualError2, expectedError); }, }); },});
Deno.test({ name: "[streams] toTransformStream() Propagate cancellation from readable 2", async fn(t) { // When data is pipelined in the order of readable1 → generator → readable2, // Propagate the cancellation that occurred in readable2 to readable1 and generator. const expectedError = new Error("Error from readable2"); await t.step({ name: "to readable 1", async fn() { let actualError = null;
const readable1 = new ReadableStream({ cancel(reason) { actualError = reason; // catch error in readable1 }, }); const readable2 = readable1.pipeThrough( toTransformStream(function* () { yield 0; }), );
await readable2.cancel(expectedError); // cancellation from readable2 assertEquals(actualError, expectedError); }, }); await t.step({ name: "to readable 2", async fn() { let actualError = null;
const readable1 = new ReadableStream(); const readable2 = readable1.pipeThrough( toTransformStream(function* () { try { yield 0; } catch (error) { actualError = error; // catch error in generator } }), );
const reader = readable2.getReader(); await reader.read(); await reader.cancel(expectedError); // cancellation from readable2 assertEquals(actualError, expectedError); }, }); },});
Deno.test({ name: "[streams] toTransformStream() Cancel streams with the correct error message", async fn() { const src = readableStreamFromIterable([0, 1, 2]); // deno-lint-ignore require-yield const transform = toTransformStream(function* (src) { src.getReader(); // lock the source stream to cause error at cancel throw new Error("foo"); });
await assertRejects( async () => { for await (const _ of src.pipeThrough(transform)); }, Error, "foo", ); },});
class MockReaderCloser implements Deno.Reader, Deno.Closer { chunks: Uint8Array[] = []; closeCall = 0;
read(p: Uint8Array): Promise<number | null> { if (this.closeCall) { throw new Error("already closed"); } if (p.length === 0) { return Promise.resolve(0); } const chunk = this.chunks.shift(); if (chunk) { const copied = copyBytes(chunk, p); if (copied < chunk.length) { this.chunks.unshift(chunk.subarray(copied)); } return Promise.resolve(copied); } return Promise.resolve(null); }
close() { this.closeCall++; }}
Deno.test("[streams] readableStreamFromReader()", async function () { const encoder = new TextEncoder(); const reader = new Buffer(encoder.encode("hello deno land")); const stream = readableStreamFromReader(reader); const actual: Uint8Array[] = []; for await (const read of stream) { actual.push(read); } const decoder = new TextDecoder(); assertEquals(decoder.decode(concat(...actual)), "hello deno land");});
Deno.test({ name: "[streams] readableStreamFromReader() auto closes closer", async fn() {},});
Deno.test("[streams] readableStreamFromReader() - calls close", async function () { const encoder = new TextEncoder(); const reader = new MockReaderCloser(); reader.chunks = [ encoder.encode("hello "), encoder.encode("deno "), encoder.encode("land"), ]; const stream = readableStreamFromReader(reader); const actual: Uint8Array[] = []; for await (const read of stream) { actual.push(read); } const decoder = new TextDecoder(); assertEquals(decoder.decode(concat(...actual)), "hello deno land"); assertEquals(reader.closeCall, 1);});
Deno.test("[streams] readableStreamFromReader() - doesn't call close with autoClose false", async function () { const encoder = new TextEncoder(); const reader = new MockReaderCloser(); reader.chunks = [ encoder.encode("hello "), encoder.encode("deno "), encoder.encode("land"), ]; const stream = readableStreamFromReader(reader, { autoClose: false }); const actual: Uint8Array[] = []; for await (const read of stream) { actual.push(read); } const decoder = new TextDecoder(); assertEquals(decoder.decode(concat(...actual)), "hello deno land"); assertEquals(reader.closeCall, 0);});
Deno.test("[streams] readableStreamFromReader() - chunkSize", async function () { const encoder = new TextEncoder(); const reader = new MockReaderCloser(); reader.chunks = [ encoder.encode("hello "), encoder.encode("deno "), encoder.encode("land"), ]; const stream = readableStreamFromReader(reader, { chunkSize: 2 }); const actual: Uint8Array[] = []; for await (const read of stream) { actual.push(read); } const decoder = new TextDecoder(); assertEquals(actual.length, 8); assertEquals(decoder.decode(concat(...actual)), "hello deno land"); assertEquals(reader.closeCall, 1);});
// N controls how many iterations of certain checks are performed.const N = 100;let testBytes: Uint8Array | null;
export function init() { if (testBytes == null) { testBytes = new Uint8Array(N); for (let i = 0; i < N; i++) { testBytes[i] = "a".charCodeAt(0) + (i % 26); } }}
Deno.test("testReadAll", async () => { init(); assert(testBytes); const reader = new Buffer(testBytes.buffer); const actualBytes = await readAll(reader); assertEquals(testBytes.byteLength, actualBytes.byteLength); for (let i = 0; i < testBytes.length; ++i) { assertEquals(testBytes[i], actualBytes[i]); }});
Deno.test("testReadAllSync", () => { init(); assert(testBytes); const reader = new Buffer(testBytes.buffer); const actualBytes = readAllSync(reader); assertEquals(testBytes.byteLength, actualBytes.byteLength); for (let i = 0; i < testBytes.length; ++i) { assertEquals(testBytes[i], actualBytes[i]); }});
Deno.test("testwriteAll", async () => { init(); assert(testBytes); const writer = new Buffer(); await writeAll(writer, testBytes); const actualBytes = writer.bytes(); assertEquals(testBytes.byteLength, actualBytes.byteLength); for (let i = 0; i < testBytes.length; ++i) { assertEquals(testBytes[i], actualBytes[i]); }});
Deno.test("testWriteAllSync", () => { init(); assert(testBytes); const writer = new Buffer(); writeAllSync(writer, testBytes); const actualBytes = writer.bytes(); assertEquals(testBytes.byteLength, actualBytes.byteLength); for (let i = 0; i < testBytes.length; ++i) { assertEquals(testBytes[i], actualBytes[i]); }});
Deno.test("iterateReader", async () => { // ref: https://github.com/denoland/deno/issues/2330 const encoder = new TextEncoder();
class TestReader implements Deno.Reader { #offset = 0; #buf: Uint8Array;
constructor(s: string) { this.#buf = new Uint8Array(encoder.encode(s)); }
read(p: Uint8Array): Promise<number | null> { const n = Math.min(p.byteLength, this.#buf.byteLength - this.#offset); p.set(this.#buf.slice(this.#offset, this.#offset + n)); this.#offset += n;
if (n === 0) { return Promise.resolve(null); }
return Promise.resolve(n); } }
const reader = new TestReader("hello world!");
let totalSize = 0; for await (const buf of iterateReader(reader)) { totalSize += buf.byteLength; }
assertEquals(totalSize, 12);});
Deno.test("iterateReader works with slow consumer", async () => { const a = new Uint8Array([97]); const b = new Uint8Array([98]); const iter = iterateReader(readerFromIterable([a, b])); const promises = []; for await (const bytes of iter) { promises.push(delay(10).then(() => bytes)); } assertEquals([a, b], await Promise.all(promises));});
Deno.test("iterateReaderSync", () => { // ref: https://github.com/denoland/deno/issues/2330 const encoder = new TextEncoder();
class TestReader implements Deno.ReaderSync { #offset = 0; #buf: Uint8Array;
constructor(s: string) { this.#buf = new Uint8Array(encoder.encode(s)); }
readSync(p: Uint8Array): number | null { const n = Math.min(p.byteLength, this.#buf.byteLength - this.#offset); p.set(this.#buf.slice(this.#offset, this.#offset + n)); this.#offset += n;
if (n === 0) { return null; }
return n; } }
const reader = new TestReader("hello world!");
let totalSize = 0; for (const buf of iterateReaderSync(reader)) { totalSize += buf.byteLength; }
assertEquals(totalSize, 12);});
Deno.test("iterateReaderSync works with slow consumer", async () => { const a = new Uint8Array([97]); const b = new Uint8Array([98]); const data = [a, b]; const readerSync = { readSync(u8: Uint8Array) { const bytes = data.shift(); if (bytes) { u8.set(bytes); return bytes.length; } return null; }, }; const iter = iterateReaderSync(readerSync); const promises = []; for (const bytes of iter) { promises.push(delay(10).then(() => bytes)); } assertEquals([a, b], await Promise.all(promises));});
std
Deno standard library
GitHub Repositorydenoland/deno_std
GitHub Stars
2458

Version Info

Tagged at
2 months ago