-//\r
-// MethodBuilderTest.cs - NUnit Test Cases for the MethodBuilder class\r
-//\r
-// Zoltan Varga (vargaz@freemail.hu)\r
-//\r
-// (C) Ximian, Inc. http://www.ximian.com\r
-\r
-// TODO:\r
-// - implement 'Signature' (what the hell it does???) and test it\r
-// - implement Equals and test it\r
-\r
-using System;\r
-using System.Threading;\r
-using System.Reflection;\r
-using System.Reflection.Emit;\r
-using System.Runtime.CompilerServices;\r
-using System.Security;\r
-using System.Security.Permissions;\r
-\r
-using NUnit.Framework;\r
-\r
-namespace MonoTests.System.Reflection.Emit\r
-{\r
-\r
-[TestFixture]\r
-public class MethodBuilderTest : Assertion\r
-{ \r
- private TypeBuilder genClass;\r
-\r
- private ModuleBuilder module;\r
-\r
- [SetUp]\r
- protected void SetUp () {\r
- AssemblyName assemblyName = new AssemblyName();\r
- assemblyName.Name = "MonoTests.System.Reflection.Emit.MethodBuilderTest";\r
-\r
- AssemblyBuilder assembly \r
- = Thread.GetDomain().DefineDynamicAssembly(\r
- assemblyName, AssemblyBuilderAccess.Run);\r
-\r
- module = assembly.DefineDynamicModule("module1");\r
- \r
- genClass = module.DefineType(genTypeName (), \r
- TypeAttributes.Public);\r
- }\r
-\r
- static int methodIndexer = 0;\r
-\r
- static int typeIndexer = 0;\r
-\r
- // Return a unique method name\r
- private string genMethodName () {\r
- return "m" + (methodIndexer ++);\r
- }\r
-\r
- // Return a unique type name\r
- private string genTypeName () {\r
- return "class" + (typeIndexer ++);\r
- }\r
-\r
- public void TestAttributes () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("Attributes works", \r
- MethodAttributes.Public, mb.Attributes);\r
- }\r
-\r
- public void TestCallingConvention () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type[0]);\r
- AssertEquals ("CallingConvetion defaults to Standard+HasThis",\r
- CallingConventions.Standard | CallingConventions.HasThis,\r
- mb.CallingConvention);\r
-\r
- MethodBuilder mb3 = genClass.DefineMethod (\r
- genMethodName (), 0, CallingConventions.VarArgs, typeof (void), new Type[0]);\r
- AssertEquals ("CallingConvetion works",\r
- CallingConventions.VarArgs | CallingConventions.HasThis,\r
- mb3.CallingConvention);\r
-\r
- MethodBuilder mb4 = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Static, CallingConventions.Standard,\r
- typeof (void), new Type [0]);\r
- AssertEquals ("Static implies !HasThis",\r
- CallingConventions.Standard,\r
- mb4.CallingConvention);\r
- }\r
-\r
- public void TestDeclaringType () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type[0]);\r
-\r
- AssertEquals ("DeclaringType works",\r
- genClass, mb.DeclaringType);\r
- }\r
-\r
- public void TestInitLocals () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type[0]);\r
-\r
- Assert ("InitLocals defaults to true", mb.InitLocals);\r
- mb.InitLocals = false;\r
- Assert ("InitLocals is settable", !mb.InitLocals);\r
- }\r
-\r
- public void TestMethodHandle () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- try {\r
- RuntimeMethodHandle handle = mb.MethodHandle;\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestName () {\r
- string name = genMethodName ();\r
- MethodBuilder mb = genClass.DefineMethod (\r
- name, 0, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("Name works", name, mb.Name);\r
- }\r
-\r
- public void TestReflectedType () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("ReflectedType works", \r
- genClass, mb.ReflectedType);\r
- }\r
-\r
- public void TestReturnType () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (Console), new Type [0]);\r
-\r
- AssertEquals ("ReturnType works", typeof (Console),\r
- mb.ReturnType);\r
-\r
- \r
- MethodBuilder mb2 = genClass.DefineMethod (\r
- genMethodName (), 0, null, new Type [0]);\r
-\r
- Assert ("void ReturnType works", (mb2.ReturnType == null) || (mb2.ReturnType == typeof (void)));\r
- }\r
-\r
- public void TestReturnTypeCustomAttributes () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (Console), new Type [0]);\r
-\r
- AssertEquals ("ReturnTypeCustomAttributes must be null", null,\r
- mb.ReturnTypeCustomAttributes);\r
- }\r
-\r
- /*\r
- public void TestSignature () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- "m91", 0, typeof (Console), new Type [1] { typeof (Console) });\r
-\r
- Console.WriteLine (mb.Signature);\r
- }\r
- */\r
-\r
- public void TestCreateMethodBody () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- // Clear body\r
- mb.CreateMethodBody (null, 999);\r
-\r
- // Check arguments 1.\r
- try {\r
- mb.CreateMethodBody (new byte[1], -1);\r
- Fail ();\r
- } catch (ArgumentException) {\r
- }\r
-\r
- // Check arguments 2.\r
- try {\r
- mb.CreateMethodBody (new byte[1], 2);\r
- Fail ();\r
- } catch (ArgumentException) {\r
- }\r
-\r
- mb.CreateMethodBody (new byte[2], 1);\r
-\r
- // Could only be called once\r
- try {\r
- mb.CreateMethodBody (new byte[2], 1);\r
- Fail ();\r
- } catch (InvalidOperationException) {\r
- }\r
-\r
- // Can not be called on a created type\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- MethodBuilder mb2 = tb.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
- ILGenerator ilgen = mb2.GetILGenerator ();\r
- ilgen.Emit (OpCodes.Ret);\r
- tb.CreateType ();\r
-\r
- try {\r
- mb2.CreateMethodBody (new byte[2], 1);\r
- Fail ();\r
- } catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineParameter () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- MethodBuilder mb = tb.DefineMethod (\r
- genMethodName (), 0, typeof (void), \r
- new Type [2] { typeof(int), typeof(int) });\r
-\r
- // index out of range\r
-\r
- // This fails on mono because the mono version accepts a 0 index\r
- /*\r
- try {\r
- mb.DefineParameter (0, 0, "param1");\r
- Fail ();\r
- } catch (ArgumentOutOfRangeException) {\r
- }\r
- */\r
-\r
- try {\r
- mb.DefineParameter (3, 0, "param1");\r
- Fail ();\r
- } catch (ArgumentOutOfRangeException) {\r
- }\r
-\r
- // Normal usage\r
- mb.DefineParameter (1, 0, "param1");\r
- mb.DefineParameter (1, 0, "param1");\r
- mb.DefineParameter (2, 0, null);\r
-\r
- // Can not be called on a created type\r
- mb.CreateMethodBody (new byte[2], 0);\r
- tb.CreateType ();\r
- try {\r
- mb.DefineParameter (1, 0, "param1");\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestGetBaseDefinition () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("GetBaseDefinition works",\r
- mb.GetBaseDefinition (), mb);\r
- }\r
-\r
- public void TestGetILGenerator () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- // The same instance is returned on the second call\r
- ILGenerator ilgen1 = mb.GetILGenerator ();\r
- ILGenerator ilgen2 = mb.GetILGenerator ();\r
-\r
- AssertEquals ("The same ilgen is returned on the second call",\r
- ilgen1, ilgen2);\r
-\r
- // Does not work on unmanaged code\r
- MethodBuilder mb2 = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]); \r
- try {\r
- mb2.SetImplementationFlags (MethodImplAttributes.Unmanaged);\r
- mb2.GetILGenerator ();\r
- Fail ();\r
- } catch (InvalidOperationException) {\r
- }\r
- try {\r
- mb2.SetImplementationFlags (MethodImplAttributes.Native);\r
- mb2.GetILGenerator ();\r
- Fail ();\r
- } catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestMethodImplementationFlags () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- MethodBuilder mb = tb.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("MethodImplementationFlags defaults to Managed+IL",\r
- MethodImplAttributes.Managed | MethodImplAttributes.IL,\r
- mb.GetMethodImplementationFlags ());\r
-\r
- mb.SetImplementationFlags (MethodImplAttributes.OPTIL);\r
-\r
- AssertEquals ("SetImplementationFlags works",\r
- MethodImplAttributes.OPTIL, \r
- mb.GetMethodImplementationFlags ());\r
-\r
- // Can not be called on a created type\r
- mb.CreateMethodBody (new byte[2], 0);\r
- mb.SetImplementationFlags (MethodImplAttributes.Managed);\r
- tb.CreateType ();\r
- try {\r
- mb.SetImplementationFlags (MethodImplAttributes.OPTIL);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestGetModule () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [0]);\r
-\r
- AssertEquals ("GetMethod works", module, \r
- mb.GetModule ());\r
- }\r
-\r
- public void TestGetParameters () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- MethodBuilder mb = tb.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});\r
-\r
- /*\r
- * According to the MSDN docs, this method should fail with a\r
- * NotSupportedException. In reality, it throws an \r
- * InvalidOperationException under MS .NET, and returns the \r
- * requested data under mono.\r
- */\r
- /*\r
- try {\r
- mb.GetParameters ();\r
- Fail ("#161");\r
- } catch (InvalidOperationException ex) {\r
- Console.WriteLine (ex);\r
- }\r
- */\r
- }\r
-\r
- public void TestGetToken () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- MethodBuilder mb = tb.DefineMethod (\r
- genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});\r
-\r
- mb.GetToken ();\r
- }\r
-\r
- public void TestInvoke () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), \r
- new Type [1] {typeof(int)});\r
-\r
- try {\r
- mb.Invoke (null, new object [1] { 42 });\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
-\r
- try {\r
- mb.Invoke (null, 0, null, new object [1] { 42 }, null);\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestIsDefined () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), \r
- new Type [1] {typeof(int)});\r
-\r
- try {\r
- mb.IsDefined (null, true);\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestGetCustomAttributes () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), 0, typeof (void), \r
- new Type [1] {typeof(int)});\r
-\r
- try {\r
- mb.GetCustomAttributes (true);\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
-\r
- try {\r
- mb.GetCustomAttributes (null, true);\r
- Fail ();\r
- } catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestSetCustomAttribute () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- string name = genMethodName ();\r
- MethodBuilder mb = tb.DefineMethod (\r
- name, MethodAttributes.Public, typeof (void), \r
- new Type [1] {typeof(int)});\r
-\r
- // Null argument\r
- try {\r
- mb.SetCustomAttribute (null);\r
- Fail ();\r
- } catch (ArgumentNullException) {\r
- }\r
-\r
- byte[] custAttrData = { 1, 0, 0, 0, 0};\r
- Type attrType = Type.GetType\r
- ("System.Reflection.AssemblyKeyNameAttribute");\r
- Type[] paramTypes = new Type[1];\r
- paramTypes[0] = typeof(String);\r
- ConstructorInfo ctorInfo =\r
- attrType.GetConstructor(paramTypes);\r
-\r
- mb.SetCustomAttribute (ctorInfo, custAttrData);\r
-\r
- // Test MethodImplAttribute\r
- mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (MethodImplAttribute).GetConstructor (new Type[1] { typeof (short) }), new object[1] {(short)MethodImplAttributes.Synchronized}));\r
- mb.GetILGenerator ().Emit (OpCodes.Ret);\r
-\r
- Type t = tb.CreateType ();\r
-\r
- AssertEquals ("Setting MethodImplAttributes works",\r
- t.GetMethod (name).GetMethodImplementationFlags (),\r
- MethodImplAttributes.Synchronized);\r
-\r
- // Null arguments again\r
- try {\r
- mb.SetCustomAttribute (null, new byte[2]);\r
- Fail ();\r
- } catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- mb.SetCustomAttribute (ctorInfo, null);\r
- Fail ();\r
- } catch (ArgumentNullException) {\r
- }\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (InvalidOperationException))]\r
- public void TestAddDeclarativeSecurityAlreadyCreated () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Public, typeof (void),\r
- new Type [0]);\r
- ILGenerator ilgen = mb.GetILGenerator ();\r
- ilgen.Emit (OpCodes.Ret);\r
- genClass.CreateType ();\r
-\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
- mb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (ArgumentNullException))]\r
- public void TestAddDeclarativeSecurityNullPermissionSet () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Public, typeof (void), \r
- new Type [0]);\r
- mb.AddDeclarativeSecurity (SecurityAction.Demand, null);\r
- }\r
-\r
- [Test]\r
- public void TestAddDeclarativeSecurityInvalidAction () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Public, typeof (void), \r
- new Type [0]);\r
-\r
- SecurityAction[] actions = new SecurityAction [] { \r
- SecurityAction.RequestMinimum,\r
- SecurityAction.RequestOptional,\r
- SecurityAction.RequestRefuse };\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
-\r
- foreach (SecurityAction action in actions) {\r
- try {\r
- mb.AddDeclarativeSecurity (action, set);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
- }\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (InvalidOperationException))]\r
- public void TestAddDeclarativeSecurityDuplicateAction () {\r
- MethodBuilder mb = genClass.DefineMethod (\r
- genMethodName (), MethodAttributes.Public, typeof (void), \r
- new Type [0]);\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
- mb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- mb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- }\r
-\r
- [AttributeUsage (AttributeTargets.Parameter)]\r
- class ParamAttribute : Attribute {\r
-\r
- public ParamAttribute () {\r
- }\r
- }\r
-\r
- [Test]\r
- public void TestDynamicParams () {\r
- string mname = genMethodName ();\r
-\r
- MethodBuilder mb = genClass.DefineMethod (\r
- mname, MethodAttributes.Public, typeof (void), \r
- new Type [] { typeof (string) });\r
- ParameterBuilder pb = mb.DefineParameter (1, 0, "foo");\r
- pb.SetCustomAttribute (new CustomAttributeBuilder (typeof (ParamAttribute).GetConstructors () [0], new object [] { }));\r
- mb.GetILGenerator ().Emit (OpCodes.Ret);\r
-\r
- Type t = genClass.CreateType ();\r
- MethodInfo m = t.GetMethod (mname);\r
- ParameterInfo pi = m.GetParameters ()[0];\r
-\r
- AssertEquals ("foo", pi.Name);\r
-\r
- object[] cattrs = pi.GetCustomAttributes (true);\r
-\r
- /* This test does not run under MS.NET: */\r
- /*\r
- AssertEquals (1, cattrs.Length);\r
- AssertEquals (typeof (ParamAttribute), cattrs [0].GetType ());\r
- */\r
- }\r
-}\r
-}\r
+//
+// MethodBuilderTest.cs - NUnit Test Cases for the MethodBuilder class
+//
+// Zoltan Varga (vargaz@freemail.hu)
+//
+// (C) Ximian, Inc. http://www.ximian.com
+
+// TODO:
+// - implement 'Signature' (what the hell it does???) and test it
+// - implement Equals and test it
+
+using System;
+using System.Threading;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
+using System.Security;
+using System.Security.Permissions;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Reflection.Emit
+{
+
+[TestFixture]
+public class MethodBuilderTest : Assertion
+{
+ private TypeBuilder genClass;
+
+ private ModuleBuilder module;
+
+ [SetUp]
+ protected void SetUp () {
+ AssemblyName assemblyName = new AssemblyName();
+ assemblyName.Name = "MonoTests.System.Reflection.Emit.MethodBuilderTest";
+
+ AssemblyBuilder assembly
+ = Thread.GetDomain().DefineDynamicAssembly(
+ assemblyName, AssemblyBuilderAccess.Run);
+
+ module = assembly.DefineDynamicModule("module1");
+
+ genClass = module.DefineType(genTypeName (),
+ TypeAttributes.Public);
+ }
+
+ static int methodIndexer = 0;
+
+ static int typeIndexer = 0;
+
+ // Return a unique method name
+ private string genMethodName () {
+ return "m" + (methodIndexer ++);
+ }
+
+ // Return a unique type name
+ private string genTypeName () {
+ return "class" + (typeIndexer ++);
+ }
+
+ public void TestAttributes () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Public, typeof (void), new Type [0]);
+
+ AssertEquals ("Attributes works",
+ MethodAttributes.Public, mb.Attributes);
+ }
+
+ public void TestCallingConvention () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type[0]);
+ AssertEquals ("CallingConvetion defaults to Standard+HasThis",
+ CallingConventions.Standard | CallingConventions.HasThis,
+ mb.CallingConvention);
+
+ MethodBuilder mb3 = genClass.DefineMethod (
+ genMethodName (), 0, CallingConventions.VarArgs, typeof (void), new Type[0]);
+ AssertEquals ("CallingConvetion works",
+ CallingConventions.VarArgs | CallingConventions.HasThis,
+ mb3.CallingConvention);
+
+ MethodBuilder mb4 = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Static, CallingConventions.Standard,
+ typeof (void), new Type [0]);
+ AssertEquals ("Static implies !HasThis",
+ CallingConventions.Standard,
+ mb4.CallingConvention);
+ }
+
+ public void TestDeclaringType () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type[0]);
+
+ AssertEquals ("DeclaringType works",
+ genClass, mb.DeclaringType);
+ }
+
+ public void TestInitLocals () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type[0]);
+
+ Assert ("InitLocals defaults to true", mb.InitLocals);
+ mb.InitLocals = false;
+ Assert ("InitLocals is settable", !mb.InitLocals);
+ }
+
+ public void TestMethodHandle () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ try {
+ RuntimeMethodHandle handle = mb.MethodHandle;
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+ }
+
+ public void TestName () {
+ string name = genMethodName ();
+ MethodBuilder mb = genClass.DefineMethod (
+ name, 0, typeof (void), new Type [0]);
+
+ AssertEquals ("Name works", name, mb.Name);
+ }
+
+ public void TestReflectedType () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ AssertEquals ("ReflectedType works",
+ genClass, mb.ReflectedType);
+ }
+
+ public void TestReturnType () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (Console), new Type [0]);
+
+ AssertEquals ("ReturnType works", typeof (Console),
+ mb.ReturnType);
+
+
+ MethodBuilder mb2 = genClass.DefineMethod (
+ genMethodName (), 0, null, new Type [0]);
+
+ Assert ("void ReturnType works", (mb2.ReturnType == null) || (mb2.ReturnType == typeof (void)));
+ }
+
+ public void TestReturnTypeCustomAttributes () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (Console), new Type [0]);
+
+ AssertEquals ("ReturnTypeCustomAttributes must be null", null,
+ mb.ReturnTypeCustomAttributes);
+ }
+
+ /*
+ public void TestSignature () {
+ MethodBuilder mb = genClass.DefineMethod (
+ "m91", 0, typeof (Console), new Type [1] { typeof (Console) });
+
+ Console.WriteLine (mb.Signature);
+ }
+ */
+
+ public void TestCreateMethodBody () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ // Clear body
+ mb.CreateMethodBody (null, 999);
+
+ // Check arguments 1.
+ try {
+ mb.CreateMethodBody (new byte[1], -1);
+ Fail ();
+ } catch (ArgumentException) {
+ }
+
+ // Check arguments 2.
+ try {
+ mb.CreateMethodBody (new byte[1], 2);
+ Fail ();
+ } catch (ArgumentException) {
+ }
+
+ mb.CreateMethodBody (new byte[2], 1);
+
+ // Could only be called once
+ try {
+ mb.CreateMethodBody (new byte[2], 1);
+ Fail ();
+ } catch (InvalidOperationException) {
+ }
+
+ // Can not be called on a created type
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb2 = tb.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+ ILGenerator ilgen = mb2.GetILGenerator ();
+ ilgen.Emit (OpCodes.Ret);
+ tb.CreateType ();
+
+ try {
+ mb2.CreateMethodBody (new byte[2], 1);
+ Fail ();
+ } catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof(InvalidOperationException))]
+ public void TestDefineParameterInvalidIndexComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type[2] {
+ typeof(int), typeof(int)
+ });
+ tb.CreateType ();
+ mb.DefineParameter (-5, ParameterAttributes.None, "param1");
+ }
+
+ [Test]
+ [ExpectedException (typeof(InvalidOperationException))]
+ public void TestDefineParameterValidIndexComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type[2] {
+ typeof(int), typeof(int)
+ });
+ tb.CreateType ();
+ mb.DefineParameter (1, ParameterAttributes.None, "param1");
+ }
+
+ public void TestDefineParameter () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type [2] { typeof(int), typeof(int) });
+
+ // index out of range
+
+ // This fails on mono because the mono version accepts a 0 index
+ /*
+ try {
+ mb.DefineParameter (0, 0, "param1");
+ Fail ();
+ } catch (ArgumentOutOfRangeException) {
+ }
+ */
+
+ try {
+ mb.DefineParameter (3, 0, "param1");
+ Fail ();
+ } catch (ArgumentOutOfRangeException) {
+ }
+
+ // Normal usage
+ mb.DefineParameter (1, 0, "param1");
+ mb.DefineParameter (1, 0, "param1");
+ mb.DefineParameter (2, 0, null);
+
+ // Can not be called on a created type
+ mb.CreateMethodBody (new byte[2], 0);
+ tb.CreateType ();
+ try {
+ mb.DefineParameter (1, 0, "param1");
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestHashCode ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ string methodName = genMethodName ();
+ MethodBuilder mb = tb.DefineMethod (
+ methodName, 0, typeof (void),
+ new Type[2] {
+ typeof(int), typeof(int)
+ });
+ AssertEquals ("Hashcode of method should be equal to hashcode of method name",
+ methodName.GetHashCode (), mb.GetHashCode ());
+ }
+
+ public void TestGetBaseDefinition () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ AssertEquals ("GetBaseDefinition works",
+ mb.GetBaseDefinition (), mb);
+ }
+
+ public void TestGetILGenerator () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ // The same instance is returned on the second call
+ ILGenerator ilgen1 = mb.GetILGenerator ();
+ ILGenerator ilgen2 = mb.GetILGenerator ();
+
+ AssertEquals ("The same ilgen is returned on the second call",
+ ilgen1, ilgen2);
+
+ // Does not work on unmanaged code
+ MethodBuilder mb2 = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+ try {
+ mb2.SetImplementationFlags (MethodImplAttributes.Unmanaged);
+ mb2.GetILGenerator ();
+ Fail ();
+ } catch (InvalidOperationException) {
+ }
+ try {
+ mb2.SetImplementationFlags (MethodImplAttributes.Native);
+ mb2.GetILGenerator ();
+ Fail ();
+ } catch (InvalidOperationException) {
+ }
+ }
+
+ public void TestMethodImplementationFlags () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ AssertEquals ("MethodImplementationFlags defaults to Managed+IL",
+ MethodImplAttributes.Managed | MethodImplAttributes.IL,
+ mb.GetMethodImplementationFlags ());
+
+ mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
+
+ AssertEquals ("SetImplementationFlags works",
+ MethodImplAttributes.OPTIL,
+ mb.GetMethodImplementationFlags ());
+
+ // Can not be called on a created type
+ mb.CreateMethodBody (new byte[2], 0);
+ mb.SetImplementationFlags (MethodImplAttributes.Managed);
+ tb.CreateType ();
+ try {
+ mb.SetImplementationFlags (MethodImplAttributes.OPTIL);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ public void TestGetModule () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [0]);
+
+ AssertEquals ("GetMethod works", module,
+ mb.GetModule ());
+ }
+
+ public void TestGetParameters () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});
+
+ /*
+ * According to the MSDN docs, this method should fail with a
+ * NotSupportedException. In reality, it throws an
+ * InvalidOperationException under MS .NET, and returns the
+ * requested data under mono.
+ */
+ /*
+ try {
+ mb.GetParameters ();
+ Fail ("#161");
+ } catch (InvalidOperationException ex) {
+ Console.WriteLine (ex);
+ }
+ */
+ }
+
+ public void TestGetToken () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ MethodBuilder mb = tb.DefineMethod (
+ genMethodName (), 0, typeof (void), new Type [1] {typeof(void)});
+
+ mb.GetToken ();
+ }
+
+ public void TestInvoke () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type [1] {typeof(int)});
+
+ try {
+ mb.Invoke (null, new object [1] { 42 });
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+
+ try {
+ mb.Invoke (null, 0, null, new object [1] { 42 }, null);
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+ }
+
+ public void TestIsDefined () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type [1] {typeof(int)});
+
+ try {
+ mb.IsDefined (null, true);
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+ }
+
+ public void TestGetCustomAttributes () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), 0, typeof (void),
+ new Type [1] {typeof(int)});
+
+ try {
+ mb.GetCustomAttributes (true);
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+
+ try {
+ mb.GetCustomAttributes (null, true);
+ Fail ();
+ } catch (NotSupportedException) {
+ }
+ }
+
+ public void TestSetCustomAttribute () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ string name = genMethodName ();
+ MethodBuilder mb = tb.DefineMethod (
+ name, MethodAttributes.Public, typeof (void),
+ new Type [1] {typeof(int)});
+
+ // Null argument
+ try {
+ mb.SetCustomAttribute (null);
+ Fail ();
+ } catch (ArgumentNullException) {
+ }
+
+ byte[] custAttrData = { 1, 0, 0, 0, 0};
+ Type attrType = Type.GetType
+ ("System.Reflection.AssemblyKeyNameAttribute");
+ Type[] paramTypes = new Type[1];
+ paramTypes[0] = typeof(String);
+ ConstructorInfo ctorInfo =
+ attrType.GetConstructor(paramTypes);
+
+ mb.SetCustomAttribute (ctorInfo, custAttrData);
+
+ // Test MethodImplAttribute
+ mb.SetCustomAttribute (new CustomAttributeBuilder (typeof (MethodImplAttribute).GetConstructor (new Type[1] { typeof (short) }), new object[1] {(short)MethodImplAttributes.Synchronized}));
+ mb.GetILGenerator ().Emit (OpCodes.Ret);
+
+ Type t = tb.CreateType ();
+
+ AssertEquals ("Setting MethodImplAttributes works",
+ t.GetMethod (name).GetMethodImplementationFlags (),
+ MethodImplAttributes.Synchronized);
+
+ // Null arguments again
+ try {
+ mb.SetCustomAttribute (null, new byte[2]);
+ Fail ();
+ } catch (ArgumentNullException) {
+ }
+
+ try {
+ mb.SetCustomAttribute (ctorInfo, null);
+ Fail ();
+ } catch (ArgumentNullException) {
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof (InvalidOperationException))]
+ public void TestAddDeclarativeSecurityAlreadyCreated () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Public, typeof (void),
+ new Type [0]);
+ ILGenerator ilgen = mb.GetILGenerator ();
+ ilgen.Emit (OpCodes.Ret);
+ genClass.CreateType ();
+
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+ mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ }
+
+ [Test]
+ [ExpectedException (typeof (ArgumentNullException))]
+ public void TestAddDeclarativeSecurityNullPermissionSet () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Public, typeof (void),
+ new Type [0]);
+ mb.AddDeclarativeSecurity (SecurityAction.Demand, null);
+ }
+
+ [Test]
+ public void TestAddDeclarativeSecurityInvalidAction () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Public, typeof (void),
+ new Type [0]);
+
+ SecurityAction[] actions = new SecurityAction [] {
+ SecurityAction.RequestMinimum,
+ SecurityAction.RequestOptional,
+ SecurityAction.RequestRefuse };
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+
+ foreach (SecurityAction action in actions) {
+ try {
+ mb.AddDeclarativeSecurity (action, set);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof (InvalidOperationException))]
+ public void TestAddDeclarativeSecurityDuplicateAction () {
+ MethodBuilder mb = genClass.DefineMethod (
+ genMethodName (), MethodAttributes.Public, typeof (void),
+ new Type [0]);
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+ mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ mb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ }
+
+ [AttributeUsage (AttributeTargets.Parameter)]
+ class ParamAttribute : Attribute {
+
+ public ParamAttribute () {
+ }
+ }
+
+ [Test]
+ public void TestDynamicParams () {
+ string mname = genMethodName ();
+
+ MethodBuilder mb = genClass.DefineMethod (
+ mname, MethodAttributes.Public, typeof (void),
+ new Type [] { typeof (string) });
+ ParameterBuilder pb = mb.DefineParameter (1, 0, "foo");
+ pb.SetCustomAttribute (new CustomAttributeBuilder (typeof (ParamAttribute).GetConstructors () [0], new object [] { }));
+ mb.GetILGenerator ().Emit (OpCodes.Ret);
+
+ Type t = genClass.CreateType ();
+ MethodInfo m = t.GetMethod (mname);
+ ParameterInfo pi = m.GetParameters ()[0];
+
+ AssertEquals ("foo", pi.Name);
+
+ object[] cattrs = pi.GetCustomAttributes (true);
+
+ /* This test does not run under MS.NET: */
+ /*
+ AssertEquals (1, cattrs.Length);
+ AssertEquals (typeof (ParamAttribute), cattrs [0].GetType ());
+ */
+ }
+}
+}
-//\r
-// TypeBuilderTest.cs - NUnit Test Cases for the TypeBuilder class\r
-//\r
-// Zoltan Varga (vargaz@freemail.hu)\r
-//\r
-// (C) Ximian, Inc. http://www.ximian.com\r
-//\r
-// TODO:\r
-// - implement a mechnanism for easier testing of null argument exceptions\r
-// - with overloaded methods like DefineNestedType (), check the defaults\r
-// on the shorter versions.\r
-// - ToString on enums with the flags attribute set should print all\r
-// values which match, e.g. 0 == AutoLayou,AnsiClass,NotPublic\r
-//\r
-\r
-\r
-using System;\r
-using System.Threading;\r
-using System.Reflection;\r
-using System.Reflection.Emit;\r
-using System.Security;\r
-using System.Security.Permissions;\r
-using System.Runtime.InteropServices;\r
-using NUnit.Framework;\r
-\r
-namespace MonoTests.System.Reflection.Emit\r
-{\r
-\r
-[TestFixture]\r
-public class TypeBuilderTest : Assertion\r
-{ \r
- private interface AnInterface {\r
- }\r
-\r
- private AssemblyBuilder assembly;\r
-\r
- private ModuleBuilder module;\r
-\r
- static string ASSEMBLY_NAME = "MonoTests.System.Reflection.Emit.TypeBuilderTest";\r
-\r
- [SetUp]\r
- protected void SetUp () {\r
- AssemblyName assemblyName = new AssemblyName();\r
- assemblyName.Name = ASSEMBLY_NAME;\r
-\r
- assembly = \r
- Thread.GetDomain().DefineDynamicAssembly(\r
- assemblyName, AssemblyBuilderAccess.Run);\r
-\r
- module = assembly.DefineDynamicModule("module1");\r
- }\r
-\r
- static int typeIndexer = 0;\r
-\r
- // Return a unique type name\r
- private string genTypeName () {\r
- return "t" + (typeIndexer ++);\r
- }\r
-\r
- private string nullName () {\r
- return String.Format ("{0}", (char)0);\r
- }\r
-\r
- public void TestAssembly () {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);\r
- AssertEquals ("Assembly works",\r
- tb.Assembly, assembly);\r
- }\r
-\r
- public void TestAssemblyQualifiedName () {\r
- TypeBuilder tb = module.DefineType ("A.B.C.D", TypeAttributes.Public);\r
-\r
- AssertEquals ("AssemblyQualifiedName works",\r
- tb.AssemblyQualifiedName, "A.B.C.D, " + assembly.GetName ().FullName);\r
- }\r
-\r
- public void TestAttributes () {\r
- TypeAttributes attrs = TypeAttributes.Public | TypeAttributes.BeforeFieldInit;\r
- TypeBuilder tb = module.DefineType (genTypeName (), attrs);\r
-\r
- AssertEquals ("Attributes works",\r
- tb.Attributes, attrs);\r
- }\r
-\r
- public void TestBaseType () {\r
- TypeAttributes attrs = TypeAttributes.Public;\r
- TypeBuilder tb = module.DefineType (genTypeName (), attrs);\r
- AssertEquals ("BaseType defaults to Object",\r
- tb.BaseType, typeof (object));\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), attrs, tb);\r
- AssertEquals ("BaseType works",\r
- tb2.BaseType, tb);\r
-\r
- /* This does not run under mono\r
- TypeBuilder tb3 = module.DefineType (genTypeName (),\r
- TypeAttributes.Interface |\r
- TypeAttributes.Abstract);\r
- AssertEquals ("Interfaces default to no base type",\r
- null, tb3.BaseType);\r
- */\r
- }\r
-\r
- public void TestDeclaringType () {\r
- TypeAttributes attrs = 0;\r
- TypeBuilder tb = module.DefineType (genTypeName (), attrs);\r
-\r
- AssertEquals ("Has no declaring type",\r
- null, tb.DeclaringType);\r
-\r
- attrs = TypeAttributes.NestedPublic;\r
- TypeBuilder tb2 = tb.DefineNestedType (genTypeName (), attrs);\r
- TypeBuilder tb3 = tb2.DefineNestedType (genTypeName (), attrs);\r
- AssertEquals ("DeclaringType works",\r
- tb, tb3.DeclaringType.DeclaringType);\r
- }\r
-\r
- public void TestFullName () {\r
- string name = genTypeName ();\r
- TypeAttributes attrs = 0;\r
- TypeBuilder tb = module.DefineType (name, attrs);\r
- AssertEquals ("FullName works",\r
- name, tb.FullName);\r
-\r
- string name2 = genTypeName ();\r
- attrs = TypeAttributes.NestedPublic;\r
- TypeBuilder tb2 = tb.DefineNestedType (name2, attrs);\r
-\r
- string name3 = genTypeName ();\r
- attrs = TypeAttributes.NestedPublic;\r
- TypeBuilder tb3 = tb2.DefineNestedType (name3, attrs);\r
-\r
- AssertEquals ("FullName works on nested types",\r
- name + "+" + name2 + "+" + name3, tb3.FullName);\r
- }\r
-\r
- public void TestGUID () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- try {\r
- Guid g = tb.GUID;\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestHasElementType () {\r
- // According to the MSDN docs, this member works, but in reality, it\r
- // returns a NotSupportedException\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- try {\r
- bool b = tb.HasElementType;\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestIsAbstract () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsAbstract);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Abstract);\r
- AssertEquals ("",\r
- true, tb2.IsAbstract);\r
- }\r
-\r
- public void TestIsAnsiClass () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- true, tb.IsAnsiClass);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);\r
- AssertEquals ("",\r
- false, tb2.IsAnsiClass);\r
- }\r
-\r
- public void TestIsArray () {\r
- // How can a TypeBuilder be an array ?\r
- string name = genTypeName ();\r
- TypeBuilder tb = module.DefineType (name);\r
- AssertEquals ("IsArray works",\r
- false, tb.IsArray);\r
- }\r
-\r
- public void TestIsAutoClass () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsAutoClass);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.AutoClass);\r
- AssertEquals ("",\r
- true, tb2.IsAutoClass);\r
- } \r
-\r
- public void TestIsAutoLayout () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("AutoLayout defaults to true",\r
- true, tb.IsAutoLayout);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);\r
- AssertEquals ("",\r
- false, tb2.IsAutoLayout);\r
- }\r
-\r
- public void TestIsByRef () {\r
- // How can a TypeBuilder be ByRef ?\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("IsByRef works",\r
- false, tb.IsByRef);\r
- }\r
-\r
- public void TestIsClass () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Most types are classes",\r
- true, tb.IsClass);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
- AssertEquals ("Interfaces are not classes",\r
- false, tb2.IsClass);\r
-\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));\r
- AssertEquals ("value types are not classes",\r
- false, tb3.IsClass);\r
-\r
- TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));\r
- AssertEquals ("enums are not classes",\r
- false, tb4.IsClass);\r
- }\r
-\r
- public void TestIsCOMObject () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Probably not",\r
- false, tb.IsCOMObject);\r
- }\r
-\r
- public void TestIsContextful () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsContextful);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));\r
- AssertEquals ("",\r
- true, tb2.IsContextful);\r
- }\r
-\r
- public void TestIsEnum () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsEnum);\r
-\r
- // This returns true under both mono and MS .NET ???\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ValueType));\r
- AssertEquals ("value types are not necessary enums",\r
- false, tb2.IsEnum);\r
-\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (Enum));\r
- AssertEquals ("enums are enums",\r
- true, tb3.IsEnum);\r
- }\r
-\r
- public void TestIsExplicitLayout () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("ExplicitLayout defaults to false",\r
- false, tb.IsExplicitLayout);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);\r
- AssertEquals ("",\r
- true, tb2.IsExplicitLayout);\r
- }\r
-\r
- public void TestIsImport () {\r
- // How can this be true ?\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsImport);\r
- }\r
-\r
- public void TestIsInterface () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Most types are not interfaces",\r
- false, tb.IsInterface);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
- AssertEquals ("Interfaces are interfaces",\r
- true, tb2.IsInterface);\r
-\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));\r
- AssertEquals ("value types are not interfaces",\r
- false, tb3.IsInterface);\r
- }\r
-\r
- public void TestIsLayoutSequential () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("SequentialLayout defaults to false",\r
- false, tb.IsLayoutSequential);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SequentialLayout);\r
- AssertEquals ("",\r
- true, tb2.IsLayoutSequential);\r
- }\r
-\r
- public void TestIsMarshalByRef () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsMarshalByRef);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (MarshalByRefObject));\r
- AssertEquals ("",\r
- true, tb2.IsMarshalByRef);\r
-\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));\r
- AssertEquals ("",\r
- true, tb3.IsMarshalByRef);\r
- }\r
-\r
- // TODO: Visibility properties\r
-\r
- public void TestIsPointer () {\r
- // How can this be true?\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsPointer);\r
- }\r
-\r
- public void TestIsPrimitive () {\r
- TypeBuilder tb = module.DefineType ("int");\r
- AssertEquals ("",\r
- false, tb.IsPrimitive);\r
- }\r
-\r
- public void IsSealed () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Sealed defaults to false",\r
- false, tb.IsSealed);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);\r
- AssertEquals ("IsSealed works",\r
- true, tb2.IsSealed);\r
- }\r
-\r
- public void IsSerializable () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsSerializable);\r
-\r
- tb.SetCustomAttribute (new CustomAttributeBuilder (typeof (SerializableAttribute).GetConstructors (BindingFlags.Public)[0], null));\r
- AssertEquals ("",\r
- true, tb.IsSerializable);\r
- }\r
-\r
- public void TestIsSpecialName () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("SpecialName defaults to false",\r
- false, tb.IsSpecialName);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SpecialName);\r
- AssertEquals ("IsSpecialName works",\r
- true, tb2.IsSpecialName);\r
- }\r
-\r
- public void TestIsUnicodeClass () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- false, tb.IsUnicodeClass);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);\r
- AssertEquals ("",\r
- true, tb2.IsUnicodeClass);\r
- }\r
-\r
- public void TestIsValueType () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Most types are not value types",\r
- false, tb.IsValueType);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
- AssertEquals ("Interfaces are not value types",\r
- false, tb2.IsValueType);\r
-\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));\r
- AssertEquals ("value types are value types",\r
- true, tb3.IsValueType);\r
-\r
- TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));\r
- AssertEquals ("enums are value types",\r
- true, tb4.IsValueType);\r
- }\r
-\r
- public void TestMemberType () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("A type is a type",\r
- MemberTypes.TypeInfo, tb.MemberType);\r
- }\r
-\r
- public void TestModule () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("Module works",\r
- module, tb.Module);\r
- }\r
-\r
- public void TestName () {\r
- TypeBuilder tb = module.DefineType ("A");\r
- AssertEquals ("",\r
- "A", tb.Name);\r
-\r
- TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");\r
- AssertEquals ("",\r
- "E", tb2.Name);\r
-\r
- TypeBuilder tb3 = tb2.DefineNestedType ("A");\r
- AssertEquals ("",\r
- "A", tb3.Name);\r
-\r
- /* Is .E a valid name ?\r
- TypeBuilder tb4 = module.DefineType (".E");\r
- AssertEquals ("",\r
- "E", tb4.Name);\r
- */\r
- }\r
-\r
- public void TestNamespace () {\r
- TypeBuilder tb = module.DefineType ("A");\r
- AssertEquals ("",\r
- "", tb.Namespace);\r
-\r
- TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");\r
- AssertEquals ("",\r
- "A.B.C.D", tb2.Namespace);\r
-\r
- TypeBuilder tb3 = tb2.DefineNestedType ("A");\r
- AssertEquals ("",\r
- "", tb3.Namespace);\r
-\r
- /* Is .E a valid name ?\r
- TypeBuilder tb4 = module.DefineType (".E");\r
- AssertEquals ("",\r
- "E", tb4.Name);\r
- */ \r
- }\r
-\r
- public void TestPackingSize () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- PackingSize.Unspecified, tb.PackingSize);\r
-\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (object),\r
- PackingSize.Size16, 16);\r
- AssertEquals ("",\r
- PackingSize.Size16, tb2.PackingSize);\r
- }\r
-\r
- public void TestReflectedType () {\r
- // It is the same as DeclaringType, but why?\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- null, tb.ReflectedType);\r
-\r
- TypeBuilder tb2 = tb.DefineNestedType (genTypeName ());\r
- AssertEquals ("",\r
- tb, tb2.ReflectedType);\r
- }\r
-\r
- public void TestSize () {\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("",\r
- 0, tb.Size);\r
- tb.CreateType ();\r
- AssertEquals ("",\r
- 0, tb.Size);\r
- }\r
-\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (object),\r
- PackingSize.Size16, 32);\r
- AssertEquals ("",\r
- 32, tb.Size);\r
- }\r
- }\r
-\r
- public void TestTypeHandle () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- try {\r
- RuntimeTypeHandle handle = tb.TypeHandle;\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestTypeInitializer () {\r
- // According to the MSDN docs, this works, but it doesn't\r
- /* TODO:\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- try {\r
- ConstructorInfo cb = tb.TypeInitializer;\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- */\r
- }\r
-\r
- public void TestTypeToken () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- TypeToken token = tb.TypeToken;\r
- }\r
-\r
- public void TestUnderlyingSystemType () {\r
- //\r
- // For non-enum types, UnderlyingSystemType should return itself.\r
- // But if I modify the code to do this, I get an exception in mcs.\r
- // Reason: the enums created during corlib compilation do not seem\r
- // to be an enum according to IsEnum.\r
- //\r
- /*\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- AssertEquals ("For non-enums this equals itself",\r
- tb, tb.UnderlyingSystemType);\r
- }\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
- AssertEquals ("",\r
- tb, tb.UnderlyingSystemType);\r
- }\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (ValueType));\r
- AssertEquals ("",\r
- tb, tb.UnderlyingSystemType);\r
- }\r
- */\r
- {\r
- TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (Enum));\r
- try {\r
- Type t = tb.UnderlyingSystemType;\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
-\r
- tb.DefineField ("val", typeof (int), 0);\r
- AssertEquals ("",\r
- typeof (int), tb.UnderlyingSystemType);\r
- }\r
- }\r
-\r
- public void TestAddInterfaceImplementation () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- try {\r
- tb.AddInterfaceImplementation (null);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- tb.AddInterfaceImplementation (typeof (AnInterface));\r
- tb.AddInterfaceImplementation (typeof (AnInterface));\r
-\r
- Type t = tb.CreateType ();\r
- AssertEquals ("Should merge identical interfaces",\r
- tb.GetInterfaces ().Length, 1);\r
-\r
- // Can not be called on a created type\r
- try {\r
- tb.AddInterfaceImplementation (typeof (AnInterface));\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestCreateType () {\r
- // TODO: LOTS OF TEST SHOULD GO THERE\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- tb.CreateType ();\r
-\r
- // Can not be called on a created type\r
- try {\r
- tb.CreateType ();\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineConstructor () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- ConstructorBuilder cb = tb.DefineConstructor (0, 0, null);\r
- cb.GetILGenerator ().Emit (OpCodes.Ret);\r
- tb.CreateType ();\r
-\r
- // Can not be called on a created type\r
- try {\r
- tb.DefineConstructor (0, 0, null);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineDefaultConstructor () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- tb.DefineDefaultConstructor (0);\r
-\r
- tb.CreateType ();\r
-\r
- // Can not be called on a created type, altough the MSDN docs does not mention this\r
- try {\r
- tb.DefineDefaultConstructor (0);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineEvent () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- // Test invalid arguments\r
- try {\r
- tb.DefineEvent (null, 0, typeof (int));\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineEvent ("FOO", 0, null);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineEvent ("", 0, typeof (int));\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- tb.CreateType ();\r
- // Can not be called on a created type\r
- try {\r
- tb.DefineEvent ("BAR", 0, typeof (int));\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineField () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- // Check invalid arguments\r
- try {\r
- tb.DefineField (null, typeof (int), 0);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineField ("", typeof (int), 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- try {\r
- // Strangely, 'A<NULL>' is accepted...\r
- string name = String.Format ("{0}", (char)0);\r
- tb.DefineField (name, typeof (int), 0);\r
- Fail ("Names with embedded nulls should be rejected");\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- try {\r
- tb.DefineField ("A", typeof (void), 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- tb.CreateType ();\r
- // Can not be called on a created type\r
- try {\r
- tb.DefineField ("B", typeof (int), 0);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- public void TestDefineInitializedData () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- \r
- // Check invalid arguments\r
- try {\r
- tb.DefineInitializedData (null, new byte[1], 0);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineInitializedData ("FOO", null, 0);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineInitializedData ("", new byte[1], 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // The size of the data is less than or equal to zero ???\r
- try {\r
- tb.DefineInitializedData ("BAR", new byte[0], 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- try {\r
- string name = String.Format ("{0}", (char)0);\r
- tb.DefineInitializedData (name, new byte[1], 0);\r
- Fail ("Names with embedded nulls should be rejected");\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- tb.CreateType ();\r
-\r
- // Can not be called on a created type, altough the MSDN docs does not mention this\r
- try {\r
- tb.DefineInitializedData ("BAR2", new byte[1], 0);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- [Test]\r
- public void DefineUninitializedDataInvalidArgs () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- \r
- try {\r
- tb.DefineUninitializedData (null, 1, 0);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineUninitializedData ("", 1, 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // The size of the data is less than or equal to zero ???\r
- try {\r
- tb.DefineUninitializedData ("BAR", 0, 0);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- try {\r
- string name = String.Format ("{0}", (char)0);\r
- tb.DefineUninitializedData (name, 1, 0);\r
- Fail ("Names with embedded nulls should be rejected");\r
- }\r
- catch (ArgumentException) {\r
- }\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (InvalidOperationException))]\r
- public void DefineUninitializedDataAlreadyCreated () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- tb.CreateType ();\r
-\r
- tb.DefineUninitializedData ("BAR2", 1, 0);\r
- }\r
-\r
- [Test]\r
- public void DefineUninitializedData () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- tb.DefineUninitializedData ("foo", 4, FieldAttributes.Public);\r
-\r
- Type t = tb.CreateType ();\r
-\r
- object o = Activator.CreateInstance (t);\r
-\r
- FieldInfo fi = t.GetField ("foo");\r
-\r
- object fieldVal = fi.GetValue (o);\r
-\r
- IntPtr ptr = Marshal.AllocHGlobal (4);\r
- Marshal.StructureToPtr (fieldVal, ptr, true);\r
- Marshal.FreeHGlobal (ptr);\r
- }\r
-\r
- public void TestDefineMethod () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- // Check invalid arguments\r
- try {\r
- tb.DefineMethod (null, 0, null, null);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineMethod ("", 0, null, null);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // Check non-virtual methods on an interface\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
- try {\r
- tb2.DefineMethod ("FOO", MethodAttributes.Abstract, null, null);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- tb.CreateType ();\r
- // Can not be called on a created type\r
- try {\r
- tb.DefineMethod ("bar", 0, null, null);\r
- Fail ();\r
- }\r
- catch (InvalidOperationException) {\r
- }\r
- }\r
-\r
- // TODO: DefineMethodOverride\r
-\r
- public void TestDefineNestedType () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- // Check invalid arguments\r
- try {\r
- tb.DefineNestedType (null);\r
- Fail ("Should reject null name");\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
-\r
- try {\r
- tb.DefineNestedType ("");\r
- Fail ("Should reject empty name");\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- try {\r
- tb.DefineNestedType (nullName ());\r
- Fail ("Should reject name with embedded 0s");\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // If I fix the code so this works then mcs breaks -> how can mcs\r
- // works under MS .NET in the first place ???\r
- /*\r
- try {\r
- tb.DefineNestedType ("AA", TypeAttributes.Public, null, null);\r
- Fail ("Nested visibility must be specified.");\r
- }\r
- catch (ArgumentException) {\r
- }\r
- */\r
-\r
- try {\r
- tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,\r
- new Type[1]);\r
- Fail ("Should reject empty interface");\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // I think this should reject non-interfaces, but it does not\r
- tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,\r
- new Type[1] { typeof (object) });\r
-\r
- // Normal invocation\r
- tb.DefineNestedType ("Nest");\r
-\r
- tb.CreateType ();\r
-\r
- // According to the MSDN docs, this cannnot be called after the type\r
- // is created, but it works.\r
- tb.DefineNestedType ("Nest2");\r
-\r
- // According to the MSDN docs, a Sealed class can't contain nested \r
- // types, but this is not true\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);\r
- tb2.DefineNestedType ("AA");\r
-\r
- // According to the MSDN docs, interfaces can only contain interfaces,\r
- // but this is not true\r
- TypeBuilder tb3 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
-\r
- tb3.DefineNestedType ("AA");\r
-\r
- // Check shorter versions\r
- {\r
- TypeBuilder nested = tb.DefineNestedType ("N1");\r
-\r
- AssertEquals (nested.Name, "N1");\r
- AssertEquals (nested.BaseType, typeof (object));\r
- AssertEquals (nested.Attributes, TypeAttributes.NestedPrivate);\r
- AssertEquals (nested.GetInterfaces ().Length, 0);\r
- }\r
-\r
- // TODO:\r
- }\r
-\r
- public void TestDefinePInvokeMethod () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- tb.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);\r
-\r
- // Try invalid parameters\r
- try {\r
- tb.DefinePInvokeMethod (null, "B", "C", 0, 0, null, null, 0, 0);\r
- Fail ();\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
- // etc...\r
-\r
- // Try invalid attributes\r
- try {\r
- tb.DefinePInvokeMethod ("A2", "B", "C", MethodAttributes.Abstract, 0, null, null, 0, 0);\r
- }\r
- catch (ArgumentException) {\r
- }\r
-\r
- // Try an interface parent\r
- TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);\r
-\r
- try {\r
- tb2.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);\r
- }\r
- catch (ArgumentException) {\r
- }\r
- }\r
-\r
- public void TestDefineProperty () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- // Check null parameter types\r
- try {\r
- tb.DefineProperty ("A", 0, null, new Type[1]);\r
- }\r
- catch (ArgumentNullException) {\r
- }\r
- }\r
-\r
- /* IsDefined actually works under mono */\r
- /*\r
- public void TestIsDefined () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.IsDefined (typeof (int), true);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
- */\r
-\r
- /* FIXME: This does not work under mono\r
- public void TestGetEvents () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.GetEvents ();\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
-\r
- try {\r
- tb.GetEvents (BindingFlags.Public);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
- */\r
-\r
- public void TestGetEvent () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.GetEvent ("FOO", BindingFlags.Public);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestGetMember () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.GetMember ("FOO", MemberTypes.All, BindingFlags.Public);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestGetMembers () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.GetMembers (BindingFlags.Public);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- public void TestGetInterface () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- try {\r
- tb.GetInterface ("FOO", true);\r
- Fail ();\r
- }\r
- catch (NotSupportedException) {\r
- }\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (InvalidOperationException))]\r
- public void TestAddDeclarativeSecurityAlreadyCreated () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
- tb.CreateType ();\r
-\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
- tb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (ArgumentNullException))]\r
- public void TestAddDeclarativeSecurityNullPermissionSet () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- tb.AddDeclarativeSecurity (SecurityAction.Demand, null);\r
- }\r
-\r
- [Test]\r
- public void TestAddDeclarativeSecurityInvalidAction () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- SecurityAction[] actions = new SecurityAction [] { \r
- SecurityAction.RequestMinimum,\r
- SecurityAction.RequestOptional,\r
- SecurityAction.RequestRefuse };\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
-\r
- foreach (SecurityAction action in actions) {\r
- try {\r
- tb.AddDeclarativeSecurity (action, set);\r
- Fail ();\r
- }\r
- catch (ArgumentException) {\r
- }\r
- }\r
- }\r
-\r
- [Test]\r
- [ExpectedException (typeof (InvalidOperationException))]\r
- public void TestAddDeclarativeSecurityDuplicateAction () {\r
- TypeBuilder tb = module.DefineType (genTypeName ());\r
-\r
- PermissionSet set = new PermissionSet (PermissionState.Unrestricted);\r
- tb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- tb.AddDeclarativeSecurity (SecurityAction.Demand, set);\r
- }\r
-\r
- /* Test for dynamically generated enums */\r
- public void TestEnums () {\r
- TypeAttributes typeAttrs = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed; \r
- TypeBuilder enumToCreate = module.DefineType(genTypeName (), typeAttrs, \r
- typeof(Enum));\r
- enumToCreate.SetCustomAttribute (new CustomAttributeBuilder (typeof (FlagsAttribute).GetConstructors ()[0], new Type [0]));\r
- // add value__ field, see DefineEnum method of ModuleBuilder\r
- enumToCreate.DefineField("value__", typeof(Int32), \r
- FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);\r
- \r
- // add enum entries\r
- FieldBuilder fb = enumToCreate.DefineField("A", enumToCreate, \r
- FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);\r
- fb.SetConstant((Int32) 0);\r
- \r
- fb = enumToCreate.DefineField("B", enumToCreate, \r
- FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);\r
- fb.SetConstant((Int32) 1);\r
-\r
- fb = enumToCreate.DefineField("C", enumToCreate, \r
- FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);\r
- fb.SetConstant((Int32) 2);\r
- \r
- Type enumType = enumToCreate.CreateType();\r
- \r
- object enumVal = Enum.ToObject(enumType, (Int32) 3);\r
-\r
- AssertEquals ("B, C", enumVal.ToString ());\r
- AssertEquals (3, (Int32)enumVal);\r
- } \r
-}\r
-}\r
-\r
+
+//
+// TypeBuilderTest.cs - NUnit Test Cases for the TypeBuilder class
+//
+// Zoltan Varga (vargaz@freemail.hu)
+//
+// (C) Ximian, Inc. http://www.ximian.com
+//
+// TODO:
+// - implement a mechnanism for easier testing of null argument exceptions
+// - with overloaded methods like DefineNestedType (), check the defaults
+// on the shorter versions.
+// - ToString on enums with the flags attribute set should print all
+// values which match, e.g. 0 == AutoLayou,AnsiClass,NotPublic
+//
+
+using System;
+using System.Threading;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Security;
+using System.Security.Permissions;
+using System.Runtime.InteropServices;
+using NUnit.Framework;
+
+namespace MonoTests.System.Reflection.Emit
+{
+
+[TestFixture]
+public class TypeBuilderTest : Assertion
+{
+ private interface AnInterface {
+ }
+
+ private AssemblyBuilder assembly;
+
+ private ModuleBuilder module;
+
+ static string ASSEMBLY_NAME = "MonoTests.System.Reflection.Emit.TypeBuilderTest";
+
+ [SetUp]
+ protected void SetUp () {
+ AssemblyName assemblyName = new AssemblyName();
+ assemblyName.Name = ASSEMBLY_NAME;
+
+ assembly =
+ Thread.GetDomain().DefineDynamicAssembly(
+ assemblyName, AssemblyBuilderAccess.RunAndSave, "c:\\");
+
+ module = assembly.DefineDynamicModule("module1");
+ }
+
+ static int typeIndexer = 0;
+
+ // Return a unique type name
+ private string genTypeName () {
+ return "t" + (typeIndexer ++);
+ }
+
+ private string nullName () {
+ return String.Format ("{0}", (char)0);
+ }
+
+ [Test]
+ public void TestAssembly () {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
+ AssertEquals ("Assembly works",
+ tb.Assembly, assembly);
+ }
+
+ [Test]
+ public void TestAssemblyQualifiedName () {
+ TypeBuilder tb = module.DefineType ("A.B.C.D", TypeAttributes.Public);
+
+ AssertEquals ("AssemblyQualifiedName works",
+ tb.AssemblyQualifiedName, "A.B.C.D, " + assembly.GetName ().FullName);
+ }
+
+ [Test]
+ public void TestAttributes () {
+ TypeAttributes attrs = TypeAttributes.Public | TypeAttributes.BeforeFieldInit;
+ TypeBuilder tb = module.DefineType (genTypeName (), attrs);
+
+ AssertEquals ("Attributes works",
+ tb.Attributes, attrs);
+ }
+
+ [Test]
+ public void TestBaseTypeClass () {
+ TypeAttributes attrs = TypeAttributes.Public;
+ TypeBuilder tb = module.DefineType (genTypeName (), attrs);
+ AssertEquals ("BaseType defaults to Object",
+ tb.BaseType, typeof (object));
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), attrs, tb);
+ AssertEquals ("BaseType works",
+ tb2.BaseType, tb);
+ }
+
+ [Test]
+ public void TestBaseTypeInterface ()
+ {
+ TypeBuilder tb3 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ AssertEquals ("Interfaces should default to no base type", null, tb3.BaseType);
+ }
+
+ [Test]
+ public void TestDeclaringType () {
+ TypeAttributes attrs = 0;
+ TypeBuilder tb = module.DefineType (genTypeName (), attrs);
+
+ AssertEquals ("Has no declaring type",
+ null, tb.DeclaringType);
+
+ attrs = TypeAttributes.NestedPublic;
+ TypeBuilder tb2 = tb.DefineNestedType (genTypeName (), attrs);
+ TypeBuilder tb3 = tb2.DefineNestedType (genTypeName (), attrs);
+ AssertEquals ("DeclaringType works",
+ tb, tb3.DeclaringType.DeclaringType);
+ }
+
+ [Test]
+ public void TestFullName () {
+ string name = genTypeName ();
+ TypeAttributes attrs = 0;
+ TypeBuilder tb = module.DefineType (name, attrs);
+ AssertEquals ("FullName works",
+ name, tb.FullName);
+
+ string name2 = genTypeName ();
+ attrs = TypeAttributes.NestedPublic;
+ TypeBuilder tb2 = tb.DefineNestedType (name2, attrs);
+
+ string name3 = genTypeName ();
+ attrs = TypeAttributes.NestedPublic;
+ TypeBuilder tb3 = tb2.DefineNestedType (name3, attrs);
+
+ AssertEquals ("FullName works on nested types",
+ name + "+" + name2 + "+" + name3, tb3.FullName);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGUIDIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ Guid g = tb.GUID;
+ }
+
+ [Test]
+ public void TestGUIDComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+ Assert(tb.GUID != Guid.Empty);
+ }
+
+ [Test]
+ public void TestFixedGUIDComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ Guid guid = Guid.NewGuid ();
+
+ ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor(
+ new Type[] {typeof(string)});
+
+ CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
+ new object[] { guid.ToString("D") }, new FieldInfo[0], new object[0]);
+
+ tb.SetCustomAttribute (caBuilder);
+ tb.CreateType ();
+ AssertEquals (guid, tb.GUID);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestHasElementType () {
+ // According to the MSDN docs, this member works, but in reality, it
+ // returns a NotSupportedException
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ bool b = tb.HasElementType;
+ }
+
+ [Test]
+ public void TestIsAbstract () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("",
+ false, tb.IsAbstract);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Abstract);
+ AssertEquals ("",
+ true, tb2.IsAbstract);
+ }
+
+ [Test]
+ public void TestIsAnsiClass () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("",
+ true, tb.IsAnsiClass);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);
+ AssertEquals ("",
+ false, tb2.IsAnsiClass);
+ }
+
+ [Test]
+ public void TestIsArray () {
+ // How can a TypeBuilder be an array ?
+ string name = genTypeName ();
+ TypeBuilder tb = module.DefineType (name);
+ AssertEquals ("IsArray works",
+ false, tb.IsArray);
+ }
+
+ [Test]
+ public void TestIsAutoClass () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("",
+ false, tb.IsAutoClass);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.AutoClass);
+ AssertEquals ("",
+ true, tb2.IsAutoClass);
+ }
+
+ [Test]
+ public void TestIsAutoLayout () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("AutoLayout defaults to true",
+ true, tb.IsAutoLayout);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);
+ AssertEquals ("",
+ false, tb2.IsAutoLayout);
+ }
+
+ [Test]
+ public void TestIsByRef () {
+ // How can a TypeBuilder be ByRef ?
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("IsByRef works",
+ false, tb.IsByRef);
+ }
+
+ [Test]
+ public void TestIsClass () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Most types are classes",
+ true, tb.IsClass);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ AssertEquals ("Interfaces are not classes",
+ false, tb2.IsClass);
+
+ TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
+ AssertEquals ("value types are not classes",
+ false, tb3.IsClass);
+
+ TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));
+ AssertEquals ("enums are not classes",
+ false, tb4.IsClass);
+ }
+
+ [Test]
+ public void TestIsCOMObject () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Probably not", false, tb.IsCOMObject);
+
+ tb = module.DefineType (genTypeName (), TypeAttributes.Import);
+ AssertEquals ("type with Import attribute is COM object",
+ true, tb.IsCOMObject);
+ }
+
+ [Test]
+ public void TestIsContextful () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsContextful);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));
+ AssertEquals (true, tb2.IsContextful);
+ }
+
+ [Test]
+ public void TestIsEnum () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsEnum);
+
+ // This returns true under both mono and MS .NET ???
+ TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ValueType));
+ AssertEquals ("value types are not necessary enums",
+ false, tb2.IsEnum);
+
+ TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (Enum));
+ AssertEquals ("enums are enums", true, tb3.IsEnum);
+ }
+
+ [Test]
+ public void TestIsExplicitLayout () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("ExplicitLayout defaults to false",
+ false, tb.IsExplicitLayout);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);
+ AssertEquals (true, tb2.IsExplicitLayout);
+ }
+
+ [Test]
+ public void TestIsImport () {
+ // How can this be true ?
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsImport);
+ }
+
+ [Test]
+ public void TestIsInterface () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Most types are not interfaces",
+ false, tb.IsInterface);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ AssertEquals ("Interfaces are interfaces",
+ true, tb2.IsInterface);
+
+ TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
+ AssertEquals ("value types are not interfaces",
+ false, tb3.IsInterface);
+ }
+
+ [Test]
+ public void TestIsLayoutSequential () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("SequentialLayout defaults to false",
+ false, tb.IsLayoutSequential);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SequentialLayout);
+ AssertEquals (true, tb2.IsLayoutSequential);
+ }
+
+ [Test]
+ public void TestIsMarshalByRef () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsMarshalByRef);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (MarshalByRefObject));
+ AssertEquals (true, tb2.IsMarshalByRef);
+
+ TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));
+ AssertEquals (true, tb3.IsMarshalByRef);
+ }
+
+ // TODO: Visibility properties
+
+ [Test]
+ public void TestIsPointer () {
+ // How can this be true?
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsPointer);
+ }
+
+ [Test]
+ public void TestIsPrimitive () {
+ TypeBuilder tb = module.DefineType ("int");
+ AssertEquals (false, tb.IsPrimitive);
+ }
+
+ [Test]
+ public void IsSealed () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Sealed defaults to false",
+ false, tb.IsSealed);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);
+ AssertEquals ("IsSealed works", true, tb2.IsSealed);
+ }
+
+ [Test]
+ public void IsSerializable () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsSerializable);
+
+ ConstructorInfo[] ctors = typeof (SerializableAttribute).GetConstructors (BindingFlags.Instance | BindingFlags.Public);
+ Assert ("SerializableAttribute should have more than 0 public instance ctors",
+ ctors.Length > 0);
+
+ tb.SetCustomAttribute (new CustomAttributeBuilder (ctors[0], new object[0]));
+ Type createdType = tb.CreateType ();
+
+ assembly.Save ("TestAssembly.dll");
+ AssertEquals (true, createdType.IsSerializable);
+ }
+
+ [Test]
+ public void TestIsSpecialName () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("SpecialName defaults to false",
+ false, tb.IsSpecialName);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SpecialName);
+ AssertEquals ("IsSpecialName works",
+ true, tb2.IsSpecialName);
+ }
+
+ [Test]
+ public void TestIsUnicodeClass () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (false, tb.IsUnicodeClass);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);
+ AssertEquals (true, tb2.IsUnicodeClass);
+ }
+
+ [Test]
+ public void TestIsValueType () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Most types are not value types",
+ false, tb.IsValueType);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ AssertEquals ("Interfaces are not value types",
+ false, tb2.IsValueType);
+
+ TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
+ AssertEquals ("value types are value types",
+ true, tb3.IsValueType);
+
+ TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));
+ AssertEquals ("enums are value types",
+ true, tb4.IsValueType);
+ }
+
+ [Test]
+ public void TestMemberType () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("A type is a type",
+ MemberTypes.TypeInfo, tb.MemberType);
+ }
+
+ [Test]
+ public void TestModule () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("Module works", module, tb.Module);
+ }
+
+ [Test]
+ public void TestName () {
+ TypeBuilder tb = module.DefineType ("A");
+ AssertEquals ("A", tb.Name);
+
+ TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");
+ AssertEquals ("E", tb2.Name);
+
+ TypeBuilder tb3 = tb2.DefineNestedType ("A");
+ AssertEquals ("A", tb3.Name);
+
+ /* Is .E a valid name ?
+ TypeBuilder tb4 = module.DefineType (".E");
+ AssertEquals ("",
+ "E", tb4.Name);
+ */
+ }
+
+ [Test]
+ public void TestNamespace () {
+ TypeBuilder tb = module.DefineType ("A");
+ AssertEquals ("", tb.Namespace);
+
+ TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");
+ AssertEquals ("A.B.C.D", tb2.Namespace);
+
+ TypeBuilder tb3 = tb2.DefineNestedType ("A");
+ AssertEquals ("", tb3.Namespace);
+
+ /* Is .E a valid name ?
+ TypeBuilder tb4 = module.DefineType (".E");
+ AssertEquals ("",
+ "E", tb4.Name);
+ */
+ }
+
+ [Test]
+ public void TestPackingSize () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (PackingSize.Unspecified, tb.PackingSize);
+
+ TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (object),
+ PackingSize.Size16, 16);
+ AssertEquals (PackingSize.Size16, tb2.PackingSize);
+ }
+
+ [Test]
+ public void TestReflectedType () {
+ // It is the same as DeclaringType, but why?
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (null, tb.ReflectedType);
+
+ TypeBuilder tb2 = tb.DefineNestedType (genTypeName ());
+ AssertEquals (tb, tb2.ReflectedType);
+ }
+
+ [Test]
+ [ExpectedException (typeof(ArgumentNullException))]
+ public void TestSetParentNull ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.SetParent (null);
+ }
+
+ [Test]
+ public void TestSetParentIncomplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.SetParent (typeof(Attribute));
+ AssertEquals (typeof(Attribute), tb.BaseType);
+ }
+
+ [Test]
+ [ExpectedException (typeof(InvalidOperationException))]
+ public void TestSetParentComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+ tb.SetParent (typeof(Attribute));
+ }
+
+ [Test]
+ public void TestSize () {
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals (0, tb.Size);
+ tb.CreateType ();
+ AssertEquals (0, tb.Size);
+ }
+
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (object),
+ PackingSize.Size16, 32);
+ AssertEquals (32, tb.Size);
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestTypeHandle () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ RuntimeTypeHandle handle = tb.TypeHandle;
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestTypeInitializerIncomplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ ConstructorInfo cb = tb.TypeInitializer;
+ }
+
+ [Test]
+ public void TestTypeInitializerComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+ ConstructorInfo cb = tb.TypeInitializer;
+ }
+
+ [Test]
+ public void TestTypeToken () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ TypeToken token = tb.TypeToken;
+ }
+
+ [Test]
+ public void TestUnderlyingSystemType () {
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ AssertEquals ("For non-enums this equals itself",
+ tb, tb.UnderlyingSystemType);
+ }
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ AssertEquals (tb, tb.UnderlyingSystemType);
+ }
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (ValueType));
+ AssertEquals (tb, tb.UnderlyingSystemType);
+ }
+
+ {
+ TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (Enum));
+ try {
+ Type t = tb.UnderlyingSystemType;
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+
+ tb.DefineField ("val", typeof (int), 0);
+ AssertEquals (typeof (int), tb.UnderlyingSystemType);
+ }
+ }
+
+ [Test]
+ public void TestAddInterfaceImplementation () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ try {
+ tb.AddInterfaceImplementation (null);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ tb.AddInterfaceImplementation (typeof (AnInterface));
+ tb.AddInterfaceImplementation (typeof (AnInterface));
+
+ Type t = tb.CreateType ();
+ AssertEquals ("Should merge identical interfaces",
+ tb.GetInterfaces ().Length, 1);
+
+ // Can not be called on a created type
+ try {
+ tb.AddInterfaceImplementation (typeof (AnInterface));
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestCreateType () {
+ // TODO: LOTS OF TEST SHOULD GO THERE
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+
+ // Can not be called on a created type
+ try {
+ tb.CreateType ();
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineConstructor () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ ConstructorBuilder cb = tb.DefineConstructor (0, 0, null);
+ cb.GetILGenerator ().Emit (OpCodes.Ret);
+ tb.CreateType ();
+
+ // Can not be called on a created type
+ try {
+ tb.DefineConstructor (0, 0, null);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineDefaultConstructor () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineDefaultConstructor (0);
+ tb.CreateType ();
+
+ // Can not be called on a created type, altough the MSDN docs does not mention this
+ try {
+ tb.DefineDefaultConstructor (0);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineEvent () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Test invalid arguments
+ try {
+ tb.DefineEvent (null, 0, typeof (int));
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineEvent ("FOO", 0, null);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineEvent ("", 0, typeof (int));
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ tb.CreateType ();
+ // Can not be called on a created type
+ try {
+ tb.DefineEvent ("BAR", 0, typeof (int));
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineField () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Check invalid arguments
+ try {
+ tb.DefineField (null, typeof (int), 0);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineField ("", typeof (int), 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ try {
+ // Strangely, 'A<NULL>' is accepted...
+ string name = String.Format ("{0}", (char)0);
+ tb.DefineField (name, typeof (int), 0);
+ Fail ("Names with embedded nulls should be rejected");
+ }
+ catch (ArgumentException) {
+ }
+
+ try {
+ tb.DefineField ("A", typeof (void), 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ tb.CreateType ();
+ // Can not be called on a created type
+ try {
+ tb.DefineField ("B", typeof (int), 0);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineInitializedData () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Check invalid arguments
+ try {
+ tb.DefineInitializedData (null, new byte[1], 0);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineInitializedData ("FOO", null, 0);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineInitializedData ("", new byte[1], 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ // The size of the data is less than or equal to zero ???
+ try {
+ tb.DefineInitializedData ("BAR", new byte[0], 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ try {
+ string name = String.Format ("{0}", (char)0);
+ tb.DefineInitializedData (name, new byte[1], 0);
+ Fail ("Names with embedded nulls should be rejected");
+ }
+ catch (ArgumentException) {
+ }
+
+ tb.CreateType ();
+
+ // Can not be called on a created type, altough the MSDN docs does not mention this
+ try {
+ tb.DefineInitializedData ("BAR2", new byte[1], 0);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ [Test]
+ public void DefineUninitializedDataInvalidArgs () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ try {
+ tb.DefineUninitializedData (null, 1, 0);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineUninitializedData ("", 1, 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ // The size of the data is less than or equal to zero ???
+ try {
+ tb.DefineUninitializedData ("BAR", 0, 0);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ try {
+ string name = String.Format ("{0}", (char)0);
+ tb.DefineUninitializedData (name, 1, 0);
+ Fail ("Names with embedded nulls should be rejected");
+ }
+ catch (ArgumentException) {
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof (InvalidOperationException))]
+ public void DefineUninitializedDataAlreadyCreated () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+
+ tb.DefineUninitializedData ("BAR2", 1, 0);
+ }
+
+ [Test]
+ public void DefineUninitializedData () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ tb.DefineUninitializedData ("foo", 4, FieldAttributes.Public);
+
+ Type t = tb.CreateType ();
+
+ object o = Activator.CreateInstance (t);
+
+ FieldInfo fi = t.GetField ("foo");
+
+ object fieldVal = fi.GetValue (o);
+
+ IntPtr ptr = Marshal.AllocHGlobal (4);
+ Marshal.StructureToPtr (fieldVal, ptr, true);
+ Marshal.FreeHGlobal (ptr);
+ }
+
+ [Test]
+ public void TestDefineMethod () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Check invalid arguments
+ try {
+ tb.DefineMethod (null, 0, null, null);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineMethod ("", 0, null, null);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ // Check non-virtual methods on an interface
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+ try {
+ tb2.DefineMethod ("FOO", MethodAttributes.Abstract, null, null);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+
+ tb.CreateType ();
+ // Can not be called on a created type
+ try {
+ tb.DefineMethod ("bar", 0, null, null);
+ Fail ();
+ }
+ catch (InvalidOperationException) {
+ }
+ }
+
+ // TODO: DefineMethodOverride
+
+ [Test]
+ public void TestDefineNestedType () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Check invalid arguments
+ try {
+ tb.DefineNestedType (null);
+ Fail ("Should reject null name");
+ }
+ catch (ArgumentNullException) {
+ }
+
+ try {
+ tb.DefineNestedType ("");
+ Fail ("Should reject empty name");
+ }
+ catch (ArgumentException) {
+ }
+
+ try {
+ tb.DefineNestedType (nullName ());
+ Fail ("Should reject name with embedded 0s");
+ }
+ catch (ArgumentException) {
+ }
+
+ // If I fix the code so this works then mcs breaks -> how can mcs
+ // works under MS .NET in the first place ???
+ /*
+ try {
+ tb.DefineNestedType ("AA", TypeAttributes.Public, null, null);
+ Fail ("Nested visibility must be specified.");
+ }
+ catch (ArgumentException) {
+ }
+ */
+
+ try {
+ tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,
+ new Type[1]);
+ Fail ("Should reject empty interface");
+ }
+ catch (ArgumentException) {
+ }
+
+ // I think this should reject non-interfaces, but it does not
+ tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,
+ new Type[1] { typeof (object) });
+
+ // Normal invocation
+ tb.DefineNestedType ("Nest");
+
+ tb.CreateType ();
+
+ // According to the MSDN docs, this cannnot be called after the type
+ // is created, but it works.
+ tb.DefineNestedType ("Nest2");
+
+ // According to the MSDN docs, a Sealed class can't contain nested
+ // types, but this is not true
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);
+ tb2.DefineNestedType ("AA");
+
+ // According to the MSDN docs, interfaces can only contain interfaces,
+ // but this is not true
+ TypeBuilder tb3 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+
+ tb3.DefineNestedType ("AA");
+
+ // Check shorter versions
+ {
+ TypeBuilder nested = tb.DefineNestedType ("N1");
+
+ AssertEquals (nested.Name, "N1");
+ AssertEquals (nested.BaseType, typeof (object));
+ AssertEquals (nested.Attributes, TypeAttributes.NestedPrivate);
+ AssertEquals (nested.GetInterfaces ().Length, 0);
+ }
+
+ // TODO:
+ }
+
+ [Test]
+ public void TestDefinePInvokeMethod () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ tb.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);
+
+ // Try invalid parameters
+ try {
+ tb.DefinePInvokeMethod (null, "B", "C", 0, 0, null, null, 0, 0);
+ Fail ();
+ }
+ catch (ArgumentNullException) {
+ }
+ // etc...
+
+ // Try invalid attributes
+ try {
+ tb.DefinePInvokeMethod ("A2", "B", "C", MethodAttributes.Abstract, 0, null, null, 0, 0);
+ }
+ catch (ArgumentException) {
+ }
+
+ // Try an interface parent
+ TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
+
+ try {
+ tb2.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);
+ }
+ catch (ArgumentException) {
+ }
+ }
+
+ [Test]
+ public void TestDefineProperty () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ // Check null parameter types
+ try {
+ tb.DefineProperty ("A", 0, null, new Type[1]);
+ }
+ catch (ArgumentNullException) {
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestIsDefinedIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.IsDefined (typeof (int), true);
+ }
+
+ [Test]
+ public void TestIsDefinedComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ ConstructorInfo obsoleteCtor = typeof(ObsoleteAttribute).GetConstructor(
+ new Type[] {typeof(string)});
+
+ CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (obsoleteCtor,
+ new object[] { "obsolete message" }, new FieldInfo[0], new object[0]);
+
+ tb.SetCustomAttribute (caBuilder);
+ tb.CreateType ();
+ AssertEquals (true, tb.IsDefined (typeof(ObsoleteAttribute), false));
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetCustomAttributesIncomplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetCustomAttributes (false);
+ }
+
+ [Test]
+ public void TestGetCustomAttributesComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor (
+ new Type[] { typeof(string) });
+
+ CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
+ new object[] { Guid.NewGuid ().ToString ("D") }, new FieldInfo[0], new object[0]);
+
+ tb.SetCustomAttribute (caBuilder);
+ tb.CreateType ();
+
+ AssertEquals (1, tb.GetCustomAttributes (false).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetCustomAttributesOfTypeIncomplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetCustomAttributes (typeof(ObsoleteAttribute), false);
+ }
+
+ [Test]
+ public void TestGetCustomAttributesOfTypeComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor (
+ new Type[] { typeof(string) });
+
+ CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
+ new object[] { Guid.NewGuid ().ToString ("D") }, new FieldInfo[0], new object[0]);
+
+ tb.SetCustomAttribute (caBuilder);
+ tb.CreateType ();
+
+ AssertEquals (1, tb.GetCustomAttributes (typeof(GuidAttribute), false).Length);
+ AssertEquals (0, tb.GetCustomAttributes (typeof(ObsoleteAttribute), false).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetCustomAttributesOfNullTypeIncomplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetCustomAttributes (null, false);
+ }
+
+ [Test]
+ [ExpectedException (typeof(ArgumentNullException))]
+ public void TestGetCustomAttributesOfNullTypeComplete ()
+ {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+ tb.GetCustomAttributes (null, false);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetEventsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetEvents ();
+ }
+
+ [Test]
+ public void TestGetEventsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
+ typeof(void), new Type[] { typeof(Object) });
+ onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
+
+ // create public event
+ EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
+ typeof(ResolveEventHandler));
+ eventbuilder.SetRaiseMethod (onclickMethod);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetEvents ().Length);
+ AssertEquals (tb.GetEvents ().Length, emittedType.GetEvents ().Length);
+ }
+
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetEventsFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetEvents (BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetEventsFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ MethodBuilder onchangeMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
+ typeof(void), new Type[] { typeof(Object) });
+ onchangeMethod.GetILGenerator ().Emit (OpCodes.Ret);
+
+ // create public event
+ EventBuilder changeEvent = tb.DefineEvent ("Change", EventAttributes.None,
+ typeof(ResolveEventHandler));
+ changeEvent.SetRaiseMethod (onchangeMethod);
+
+ // create non-public event
+ EventBuilder redoChangeEvent = tb.DefineEvent ("RedoChange", EventAttributes.None,
+ typeof(ResolveEventHandler));
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (1, tb.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ AssertEquals (2, tb.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length);
+ AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length,
+ emittedType.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length,
+ emittedType.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length,
+ emittedType.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetEventIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetEvent ("FOO");
+ }
+
+ [Test]
+ public void TestGetEventComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
+ typeof(void), new Type[] { typeof(Object) });
+ onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
+
+ EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
+ typeof(ResolveEventHandler));
+ eventbuilder.SetRaiseMethod (onclickMethod);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (tb.GetEvent ("Change"));
+ AssertEquals (tb.GetEvent ("Change"), emittedType.GetEvent ("Change"));
+ AssertNull (tb.GetEvent ("NotChange"));
+ AssertEquals (tb.GetEvent ("NotChange"), emittedType.GetEvent ("NotChange"));
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetEventFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetEvent ("FOO", BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetEventFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
+ typeof(void), new Type[] { typeof(Object) });
+ onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
+
+ EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
+ typeof(ResolveEventHandler));
+ eventbuilder.SetRaiseMethod (onclickMethod);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public));
+ AssertEquals (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public),
+ emittedType.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public));
+ AssertNull (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic));
+ AssertEquals (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic),
+ emittedType.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic));
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetFieldsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetFields ();
+ }
+
+ [Test]
+ public void TestGetFieldsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetFields ().Length);
+ AssertEquals (tb.GetFields ().Length, emittedType.GetFields().Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetFieldsFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetFields (BindingFlags.Instance | BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetFieldsFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetFields (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (tb.GetFields (BindingFlags.Instance | BindingFlags.Public).Length,
+ emittedType.GetFields (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (0, tb.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ AssertEquals (tb.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length,
+ emittedType.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetFieldIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetField ("test");
+ }
+
+ [Test]
+ public void TestGetFieldComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (tb.GetField ("TestField"));
+ AssertEquals (tb.GetField ("TestField"), emittedType.GetField ("TestField"));
+ AssertNull (tb.GetField ("TestOtherField"));
+ AssertEquals (tb.GetField ("TestOtherField"),
+ emittedType.GetField ("TestOtherField"));
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetFieldFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetField ("test", BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetFieldFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public));
+ AssertEquals (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public),
+ emittedType.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public));
+ AssertNull (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic));
+ AssertEquals (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic),
+ emittedType.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic));
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetPropertiesIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetProperties ();
+ }
+
+ [Test]
+ public void TestGetPropertiesComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetProperties ().Length);
+ AssertEquals (tb.GetProperties ().Length, emittedType.GetProperties ().Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetPropertiesFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetProperties (BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetPropertiesFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (tb.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length,
+ emittedType.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (0, tb.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ AssertEquals (tb.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length,
+ emittedType.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetPropertyIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetProperty ("test");
+ }
+
+ [Test]
+ public void TestGetPropertyComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (emittedType.GetProperty ("CustomerName"));
+ AssertNull (emittedType.GetProperty ("OtherCustomerName"));
+
+ try {
+ tb.GetProperty ("CustomerName");
+ Fail ();
+ } catch (NotSupportedException) {}
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetPropertyFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetProperty ("test", BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetPropertyFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertNotNull (emittedType.GetProperty ("CustomerName", BindingFlags.Instance |
+ BindingFlags.Public));
+ AssertNull (emittedType.GetProperty ("CustomerName", BindingFlags.Instance |
+ BindingFlags.NonPublic));
+
+ try {
+ tb.GetProperty ("CustomerName", BindingFlags.Instance | BindingFlags.Public);
+ Fail ();
+ }
+ catch (NotSupportedException) { }
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetMethodsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetMethods ();
+ }
+
+ [Test]
+ public void TestGetMethodsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ MethodBuilder helloMethod = tb.DefineMethod ("HelloMethod",
+ MethodAttributes.Public, typeof(string), new Type[0]);
+ ILGenerator helloMethodIL = helloMethod.GetILGenerator ();
+ helloMethodIL.Emit (OpCodes.Ldstr, "Hi! ");
+ helloMethodIL.Emit (OpCodes.Ldarg_1);
+ MethodInfo infoMethod = typeof(string).GetMethod ("Concat",
+ new Type[] { typeof(string), typeof(string) });
+ helloMethodIL.Emit (OpCodes.Call, infoMethod);
+ helloMethodIL.Emit (OpCodes.Ret);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (typeof(object).GetMethods (BindingFlags.Public | BindingFlags.Instance).Length + 1,
+ tb.GetMethods ().Length);
+ AssertEquals (tb.GetMethods ().Length, emittedType.GetMethods ().Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetMethodsFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetMethods (BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetMethodsFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ MethodBuilder helloMethod = tb.DefineMethod ("HelloMethod",
+ MethodAttributes.Public, typeof(string), new Type[0]);
+ ILGenerator helloMethodIL = helloMethod.GetILGenerator ();
+ helloMethodIL.Emit (OpCodes.Ldstr, "Hi! ");
+ helloMethodIL.Emit (OpCodes.Ldarg_1);
+ MethodInfo infoMethod = typeof(string).GetMethod ("Concat",
+ new Type[] { typeof(string), typeof(string) });
+ helloMethodIL.Emit (OpCodes.Call, infoMethod);
+ helloMethodIL.Emit (OpCodes.Ret);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetMethods (BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Length);
+ AssertEquals (tb.GetMethods (BindingFlags.Instance | BindingFlags.Public).Length,
+ emittedType.GetMethods (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (0, tb.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).Length);
+ AssertEquals (tb.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic).Length,
+ emittedType.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetMemberIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetMember ("FOO", MemberTypes.All, BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetMemberComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("FOO", typeof(int), FieldAttributes.Private);
+
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (1, tb.GetMember ("FOO", MemberTypes.Field, BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ AssertEquals (0, tb.GetMember ("FOO", MemberTypes.Field, BindingFlags.Instance | BindingFlags.Public).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetMembersIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetMembers ();
+ }
+
+ [Test]
+ public void TestGetMembersComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ Type emittedType = tb.CreateType ();
+
+ AssertEquals (tb.GetMembers ().Length, emittedType.GetMembers ().Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetMembersFlagsIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetMembers (BindingFlags.Public);
+ }
+
+ [Test]
+ public void TestGetMembersFlagsComplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.DefineField ("FOO", typeof(int), FieldAttributes.Public);
+
+ Type emittedType = tb.CreateType ();
+
+ Assert (tb.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length != 0);
+ AssertEquals (tb.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length,
+ emittedType.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length);
+ AssertEquals (tb.GetMembers (BindingFlags.Instance | BindingFlags.NonPublic).Length,
+ emittedType.GetMembers (BindingFlags.Instance | BindingFlags.NonPublic).Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof(NotSupportedException))]
+ public void TestGetInterfaceIncomplete () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.GetInterface ("FOO", true);
+ }
+
+ [Test]
+ public void TestGetInterfaces () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ Type[] interfaces = tb.GetInterfaces ();
+ AssertEquals (0, interfaces.Length);
+
+ TypeBuilder tbInterface = module.DefineType (genTypeName (), TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
+ Type emittedInterface = tbInterface.CreateType ();
+
+ tb = module.DefineType (genTypeName (), TypeAttributes.Public, typeof(object), new Type[] { emittedInterface });
+ interfaces = tb.GetInterfaces ();
+ AssertEquals (1, interfaces.Length);
+ }
+
+ [Test]
+ [ExpectedException (typeof (InvalidOperationException))]
+ public void TestAddDeclarativeSecurityAlreadyCreated () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+ tb.CreateType ();
+
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+ tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ }
+
+ [Test]
+ [ExpectedException (typeof (ArgumentNullException))]
+ public void TestAddDeclarativeSecurityNullPermissionSet () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ tb.AddDeclarativeSecurity (SecurityAction.Demand, null);
+ }
+
+ [Test]
+ public void TestAddDeclarativeSecurityInvalidAction () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ SecurityAction[] actions = new SecurityAction [] {
+ SecurityAction.RequestMinimum,
+ SecurityAction.RequestOptional,
+ SecurityAction.RequestRefuse };
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+
+ foreach (SecurityAction action in actions) {
+ try {
+ tb.AddDeclarativeSecurity (action, set);
+ Fail ();
+ }
+ catch (ArgumentException) {
+ }
+ }
+ }
+
+ [Test]
+ [ExpectedException (typeof (InvalidOperationException))]
+ public void TestAddDeclarativeSecurityDuplicateAction () {
+ TypeBuilder tb = module.DefineType (genTypeName ());
+
+ PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
+ tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
+ }
+
+ [Test]
+ public void TestEnums () {
+ TypeAttributes typeAttrs = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;
+ TypeBuilder enumToCreate = module.DefineType(genTypeName (), typeAttrs,
+ typeof(Enum));
+ enumToCreate.SetCustomAttribute (new CustomAttributeBuilder (typeof (FlagsAttribute).GetConstructors ()[0], new Type [0]));
+ // add value__ field, see DefineEnum method of ModuleBuilder
+ enumToCreate.DefineField("value__", typeof(Int32),
+ FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
+
+ // add enum entries
+ FieldBuilder fb = enumToCreate.DefineField("A", enumToCreate,
+ FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
+ fb.SetConstant((Int32) 0);
+
+ fb = enumToCreate.DefineField("B", enumToCreate,
+ FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
+ fb.SetConstant((Int32) 1);
+
+ fb = enumToCreate.DefineField("C", enumToCreate,
+ FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
+ fb.SetConstant((Int32) 2);
+
+ Type enumType = enumToCreate.CreateType();
+
+ object enumVal = Enum.ToObject(enumType, (Int32) 3);
+
+ AssertEquals ("B, C", enumVal.ToString ());
+ AssertEquals (3, (Int32)enumVal);
+ }
+
+ private void DefineStringProperty (TypeBuilder tb, string propertyName, string fieldName, MethodAttributes methodAttribs) {
+ // define the field holding the property value
+ FieldBuilder fieldBuilder = tb.DefineField (fieldName,
+ typeof(string), FieldAttributes.Private);
+
+ PropertyBuilder propertyBuilder = tb.DefineProperty (
+ propertyName, PropertyAttributes.HasDefault, typeof(string),
+ new Type[] { typeof(string) });
+
+ // First, we'll define the behavior of the "get" property for CustomerName as a method.
+ MethodBuilder getMethodBuilder = tb.DefineMethod ("Get" + propertyName,
+ methodAttribs,
+ typeof(string),
+ new Type[] { });
+
+ ILGenerator getIL = getMethodBuilder.GetILGenerator ();
+
+ getIL.Emit (OpCodes.Ldarg_0);
+ getIL.Emit (OpCodes.Ldfld, fieldBuilder);
+ getIL.Emit (OpCodes.Ret);
+
+ // Now, we'll define the behavior of the "set" property for CustomerName.
+ MethodBuilder setMethodBuilder = tb.DefineMethod ("Set" + propertyName,
+ methodAttribs,
+ null,
+ new Type[] { typeof(string) });
+
+ ILGenerator setIL = setMethodBuilder.GetILGenerator ();
+
+ setIL.Emit (OpCodes.Ldarg_0);
+ setIL.Emit (OpCodes.Ldarg_1);
+ setIL.Emit (OpCodes.Stfld, fieldBuilder);
+ setIL.Emit (OpCodes.Ret);
+
+ // Last, we must map the two methods created above to our PropertyBuilder to
+ // their corresponding behaviors, "get" and "set" respectively.
+ propertyBuilder.SetGetMethod (getMethodBuilder);
+ propertyBuilder.SetSetMethod (setMethodBuilder);
+ }
+}
+}