Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,289 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Threading;
using System.Web.Http.Controllers;
using Microsoft.TestCommon;
using Moq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class AuthorizeAttributeTest : IDisposable
{
private readonly Mock<HttpActionDescriptor> _actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true };
private readonly Collection<AllowAnonymousAttribute> _allowAnonymousAttributeCollection = new Collection<AllowAnonymousAttribute>(new AllowAnonymousAttribute[] { new AllowAnonymousAttribute() });
private readonly MockableAuthorizeAttribute _attribute;
private readonly Mock<MockableAuthorizeAttribute> _attributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };
private readonly Mock<HttpControllerDescriptor> _controllerDescriptorMock = new Mock<HttpControllerDescriptor>() { CallBase = true };
private readonly HttpControllerContext _controllerContext;
private readonly HttpActionContext _actionContext;
private readonly Mock<IPrincipal> _principalMock = new Mock<IPrincipal>();
private readonly IPrincipal _originalPrincipal;
private readonly HttpRequestMessage _request = new HttpRequestMessage();
public AuthorizeAttributeTest()
{
_attribute = _attributeMock.Object;
_controllerContext = new Mock<HttpControllerContext>() { CallBase = true }.Object;
_controllerDescriptorMock.Setup(cd => cd.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(new Collection<AllowAnonymousAttribute>(Enumerable.Empty<AllowAnonymousAttribute>().ToList()));
_actionDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(new Collection<AllowAnonymousAttribute>(Enumerable.Empty<AllowAnonymousAttribute>().ToList()));
_controllerContext.ControllerDescriptor = _controllerDescriptorMock.Object;
_controllerContext.Request = _request;
_actionContext = ContextUtil.CreateActionContext(_controllerContext, _actionDescriptorMock.Object);
_originalPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = _principalMock.Object;
}
public void Dispose()
{
Thread.CurrentPrincipal = _originalPrincipal;
}
[Fact]
public void Roles_Property()
{
AuthorizeAttribute attribute = new AuthorizeAttribute();
Assert.Reflection.StringProperty(attribute, a => a.Roles, expectedDefaultValue: String.Empty);
}
[Fact]
public void Users_Property()
{
AuthorizeAttribute attribute = new AuthorizeAttribute();
Assert.Reflection.StringProperty(attribute, a => a.Users, expectedDefaultValue: String.Empty);
}
[Fact]
public void AllowMultiple_ReturnsTrue()
{
Assert.True(_attribute.AllowMultiple);
}
[Fact]
public void TypeId_ReturnsUniqueInstances()
{
var attribute1 = new AuthorizeAttribute();
var attribute2 = new AuthorizeAttribute();
Assert.NotSame(attribute1.TypeId, attribute2.TypeId);
}
[Fact]
public void OnAuthorization_IfContextParameterIsNull_ThrowsException()
{
Assert.ThrowsArgumentNull(() =>
{
_attribute.OnAuthorization(actionContext: null);
}, "actionContext");
}
[Fact]
public void OnAuthorization_IfUserIsAuthenticated_DoesNotShortCircuitRequest()
{
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true);
_attribute.OnAuthorization(_actionContext);
Assert.Null(_actionContext.Response);
}
[Fact]
public void OnAuthorization_IfThreadDoesNotContainPrincipal_DoesShortCircuitRequest()
{
Thread.CurrentPrincipal = null;
_attribute.OnAuthorization(_actionContext);
AssertUnauthorizedRequestSet(_actionContext);
}
[Fact]
public void OnAuthorization_IfUserIsNotAuthenticated_DoesShortCircuitRequest()
{
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(false).Verifiable();
_attribute.OnAuthorization(_actionContext);
AssertUnauthorizedRequestSet(_actionContext);
_principalMock.Verify();
}
[Fact]
public void OnAuthorization_IfUserIsNotInUsersCollection_DoesShortCircuitRequest()
{
_attribute.Users = "John";
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();
_principalMock.Setup(p => p.Identity.Name).Returns("Mary").Verifiable();
_attribute.OnAuthorization(_actionContext);
AssertUnauthorizedRequestSet(_actionContext);
_principalMock.Verify();
}
[Fact]
public void OnAuthorization_IfUserIsInUsersCollection_DoesNotShortCircuitRequest()
{
_attribute.Users = " John , Mary ";
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();
_principalMock.Setup(p => p.Identity.Name).Returns("Mary").Verifiable();
_attribute.OnAuthorization(_actionContext);
Assert.Null(_actionContext.Response);
_principalMock.Verify();
}
[Fact]
public void OnAuthorization_IfUserIsNotInRolesCollection_DoesShortCircuitRequest()
{
_attribute.Users = " John , Mary ";
_attribute.Roles = "Administrators,PowerUsers";
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();
_principalMock.Setup(p => p.Identity.Name).Returns("Mary").Verifiable();
_principalMock.Setup(p => p.IsInRole("Administrators")).Returns(false).Verifiable();
_principalMock.Setup(p => p.IsInRole("PowerUsers")).Returns(false).Verifiable();
_attribute.OnAuthorization(_actionContext);
AssertUnauthorizedRequestSet(_actionContext);
_principalMock.Verify();
}
[Fact]
public void OnAuthorization_IfUserIsInRolesCollection_DoesNotShortCircuitRequest()
{
_attribute.Users = " John , Mary ";
_attribute.Roles = "Administrators,PowerUsers";
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();
_principalMock.Setup(p => p.Identity.Name).Returns("Mary").Verifiable();
_principalMock.Setup(p => p.IsInRole("Administrators")).Returns(false).Verifiable();
_principalMock.Setup(p => p.IsInRole("PowerUsers")).Returns(true).Verifiable();
_attribute.OnAuthorization(_actionContext);
Assert.Null(_actionContext.Response);
_principalMock.Verify();
}
[Fact]
public void OnAuthorization_IfActionDescriptorIsMarkedWithAllowAnonymousAttribute_DoesNotShortCircuitResponse()
{
_actionDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(_allowAnonymousAttributeCollection);
Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };
AuthorizeAttribute attribute = authorizeAttributeMock.Object;
attribute.OnAuthorization(_actionContext);
Assert.Null(_actionContext.Response);
}
[Fact]
public void OnAuthorization_IfControllerDescriptorIsMarkedWithAllowAnonymousAttribute_DoesNotShortCircuitResponse()
{
_controllerDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(_allowAnonymousAttributeCollection);
Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };
AuthorizeAttribute attribute = authorizeAttributeMock.Object;
attribute.OnAuthorization(_actionContext);
Assert.Null(_actionContext.Response);
}
[Fact]
public void OnAuthorization_IfRequestNotAuthorized_CallsHandleUnauthorizedRequest()
{
Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };
_principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(false);
authorizeAttributeMock.Setup(a => a.HandleUnauthorizedRequestPublic(_actionContext)).Verifiable();
AuthorizeAttribute attribute = authorizeAttributeMock.Object;
attribute.OnAuthorization(_actionContext);
authorizeAttributeMock.Verify();
}
[Fact]
public void HandleUnauthorizedRequest_IfContextParameterIsNull_ThrowsArgumentNullException()
{
Assert.ThrowsArgumentNull(() =>
{
_attribute.HandleUnauthorizedRequestPublic(context: null);
}, "actionContext");
}
[Fact]
public void HandleUnauthorizedRequest_SetsResponseWithUnauthorizedStatusCode()
{
_attribute.HandleUnauthorizedRequestPublic(_actionContext);
Assert.NotNull(_actionContext.Response);
Assert.Equal(HttpStatusCode.Unauthorized, _actionContext.Response.StatusCode);
Assert.Same(_request, _actionContext.Response.RequestMessage);
}
[Theory]
[PropertyData("SplitStringTestData")]
public void SplitString_SplitsOnCommaAndTrimsWhitespaceAndIgnoresEmptyStrings(string input, params string[] expectedResult)
{
string[] result = AuthorizeAttribute.SplitString(input);
Assert.Equal(expectedResult, result);
}
public static IEnumerable<object[]> SplitStringTestData
{
get
{
return new ParamsTheoryDataSet<string, string>() {
{ null },
{ String.Empty },
{ " " },
{ " A ", "A" },
{ " A, B ", "A", "B" },
{ " , A, ,B, ", "A", "B" },
{ " A B ", "A B" },
};
}
}
[CLSCompliant(false)]
public class ParamsTheoryDataSet<TParam1, TParam2> : TheoryDataSet
{
public void Add(TParam1 p1, params TParam2[] p2)
{
AddItem(p1, p2);
}
}
private static void AssertUnauthorizedRequestSet(HttpActionContext actionContext)
{
Assert.NotNull(actionContext.Response);
Assert.Equal(HttpStatusCode.Unauthorized, actionContext.Response.StatusCode);
Assert.Same(actionContext.ControllerContext.Request, actionContext.Response.RequestMessage);
}
public class MockableAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext context)
{
HandleUnauthorizedRequestPublic(context);
}
public virtual void HandleUnauthorizedRequestPublic(HttpActionContext context)
{
base.HandleUnauthorizedRequest(context);
}
}
}
}

