From 6cb35e4481fb9ee5a0b5879f1816eda42fa49c74 Mon Sep 17 00:00:00 2001 From: Mirza Kapetanovic Date: Sun, 4 Oct 2020 13:19:58 +0200 Subject: [PATCH] Add task extensions tests --- Tests/Utils/TaskExtensionsTest.cs | 67 +++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Tests/Utils/TaskExtensionsTest.cs diff --git a/Tests/Utils/TaskExtensionsTest.cs b/Tests/Utils/TaskExtensionsTest.cs new file mode 100644 index 0000000..489abf2 --- /dev/null +++ b/Tests/Utils/TaskExtensionsTest.cs @@ -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 tcs = new TaskCompletionSource(); + Task 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 tcs = new TaskCompletionSource(); + Task resultTask = tcs.Task.WithCancellation(cts.Token); + + cts.Cancel(); + + OperationCanceledException e = + await Assert.ThrowsAsync(() => resultTask); + Assert.Equal(cts.Token, e.CancellationToken); + } + + [Fact] + public async Task WithoutCancellationTimeout() { + object obj = new object(); + TaskCompletionSource tcs = new TaskCompletionSource(); + Task 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 tcs = new TaskCompletionSource(); + Task resultTask = tcs.Task.WithCancellationTimeout(TimeSpan.FromMilliseconds(60000), cts.Token); + + cts.Cancel(); + + await Assert.ThrowsAsync(() => resultTask); + } + + [Fact] + public async Task WithCancellationTimeout() { + TaskCompletionSource tcs = new TaskCompletionSource(); + Task resultTask = tcs.Task.WithCancellationTimeout(TimeSpan.FromMilliseconds(100)); + + await Assert.ThrowsAsync(() => resultTask); + } + } +}