PropertyInfoTest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. //
  2. // PropertyInfoTest.cs - NUnit Test Cases for PropertyInfo
  3. //
  4. // Author:
  5. // Gert Driesen ([email protected])
  6. //
  7. // (C) 2004-2007 Gert Driesen
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Reflection;
  30. using System.Runtime.InteropServices;
  31. using System.Threading;
  32. #if !MONOTOUCH && !FULL_AOT_RUNTIME
  33. using System.Reflection.Emit;
  34. #endif
  35. using System.IO;
  36. using NUnit.Framework;
  37. namespace MonoTests.System.Reflection
  38. {
  39. [TestFixture]
  40. public class PropertyInfoTest
  41. {
  42. [Test]
  43. public void GetAccessorsTest ()
  44. {
  45. Type type = typeof (TestClass);
  46. PropertyInfo property = type.GetProperty ("ReadOnlyProperty");
  47. Assert.IsNotNull (property.Module, "#0");
  48. MethodInfo [] methods = property.GetAccessors (true);
  49. Assert.AreEqual (1, methods.Length, "#A1");
  50. Assert.IsNotNull (methods [0], "#A2");
  51. Assert.AreEqual ("get_ReadOnlyProperty", methods [0].Name, "#A3");
  52. methods = property.GetAccessors (false);
  53. Assert.AreEqual (1, methods.Length, "#B1");
  54. Assert.IsNotNull (methods [0], "#B2");
  55. Assert.AreEqual ("get_ReadOnlyProperty", methods [0].Name, "#B3");
  56. property = typeof (Base).GetProperty ("P");
  57. methods = property.GetAccessors (true);
  58. Assert.AreEqual (2, methods.Length, "#C1");
  59. Assert.IsNotNull (methods [0], "#C2");
  60. Assert.IsNotNull (methods [1], "#C3");
  61. Assert.IsTrue (HasMethod (methods, "get_P"), "#C4");
  62. Assert.IsTrue (HasMethod (methods, "set_P"), "#C5");
  63. methods = property.GetAccessors (false);
  64. Assert.AreEqual (2, methods.Length, "#D1");
  65. Assert.IsNotNull (methods [0], "#D2");
  66. Assert.IsNotNull (methods [1], "#D3");
  67. Assert.IsTrue (HasMethod (methods, "get_P"), "#D4");
  68. Assert.IsTrue (HasMethod (methods, "set_P"), "#D5");
  69. methods = property.GetAccessors ();
  70. Assert.AreEqual (2, methods.Length, "#E1");
  71. Assert.IsNotNull (methods [0], "#E2");
  72. Assert.IsNotNull (methods [1], "#E3");
  73. Assert.IsTrue (HasMethod (methods, "get_P"), "#E4");
  74. Assert.IsTrue (HasMethod (methods, "set_P"), "#E5");
  75. property = typeof (TestClass).GetProperty ("Private",
  76. BindingFlags.NonPublic | BindingFlags.Instance);
  77. methods = property.GetAccessors (true);
  78. Assert.AreEqual (2, methods.Length, "#F1");
  79. Assert.IsNotNull (methods [0], "#F2");
  80. Assert.IsNotNull (methods [1], "#F3");
  81. Assert.IsTrue (HasMethod (methods, "get_Private"), "#F4");
  82. Assert.IsTrue (HasMethod (methods, "set_Private"), "#F5");
  83. methods = property.GetAccessors (false);
  84. Assert.AreEqual (0, methods.Length, "#G");
  85. methods = property.GetAccessors ();
  86. Assert.AreEqual (0, methods.Length, "#H");
  87. property = typeof (TestClass).GetProperty ("PrivateSetter");
  88. methods = property.GetAccessors (true);
  89. Assert.AreEqual (2, methods.Length, "#H1");
  90. Assert.IsNotNull (methods [0], "#H2");
  91. Assert.IsNotNull (methods [1], "#H3");
  92. Assert.IsTrue (HasMethod (methods, "get_PrivateSetter"), "#H4");
  93. Assert.IsTrue (HasMethod (methods, "set_PrivateSetter"), "#H5");
  94. methods = property.GetAccessors (false);
  95. Assert.AreEqual (1, methods.Length, "#I1");
  96. Assert.IsNotNull (methods [0], "#I2");
  97. Assert.AreEqual ("get_PrivateSetter", methods [0].Name, "#I3");
  98. methods = property.GetAccessors ();
  99. Assert.AreEqual (1, methods.Length, "#J1");
  100. Assert.IsNotNull (methods [0], "#J2");
  101. Assert.AreEqual ("get_PrivateSetter", methods [0].Name, "#J3");
  102. }
  103. [Test]
  104. public void GetCustomAttributes ()
  105. {
  106. object [] attrs;
  107. PropertyInfo p = typeof (Base).GetProperty ("P");
  108. attrs = p.GetCustomAttributes (false);
  109. Assert.AreEqual (1, attrs.Length, "#A1");
  110. Assert.AreEqual (typeof (ThisAttribute), attrs [0].GetType (), "#A2");
  111. attrs = p.GetCustomAttributes (true);
  112. Assert.AreEqual (1, attrs.Length, "#A3");
  113. Assert.AreEqual (typeof (ThisAttribute), attrs [0].GetType (), "#A4");
  114. p = typeof (Base).GetProperty ("T");
  115. attrs = p.GetCustomAttributes (false);
  116. Assert.AreEqual (2, attrs.Length, "#B1");
  117. Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B2");
  118. Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B3");
  119. attrs = p.GetCustomAttributes (true);
  120. Assert.AreEqual (2, attrs.Length, "#B41");
  121. Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B5");
  122. Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B6");
  123. p = typeof (Base).GetProperty ("Z");
  124. attrs = p.GetCustomAttributes (false);
  125. Assert.AreEqual (0, attrs.Length, "#C1");
  126. attrs = p.GetCustomAttributes (true);
  127. Assert.AreEqual (0, attrs.Length, "#C2");
  128. }
  129. [Test]
  130. public void GetCustomAttributes_Inherited ()
  131. {
  132. object [] attrs;
  133. PropertyInfo p = typeof (Derived).GetProperty ("P");
  134. attrs = p.GetCustomAttributes (false);
  135. Assert.AreEqual (0, attrs.Length, "#A1");
  136. attrs = p.GetCustomAttributes (true);
  137. Assert.AreEqual (0, attrs.Length, "#A3");
  138. p = typeof (Derived).GetProperty ("T");
  139. attrs = p.GetCustomAttributes (false);
  140. Assert.AreEqual (2, attrs.Length, "#B1");
  141. Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B2");
  142. Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B3");
  143. attrs = p.GetCustomAttributes (true);
  144. Assert.AreEqual (2, attrs.Length, "#B41");
  145. Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B5");
  146. Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B6");
  147. p = typeof (Derived).GetProperty ("Z");
  148. attrs = p.GetCustomAttributes (false);
  149. Assert.AreEqual (0, attrs.Length, "#C1");
  150. attrs = p.GetCustomAttributes (true);
  151. Assert.AreEqual (0, attrs.Length, "#C2");
  152. }
  153. [Test]
  154. public void IsDefined_AttributeType_Null ()
  155. {
  156. Type derived = typeof (Derived);
  157. PropertyInfo pi = derived.GetProperty ("P");
  158. try {
  159. pi.IsDefined ((Type) null, false);
  160. Assert.Fail ("#1");
  161. } catch (ArgumentNullException ex) {
  162. Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
  163. Assert.IsNull (ex.InnerException, "#3");
  164. Assert.IsNotNull (ex.Message, "#4");
  165. Assert.IsNotNull (ex.ParamName, "#5");
  166. Assert.AreEqual ("attributeType", ex.ParamName, "#6");
  167. }
  168. }
  169. [Test]
  170. public void AccessorsReflectedType ()
  171. {
  172. PropertyInfo pi = typeof (Derived).GetProperty ("T");
  173. Assert.AreEqual (typeof (Derived), pi.GetGetMethod ().ReflectedType);
  174. Assert.AreEqual (typeof (Derived), pi.GetSetMethod ().ReflectedType);
  175. }
  176. [Test] // bug #399985
  177. public void SetValue_Enum ()
  178. {
  179. TestClass t = new TestClass ();
  180. PropertyInfo pi = t.GetType ().GetProperty ("Targets");
  181. pi.SetValue (t, AttributeTargets.Field, null);
  182. Assert.AreEqual (AttributeTargets.Field, t.Targets, "#1");
  183. pi.SetValue (t, (int) AttributeTargets.Interface, null);
  184. Assert.AreEqual (AttributeTargets.Interface, t.Targets, "#2");
  185. }
  186. public class ThisAttribute : Attribute
  187. {
  188. }
  189. class Base
  190. {
  191. [ThisAttribute]
  192. public virtual string P {
  193. get { return null; }
  194. set { }
  195. }
  196. [ThisAttribute]
  197. [ComVisible (false)]
  198. public virtual string T {
  199. get { return null; }
  200. set { }
  201. }
  202. public virtual string Z {
  203. get { return null; }
  204. set { }
  205. }
  206. }
  207. class Derived : Base
  208. {
  209. public override string P {
  210. get { return null; }
  211. set { }
  212. }
  213. }
  214. static void RunTest (Type t, bool use_getter) {
  215. var p = t.GetProperty ("Item");
  216. var idx = p.GetIndexParameters ();
  217. var m_args = t.GetMethod (use_getter ? "get_Item" : "set_Item").GetParameters ();
  218. Assert.AreEqual (2, idx.Length, "#1");
  219. Assert.AreEqual (typeof (double), idx [0].ParameterType, "#2");
  220. Assert.AreEqual (p, idx [0].Member, "#3");
  221. Assert.AreEqual ("a", idx [0].Name, "#4");
  222. Assert.AreEqual (0, idx [0].Position, "#5");
  223. Assert.AreEqual (m_args [0].MetadataToken, idx [0].MetadataToken, "#6");
  224. Assert.AreEqual (ParameterAttributes.None, idx [0].Attributes, "#7");
  225. Assert.AreEqual (typeof (string), idx [1].ParameterType, "#8");
  226. Assert.AreEqual (p, idx [1].Member, "#9");
  227. Assert.AreEqual ("b", idx [1].Name, "#10");
  228. Assert.AreEqual (1, idx [1].Position, "#11");
  229. Assert.AreEqual (m_args [1].MetadataToken, idx [1].MetadataToken, "#12");
  230. Assert.AreEqual (ParameterAttributes.None, idx [1].Attributes, "#13");
  231. var idx2 = p.GetIndexParameters ();
  232. //No interning exposed
  233. Assert.AreNotSame (idx, idx2, "#14");
  234. Assert.AreNotSame (idx [0], idx2 [1], "#15");
  235. }
  236. [Test]
  237. public void GetIndexParameterReturnsObjectsBoundToTheProperty ()
  238. {
  239. RunTest (typeof (TestA), false);
  240. RunTest (typeof (TestB), true);
  241. }
  242. public class TestA {
  243. public int this[double a, string b] {
  244. set {}
  245. }
  246. }
  247. public class TestB {
  248. public int this[double a, string b] {
  249. get { return 1; }
  250. set {}
  251. }
  252. }
  253. [Test]
  254. public void GetIndexParameterReturnedObjectsCustomAttributes () {
  255. var pa = typeof (TestC).GetProperty ("Item").GetIndexParameters () [0];
  256. Assert.IsTrue (pa.IsDefined (typeof (ParamArrayAttribute), false), "#1");
  257. var pb = typeof (TestD).GetProperty ("Item").GetIndexParameters () [0];
  258. Assert.IsTrue (pb.IsDefined (typeof (ParamArrayAttribute), false), "#2");
  259. Assert.AreEqual (1, Attribute.GetCustomAttributes (pa).Length, "#3");
  260. Assert.AreEqual (1, Attribute.GetCustomAttributes (pb).Length, "#4");
  261. Assert.AreEqual (0, pa.GetOptionalCustomModifiers ().Length, "#5");
  262. Assert.AreEqual (0, pb.GetRequiredCustomModifiers ().Length, "#6");
  263. }
  264. public class TestC {
  265. public int this[params double[] a] {
  266. get { return 99; }
  267. }
  268. }
  269. public class TestD {
  270. public int this[params double[] a] {
  271. set { }
  272. }
  273. }
  274. static string CreateTempAssembly ()
  275. {
  276. FileStream f = null;
  277. string path;
  278. Random rnd;
  279. int num = 0;
  280. rnd = new Random ();
  281. do {
  282. num = rnd.Next ();
  283. num++;
  284. path = Path.Combine (Path.GetTempPath (), "tmp" + num.ToString ("x") + ".dll");
  285. try {
  286. f = new FileStream (path, FileMode.CreateNew);
  287. } catch { }
  288. } while (f == null);
  289. f.Close ();
  290. return "tmp" + num.ToString ("x") + ".dll";
  291. }
  292. public class TestE {
  293. public int PropE {
  294. get { return 99; }
  295. }
  296. }
  297. #if !MONOTOUCH && !FULL_AOT_RUNTIME
  298. [Test]
  299. public void ConstantValue () {
  300. /*This test looks scary because we can't generate a default value with C# */
  301. var assemblyName = new AssemblyName ();
  302. assemblyName.Name = "MonoTests.System.Reflection.Emit.PropertyInfoTest";
  303. string an = CreateTempAssembly ();
  304. var assembly = Thread.GetDomain ().DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
  305. var module = assembly.DefineDynamicModule ("module1", an);
  306. var tb = module.DefineType ("Test", TypeAttributes.Public);
  307. var prop = tb.DefineProperty ("Prop", PropertyAttributes.HasDefault, typeof (string), new Type [0]);
  308. var getter = tb.DefineMethod ("get_Prop", MethodAttributes.Public, typeof (string), new Type [0]);
  309. var ilgen = getter.GetILGenerator ();
  310. ilgen.Emit (OpCodes.Ldnull);
  311. ilgen.Emit (OpCodes.Ret);
  312. var setter = tb.DefineMethod ("set_Prop", MethodAttributes.Public, null, new Type [1] { typeof (string) });
  313. setter.GetILGenerator ().Emit (OpCodes.Ret);
  314. prop.SetConstant ("test");
  315. prop.SetGetMethod (getter);
  316. prop.SetSetMethod (setter);
  317. tb.CreateType ();
  318. File.Delete (Path.Combine (Path.GetTempPath (), an));
  319. assembly.Save (an);
  320. var asm = Assembly.LoadFrom (Path.Combine (Path.GetTempPath (), an));
  321. var t = asm.GetType ("Test");
  322. var p = t.GetProperty ("Prop");
  323. Assert.AreEqual ("test", p.GetConstantValue (), "#1");
  324. try {
  325. // This throws an exception under MS.NET and Mono on Windows,
  326. // open files cannot be deleted. That's fine.
  327. File.Delete (Path.Combine (Path.GetTempPath (), an));
  328. } catch (Exception) {
  329. }
  330. var pa = typeof (TestE).GetProperty ("PropE");
  331. try {
  332. pa.GetConstantValue ();
  333. Assert.Fail ("#2");
  334. } catch (InvalidOperationException) {
  335. }
  336. }
  337. #endif
  338. public class A<T>
  339. {
  340. public string Property {
  341. get { return typeof (T).FullName; }
  342. }
  343. }
  344. public int? nullable_field;
  345. public int? NullableProperty {
  346. get { return nullable_field; }
  347. set { nullable_field = value; }
  348. }
  349. [Test]
  350. public void NullableTests ()
  351. {
  352. PropertyInfoTest t = new PropertyInfoTest ();
  353. PropertyInfo pi = typeof(PropertyInfoTest).GetProperty("NullableProperty");
  354. pi.SetValue (t, 100, null);
  355. Assert.AreEqual (100, pi.GetValue (t, null));
  356. pi.SetValue (t, null, null);
  357. Assert.AreEqual (null, pi.GetValue (t, null));
  358. }
  359. [Test]
  360. public void Bug77160 ()
  361. {
  362. object instance = new A<string> ();
  363. Type type = instance.GetType ();
  364. PropertyInfo property = type.GetProperty ("Property");
  365. Assert.AreEqual (typeof (string).FullName, property.GetValue (instance, null));
  366. }
  367. [Test]
  368. public void ToStringTest ()
  369. {
  370. var pa = typeof (TestC).GetProperty ("Item");
  371. Assert.AreEqual ("Int32 Item [Double[]]", pa.ToString ());
  372. }
  373. static bool HasAttribute (object [] attrs, Type attributeType)
  374. {
  375. foreach (object attr in attrs)
  376. if (attr.GetType () == attributeType)
  377. return true;
  378. return false;
  379. }
  380. static bool HasMethod (MethodInfo [] methods, string name)
  381. {
  382. foreach (MethodInfo method in methods)
  383. if (method.Name == name)
  384. return true;
  385. return false;
  386. }
  387. private class TestClass
  388. {
  389. private AttributeTargets _targets = AttributeTargets.Assembly;
  390. public AttributeTargets Targets {
  391. get { return _targets; }
  392. set { _targets = value; }
  393. }
  394. public string ReadOnlyProperty {
  395. get { return string.Empty; }
  396. }
  397. private string Private {
  398. get { return null; }
  399. set { }
  400. }
  401. public string PrivateSetter {
  402. get { return null; }
  403. private set { }
  404. }
  405. }
  406. [Test] // bug #633671
  407. public void DeclaringTypeOfPropertyFromInheritedTypePointsToBase ()
  408. {
  409. var inherit1 = typeof(InheritsFromClassWithNullableDateTime);
  410. var siblingProperty = inherit1.GetProperty("Property1");
  411. Assert.AreEqual (typeof (ClassWithNullableDateTime), siblingProperty.DeclaringType, "#1");
  412. Assert.AreEqual (typeof (InheritsFromClassWithNullableDateTime), siblingProperty.ReflectedType, "#2");
  413. //The check is done twice since the bug is related to getting those 2 properties multiple times.
  414. Assert.AreEqual (typeof (ClassWithNullableDateTime), siblingProperty.DeclaringType, "#3");
  415. Assert.AreEqual (typeof (InheritsFromClassWithNullableDateTime), siblingProperty.ReflectedType, "#4");
  416. }
  417. class Super { public long A { get; private set; } }
  418. class Sub : Super { }
  419. [Test]
  420. public void PrivateSetterFromDerivedType ()
  421. {
  422. var prop = typeof (Sub).GetProperty ("A");
  423. Assert.AreEqual (1, prop.GetAccessors (true).Length, "#1");
  424. Assert.IsFalse (prop.CanWrite, "#2");
  425. Assert.IsNull (prop.GetSetMethod (true), "#3");
  426. }
  427. public class ClassWithNullableDateTime
  428. {
  429. public DateTime? Property1 { get; set; }
  430. }
  431. public class InheritsFromClassWithNullableDateTime : ClassWithNullableDateTime
  432. {
  433. }
  434. public static int ThrowingProperty {
  435. get {
  436. throw new ObjectDisposedException("TestClass");
  437. }
  438. }
  439. [Test]
  440. public void GetException () {
  441. var prop = typeof(PropertyInfoTest).GetProperty("ThrowingProperty");
  442. try {
  443. prop.GetValue (null, null);
  444. Assert.Fail ();
  445. } catch (TargetInvocationException ex) {
  446. Assert.IsTrue (ex.InnerException is ObjectDisposedException);
  447. }
  448. }
  449. public class DefaultValueTest
  450. {
  451. public string this[int val, string param = "test"]
  452. {
  453. get{ return val + param; }
  454. }
  455. }
  456. [Test]
  457. public void PropertyWithDefaultValue ()
  458. {
  459. var parameters = typeof (DefaultValueTest).GetProperty ("Item").GetIndexParameters ();
  460. var defaultParam = parameters[parameters.Length - 1];
  461. Assert.AreEqual ("param", defaultParam.Name, "#1");
  462. Assert.AreEqual ("test", defaultParam.DefaultValue, "#2");
  463. }
  464. [Test]
  465. public void MetadataToken ()
  466. {
  467. PropertyInfo property = typeof (Base).GetProperty ("P");
  468. Assert.IsTrue ((int)property.MetadataToken > 0);
  469. }
  470. }
  471. }