// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.TestCommon
{
///
/// MSTest assert class to make assertions about tests using .
///
public class TaskAssert
{
private static int timeOutMs = System.Diagnostics.Debugger.IsAttached ? TimeoutConstant.DefaultTimeout : TimeoutConstant.DefaultTimeout * 10;
private static TaskAssert singleton = new TaskAssert();
public static TaskAssert Singleton { get { return singleton; } }
///
/// Asserts the given task has been started. TAP guidelines are that all
/// objects returned from public API's have been started.
///
/// The to test.
public void IsStarted(Task task)
{
Assert.NotNull(task);
Assert.True(task.Status != TaskStatus.Created);
}
///
/// Asserts the given task completes successfully. This method will block the
/// current thread waiting for the task, but will timeout if it does not complete.
///
/// The to test.
public void Succeeds(Task task)
{
IsStarted(task);
task.Wait(timeOutMs);
AggregateException aggregateException = task.Exception;
Exception innerException = aggregateException == null ? null : aggregateException.InnerException;
Assert.Null(innerException);
}
///
/// Asserts the given task completes successfully and returns a result.
/// Use this overload for a generic whose generic parameter is not known at compile time.
/// This method will block the current thread waiting for the task, but will timeout if it does not complete.
///
/// The to test.
/// The result from that task.
public object SucceedsWithResult(Task task)
{
Succeeds(task);
Assert.True(task.GetType().IsGenericType);
Type[] genericArguments = task.GetType().GetGenericArguments();
Assert.Equal(1, genericArguments.Length);
PropertyInfo resultProperty = task.GetType().GetProperty("Result");
Assert.NotNull(resultProperty);
return resultProperty.GetValue(task, null);
}
///
/// Asserts the given task completes successfully and returns a result.
/// This method will block the current thread waiting for the task, but will timeout if it does not complete.
///
/// The result of the .
/// The to test.
/// The result from that task.
public T SucceedsWithResult(Task task)
{
Succeeds(task);
return task.Result;
}
///
/// Asserts the given completes successfully and yields
/// the expected result.
///
/// The to test.
/// The expected result.
public void ResultEquals(Task task, object expectedObj)
{
object actualObj = SucceedsWithResult(task);
Assert.Equal(expectedObj, actualObj);
}
///
/// Asserts the given completes successfully and yields
/// the expected result.
///
/// The type the task will return.
/// The task to test.
/// The expected result.
public void ResultEquals(Task task, T expectedObj)
{
T actualObj = SucceedsWithResult(task);
Assert.Equal(expectedObj, actualObj);
}
}
}