View File

@ -0,0 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ErrorTests
{
[Fact]
public void Format()
{
// Arrange
string expected = "The formatted message";
// Act
string actual = Error.Format("The {0} message", "formatted");
// Assert
Assert.Equal(expected, actual);
}
}
}

View File

@ -0,0 +1,208 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web
{
[CLSCompliant(false)]
public class PrefixContainerTests
{
[Fact]
public void Constructor_GuardClauses()
{
// Act & assert
Assert.ThrowsArgumentNull(() => new PrefixContainer(null), "values");
}
[Fact]
public void ContainsPrefix_GuardClauses()
{
// Arrange
var container = new PrefixContainer(new string[0]);
// Act & assert
Assert.ThrowsArgumentNull(() => container.ContainsPrefix(null), "prefix");
}
[Fact]
public void ContainsPrefix_EmptyCollectionReturnsFalse()
{
// Arrange
var container = new PrefixContainer(new string[0]);
// Act & Assert
Assert.False(container.ContainsPrefix(""));
}
[Fact]
public void ContainsPrefix_ExactMatch()
{
// Arrange
var container = new PrefixContainer(new[] { "Hello" });
// Act & Assert
Assert.True(container.ContainsPrefix("Hello"));
}
[Fact]
public void ContainsPrefix_MatchIsCaseInsensitive()
{
// Arrange
var container = new PrefixContainer(new[] { "Hello" });
// Act & Assert
Assert.True(container.ContainsPrefix("hello"));
}
[Fact]
public void ContainsPrefix_MatchIsNotSimpleSubstringMatch()
{
// Arrange
var container = new PrefixContainer(new[] { "Hello" });
// Act & Assert
Assert.False(container.ContainsPrefix("He"));
}
[Fact]
public void ContainsPrefix_NonEmptyCollectionReturnsTrueIfPrefixIsEmptyString()
{
// Arrange
var container = new PrefixContainer(new[] { "Hello" });
// Act & Assert
Assert.True(container.ContainsPrefix(""));
}
[Fact]
public void ContainsPrefix_PrefixBoundaries()
{
// Arrange
var container = new PrefixContainer(new[] { "Hello.There[0]" });
// Act & Assert
Assert.True(container.ContainsPrefix("hello"));
Assert.True(container.ContainsPrefix("hello.there"));
Assert.True(container.ContainsPrefix("hello.there[0]"));
Assert.False(container.ContainsPrefix("hello.there.0"));
}
[Theory]
[InlineData("a")]
[InlineData("a[d]")]
[InlineData("c.b")]
[InlineData("c.b.a")]
public void ContainsPrefix_PositiveTests(string testValue)
{
// Arrange
var container = new PrefixContainer(new[] { "a.b", "c.b.a", "a[d]", "a.c" });
// Act & Assert
Assert.True(container.ContainsPrefix(testValue));
}
[Theory]
[InlineData("a.d")]
[InlineData("b")]
[InlineData("c.a")]
[InlineData("c.b.a.a")]
public void ContainsPrefix_NegativeTests(string testValue)
{
// Arrange
var container = new PrefixContainer(new[] { "a.b", "c.b.a", "a[d]", "a.c" });
// Act & Assert
Assert.False(container.ContainsPrefix(testValue));
}
[Fact]
public void GetKeysFromPrefix_DotsNotation()
{
// Arrange
var container = new PrefixContainer(new[] { "foo.bar.baz", "something.other", "foo.baz", "foot.hello", "fo.nothing", "foo" });
string prefix = "foo";
// Act
IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);
// Assert
Assert.Equal(2, result.Count());
Assert.True(result.ContainsKey("bar"));
Assert.True(result.ContainsKey("baz"));
Assert.Equal("foo.bar", result["bar"]);
Assert.Equal("foo.baz", result["baz"]);
}
[Fact]
public void GetKeysFromPrefix_BracketsNotation()
{
// Arrange
var container = new PrefixContainer(new[] { "foo[bar]baz", "something[other]", "foo[baz]", "foot[hello]", "fo[nothing]", "foo" });
string prefix = "foo";
// Act
IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);
// Assert
Assert.Equal(2, result.Count());
Assert.True(result.ContainsKey("bar"));
Assert.True(result.ContainsKey("baz"));
Assert.Equal("foo[bar]", result["bar"]);
Assert.Equal("foo[baz]", result["baz"]);
}
[Fact]
public void GetKeysFromPrefix_MixedDotsAndBrackets()
{
// Arrange
var container = new PrefixContainer(new[] { "foo[bar]baz", "something[other]", "foo.baz", "foot[hello]", "fo[nothing]", "foo" });
string prefix = "foo";
// Act
IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);
// Assert
Assert.Equal(2, result.Count());
Assert.True(result.ContainsKey("bar"));
Assert.True(result.ContainsKey("baz"));
Assert.Equal("foo[bar]", result["bar"]);
Assert.Equal("foo.baz", result["baz"]);
}
[Fact]
public void GetKeysFromPrefix_AllValues()
{
// Arrange
var container = new PrefixContainer(new[] { "foo[bar]baz", "something[other]", "foo.baz", "foot[hello]", "fo[nothing]", "foo" });
string prefix = "";
// Act
IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);
// Assert
Assert.Equal(4, result.Count());
Assert.Equal("foo", result["foo"]);
Assert.Equal("something", result["something"]);
Assert.Equal("foot", result["foot"]);
Assert.Equal("fo", result["fo"]);
}
[Fact]
public void GetKeysFromPrefix_PrefixNotFound()
{
// Arrange
var container = new PrefixContainer(new[] { "foo[bar]", "something[other]", "foo.baz", "foot[hello]", "fo[nothing]", "foo" });
string prefix = "notfound";
// Act
IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);
// Assert
Assert.Empty(result);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,391 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.TestCommon;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Threading.Tasks
{
public class TaskHelpersTest
{
// -----------------------------------------------------------------
// TaskHelpers.Canceled
[Fact]
public void Canceled_ReturnsCanceledTask()
{
Task result = TaskHelpers.Canceled();
Assert.NotNull(result);
Assert.True(result.IsCanceled);
}
// -----------------------------------------------------------------
// TaskHelpers.Canceled<T>
[Fact]
public void Canceled_Generic_ReturnsCanceledTask()
{
Task<string> result = TaskHelpers.Canceled<string>();
Assert.NotNull(result);
Assert.True(result.IsCanceled);
}
// -----------------------------------------------------------------
// TaskHelpers.Completed
[Fact]
public void Completed_ReturnsCompletedTask()
{
Task result = TaskHelpers.Completed();
Assert.NotNull(result);
Assert.Equal(TaskStatus.RanToCompletion, result.Status);
}
// -----------------------------------------------------------------
// TaskHelpers.FromError
[Fact]
public void FromError_ReturnsFaultedTaskWithGivenException()
{
var exception = new Exception();
Task result = TaskHelpers.FromError(exception);
Assert.NotNull(result);
Assert.True(result.IsFaulted);
Assert.Same(exception, result.Exception.InnerException);
}
// -----------------------------------------------------------------
// TaskHelpers.FromError<T>
[Fact]
public void FromError_Generic_ReturnsFaultedTaskWithGivenException()
{
var exception = new Exception();
Task<string> result = TaskHelpers.FromError<string>(exception);
Assert.NotNull(result);
Assert.True(result.IsFaulted);
Assert.Same(exception, result.Exception.InnerException);
}
// -----------------------------------------------------------------
// TaskHelpers.FromErrors
[Fact]
public void FromErrors_ReturnsFaultedTaskWithGivenExceptions()
{
var exceptions = new[] { new Exception(), new InvalidOperationException() };
Task result = TaskHelpers.FromErrors(exceptions);
Assert.NotNull(result);
Assert.True(result.IsFaulted);
Assert.Equal(exceptions, result.Exception.InnerExceptions.ToArray());
}
// -----------------------------------------------------------------
// TaskHelpers.FromErrors<T>
[Fact]
public void FromErrors_Generic_ReturnsFaultedTaskWithGivenExceptions()
{
var exceptions = new[] { new Exception(), new InvalidOperationException() };
Task<string> result = TaskHelpers.FromErrors<string>(exceptions);
Assert.NotNull(result);
Assert.True(result.IsFaulted);
Assert.Equal(exceptions, result.Exception.InnerExceptions.ToArray());
}
// -----------------------------------------------------------------
// TaskHelpers.FromResult<T>
[Fact]
public void FromResult_ReturnsCompletedTaskWithGivenResult()
{
string s = "ABC";
Task<string> result = TaskHelpers.FromResult(s);
Assert.NotNull(result);
Assert.True(result.Status == TaskStatus.RanToCompletion);
Assert.Same(s, result.Result);
}
// -----------------------------------------------------------------
// Task TaskHelpers.Iterate(IEnumerable<Task>)
[Fact]
public void Iterate_NonGeneric_IfProvidedEnumerationContainsNullValue_ReturnsFaultedTaskWithNullReferenceException()
{
List<string> log = new List<string>();
var result = TaskHelpers.Iterate(NullTaskEnumerable(log));
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.IsType<NullReferenceException>(result.Exception.GetBaseException());
}
private static IEnumerable<Task> NullTaskEnumerable(List<string> log)
{
log.Add("first");
yield return null;
log.Add("second");
}
[Fact]
public void Iterate_NonGeneric_IfProvidedEnumerationThrowsException_ReturnsFaultedTask()
{
List<string> log = new List<string>();
Exception exception = new Exception();
var result = TaskHelpers.Iterate(ThrowingTaskEnumerable(exception, log));
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.Same(exception, result.Exception.InnerException);
Assert.Equal(new[] { "first" }, log.ToArray());
}
private static IEnumerable<Task> ThrowingTaskEnumerable(Exception e, List<string> log)
{
log.Add("first");
bool a = true; // work around unreachable code warning
if (a) throw e;
log.Add("second");
yield return null;
}
[Fact]
public void Iterate_NonGeneric_IfProvidedEnumerableExecutesCancellingTask_ReturnsCanceledTaskAndHaltsEnumeration()
{
List<string> log = new List<string>();
var result = TaskHelpers.Iterate(CanceledTaskEnumerable(log));
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Canceled, result.Status);
Assert.Equal(new[] { "first" }, log.ToArray());
}
private static IEnumerable<Task> CanceledTaskEnumerable(List<string> log)
{
log.Add("first");
yield return TaskHelpers.Canceled();
log.Add("second");
}
[Fact]
public void Iterate_NonGeneric_IfProvidedEnumerableExecutesFaultingTask_ReturnsCanceledTaskAndHaltsEnumeration()
{
List<string> log = new List<string>();
Exception exception = new Exception();
var result = TaskHelpers.Iterate(FaultedTaskEnumerable(exception, log));
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.Same(exception, result.Exception.InnerException);
Assert.Equal(new[] { "first" }, log.ToArray());
}
private static IEnumerable<Task> FaultedTaskEnumerable(Exception e, List<string> log)
{
log.Add("first");
yield return TaskHelpers.FromError(e);
log.Add("second");
}
[Fact]
public void Iterate_NonGeneric_ExecutesNextTaskOnlyAfterPreviousTaskSucceeded()
{
List<string> log = new List<string>();
var result = TaskHelpers.Iterate(SuccessTaskEnumerable(log));
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.RanToCompletion, result.Status);
Assert.Equal(
new[] { "first", "Executing first task. Log size: 1", "second", "Executing second task. Log size: 3" },
log.ToArray());
}
private static IEnumerable<Task> SuccessTaskEnumerable(List<string> log)
{
log.Add("first");
yield return Task.Factory.StartNew(() => log.Add("Executing first task. Log size: " + log.Count));
log.Add("second");
yield return Task.Factory.StartNew(() => log.Add("Executing second task. Log size: " + log.Count));
}
[Fact]
public void Iterate_NonGeneric_TasksRunSequentiallyRegardlessOfExecutionTime()
{
List<string> log = new List<string>();
Task task = TaskHelpers.Iterate(TasksWithVaryingDelays(log, 100, 1, 50, 2));
task.WaitUntilCompleted();
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
Assert.Equal(new[] { "ENTER: 100", "EXIT: 100", "ENTER: 1", "EXIT: 1", "ENTER: 50", "EXIT: 50", "ENTER: 2", "EXIT: 2" }, log);
}
private static IEnumerable<Task> TasksWithVaryingDelays(List<string> log, params int[] delays)
{
foreach (int delay in delays)
yield return Task.Factory.StartNew(timeToSleep =>
{
log.Add("ENTER: " + timeToSleep);
Thread.Sleep((int)timeToSleep);
log.Add("EXIT: " + timeToSleep);
}, delay);
}
[Fact]
public void Iterate_NonGeneric_StopsTaskIterationIfCancellationWasRequested()
{
List<string> log = new List<string>();
CancellationTokenSource cts = new CancellationTokenSource();
var result = TaskHelpers.Iterate(CancelingTaskEnumerable(log, cts), cts.Token);
Assert.NotNull(result);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Canceled, result.Status);
Assert.Equal(
new[] { "first", "Executing first task. Log size: 1" },
log.ToArray());
}
private static IEnumerable<Task> CancelingTaskEnumerable(List<string> log, CancellationTokenSource cts)
{
log.Add("first");
yield return Task.Factory.StartNew(() =>
{
log.Add("Executing first task. Log size: " + log.Count);
cts.Cancel();
});
log.Add("second");
yield return Task.Factory.StartNew(() =>
{
log.Add("Executing second task. Log size: " + log.Count);
});
}
[Fact, PreserveSyncContext]
public Task Iterate_NonGeneric_IteratorRunsInSynchronizationContext()
{
ThreadPoolSyncContext sc = new ThreadPoolSyncContext();
SynchronizationContext.SetSynchronizationContext(sc);
return TaskHelpers.Iterate(SyncContextVerifyingEnumerable(sc)).Then(() =>
{
Assert.Same(sc, SynchronizationContext.Current);
});
}
private static IEnumerable<Task> SyncContextVerifyingEnumerable(SynchronizationContext sc)
{
for (int i = 0; i < 10; i++)
{
Assert.Same(sc, SynchronizationContext.Current);
yield return TaskHelpers.Completed();
}
}
// -----------------------------------------------------------------
// TaskHelpers.TrySetFromTask<T>
[Fact]
public void TrySetFromTask_IfSourceTaskIsCanceled_CancelsTaskCompletionSource()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
Task canceledTask = TaskHelpers.Canceled<object>();
tcs.TrySetFromTask(canceledTask);
Assert.Equal(TaskStatus.Canceled, tcs.Task.Status);
}
[Fact]
public void TrySetFromTask_IfSourceTaskIsFaulted_FaultsTaskCompletionSource()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
Exception exception = new Exception();
Task faultedTask = TaskHelpers.FromError<object>(exception);
tcs.TrySetFromTask(faultedTask);
Assert.Equal(TaskStatus.Faulted, tcs.Task.Status);
Assert.Same(exception, tcs.Task.Exception.InnerException);
}
[Fact]
public void TrySetFromTask_IfSourceTaskIsSuccessfulAndOfSameResultType_SucceedsTaskCompletionSourceAndSetsResult()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
Task<string> successfulTask = TaskHelpers.FromResult("abc");
tcs.TrySetFromTask(successfulTask);
Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);
Assert.Equal("abc", tcs.Task.Result);
}
[Fact]
public void TrySetFromTask_IfSourceTaskIsSuccessfulAndOfDifferentResultType_SucceedsTaskCompletionSourceAndSetsDefaultValueAsResult()
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
Task<object> successfulTask = TaskHelpers.FromResult(new object());
tcs.TrySetFromTask(successfulTask);
Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status);
Assert.Equal(null, tcs.Task.Result);
}
// -----------------------------------------------------------------
// TaskHelpers.RunSynchronously
[Fact]
public void RunSynchronously_Executes_Action()
{
bool wasRun = false;
Task t = TaskHelpers.RunSynchronously(() => { wasRun = true; });
t.WaitUntilCompleted();
Assert.True(wasRun);
}
[Fact]
public void RunSynchronously_Captures_Exception_In_AggregateException()
{
Task t = TaskHelpers.RunSynchronously(() => { throw new InvalidOperationException(); });
Assert.Throws<InvalidOperationException>(() => t.Wait());
}
[Fact]
public void RunSynchronously_Cancels()
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.Cancel();
Task t = TaskHelpers.RunSynchronously(() => { throw new InvalidOperationException(); }, cts.Token);
Assert.Throws<TaskCanceledException>(() => t.Wait());
}
}
}

