PageRenderTime 65ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/test/System.Web.Mvc.Test/Test/ReflectedActionDescriptorTest.cs

https://bitbucket.org/mdavid/aspnetwebstack
C# | 491 lines | 352 code | 82 blank | 57 comment | 0 complexity | 0baa903c98374bd8b889a98c187cc7a3 MD5 | raw file
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Reflection;
  4. using Moq;
  5. using Xunit;
  6. using Assert = Microsoft.TestCommon.AssertEx;
  7. namespace System.Web.Mvc.Test
  8. {
  9. public class ReflectedActionDescriptorTest
  10. {
  11. private static readonly MethodInfo _int32EqualsIntMethod = typeof(int).GetMethod("Equals", new Type[] { typeof(int) });
  12. [Fact]
  13. public void ConstructorSetsActionNameProperty()
  14. {
  15. // Arrange
  16. string name = "someName";
  17. // Act
  18. ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);
  19. // Assert
  20. Assert.Equal(name, ad.ActionName);
  21. }
  22. [Fact]
  23. public void ConstructorSetsControllerDescriptorProperty()
  24. {
  25. // Arrange
  26. ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
  27. // Act
  28. ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", cd, false /* validateMethod */);
  29. // Assert
  30. Assert.Same(cd, ad.ControllerDescriptor);
  31. }
  32. [Fact]
  33. public void ConstructorSetsMethodInfoProperty()
  34. {
  35. // Arrange
  36. MethodInfo methodInfo = new Mock<MethodInfo>().Object;
  37. // Act
  38. ReflectedActionDescriptor ad = new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);
  39. // Assert
  40. Assert.Same(methodInfo, ad.MethodInfo);
  41. }
  42. [Fact]
  43. public void ConstructorThrowsIfActionNameIsEmpty()
  44. {
  45. // Act & assert
  46. Assert.ThrowsArgumentNullOrEmpty(
  47. delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "", new Mock<ControllerDescriptor>().Object); }, "actionName");
  48. }
  49. [Fact]
  50. public void ConstructorThrowsIfActionNameIsNull()
  51. {
  52. // Act & assert
  53. Assert.ThrowsArgumentNullOrEmpty(
  54. delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, null, new Mock<ControllerDescriptor>().Object); }, "actionName");
  55. }
  56. [Fact]
  57. public void ConstructorThrowsIfControllerDescriptorIsNull()
  58. {
  59. // Act & assert
  60. Assert.ThrowsArgumentNull(
  61. delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, "someName", null); }, "controllerDescriptor");
  62. }
  63. [Fact]
  64. public void ConstructorThrowsIfMethodInfoHasRefParameters()
  65. {
  66. // Arrange
  67. MethodInfo methodInfo = typeof(MyController).GetMethod("MethodHasRefParameter");
  68. // Act & assert
  69. Assert.Throws<ArgumentException>(
  70. delegate { new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object); },
  71. @"Cannot call action method 'Void MethodHasRefParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the parameter 'Int32& i' is passed by reference.
  72. Parameter name: methodInfo");
  73. }
  74. [Fact]
  75. public void ConstructorThrowsIfMethodInfoHasOutParameters()
  76. {
  77. // Arrange
  78. MethodInfo methodInfo = typeof(MyController).GetMethod("MethodHasOutParameter");
  79. // Act & assert
  80. Assert.Throws<ArgumentException>(
  81. delegate { new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object); },
  82. @"Cannot call action method 'Void MethodHasOutParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the parameter 'Int32& i' is passed by reference.
  83. Parameter name: methodInfo");
  84. }
  85. [Fact]
  86. public void ConstructorThrowsIfMethodInfoIsInstanceMethodOnNonControllerBaseType()
  87. {
  88. // Arrange
  89. MethodInfo methodInfo = typeof(string).GetMethod("Clone");
  90. // Act & assert
  91. Assert.Throws<ArgumentException>(
  92. delegate { new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object); },
  93. @"Cannot create a descriptor for instance method 'System.Object Clone()' on type 'System.String' because the type does not derive from ControllerBase.
  94. Parameter name: methodInfo");
  95. }
  96. [Fact]
  97. public void ConstructorThrowsIfMethodIsStatic()
  98. {
  99. // Arrange
  100. MethodInfo methodInfo = typeof(MyController).GetMethod("StaticMethod");
  101. // Act & assert
  102. Assert.Throws<ArgumentException>(
  103. delegate { new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object); },
  104. @"Cannot call action method 'Void StaticMethod()' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the action method is a static method.
  105. Parameter name: methodInfo");
  106. }
  107. [Fact]
  108. public void ConstructorThrowsIfMethodInfoIsNull()
  109. {
  110. // Act & assert
  111. Assert.ThrowsArgumentNull(
  112. delegate { new ReflectedActionDescriptor(null, "someName", new Mock<ControllerDescriptor>().Object); }, "methodInfo");
  113. }
  114. [Fact]
  115. public void ConstructorThrowsIfMethodInfoIsOpenGenericType()
  116. {
  117. // Arrange
  118. MethodInfo methodInfo = typeof(MyController).GetMethod("OpenGenericMethod");
  119. // Act & assert
  120. Assert.Throws<ArgumentException>(
  121. delegate { new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object); },
  122. @"Cannot call action method 'Void OpenGenericMethod[T]()' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the action method is a generic method.
  123. Parameter name: methodInfo");
  124. }
  125. [Fact]
  126. public void ExecuteCallsMethodInfoOnSuccess()
  127. {
  128. // Arrange
  129. Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
  130. mockControllerContext.Setup(c => c.Controller).Returns(new ConcatController());
  131. Dictionary<string, object> parameters = new Dictionary<string, object>()
  132. {
  133. { "a", "hello " },
  134. { "b", "world" }
  135. };
  136. ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod("Concat"));
  137. // Act
  138. object result = ad.Execute(mockControllerContext.Object, parameters);
  139. // Assert
  140. Assert.Equal("hello world", result);
  141. }
  142. [Fact]
  143. public void ExecuteThrowsIfControllerContextIsNull()
  144. {
  145. // Arrange
  146. ReflectedActionDescriptor ad = GetActionDescriptor();
  147. // Act & assert
  148. Assert.ThrowsArgumentNull(
  149. delegate { ad.Execute(null, new Dictionary<string, object>()); }, "controllerContext");
  150. }
  151. [Fact]
  152. public void ExecuteThrowsIfParametersContainsNullForNonNullableParameter()
  153. {
  154. // Arrange
  155. ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
  156. Dictionary<string, object> parameters = new Dictionary<string, object>() { { "obj", null } };
  157. // Act & assert
  158. Assert.Throws<ArgumentException>(
  159. delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },
  160. @"The parameters dictionary contains a null entry for parameter 'obj' of non-nullable type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  161. Parameter name: parameters");
  162. }
  163. [Fact]
  164. public void ExecuteThrowsIfParametersContainsValueOfWrongTypeForParameter()
  165. {
  166. // Arrange
  167. ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
  168. Dictionary<string, object> parameters = new Dictionary<string, object>() { { "obj", "notAnInteger" } };
  169. // Act & assert
  170. Assert.Throws<ArgumentException>(
  171. delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },
  172. @"The parameters dictionary contains an invalid entry for parameter 'obj' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary contains a value of type 'System.String', but the parameter requires a value of type 'System.Int32'.
  173. Parameter name: parameters");
  174. }
  175. [Fact]
  176. public void ExecuteThrowsIfParametersIsMissingAValue()
  177. {
  178. // Arrange
  179. ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);
  180. Dictionary<string, object> parameters = new Dictionary<string, object>();
  181. // Act & assert
  182. Assert.Throws<ArgumentException>(
  183. delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },
  184. @"The parameters dictionary does not contain an entry for parameter 'obj' of type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary must contain an entry for each parameter, including parameters that have null values.
  185. Parameter name: parameters");
  186. }
  187. [Fact]
  188. public void ExecuteThrowsIfParametersIsNull()
  189. {
  190. // Arrange
  191. ReflectedActionDescriptor ad = GetActionDescriptor();
  192. // Act & assert
  193. Assert.ThrowsArgumentNull(
  194. delegate { ad.Execute(new Mock<ControllerContext>().Object, null); }, "parameters");
  195. }
  196. [Fact]
  197. public void GetCustomAttributesCallsMethodInfoGetCustomAttributes()
  198. {
  199. // Arrange
  200. object[] expected = new object[0];
  201. Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
  202. mockMethod.Setup(mi => mi.GetCustomAttributes(true)).Returns(expected);
  203. ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
  204. // Act
  205. object[] returned = ad.GetCustomAttributes(true);
  206. // Assert
  207. Assert.Same(expected, returned);
  208. }
  209. [Fact]
  210. public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes()
  211. {
  212. // Arrange
  213. object[] expected = new object[0];
  214. Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
  215. mockMethod.Setup(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);
  216. ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
  217. // Act
  218. object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);
  219. // Assert
  220. Assert.Same(expected, returned);
  221. }
  222. [Fact]
  223. public void GetParametersWrapsParameterInfos()
  224. {
  225. // Arrange
  226. ParameterInfo pInfo0 = typeof(ConcatController).GetMethod("Concat").GetParameters()[0];
  227. ParameterInfo pInfo1 = typeof(ConcatController).GetMethod("Concat").GetParameters()[1];
  228. ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod("Concat"));
  229. // Act
  230. ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();
  231. ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();
  232. // Assert
  233. Assert.NotSame(pDescsFirstCall, pDescsSecondCall);
  234. Assert.True(pDescsFirstCall.SequenceEqual(pDescsSecondCall));
  235. Assert.Equal(2, pDescsFirstCall.Length);
  236. ReflectedParameterDescriptor pDesc0 = pDescsFirstCall[0] as ReflectedParameterDescriptor;
  237. ReflectedParameterDescriptor pDesc1 = pDescsFirstCall[1] as ReflectedParameterDescriptor;
  238. Assert.NotNull(pDesc0);
  239. Assert.Same(ad, pDesc0.ActionDescriptor);
  240. Assert.Same(pInfo0, pDesc0.ParameterInfo);
  241. Assert.NotNull(pDesc1);
  242. Assert.Same(ad, pDesc1.ActionDescriptor);
  243. Assert.Same(pInfo1, pDesc1.ParameterInfo);
  244. }
  245. [Fact]
  246. public void GetSelectorsWrapsSelectorAttributes()
  247. {
  248. // Arrange
  249. ControllerContext controllerContext = new Mock<ControllerContext>().Object;
  250. Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
  251. Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();
  252. mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();
  253. mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });
  254. ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
  255. // Act
  256. ICollection<ActionSelector> selectors = ad.GetSelectors();
  257. bool executedSuccessfully = selectors.All(s => s(controllerContext));
  258. // Assert
  259. Assert.Single(selectors);
  260. Assert.True(executedSuccessfully);
  261. mockAttr.Verify();
  262. }
  263. [Fact]
  264. public void IsDefinedCallsMethodInfoIsDefined()
  265. {
  266. // Arrange
  267. Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();
  268. mockMethod.Setup(mi => mi.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);
  269. ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);
  270. // Act
  271. bool isDefined = ad.IsDefined(typeof(ObsoleteAttribute), true);
  272. // Assert
  273. Assert.True(isDefined);
  274. }
  275. [Fact]
  276. public void TryCreateDescriptorReturnsDescriptorOnSuccess()
  277. {
  278. // Arrange
  279. MethodInfo methodInfo = typeof(MyController).GetMethod("GoodActionMethod");
  280. ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
  281. // Act
  282. ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, "someName", cd);
  283. // Assert
  284. Assert.NotNull(ad);
  285. Assert.Same(methodInfo, ad.MethodInfo);
  286. Assert.Equal("someName", ad.ActionName);
  287. Assert.Same(cd, ad.ControllerDescriptor);
  288. }
  289. [Fact]
  290. public void TryCreateDescriptorReturnsNullOnFailure()
  291. {
  292. // Arrange
  293. MethodInfo methodInfo = typeof(MyController).GetMethod("OpenGenericMethod");
  294. ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
  295. // Act
  296. ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, "someName", cd);
  297. // Assert
  298. Assert.Null(ad);
  299. }
  300. private static ReflectedActionDescriptor GetActionDescriptor()
  301. {
  302. return GetActionDescriptor(new Mock<MethodInfo>().Object);
  303. }
  304. private static ReflectedActionDescriptor GetActionDescriptor(MethodInfo methodInfo)
  305. {
  306. return new ReflectedActionDescriptor(methodInfo, "someName", new Mock<ControllerDescriptor>().Object, false /* validateMethod */)
  307. {
  308. DispatcherCache = new ActionMethodDispatcherCache()
  309. };
  310. }
  311. private class ConcatController : Controller
  312. {
  313. public string Concat(string a, string b)
  314. {
  315. return a + b;
  316. }
  317. }
  318. [OutputCache(VaryByParam = "Class")]
  319. private class OverriddenAttributeController : Controller
  320. {
  321. [OutputCache(VaryByParam = "Method")]
  322. public void SomeMethod()
  323. {
  324. }
  325. }
  326. [KeyedActionFilter(Key = "BaseClass", Order = 0)]
  327. [KeyedAuthorizationFilter(Key = "BaseClass", Order = 0)]
  328. [KeyedExceptionFilter(Key = "BaseClass", Order = 0)]
  329. private class GetMemberChainController : Controller
  330. {
  331. [KeyedActionFilter(Key = "BaseMethod", Order = 0)]
  332. [KeyedAuthorizationFilter(Key = "BaseMethod", Order = 0)]
  333. public virtual void SomeVirtual()
  334. {
  335. }
  336. }
  337. [KeyedActionFilter(Key = "DerivedClass", Order = 1)]
  338. private class GetMemberChainDerivedController : GetMemberChainController
  339. {
  340. }
  341. [KeyedActionFilter(Key = "SubderivedClass", Order = 2)]
  342. private class GetMemberChainSubderivedController : GetMemberChainDerivedController
  343. {
  344. [KeyedActionFilter(Key = "SubderivedMethod", Order = 2)]
  345. public override void SomeVirtual()
  346. {
  347. }
  348. }
  349. private abstract class KeyedFilterAttribute : FilterAttribute
  350. {
  351. public string Key { get; set; }
  352. }
  353. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
  354. private class KeyedAuthorizationFilterAttribute : KeyedFilterAttribute, IAuthorizationFilter
  355. {
  356. public void OnAuthorization(AuthorizationContext filterContext)
  357. {
  358. throw new NotImplementedException();
  359. }
  360. }
  361. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
  362. private class KeyedExceptionFilterAttribute : KeyedFilterAttribute, IExceptionFilter
  363. {
  364. public void OnException(ExceptionContext filterContext)
  365. {
  366. throw new NotImplementedException();
  367. }
  368. }
  369. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
  370. private class KeyedActionFilterAttribute : KeyedFilterAttribute, IActionFilter, IResultFilter
  371. {
  372. public void OnActionExecuting(ActionExecutingContext filterContext)
  373. {
  374. throw new NotImplementedException();
  375. }
  376. public void OnActionExecuted(ActionExecutedContext filterContext)
  377. {
  378. throw new NotImplementedException();
  379. }
  380. public void OnResultExecuting(ResultExecutingContext filterContext)
  381. {
  382. throw new NotImplementedException();
  383. }
  384. public void OnResultExecuted(ResultExecutedContext filterContext)
  385. {
  386. throw new NotImplementedException();
  387. }
  388. }
  389. private class MyController : Controller
  390. {
  391. public void GoodActionMethod()
  392. {
  393. }
  394. public static void StaticMethod()
  395. {
  396. }
  397. public void OpenGenericMethod<T>()
  398. {
  399. }
  400. public void MethodHasOutParameter(out int i)
  401. {
  402. i = 0;
  403. }
  404. public void MethodHasRefParameter(ref int i)
  405. {
  406. }
  407. }
  408. }
  409. }