Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/ corefx Public archive

Commit

Permalink
Improve tests for StreamReader cancellation (#42171)
Browse files Browse the repository at this point in the history
Existing tests were only validating precancellation and not canceling once a Read{Block}Async call was already in flight.
  • Loading branch information
stephentoub authored Nov 4, 2019
1 parent 897e15d commit dbcfe7a
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions src/System.IO/tests/StreamReader/StreamReaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -506,13 +507,46 @@ public async Task ReadBlockAsync_RepeatsReadsUntilReadDesiredAmount()
}
}

[Fact]
public async Task ReadAsync_Precanceled_ThrowsException()
[Theory]
[InlineData(0, false)]
[InlineData(0, true)]
[InlineData(1, false)]
[InlineData(1, true)]
public async Task ReadAsync_Canceled_ThrowsException(int method, bool precanceled)
{
using (var sr = new StreamReader(new MemoryStream()))
Func<StreamReader, CancellationToken, Task<int>> func = method switch
{
0 => (sr, ct) => sr.ReadAsync(new char[1], ct).AsTask(),
1 => (sr, ct) => sr.ReadBlockAsync(new char[1], ct).AsTask(),
_ => throw new Exception("unknown mode")
};

string pipeName = Guid.NewGuid().ToString("N");
using (var serverStream = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
using (var clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.In, PipeOptions.Asynchronous))
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sr.ReadBlockAsync(Memory<char>.Empty, new CancellationToken(true)).AsTask());
await Task.WhenAll(
serverStream.WaitForConnectionAsync(),
clientStream.ConnectAsync());

using (var sr = new StreamReader(clientStream))
{
var cts = new CancellationTokenSource();

if (precanceled)
{
cts.Cancel();
}

Task<int> t = func(sr, cts.Token);

if (!precanceled)
{
cts.Cancel();
}

await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
}
}
}

Expand Down

0 comments on commit dbcfe7a

Please sign in to comment.