View File

@ -0,0 +1,117 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ApiControllerActionInvokerTest
{
private readonly HttpActionContext _actionContext;
private readonly Mock<HttpActionDescriptor> _actionDescriptorMock = new Mock<HttpActionDescriptor>();
private readonly ApiControllerActionInvoker _actionInvoker = new ApiControllerActionInvoker();
private readonly HttpControllerContext _controllerContext;
private readonly HttpRequestMessage _request = new HttpRequestMessage();
private readonly Mock<IActionResultConverter> _converterMock = new Mock<IActionResultConverter>();
public ApiControllerActionInvokerTest()
{
_controllerContext = new HttpControllerContext()
{
Request = _request
};
_actionContext = new HttpActionContext(_controllerContext, _actionDescriptorMock.Object);
_actionDescriptorMock.Setup(ad => ad.ResultConverter).Returns(_converterMock.Object);
}
[Fact]
public void InvokeActionAsync_Cancels_IfCancellationTokenRequested()
{
CancellationTokenSource cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
var response = _actionInvoker.InvokeActionAsync(ContextUtil.CreateActionContext(), cancellationSource.Token);
Assert.Equal<TaskStatus>(TaskStatus.Canceled, response.Status);
}
[Fact]
public void InvokeActionAsync_Throws_IfContextIsNull()
{
Assert.ThrowsArgumentNull(
() => _actionInvoker.InvokeActionAsync(null, CancellationToken.None),
"actionContext");
}
[Fact]
public void InvokeActionAsync_InvokesActionDescriptorExecuteAsync()
{
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
_actionDescriptorMock.Verify(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments), Times.Once());
}
[Fact]
public void InvokeActionAsync_PassesExecutionResultToConfiguredConverter()
{
var value = new object();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments))
.Returns(TaskHelpers.FromResult(value));
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
_converterMock.Verify(c => c.Convert(_actionContext.ControllerContext, value), Times.Once());
}
[Fact]
public void InvokeActionAsync_ReturnsResponseFromConverter()
{
var response = new HttpResponseMessage();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments))
.Returns(TaskHelpers.FromResult(new object()));
_converterMock.Setup(c => c.Convert(_actionContext.ControllerContext, It.IsAny<object>()))
.Returns(response);
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Same(response, result.Result);
}
[Fact]
public void InvokeActionAsync_WhenExecuteThrowsHttpResponseException_ReturnsResponse()
{
HttpResponseMessage response = new HttpResponseMessage();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>()))
.Throws(new HttpResponseException(response));
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Same(response, result.Result);
Assert.Same(_request, result.Result.RequestMessage);
}
[Fact]
public void InvokeActionAsync_WhenExecuteThrows_ReturnsFaultedTask()
{
Exception exception = new Exception();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>()))
.Throws(exception);
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.Same(exception, result.Exception.GetBaseException());
}
}
}

