Skip to content

Commit

Permalink
Add task extensions tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kapetan committed Oct 4, 2020
1 parent 8137012 commit 6cb35e4
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions Tests/Utils/TaskExtensionsTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using DNS.Protocol.Utils;

namespace DNS.Tests.Utils {

public class TaskExtensionsTest {
[Fact]
public async Task WithoutCancellation() {
object obj = new object();
CancellationTokenSource cts = new CancellationTokenSource();
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Task<object> resultTask = tcs.Task.WithCancellation(cts.Token);

tcs.SetResult(obj);
object result = await resultTask;

Assert.Same(obj, result);
}

[Fact]
public async Task WithCancellation() {
CancellationTokenSource cts = new CancellationTokenSource();
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Task resultTask = tcs.Task.WithCancellation(cts.Token);

cts.Cancel();

OperationCanceledException e =
await Assert.ThrowsAsync<OperationCanceledException>(() => resultTask);
Assert.Equal(cts.Token, e.CancellationToken);
}

[Fact]
public async Task WithoutCancellationTimeout() {
object obj = new object();
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Task<object> resultTask = tcs.Task.WithCancellationTimeout(TimeSpan.FromMilliseconds(60000));

tcs.SetResult(obj);
object result = await resultTask;

Assert.Same(obj, result);
}

[Fact(Timeout = 30000)]
public async Task WithoutCancellationTimeoutAndCancellationToken() {
CancellationTokenSource cts = new CancellationTokenSource();
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Task<object> resultTask = tcs.Task.WithCancellationTimeout(TimeSpan.FromMilliseconds(60000), cts.Token);

cts.Cancel();

await Assert.ThrowsAsync<OperationCanceledException>(() => resultTask);
}

[Fact]
public async Task WithCancellationTimeout() {
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
Task resultTask = tcs.Task.WithCancellationTimeout(TimeSpan.FromMilliseconds(100));

await Assert.ThrowsAsync<OperationCanceledException>(() => resultTask);
}
}
}

0 comments on commit 6cb35e4

Please sign in to comment.