-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
BufferedStreamTests.cs
551 lines (460 loc) · 19.9 KB
/
BufferedStreamTests.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
namespace System.IO.Tests
{
public class BufferedStream_StreamAsync
{
[Fact]
public static void NullConstructor_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new BufferedStream(null));
}
[Fact]
public static void NegativeBufferSize_Throws_ArgumentOutOfRangeException()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new BufferedStream(new MemoryStream(), -1));
}
[Fact]
public static void ZeroBufferSize_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new BufferedStream(new MemoryStream(), 0));
}
[Fact]
public static void UnderlyingStreamDisposed_Throws_ObjectDisposedException()
{
MemoryStream disposedStream = new MemoryStream();
disposedStream.Dispose();
Assert.Throws<ObjectDisposedException>(() => new BufferedStream(disposedStream));
}
[Fact]
public void UnderlyingStream()
{
var underlyingStream = new MemoryStream();
var bufferedStream = new BufferedStream(underlyingStream);
Assert.Same(underlyingStream, bufferedStream.UnderlyingStream);
}
[Fact]
public void BufferSize()
{
var bufferedStream = new BufferedStream(new MemoryStream(), 1234);
Assert.Equal(1234, bufferedStream.BufferSize);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
[OuterLoop]
public void WriteFromByte_InputSizeLargerThanHalfOfMaxInt_ShouldSuccess()
{
const int InputSize = int.MaxValue / 2 + 1;
byte[] bytes;
try
{
bytes = new byte[InputSize];
}
catch (OutOfMemoryException)
{
return;
}
var writableStream = new WriteOnlyStream();
using (var bs = new BufferedStream(writableStream))
{
bs.Write(bytes, 0, InputSize);
Assert.Equal(InputSize, writableStream.Position);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.Is64BitProcess))]
[OuterLoop]
public void WriteFromSpan_InputSizeLargerThanHalfOfMaxInt_ShouldSuccess()
{
const int InputSize = int.MaxValue / 2 + 1;
byte[] bytes;
try
{
bytes = new byte[InputSize];
}
catch (OutOfMemoryException)
{
return;
}
var writableStream = new WriteOnlyStream();
using (var bs = new BufferedStream(writableStream))
{
bs.Write(new ReadOnlySpan<byte>(bytes));
Assert.Equal(InputSize, writableStream.Position);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ShouldNotFlushUnderlyingStreamIfReadOnly(bool underlyingCanSeek)
{
var underlying = new DelegateStream(
canReadFunc: () => true,
canWriteFunc: () => false,
canSeekFunc: () => underlyingCanSeek,
readFunc: (_, __, ___) => 123,
writeFunc: (_, __, ___) =>
{
throw new NotSupportedException();
},
seekFunc: (_, __) => 123L
);
var wrapper = new CallTrackingStream(underlying);
var buffered = new BufferedStream(wrapper);
buffered.ReadByte();
buffered.Flush();
Assert.Equal(0, wrapper.TimesCalled(nameof(wrapper.Flush)));
await buffered.FlushAsync();
Assert.Equal(0, wrapper.TimesCalled(nameof(wrapper.FlushAsync)));
}
[Theory]
[MemberData(nameof(SetPosMethods))]
public void SetPositionInsideBufferRange_Read_WillNotReadUnderlyingStreamAgain(int sharedBufSize, Action<Stream, long> setPos)
{
var trackingStream = new CallTrackingStream(new MemoryStream());
var bufferedStream = new BufferedStream(trackingStream, sharedBufSize);
bufferedStream.Write(Enumerable.Range(0, sharedBufSize * 2).Select(i => (byte)i).ToArray(), 0, sharedBufSize * 2);
setPos(bufferedStream, 0);
var readBuf = new byte[sharedBufSize - 1];
// First half part verification
byte[] expectedReadBuf = Enumerable.Range(0, sharedBufSize - 1).Select(i => (byte)i).ToArray();
// Call Read() to fill shared read buffer
int readBytes = bufferedStream.Read(readBuf, 0, readBuf.Length);
Assert.Equal(readBuf.Length, readBytes);
Assert.Equal(sharedBufSize - 1, bufferedStream.Position);
Assert.Equal(expectedReadBuf, readBuf);
Assert.Equal(1, trackingStream.TimesCalled(nameof(trackingStream.Read)));
// Set position inside range of shared read buffer
for (int pos = 0; pos < sharedBufSize - 1; pos++)
{
setPos(bufferedStream, pos);
readBytes = bufferedStream.Read(readBuf, pos, readBuf.Length - pos);
Assert.Equal(readBuf.Length - pos, readBytes);
Assert.Equal(sharedBufSize - 1, bufferedStream.Position);
Assert.Equal(expectedReadBuf, readBuf);
// Should not trigger underlying stream's Read()
Assert.Equal(1, trackingStream.TimesCalled(nameof(trackingStream.Read)));
}
Assert.Equal(sharedBufSize - 1, bufferedStream.ReadByte());
Assert.Equal(sharedBufSize, bufferedStream.Position);
// Should not trigger underlying stream's Read()
Assert.Equal(1, trackingStream.TimesCalled(nameof(trackingStream.Read)));
// Second half part verification
expectedReadBuf = Enumerable.Range(sharedBufSize, sharedBufSize - 1).Select(i => (byte)i).ToArray();
// Call Read() to fill shared read buffer
readBytes = bufferedStream.Read(readBuf, 0, readBuf.Length);
Assert.Equal(readBuf.Length, readBytes);
Assert.Equal(sharedBufSize * 2 - 1, bufferedStream.Position);
Assert.Equal(expectedReadBuf, readBuf);
Assert.Equal(2, trackingStream.TimesCalled(nameof(trackingStream.Read)));
// Set position inside range of shared read buffer
for (int pos = 0; pos < sharedBufSize - 1; pos++)
{
setPos(bufferedStream, sharedBufSize + pos);
readBytes = bufferedStream.Read(readBuf, pos, readBuf.Length - pos);
Assert.Equal(readBuf.Length - pos, readBytes);
Assert.Equal(sharedBufSize * 2 - 1, bufferedStream.Position);
Assert.Equal(expectedReadBuf, readBuf);
// Should not trigger underlying stream's Read()
Assert.Equal(2, trackingStream.TimesCalled(nameof(trackingStream.Read)));
}
Assert.Equal(sharedBufSize * 2 - 1, bufferedStream.ReadByte());
Assert.Equal(sharedBufSize * 2, bufferedStream.Position);
// Should not trigger underlying stream's Read()
Assert.Equal(2, trackingStream.TimesCalled(nameof(trackingStream.Read)));
}
public static IEnumerable<object[]> SetPosMethods
{
get
{
var setByPosition = (Action<Stream, long>)((stream, pos) => stream.Position = pos);
var seekFromBegin = (Action<Stream, long>)((stream, pos) => stream.Seek(pos, SeekOrigin.Begin));
var seekFromCurrent = (Action<Stream, long>)((stream, pos) => stream.Seek(pos - stream.Position, SeekOrigin.Current));
var seekFromEnd = (Action<Stream, long>)((stream, pos) => stream.Seek(pos - stream.Length, SeekOrigin.End));
yield return new object[] { 3, setByPosition };
yield return new object[] { 3, seekFromBegin };
yield return new object[] { 3, seekFromCurrent };
yield return new object[] { 3, seekFromEnd };
yield return new object[] { 10, setByPosition };
yield return new object[] { 10, seekFromBegin };
yield return new object[] { 10, seekFromCurrent };
yield return new object[] { 10, seekFromEnd };
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task ConcurrentOperationsAreSerialized()
{
byte[] data = Enumerable.Range(0, 1000).Select(i => unchecked((byte)i)).ToArray();
var mcaos = new ManuallyReleaseAsyncOperationsStream();
var stream = new BufferedStream(mcaos, 1);
var tasks = new Task[4];
for (int i = 0; i < 4; i++)
{
tasks[i] = stream.WriteAsync(data, 250 * i, 250);
}
Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
mcaos.Release();
await Task.WhenAll(tasks);
stream.Position = 0;
for (int i = 0; i < tasks.Length; i++)
{
Assert.Equal(i, stream.ReadByte());
}
}
[Fact]
public void UnderlyingStreamThrowsExceptions()
{
var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream());
Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status);
Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status);
stream.WriteByte(1);
Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status);
}
[ConditionalTheory]
[InlineData(false)]
[InlineData(true)]
public async Task CopyToTest_RequiresFlushingOfWrites(bool copyAsynchronously)
{
if (copyAsynchronously && !PlatformDetection.IsThreadingSupported)
{
throw new SkipTestException(nameof(PlatformDetection.IsThreadingSupported));
}
byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray();
var manualReleaseStream = new ManuallyReleaseAsyncOperationsStream();
var src = new BufferedStream(manualReleaseStream);
src.Write(data, 0, data.Length);
src.Position = 0;
var dst = new MemoryStream();
data[0] = 42;
src.WriteByte(42);
dst.WriteByte(42);
if (copyAsynchronously)
{
Task copyTask = src.CopyToAsync(dst);
manualReleaseStream.Release();
await copyTask;
}
else
{
manualReleaseStream.Release();
src.CopyTo(dst);
}
Assert.Equal(data, dst.ToArray());
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public async Task CopyToTest_ReadBeforeCopy_CopiesAllData(bool copyAsynchronously, bool wrappedStreamCanSeek)
{
byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray();
var wrapped = new ManuallyReleaseAsyncOperationsStream();
wrapped.Release();
wrapped.Write(data, 0, data.Length);
wrapped.Position = 0;
wrapped.SetCanSeek(wrappedStreamCanSeek);
var src = new BufferedStream(wrapped, 100);
src.ReadByte();
var dst = new MemoryStream();
if (copyAsynchronously)
{
await src.CopyToAsync(dst);
}
else
{
src.CopyTo(dst);
}
var expected = new byte[data.Length - 1];
Array.Copy(data, 1, expected, 0, expected.Length);
Assert.Equal(expected, dst.ToArray());
}
}
public class BufferedStream_TestLeaveOpen : TestLeaveOpen
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_CloseTests : CloseTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamWriterWithBufferedStream_FlushTests : FlushTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public void WriteAfterRead_NonSeekableStream_Throws()
{
var wrapped = new WrappedMemoryStream(canRead: true, canWrite: true, canSeek: false, data: new byte[] { 1, 2, 3, 4, 5 });
var s = new BufferedStream(wrapped);
s.Read(new byte[3], 0, 3);
Assert.Throws<NotSupportedException>(() => s.Write(new byte[10], 0, 10));
}
}
public class StreamWriterWithBufferedStream_WriteTests : WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class StreamReaderWithBufferedStream_Tests : StreamReaderTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
protected override Stream GetSmallStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
return new BufferedStream(new MemoryStream(testData));
}
protected override Stream GetLargeStream()
{
byte[] testData = new byte[] { 72, 69, 76, 76, 79 };
List<byte> data = new List<byte>();
for (int i = 0; i < 1000; i++)
{
data.AddRange(testData);
}
return new BufferedStream(new MemoryStream(data.ToArray()));
}
}
public class BinaryWriterWithBufferedStream_Tests : BinaryWriterTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
[Fact]
public override void BinaryWriter_FlushTests()
{
// [] Check that flush updates the underlying stream
using (Stream memstr2 = CreateStream())
using (BinaryWriter bw2 = new BinaryWriter(memstr2))
{
string str = "HelloWorld";
int expectedLength = str.Length + 1; // 1 for 7-bit encoded length
bw2.Write(str);
Assert.Equal(expectedLength, memstr2.Length);
bw2.Flush();
Assert.Equal(expectedLength, memstr2.Length);
}
// [] Flushing a closed writer may throw an exception depending on the underlying stream
using (Stream memstr2 = CreateStream())
{
BinaryWriter bw2 = new BinaryWriter(memstr2);
bw2.Dispose();
Assert.Throws<ObjectDisposedException>(() => bw2.Flush());
}
}
}
public class BinaryWriterWithBufferedStream_WriteByteCharTests : BinaryWriter_WriteByteCharTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
public class BinaryWriterWithBufferedStream_WriteTests : BinaryWriter_WriteTests
{
protected override Stream CreateStream()
{
return new BufferedStream(new MemoryStream());
}
}
internal sealed class ManuallyReleaseAsyncOperationsStream : Stream
{
private readonly MemoryStream _stream = new MemoryStream();
private readonly TaskCompletionSource _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _canSeek = true;
public override bool CanSeek => _canSeek;
public override bool CanRead => _stream.CanRead;
public override bool CanWrite => _stream.CanWrite;
public override long Length => _stream.Length;
public override long Position { get => _stream.Position; set => _stream.Position = value; }
public void SetCanSeek(bool canSeek) => _canSeek = canSeek;
public void Release() => _tcs.SetResult();
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
return await _stream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
await _stream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await _tcs.Task;
await _stream.FlushAsync(cancellationToken);
}
public override void Flush() => _stream.Flush();
public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin);
public override void SetLength(long value) => _stream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count);
}
internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream
{
public override int Read(byte[] buffer, int offset, int count) =>
throw new InvalidOperationException("Exception from ReadAsync");
public override void Write(byte[] buffer, int offset, int count) =>
throw new InvalidOperationException("Exception from ReadAsync");
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
throw new InvalidOperationException("Exception from ReadAsync");
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
throw new InvalidOperationException("Exception from WriteAsync");
public override Task FlushAsync(CancellationToken cancellationToken) =>
throw new InvalidOperationException("Exception from FlushAsync");
}
internal sealed class WriteOnlyStream : Stream
{
private long _pos;
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_pos += count;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
_pos += buffer.Length;
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => _pos;
public override long Position
{
get => _pos;
set => throw new NotSupportedException();
}
}
}