View File

@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using System.Web.Http.Controllers;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ApiControllerActionSelectorTest
{
[Fact]
public void SelectAction_With_DifferentExecutionContexts()
{
ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();
HttpControllerContext GetContext = ContextUtil.CreateControllerContext();
HttpControllerDescriptor usersControllerDescriptor = new HttpControllerDescriptor(GetContext.Configuration, "Users", typeof(UsersController));
usersControllerDescriptor.HttpActionSelector = actionSelector;
GetContext.ControllerDescriptor = usersControllerDescriptor;
GetContext.Request = new HttpRequestMessage
{
Method = HttpMethod.Get
};
HttpControllerContext PostContext = ContextUtil.CreateControllerContext();
usersControllerDescriptor.HttpActionSelector = actionSelector;
PostContext.ControllerDescriptor = usersControllerDescriptor;
PostContext.Request = new HttpRequestMessage
{
Method = HttpMethod.Post
};
HttpActionDescriptor getActionDescriptor = actionSelector.SelectAction(GetContext);
HttpActionDescriptor postActionDescriptor = actionSelector.SelectAction(PostContext);
Assert.Equal("Get", getActionDescriptor.ActionName);
Assert.Equal("Post", postActionDescriptor.ActionName);
}
[Fact]
public void SelectAction_Throws_IfContextIsNull()
{
ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();
Assert.ThrowsArgumentNull(
() => actionSelector.SelectAction(null),
"controllerContext");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Web.Http
{
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

View File

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net;
using System.Net.Http;
namespace System.Web.Http
{
public class UsersController : ApiController
{
public HttpResponseMessage Get()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Default User")
};
}
public HttpResponseMessage Post()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Posted")
};
}
public HttpResponseMessage Put()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Updated")
};
}
public HttpResponseMessage Delete()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Deleted")
};
}
}
}

