PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/test/System.Web.Http.Test/Controllers/ReflectedHttpActionDescriptorTest.cs

https://bitbucket.org/mdavid/aspnetwebstack
C# | 340 lines | 283 code | 57 blank | 0 comment | 2 complexity | 16f13f7a3b1198976bf19ab6369a0d7a MD5 | raw file
  1. using System.Collections.Generic;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Reflection;
  7. using System.Threading.Tasks;
  8. using System.Web.Http.Controllers;
  9. using System.Web.Http.Filters;
  10. using Moq;
  11. using Xunit;
  12. using Xunit.Extensions;
  13. using Assert = Microsoft.TestCommon.AssertEx;
  14. namespace System.Web.Http
  15. {
  16. public class ReflectedHttpActionDescriptorTest
  17. {
  18. private readonly UsersRpcController _controller = new UsersRpcController();
  19. private readonly HttpControllerContext _context;
  20. private readonly Dictionary<string, object> _arguments = new Dictionary<string, object>();
  21. public ReflectedHttpActionDescriptorTest()
  22. {
  23. _context = ContextUtil.CreateControllerContext(instance: _controller);
  24. }
  25. [Fact]
  26. public void Default_Constructor()
  27. {
  28. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
  29. Assert.Null(actionDescriptor.ActionName);
  30. Assert.Null(actionDescriptor.Configuration);
  31. Assert.Null(actionDescriptor.ControllerDescriptor);
  32. Assert.Null(actionDescriptor.MethodInfo);
  33. Assert.Null(actionDescriptor.ReturnType);
  34. Assert.NotNull(actionDescriptor.Properties);
  35. }
  36. [Fact]
  37. public void Parameter_Constructor()
  38. {
  39. Func<string, string, User> echoUserMethod = _controller.EchoUser;
  40. HttpConfiguration config = new HttpConfiguration();
  41. HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "", typeof(UsersRpcController));
  42. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);
  43. Assert.Equal("EchoUser", actionDescriptor.ActionName);
  44. Assert.Equal(config, actionDescriptor.Configuration);
  45. Assert.Equal(typeof(UsersRpcController), actionDescriptor.ControllerDescriptor.ControllerType);
  46. Assert.Equal(echoUserMethod.Method, actionDescriptor.MethodInfo);
  47. Assert.Equal(typeof(User), actionDescriptor.ReturnType);
  48. Assert.NotNull(actionDescriptor.Properties);
  49. }
  50. [Fact]
  51. public void Constructor_Throws_IfMethodInfoIsNull()
  52. {
  53. Assert.ThrowsArgumentNull(
  54. () => new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), null),
  55. "methodInfo");
  56. }
  57. [Fact]
  58. public void MethodInfo_Property()
  59. {
  60. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
  61. Action action = new Action(() => { });
  62. Assert.Reflection.Property<ReflectedHttpActionDescriptor, MethodInfo>(
  63. instance: actionDescriptor,
  64. propertyGetter: ad => ad.MethodInfo,
  65. expectedDefaultValue: null,
  66. allowNull: false,
  67. roundTripTestValue: action.Method);
  68. }
  69. [Fact]
  70. public void ControllerDescriptor_Property()
  71. {
  72. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
  73. HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
  74. Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpControllerDescriptor>(
  75. instance: actionDescriptor,
  76. propertyGetter: ad => ad.ControllerDescriptor,
  77. expectedDefaultValue: null,
  78. allowNull: false,
  79. roundTripTestValue: controllerDescriptor);
  80. }
  81. [Fact]
  82. public void Configuration_Property()
  83. {
  84. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
  85. HttpConfiguration config = new HttpConfiguration();
  86. Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpConfiguration>(
  87. instance: actionDescriptor,
  88. propertyGetter: ad => ad.Configuration,
  89. expectedDefaultValue: null,
  90. allowNull: false,
  91. roundTripTestValue: config);
  92. }
  93. [Fact]
  94. public void GetFilter_Returns_AttributedFilter()
  95. {
  96. Func<string, string, User> echoUserMethod = _controller.AddAdmin;
  97. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  98. _arguments["firstName"] = "test";
  99. _arguments["lastName"] = "unit";
  100. IEnumerable<IFilter> filters = actionDescriptor.GetFilters();
  101. Assert.NotNull(filters);
  102. Assert.Equal(1, filters.Count());
  103. Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
  104. }
  105. [Fact]
  106. public void GetFilterPipeline_Returns_ConfigurationFilters()
  107. {
  108. IActionFilter actionFilter = new Mock<IActionFilter>().Object;
  109. IExceptionFilter exceptionFilter = new Mock<IExceptionFilter>().Object;
  110. IAuthorizationFilter authorizationFilter = new AuthorizeAttribute();
  111. Action deleteAllUsersMethod = _controller.DeleteAllUsers;
  112. HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "UsersRpcController", typeof(UsersRpcController));
  113. controllerDescriptor.Configuration.Filters.Add(actionFilter);
  114. controllerDescriptor.Configuration.Filters.Add(exceptionFilter);
  115. controllerDescriptor.Configuration.Filters.Add(authorizationFilter);
  116. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, deleteAllUsersMethod.Method);
  117. Collection<FilterInfo> filters = actionDescriptor.GetFilterPipeline();
  118. Assert.Same(actionFilter, filters[0].Instance);
  119. Assert.Same(exceptionFilter, filters[1].Instance);
  120. Assert.Same(authorizationFilter, filters[2].Instance);
  121. }
  122. [Fact]
  123. public void GetCustomAttributes_Returns_ActionAttributes()
  124. {
  125. Func<string, string, User> echoUserMethod = _controller.AddAdmin;
  126. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  127. IEnumerable<IFilter> filters = actionDescriptor.GetCustomAttributes<IFilter>();
  128. IEnumerable<HttpGetAttribute> httpGet = actionDescriptor.GetCustomAttributes<HttpGetAttribute>();
  129. Assert.NotNull(filters);
  130. Assert.Equal(1, filters.Count());
  131. Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
  132. Assert.NotNull(httpGet);
  133. Assert.Equal(1, httpGet.Count());
  134. }
  135. [Fact]
  136. public void GetParameters_Returns_ActionParameters()
  137. {
  138. Func<string, string, User> echoUserMethod = _controller.EchoUser;
  139. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  140. Collection<HttpParameterDescriptor> parameterDescriptors = actionDescriptor.GetParameters();
  141. Assert.Equal(2, parameterDescriptors.Count);
  142. Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "firstName").FirstOrDefault());
  143. Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "lastName").FirstOrDefault());
  144. }
  145. [Fact]
  146. public void ExecuteAsync_Returns_TaskOfNull_ForVoidAction()
  147. {
  148. Action deleteAllUsersMethod = _controller.DeleteAllUsers;
  149. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
  150. Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
  151. returnValue.WaitUntilCompleted();
  152. Assert.Null(returnValue.Result);
  153. }
  154. [Fact]
  155. public void ExecuteAsync_Returns_Results_ForNonVoidAction()
  156. {
  157. Func<string, string, User> echoUserMethod = _controller.EchoUser;
  158. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  159. _arguments["firstName"] = "test";
  160. _arguments["lastName"] = "unit";
  161. Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
  162. result.WaitUntilCompleted();
  163. var returnValue = Assert.IsType<User>(result.Result);
  164. Assert.Equal("test", returnValue.FirstName);
  165. Assert.Equal("unit", returnValue.LastName);
  166. }
  167. [Fact]
  168. public void ExecuteAsync_Returns_TaskOfNull_ForTaskAction()
  169. {
  170. Func<Task> deleteAllUsersMethod = _controller.DeleteAllUsersAsync;
  171. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
  172. Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
  173. returnValue.WaitUntilCompleted();
  174. Assert.Null(returnValue.Result);
  175. }
  176. [Fact]
  177. public void ExecuteAsync_Returns_Results_ForTaskOfTAction()
  178. {
  179. Func<string, string, Task<User>> echoUserMethod = _controller.EchoUserAsync;
  180. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  181. _arguments["firstName"] = "test";
  182. _arguments["lastName"] = "unit";
  183. Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
  184. result.WaitUntilCompleted();
  185. var returnValue = Assert.IsType<User>(result.Result);
  186. Assert.Equal("test", returnValue.FirstName);
  187. Assert.Equal("unit", returnValue.LastName);
  188. }
  189. [Fact]
  190. public void ExecuteAsync_Throws_IfContextIsNull()
  191. {
  192. Func<string, string, User> echoUserMethod = _controller.EchoUser;
  193. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  194. Assert.ThrowsArgumentNull(
  195. () => actionDescriptor.ExecuteAsync(null, _arguments),
  196. "controllerContext");
  197. }
  198. [Fact]
  199. public void ExecuteAsync_Throws_IfArgumentsIsNull()
  200. {
  201. Func<string, string, User> echoUserMethod = _controller.EchoUser;
  202. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
  203. Assert.ThrowsArgumentNull(
  204. () => actionDescriptor.ExecuteAsync(_context, null).RethrowFaultedTaskException(),
  205. "arguments");
  206. }
  207. [Fact]
  208. public void ExecuteAsync_Throws_IfValueTypeArgumentsIsNull()
  209. {
  210. Func<int, User> retrieveUserMethod = _controller.RetriveUser;
  211. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
  212. _arguments["id"] = null;
  213. var exception = Assert.Throws<HttpResponseException>(
  214. () => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
  215. Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
  216. var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
  217. Assert.Equal("The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' " +
  218. "for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. An optional parameter " +
  219. "must be a reference type, a nullable type, or be declared as an optional parameter.",
  220. content.Value);
  221. }
  222. [Fact]
  223. public void ExecuteAsync_Throws_IfArgumentNameIsWrong()
  224. {
  225. Func<int, User> retrieveUserMethod = _controller.RetriveUser;
  226. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
  227. _arguments["otherId"] = 6;
  228. var exception = Assert.Throws<HttpResponseException>(
  229. () => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
  230. Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
  231. var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
  232. Assert.Equal("The parameters dictionary does not contain an entry for parameter 'id' of type 'System.Int32' " +
  233. "for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
  234. "The dictionary must contain an entry for each parameter, including parameters that have null values.",
  235. content.Value);
  236. }
  237. [Fact]
  238. public void ExecuteAsync_Throws_IfArgumentTypeIsWrong()
  239. {
  240. Func<int, User> retrieveUserMethod = _controller.RetriveUser;
  241. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
  242. _arguments["id"] = new DateTime();
  243. var exception = Assert.Throws<HttpResponseException>(
  244. () => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
  245. Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
  246. var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
  247. Assert.Equal("The parameters dictionary contains an invalid entry for parameter 'id' for method " +
  248. "'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
  249. "The dictionary contains a value of type 'System.DateTime', but the parameter requires a value " +
  250. "of type 'System.Int32'.",
  251. content.Value);
  252. }
  253. [Fact]
  254. public void ExecuteAsync_IfTaskReturningMethod_ReturnsWrappedTaskInstance_Throws()
  255. {
  256. Func<Task> method = _controller.WrappedTaskReturningMethod;
  257. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
  258. var exception = Assert.Throws<InvalidOperationException>(
  259. () => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
  260. "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.");
  261. }
  262. [Fact]
  263. public void ExecuteAsync_IfObjectReturningMethod_ReturnsTaskInstance_Throws()
  264. {
  265. Func<object> method = _controller.TaskAsObjectReturningMethod;
  266. ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
  267. var exception = Assert.Throws<InvalidOperationException>(
  268. () => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
  269. "The method 'TaskAsObjectReturningMethod' on type 'UsersRpcController' returned a Task instance even though it is not an asynchronous method.");
  270. }
  271. [Theory]
  272. [InlineData(typeof(void), null)]
  273. [InlineData(typeof(string), typeof(string))]
  274. [InlineData(typeof(Task), null)]
  275. [InlineData(typeof(Task<string>), typeof(string))]
  276. public void GetReturnType_ReturnsUnwrappedActionType(Type methodReturnType, Type expectedReturnType)
  277. {
  278. Mock<MethodInfo> methodMock = new Mock<MethodInfo>();
  279. methodMock.Setup(m => m.ReturnType).Returns(methodReturnType);
  280. Assert.Equal(expectedReturnType, ReflectedHttpActionDescriptor.GetReturnType(methodMock.Object));
  281. }
  282. }
  283. }