View File

@ -0,0 +1,84 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Threading.Tasks;
namespace System.Web.Http
{
public class UsersRpcController : ApiController
{
public User EchoUser(string firstName, string lastName)
{
return new User()
{
FirstName = firstName,
LastName = lastName,
};
}
public Task<User> EchoUserAsync(string firstName, string lastName)
{
return TaskHelpers.FromResult(new User()
{
FirstName = firstName,
LastName = lastName,
});
}
[Authorize]
[HttpGet]
public User AddAdmin(string firstName, string lastName)
{
return new User()
{
FirstName = firstName,
LastName = lastName,
};
}
public User RetriveUser(int id)
{
return new User()
{
LastName = "UserLN" + id,
FirstName = "UserFN" + id
};
}
public User EchoUserObject(User user)
{
return user;
}
public User Admin()
{
return new User
{
FirstName = "Yao",
LastName = "Huang"
};
}
public void DeleteAllUsers()
{
}
public Task DeleteAllUsersAsync()
{
return TaskHelpers.Completed();
}
public void AddUser([FromBody] User user)
{
}
public Task WrappedTaskReturningMethod()
{
return TaskHelpers.FromResult(TaskHelpers.Completed());
}
public object TaskAsObjectReturningMethod()
{
return TaskHelpers.Completed();
}
}
}

View File

@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpActionContextTest
{
[Fact]
public void Default_Constructor()
{
HttpActionContext actionContext = new HttpActionContext();
Assert.Null(actionContext.ControllerContext);
Assert.Null(actionContext.ActionDescriptor);
Assert.Null(actionContext.Response);
Assert.Null(actionContext.Request);
Assert.NotNull(actionContext.ActionArguments);
Assert.NotNull(actionContext.ModelState);
}
[Fact]
public void Parameter_Constructor()
{
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;
HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);
Assert.Same(controllerContext, actionContext.ControllerContext);
Assert.Same(actionDescriptor, actionContext.ActionDescriptor);
Assert.Same(controllerContext.Request, actionContext.Request);
Assert.Null(actionContext.Response);
Assert.NotNull(actionContext.ActionArguments);
Assert.NotNull(actionContext.ModelState);
}
[Fact]
public void Constructor_Throws_IfControllerContextIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpActionContext(null, new Mock<HttpActionDescriptor>().Object),
"controllerContext");
}
[Fact]
public void Constructor_Throws_IfActionDescriptorIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpActionContext(ContextUtil.CreateControllerContext(), null),
"actionDescriptor");
}
[Fact]
public void ControllerContext_Property()
{
Assert.Reflection.Property<HttpActionContext, HttpControllerContext>(
instance: new HttpActionContext(),
propertyGetter: ac => ac.ControllerContext,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: ContextUtil.CreateControllerContext());
}
[Fact]
public void ActionDescriptor_Property()
{
Assert.Reflection.Property<HttpActionContext, HttpActionDescriptor>(
instance: new HttpActionContext(),
propertyGetter: ac => ac.ActionDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<HttpActionDescriptor>().Object);
}
}
}

View File

@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class HttpActionDescriptorTest
{
[Theory]
[InlineData(null, typeof(VoidResultConverter))]
[InlineData(typeof(HttpResponseMessage), typeof(ResponseMessageResultConverter))]
[InlineData(typeof(object), typeof(ValueResultConverter<object>))]
[InlineData(typeof(string), typeof(ValueResultConverter<string>))]
public void GetResultConverter_GetAppropriateConverterInstance(Type actionReturnType, Type expectedConverterType)
{
var result = HttpActionDescriptor.GetResultConverter(actionReturnType);
Assert.IsType(expectedConverterType, result);
}
[Fact]
public void GetResultConverter_WhenTypeIsAnGenericParameterType_Throws()
{
var genericType = typeof(HttpActionDescriptorTest).GetMethod("SampleGenericMethod").ReturnType;
Assert.Throws<InvalidOperationException>(() => HttpActionDescriptor.GetResultConverter(genericType),
"No action result converter could be constructed for a generic parameter type 'TResult'.");
}
public TResult SampleGenericMethod<TResult>()
{
return default(TResult);
}
}
}

View File

@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http.Services;
using Microsoft.TestCommon;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpConfigurationTest
{
[Fact]
public void TypeIsCorrect()
{
Assert.Type.HasProperties<HttpConfiguration>(TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsDisposable);
}
[Fact]
public void Default_Constructor()
{
HttpConfiguration configuration = new HttpConfiguration();
Assert.Empty(configuration.Filters);
Assert.NotEmpty(configuration.Formatters);
Assert.Empty(configuration.MessageHandlers);
Assert.Empty(configuration.Properties);
Assert.Empty(configuration.Routes);
Assert.NotNull(configuration.DependencyResolver);
Assert.NotNull(configuration.Services);
Assert.Equal("/", configuration.VirtualPathRoot);
}
[Fact]
public void Parameter_Constructor()
{
string path = "/some/path";
HttpRouteCollection routes = new HttpRouteCollection(path);
HttpConfiguration configuration = new HttpConfiguration(routes);
Assert.Same(routes, configuration.Routes);
Assert.Equal(path, configuration.VirtualPathRoot);
}
[Fact]
public void Dispose_Idempotent()
{
HttpConfiguration configuration = new HttpConfiguration();
configuration.Dispose();
configuration.Dispose();
}
[Fact]
public void Dispose_DisposesOfServices()
{
// Arrange
var configuration = new HttpConfiguration();
var services = new Mock<DefaultServices> { CallBase = true };
configuration.Services = services.Object;
// Act
configuration.Dispose();
// Assert
services.Verify(s => s.Dispose(), Times.Once());
}
[Fact]
public void DependencyResolver_GuardClauses()
{
// Arrange
var config = new HttpConfiguration();
// Act & assert
Assert.ThrowsArgumentNull(() => config.DependencyResolver = null, "value");
}
}
}

View File

@ -0,0 +1,110 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpControllerContextTest
{
[Fact]
public void Default_Constructor()
{
HttpControllerContext controllerContext = new HttpControllerContext();
Assert.Null(controllerContext.Configuration);
Assert.Null(controllerContext.Controller);
Assert.Null(controllerContext.ControllerDescriptor);
Assert.Null(controllerContext.Request);
Assert.Null(controllerContext.RouteData);
}
[Fact]
public void Parameter_Constructor()
{
HttpConfiguration config = new HttpConfiguration();
IHttpRouteData routeData = new Mock<IHttpRouteData>().Object;
HttpRequestMessage request = new HttpRequestMessage();
HttpControllerContext controllerContext = new HttpControllerContext(config, routeData, request);
Assert.Same(config, controllerContext.Configuration);
Assert.Same(request, controllerContext.Request);
Assert.Same(routeData, controllerContext.RouteData);
Assert.Null(controllerContext.Controller);
Assert.Null(controllerContext.ControllerDescriptor);
}
[Fact]
public void Constructor_Throws_IfConfigurationIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(null, new Mock<IHttpRouteData>().Object, new HttpRequestMessage()),
"configuration");
}
[Fact]
public void Constructor_Throws_IfRouteDataIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(new HttpConfiguration(), null, new HttpRequestMessage()),
"routeData");
}
[Fact]
public void Constructor_Throws_IfRequestIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(new HttpConfiguration(), new Mock<IHttpRouteData>().Object, null),
"request");
}
[Fact]
public void Configuration_Property()
{
Assert.Reflection.Property<HttpControllerContext, HttpConfiguration>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new HttpConfiguration());
}
[Fact]
public void Controller_Property()
{
Assert.Reflection.Property<HttpControllerContext, IHttpController>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.Controller,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<IHttpController>().Object);
}
[Fact]
public void ControllerDescriptor_Property()
{
Assert.Reflection.Property<HttpControllerContext, HttpControllerDescriptor>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.ControllerDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new HttpControllerDescriptor());
}
[Fact]
public void RouteData_Property()
{
Assert.Reflection.Property<HttpControllerContext, IHttpRouteData>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.RouteData,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<IHttpRouteData>().Object);
}
}
}

View File

@ -0,0 +1,185 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Filters;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpControllerDescriptorTest
{
[Fact]
public void Default_Constructor()
{
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Null(controllerDescriptor.ControllerName);
Assert.Null(controllerDescriptor.Configuration);
Assert.Null(controllerDescriptor.ControllerType);
Assert.Null(controllerDescriptor.HttpActionInvoker);
Assert.Null(controllerDescriptor.HttpActionSelector);
Assert.Null(controllerDescriptor.HttpControllerActivator);
Assert.NotNull(controllerDescriptor.Properties);
}
[Fact]
public void Parameter_Constructor()
{
HttpConfiguration config = new HttpConfiguration();
string controllerName = "UsersController";
Type controllerType = typeof(UsersController);
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, controllerName, controllerType);
Assert.NotNull(controllerDescriptor.ControllerName);
Assert.NotNull(controllerDescriptor.Configuration);
Assert.NotNull(controllerDescriptor.ControllerType);
Assert.NotNull(controllerDescriptor.HttpActionInvoker);
Assert.NotNull(controllerDescriptor.HttpActionSelector);
Assert.NotNull(controllerDescriptor.HttpControllerActivator);
Assert.NotNull(controllerDescriptor.Properties);
Assert.Equal(config, controllerDescriptor.Configuration);
Assert.Equal(controllerName, controllerDescriptor.ControllerName);
Assert.Equal(controllerType, controllerDescriptor.ControllerType);
}
[Fact]
public void Constructor_Throws_IfConfigurationIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(null, "UsersController", typeof(UsersController)),
"configuration");
}
[Fact]
public void Constructor_Throws_IfControllerNameIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(new HttpConfiguration(), null, typeof(UsersController)),
"controllerName");
}
[Fact]
public void Constructor_Throws_IfControllerTypeIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(new HttpConfiguration(), "UsersController", null),
"controllerType");
}
[Fact]
public void Configuration_Property()
{
HttpConfiguration config = new HttpConfiguration();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, HttpConfiguration>(
instance: controllerDescriptor,
propertyGetter: cd => cd.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void ControllerName_Property()
{
string controllerName = "UsersController";
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, string>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ControllerName,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerName);
}
[Fact]
public void ControllerType_Property()
{
Type controllerType = typeof(UsersController);
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, Type>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ControllerType,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerType);
}
[Fact]
public void HttpActionInvoker_Property()
{
IHttpActionInvoker invoker = new ApiControllerActionInvoker();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpActionInvoker>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpActionInvoker,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: invoker);
}
[Fact]
public void HttpActionSelector_Property()
{
IHttpActionSelector selector = new ApiControllerActionSelector();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpActionSelector>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpActionSelector,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: selector);
}
[Fact]
public void HttpControllerActivator_Property()
{
IHttpControllerActivator activator = new Mock<IHttpControllerActivator>().Object;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpControllerActivator>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpControllerActivator,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: activator);
}
[Fact]
public void ActionValueBinder_Property()
{
IActionValueBinder activator = new Mock<IActionValueBinder>().Object;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IActionValueBinder>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ActionValueBinder,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: activator);
}
[Fact]
public void GetFilters_InvokesGetCustomAttributesMethod()
{
var descriptorMock = new Mock<HttpControllerDescriptor> { CallBase = true };
var filters = new Collection<IFilter>(new List<IFilter>());
descriptorMock.Setup(d => d.GetCustomAttributes<IFilter>()).Returns(filters).Verifiable();
var result = descriptorMock.Object.GetFilters();
Assert.Same(filters, result);
descriptorMock.Verify();
}
}
}

View File

@ -0,0 +1,75 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpParameterDescriptorTest
{
[Fact]
public void Default_Constructor()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor>().Object;
Assert.Null(parameterDescriptor.ParameterName);
Assert.Null(parameterDescriptor.ParameterType);
Assert.Null(parameterDescriptor.Configuration);
Assert.Null(parameterDescriptor.Prefix);
Assert.Null(parameterDescriptor.ModelBinderAttribute);
Assert.Null(parameterDescriptor.ActionDescriptor);
Assert.Null(parameterDescriptor.DefaultValue);
Assert.NotNull(parameterDescriptor.Properties);
}
[Fact]
public void Configuration_Property()
{
HttpConfiguration config = new HttpConfiguration();
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
Assert.Reflection.Property<HttpParameterDescriptor, HttpConfiguration>(
instance: parameterDescriptor,
propertyGetter: pd => pd.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void ActionDescriptor_Property()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;
Assert.Reflection.Property<HttpParameterDescriptor, HttpActionDescriptor>(
instance: parameterDescriptor,
propertyGetter: pd => pd.ActionDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: actionDescriptor);
}
[Fact]
public void GetCustomAttributes_Returns_EmptyAttributes()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
IEnumerable<object> attributes = parameterDescriptor.GetCustomAttributes<object>();
Assert.Equal(0, attributes.Count());
}
[Fact]
public void GetCustomAttributes_AttributeType_Returns_EmptyAttributes()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();
Assert.Equal(0, attributes.Count());
}
}
}

View File

@ -0,0 +1,342 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Moq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ReflectedHttpActionDescriptorTest
{
private readonly UsersRpcController _controller = new UsersRpcController();
private readonly HttpControllerContext _context;
private readonly Dictionary<string, object> _arguments = new Dictionary<string, object>();
public ReflectedHttpActionDescriptorTest()
{
_context = ContextUtil.CreateControllerContext(instance: _controller);
}
[Fact]
public void Default_Constructor()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
Assert.Null(actionDescriptor.ActionName);
Assert.Null(actionDescriptor.Configuration);
Assert.Null(actionDescriptor.ControllerDescriptor);
Assert.Null(actionDescriptor.MethodInfo);
Assert.Null(actionDescriptor.ReturnType);
Assert.NotNull(actionDescriptor.Properties);
}
[Fact]
public void Parameter_Constructor()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
HttpConfiguration config = new HttpConfiguration();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "", typeof(UsersRpcController));
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);
Assert.Equal("EchoUser", actionDescriptor.ActionName);
Assert.Equal(config, actionDescriptor.Configuration);
Assert.Equal(typeof(UsersRpcController), actionDescriptor.ControllerDescriptor.ControllerType);
Assert.Equal(echoUserMethod.Method, actionDescriptor.MethodInfo);
Assert.Equal(typeof(User), actionDescriptor.ReturnType);
Assert.NotNull(actionDescriptor.Properties);
}
[Fact]
public void Constructor_Throws_IfMethodInfoIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), null),
"methodInfo");
}
[Fact]
public void MethodInfo_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
Action action = new Action(() => { });
Assert.Reflection.Property<ReflectedHttpActionDescriptor, MethodInfo>(
instance: actionDescriptor,
propertyGetter: ad => ad.MethodInfo,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: action.Method);
}
[Fact]
public void ControllerDescriptor_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpControllerDescriptor>(
instance: actionDescriptor,
propertyGetter: ad => ad.ControllerDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerDescriptor);
}
[Fact]
public void Configuration_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
HttpConfiguration config = new HttpConfiguration();
Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpConfiguration>(
instance: actionDescriptor,
propertyGetter: ad => ad.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void GetFilter_Returns_AttributedFilter()
{
Func<string, string, User> echoUserMethod = _controller.AddAdmin;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
IEnumerable<IFilter> filters = actionDescriptor.GetFilters();
Assert.NotNull(filters);
Assert.Equal(1, filters.Count());
Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
}
[Fact]
public void GetFilterPipeline_Returns_ConfigurationFilters()
{
IActionFilter actionFilter = new Mock<IActionFilter>().Object;
IExceptionFilter exceptionFilter = new Mock<IExceptionFilter>().Object;
IAuthorizationFilter authorizationFilter = new AuthorizeAttribute();
Action deleteAllUsersMethod = _controller.DeleteAllUsers;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "UsersRpcController", typeof(UsersRpcController));
controllerDescriptor.Configuration.Filters.Add(actionFilter);
controllerDescriptor.Configuration.Filters.Add(exceptionFilter);
controllerDescriptor.Configuration.Filters.Add(authorizationFilter);
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, deleteAllUsersMethod.Method);
Collection<FilterInfo> filters = actionDescriptor.GetFilterPipeline();
Assert.Same(actionFilter, filters[0].Instance);
Assert.Same(exceptionFilter, filters[1].Instance);
Assert.Same(authorizationFilter, filters[2].Instance);
}
[Fact]
public void GetCustomAttributes_Returns_ActionAttributes()
{
Func<string, string, User> echoUserMethod = _controller.AddAdmin;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
IEnumerable<IFilter> filters = actionDescriptor.GetCustomAttributes<IFilter>();
IEnumerable<HttpGetAttribute> httpGet = actionDescriptor.GetCustomAttributes<HttpGetAttribute>();
Assert.NotNull(filters);
Assert.Equal(1, filters.Count());
Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
Assert.NotNull(httpGet);
Assert.Equal(1, httpGet.Count());
}
[Fact]
public void GetParameters_Returns_ActionParameters()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Collection<HttpParameterDescriptor> parameterDescriptors = actionDescriptor.GetParameters();
Assert.Equal(2, parameterDescriptors.Count);
Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "firstName").FirstOrDefault());
Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "lastName").FirstOrDefault());
}
[Fact]
public void ExecuteAsync_Returns_TaskOfNull_ForVoidAction()
{
Action deleteAllUsersMethod = _controller.DeleteAllUsers;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
returnValue.WaitUntilCompleted();
Assert.Null(returnValue.Result);
}
[Fact]
public void ExecuteAsync_Returns_Results_ForNonVoidAction()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
result.WaitUntilCompleted();
var returnValue = Assert.IsType<User>(result.Result);
Assert.Equal("test", returnValue.FirstName);
Assert.Equal("unit", returnValue.LastName);
}
[Fact]
public void ExecuteAsync_Returns_TaskOfNull_ForTaskAction()
{
Func<Task> deleteAllUsersMethod = _controller.DeleteAllUsersAsync;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
returnValue.WaitUntilCompleted();
Assert.Null(returnValue.Result);
}
[Fact]
public void ExecuteAsync_Returns_Results_ForTaskOfTAction()
{
Func<string, string, Task<User>> echoUserMethod = _controller.EchoUserAsync;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
result.WaitUntilCompleted();
var returnValue = Assert.IsType<User>(result.Result);
Assert.Equal("test", returnValue.FirstName);
Assert.Equal("unit", returnValue.LastName);
}
[Fact]
public void ExecuteAsync_Throws_IfContextIsNull()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Assert.ThrowsArgumentNull(
() => actionDescriptor.ExecuteAsync(null, _arguments),
"controllerContext");
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentsIsNull()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Assert.ThrowsArgumentNull(
() => actionDescriptor.ExecuteAsync(_context, null).RethrowFaultedTaskException(),
"arguments");
}
[Fact]
public void ExecuteAsync_Throws_IfValueTypeArgumentsIsNull()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["id"] = null;
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' " +
"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. An optional parameter " +
"must be a reference type, a nullable type, or be declared as an optional parameter.",
content.Value);
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentNameIsWrong()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["otherId"] = 6;
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary does not contain an entry for parameter 'id' of type 'System.Int32' " +
"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
"The dictionary must contain an entry for each parameter, including parameters that have null values.",
content.Value);
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentTypeIsWrong()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["id"] = new DateTime();
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary contains an invalid entry for parameter 'id' for method " +
"'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
"The dictionary contains a value of type 'System.DateTime', but the parameter requires a value " +
"of type 'System.Int32'.",
content.Value);
}
[Fact]
public void ExecuteAsync_IfTaskReturningMethod_ReturnsWrappedTaskInstance_Throws()
{
Func<Task> method = _controller.WrappedTaskReturningMethod;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
var exception = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
"The method 'WrappedTaskReturningMethod' on type 'UsersRpcController' returned an instance of 'System.Threading.Tasks.Task`1[[System.Threading.Tasks.Task, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.");
}
[Fact]
public void ExecuteAsync_IfObjectReturningMethod_ReturnsTaskInstance_Throws()
{
Func<object> method = _controller.TaskAsObjectReturningMethod;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
var exception = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
"The method 'TaskAsObjectReturningMethod' on type 'UsersRpcController' returned a Task instance even though it is not an asynchronous method.");
}
[Theory]
[InlineData(typeof(void), null)]
[InlineData(typeof(string), typeof(string))]
[InlineData(typeof(Task), null)]
[InlineData(typeof(Task<string>), typeof(string))]
public void GetReturnType_ReturnsUnwrappedActionType(Type methodReturnType, Type expectedReturnType)
{
Mock<MethodInfo> methodMock = new Mock<MethodInfo>();
methodMock.Setup(m => m.ReturnType).Returns(methodReturnType);
Assert.Equal(expectedReturnType, ReflectedHttpActionDescriptor.GetReturnType(methodMock.Object));
}
}
}

View File

@ -0,0 +1,93 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ReflectedHttpParameterDescriptorTest
{
[Fact]
public void Parameter_Constructor()
{
UsersRpcController controller = new UsersRpcController();
Func<string, string, User> echoUserMethod = controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
ParameterInfo parameterInfo = echoUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
Assert.Equal(actionDescriptor, parameterDescriptor.ActionDescriptor);
Assert.Null(parameterDescriptor.DefaultValue);
Assert.Equal(parameterInfo, parameterDescriptor.ParameterInfo);
Assert.Equal(parameterInfo.Name, parameterDescriptor.ParameterName);
Assert.Equal(typeof(string), parameterDescriptor.ParameterType);
Assert.Null(parameterDescriptor.Prefix);
Assert.Null(parameterDescriptor.ModelBinderAttribute);
}
[Fact]
public void Constructor_Throws_IfParameterInfoIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpParameterDescriptor(new Mock<HttpActionDescriptor>().Object, null),
"parameterInfo");
}
[Fact]
public void Constructor_Throws_IfActionDescriptorIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpParameterDescriptor(null, new Mock<ParameterInfo>().Object),
"actionDescriptor");
}
[Fact]
public void ParameterInfo_Property()
{
ParameterInfo referenceParameter = new Mock<ParameterInfo>().Object;
Assert.Reflection.Property(new ReflectedHttpParameterDescriptor(), d => d.ParameterInfo, expectedDefaultValue: null, allowNull: false, roundTripTestValue: referenceParameter);
}
[Fact]
public void IsDefined_Retruns_True_WhenParameterAttributeIsFound()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
}
[Fact]
public void GetCustomAttributes_Returns_ParameterAttributes()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
object[] attributes = parameterDescriptor.GetCustomAttributes<object>().ToArray();
Assert.Equal(1, attributes.Length);
Assert.Equal(typeof(FromBodyAttribute), attributes[0].GetType());
}
[Fact]
public void GetCustomAttributes_AttributeType_Returns_ParameterAttributes()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();
Assert.Equal(1, attributes.Count());
}
}
}

View File

@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class ResponseMessageResultConverterTest
{
private readonly ResponseMessageResultConverter _converter = new ResponseMessageResultConverter();
private readonly HttpControllerContext _context = new HttpControllerContext();
private readonly HttpRequestMessage _request = new HttpRequestMessage();
public ResponseMessageResultConverterTest()
{
_context.Request = _request;
_context.Configuration = new HttpConfiguration();
}
[Fact]
public void Convert_WhenValueIsResponseMessage_ReturnsResponseMessageWithRequestAssigned()
{
HttpResponseMessage response = new HttpResponseMessage();
var result = _converter.Convert(_context, response);
Assert.Same(response, result);
Assert.Same(_request, result.RequestMessage);
}
[Fact]
public void Convert_WhenContextIsNull_Throws()
{
Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: new HttpResponseMessage()), "controllerContext");
}
[Fact]
public void Convert_WhenValueIsNull_Throws()
{
Assert.Throws<InvalidOperationException>(() => _converter.Convert(_context, null),
"A null value was returned where an instance of HttpResponseMessage was expected.");
}
[Fact]
public void Convert_WhenValueIsIncompatibleType_Throws()
{
Assert.Throws<InvalidCastException>(() => _converter.Convert(_context, "42"),
"Unable to cast object of type 'System.String' to type 'System.Net.Http.HttpResponseMessage'.");
}
}
}

Some files were not shown because too many files have changed in this diff Show More