2 // System.Reflection.Assembly Test Cases
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 // Philippe Lavoie (philippe.lavoie@cactus.ca)
7 // Sebastien Pouliot (sebastien@ximian.com)
8 // Aleksey Kliger (aleksey@xamarin.com)
10 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
11 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
12 // Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using NUnit.Framework;
36 using System.Configuration.Assemblies;
37 using System.Globalization;
39 using System.Reflection;
40 #if !MONOTOUCH && !FULL_AOT_RUNTIME
41 using System.Reflection.Emit;
43 using System.Threading;
44 using System.Runtime.Serialization;
45 using System.Runtime.CompilerServices;
46 using System.Security;
48 using System.Resources;
50 // Used by GetType_TypeForwarder_Nested ()
51 [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(System.Globalization.CultureInfo))]
53 namespace MonoTests.System.Reflection
56 public class AssemblyTest
58 static string BaseTempFolder = Path.Combine (Path.GetTempPath (),
59 "MonoTests.System.Reflection.AssemblyTest");
60 static string TempFolder;
63 public void FixtureSetUp ()
66 // Try to cleanup from any previous NUnit run.
67 Directory.Delete (BaseTempFolder, true);
77 TempFolder = Path.Combine (BaseTempFolder, (++i).ToString());
78 } while (Directory.Exists (TempFolder));
79 Directory.CreateDirectory (TempFolder);
83 public void TearDown ()
86 // This throws an exception under MS.NET and Mono on Windows,
87 // since the directory contains loaded assemblies.
88 Directory.Delete (TempFolder, true);
94 public void CreateInstance()
96 Type type = typeof (AssemblyTest);
97 Object obj = type.Assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
98 Assert.IsNotNull (obj, "#01");
99 Assert.AreEqual (GetType (), obj.GetType (), "#02");
103 public void CreateInvalidInstance()
105 Type type = typeof (AssemblyTest);
106 Object obj = type.Assembly.CreateInstance("NunitTests.ThisTypeDoesNotExist");
107 Assert.IsNull (obj, "#03");
111 [ExpectedException (typeof (ArgumentException))]
112 public void GetType_TypeName_Invalid ()
114 typeof (int).Assembly.GetType ("&blabla", true, true);
118 [ExpectedException (typeof (ArgumentException))]
119 public void GetType_Invalid_RefPtr () {
120 typeof (int).Assembly.GetType ("System.Int32&*", true, true);
124 [ExpectedException (typeof (ArgumentException))]
125 public void GetType_Invalid_RefArray () {
126 typeof (int).Assembly.GetType ("System.Int32&[]", true, true);
130 [ExpectedException (typeof (ArgumentException))]
131 public void GetType_Invalid_RefGeneric () {
132 typeof (int).Assembly.GetType ("System.Tuple`1&[System.Int32]", true, true);
136 [ExpectedException (typeof (ArgumentException))]
137 public void GetType_Invalid_PtrGeneric () {
138 typeof (int).Assembly.GetType ("System.Tuple`1*[System.Int32]", true, true);
142 public void GetType_ComposeModifiers () {
143 var a = typeof(int).Assembly;
145 var e1 = typeof (Int32).MakePointerType().MakeByRefType();
146 var t1 = a.GetType ("System.Int32*&", true, true);
147 Assert.AreEqual (e1, t1, "#1");
149 var e2 = typeof (Int32).MakeArrayType(2).MakeByRefType();
150 var t2 = a.GetType ("System.Int32[,]&", true, true);
151 Assert.AreEqual (e2, t2, "#2");
153 var e3 = typeof (Int32).MakePointerType().MakeArrayType();
154 var t3 = a.GetType ("System.Int32*[]", true, true);
155 Assert.AreEqual (e3, t3, "#3");
157 var e4 = typeof (Int32).MakeArrayType().MakePointerType().MakePointerType().MakeArrayType().MakePointerType().MakeByRefType();
158 var t4 = a.GetType ("System.Int32[]**[]*&", true, true);
159 Assert.AreEqual (e4, t4, "#4");
163 [Test] // bug #334203
164 public void GetType_TypeName_AssemblyName ()
166 Assembly a = typeof (int).Assembly;
167 string typeName = typeof (string).AssemblyQualifiedName;
169 a.GetType (typeName, true, false);
171 } catch (ArgumentException ex) {
172 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
173 Assert.IsNull (ex.InnerException, "#A3");
174 Assert.IsNotNull (ex.Message, "#A4");
175 Assert.IsNull (ex.ParamName, "#A5");
178 Type type = a.GetType (typeName, false);
179 Assert.IsNull (type, "#B1");
180 type = a.GetType (typeName, false, true);
181 Assert.IsNull (type, "#B2");
185 public void GetType_TypeForwarder_Nested () {
186 // System.Globalization is a PCL assembly
187 Type t = typeof (AssemblyTest).Assembly.GetType ("System.Globalization.CultureInfo/Data");
188 Assert.IsNotNull (t);
189 Assert.AreEqual ("System.Globalization.CultureInfo+Data", t.FullName);
193 public void GetEntryAssembly ()
195 // note: only available in default appdomain
196 // http://weblogs.asp.net/asanto/archive/2003/09/08/26710.aspx
197 // Not sure we should emulate this behavior.
199 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
200 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
202 string fname = AppDomain.CurrentDomain.FriendlyName;
203 if (fname.EndsWith (".dll")) { // nunit-console
204 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
205 Assert.IsFalse (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
207 Assert.IsNotNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
208 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
211 Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly");
212 Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain");
216 #if !MONOTOUCH && !FULL_AOT_RUNTIME // Reflection.Emit is not supported.
218 public void GetModules_MissingFile ()
220 AssemblyName newName = new AssemblyName ();
221 newName.Name = "AssemblyTest";
223 AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly (newName, AssemblyBuilderAccess.RunAndSave, TempFolder);
225 ModuleBuilder mb = ab.DefineDynamicModule ("myDynamicModule1", "myDynamicModule.dll", false);
227 ab.Save ("test_assembly.dll");
229 File.Delete (Path.Combine (TempFolder, "myDynamicModule.dll"));
231 Assembly ass = Assembly.LoadFrom (Path.Combine (TempFolder, "test_assembly.dll"));
235 } catch (FileNotFoundException ex) {
236 Assert.AreEqual ("myDynamicModule.dll", ex.FileName);
241 [Category ("NotWorking")]
243 public void Corlib ()
245 Assembly corlib = typeof (int).Assembly;
246 Assert.IsTrue (corlib.CodeBase.EndsWith ("mscorlib.dll"), "CodeBase");
247 Assert.IsNull (corlib.EntryPoint, "EntryPoint");
248 Assert.IsTrue (corlib.EscapedCodeBase.EndsWith ("mscorlib.dll"), "EscapedCodeBase");
249 Assert.IsNotNull (corlib.Evidence, "Evidence");
250 Assert.IsTrue (corlib.Location.EndsWith ("mscorlib.dll"), "Location");
252 // corlib doesn't reference anything
253 Assert.AreEqual (0, corlib.GetReferencedAssemblies ().Length, "GetReferencedAssemblies");
254 Assert.AreEqual ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName");
255 // not really "true" but it's even more trusted so...
256 Assert.IsTrue (corlib.GlobalAssemblyCache, "GlobalAssemblyCache");
257 Assert.AreEqual (0, corlib.HostContext, "HostContext");
258 Assert.AreEqual ("v2.0.50727", corlib.ImageRuntimeVersion, "ImageRuntimeVersion");
259 Assert.IsFalse (corlib.ReflectionOnly, "ReflectionOnly");
260 Assert.AreEqual (0x1, corlib.ManifestModule.MetadataToken);
264 public void Corlib_test ()
266 Assembly corlib_test = Assembly.GetExecutingAssembly ();
267 #if MONODROID || FULL_AOT_DESKTOP || __WATCHOS__
268 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
269 Assert.IsNull (corlib_test.Evidence, "Evidence");
271 Assert.IsNotNull (corlib_test.EntryPoint, "EntryPoint");
272 Assert.IsNull (corlib_test.Evidence, "Evidence");
274 Assert.IsNull (corlib_test.EntryPoint, "EntryPoint");
275 Assert.IsNotNull (corlib_test.Evidence, "Evidence");
277 Assert.IsFalse (corlib_test.GlobalAssemblyCache, "GlobalAssemblyCache");
279 Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies");
280 Assert.AreEqual (0, corlib_test.HostContext, "HostContext");
281 Assert.AreEqual ("v4.0.30319", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
283 Assert.IsNotNull (corlib_test.ManifestModule, "ManifestModule");
284 Assert.IsFalse (corlib_test.ReflectionOnly, "ReflectionOnly");
288 public void GetAssembly ()
290 Assert.IsTrue (Assembly.GetAssembly (typeof (int)).FullName.StartsWith ("mscorlib"), "GetAssembly(int)");
291 Assert.AreEqual (this.GetType ().Assembly.FullName, Assembly.GetAssembly (this.GetType ()).FullName, "GetAssembly(this)");
295 public void GetFile_Null ()
298 Assembly.GetExecutingAssembly ().GetFile (null);
300 } catch (ArgumentNullException ex) {
301 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
302 Assert.IsNull (ex.InnerException, "#3");
303 Assert.IsNotNull (ex.Message, "#4");
304 Assert.IsNull (ex.ParamName, "#5");
309 public void GetFile_Empty ()
312 Assembly.GetExecutingAssembly ().GetFile (
315 } catch (ArgumentException ex) {
316 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
317 Assert.IsNull (ex.InnerException, "#3");
318 Assert.IsNotNull (ex.Message, "#4");
319 Assert.IsNull (ex.ParamName, "#5");
324 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
325 public void GetFiles_False ()
327 Assembly corlib = typeof (int).Assembly;
328 FileStream[] fss = corlib.GetFiles ();
329 Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)");
331 Assembly corlib_test = Assembly.GetExecutingAssembly ();
332 fss = corlib_test.GetFiles ();
333 Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)");
337 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
338 public void GetFiles_True ()
340 Assembly corlib = typeof (int).Assembly;
341 FileStream[] fss = corlib.GetFiles ();
342 Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)");
344 Assembly corlib_test = Assembly.GetExecutingAssembly ();
345 fss = corlib_test.GetFiles ();
346 Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)");
350 public void GetManifestResourceStream_Name_Empty ()
352 Assembly corlib = typeof (int).Assembly;
355 corlib.GetManifestResourceStream (string.Empty);
357 } catch (ArgumentException ex) {
358 // String cannot have zero length
359 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
360 Assert.IsNull (ex.InnerException, "#A3");
361 Assert.IsNotNull (ex.Message, "#A4");
364 corlib.GetManifestResourceStream (typeof (int), string.Empty);
367 corlib.GetManifestResourceStream ((Type) null, string.Empty);
369 } catch (ArgumentException ex) {
370 // String cannot have zero length
371 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
372 Assert.IsNull (ex.InnerException, "#B3");
373 Assert.IsNotNull (ex.Message, "#B4");
378 public void GetManifestResourceStream_Name_Null ()
380 Assembly corlib = typeof (int).Assembly;
383 corlib.GetManifestResourceStream ((string) null);
385 } catch (ArgumentNullException ex) {
386 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
387 Assert.IsNull (ex.InnerException, "#A3");
388 Assert.IsNotNull (ex.Message, "#A4");
391 corlib.GetManifestResourceStream (typeof (int), (string) null);
394 corlib.GetManifestResourceStream ((Type) null, (string) null);
396 } catch (ArgumentNullException ex) {
397 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
398 Assert.IsNull (ex.InnerException, "#B3");
399 Assert.IsNotNull (ex.Message, "#B4");
400 Assert.IsNotNull (ex.ParamName, "#B5");
401 Assert.AreEqual ("type", ex.ParamName, "#B6");
406 public void IsDefined_AttributeType_Null ()
408 Assembly corlib = typeof (int).Assembly;
411 corlib.IsDefined ((Type) null, false);
413 } catch (ArgumentNullException ex) {
414 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
415 Assert.IsNull (ex.InnerException, "#3");
416 Assert.IsNotNull (ex.Message, "#4");
417 Assert.IsNotNull (ex.ParamName, "#5");
418 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
423 public void LoadFrom_Empty_Assembly ()
425 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
426 File.CreateText (tempFile).Close ();
429 Assembly.LoadFrom (tempFile);
431 } catch (BadImageFormatException ex) {
432 Assert.IsNull (ex.InnerException, "#2");
437 public void LoadFrom_Invalid_Assembly ()
439 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
440 using (StreamWriter sw = File.CreateText (tempFile)) {
441 sw.WriteLine ("foo");
446 Assembly.LoadFrom (tempFile);
448 } catch (BadImageFormatException ex) {
449 Assert.IsNull (ex.InnerException, "#2");
454 public void LoadFrom_NonExisting_Assembly ()
456 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
459 Assembly.LoadFrom (tempFile);
461 } catch (FileNotFoundException ex) {
462 Assert.IsNull (ex.InnerException, "#2");
467 public void LoadWithPartialName ()
470 // So the problem here is that if we load an assembly
471 // in a fully aot mode and then cannot load the
472 // dylib, we will assert. This test is incompatible
473 // with the semantics of aot'ed assembly loading, as
474 // aot may assert when loading. This assumes that it's
475 // safe to greedly load everything.
476 var names = new string[] { Assembly.GetCallingAssembly ().GetName ().Name };
478 foreach (string s in names)
479 if (Assembly.LoadWithPartialName (s) != null)
481 Assert.Fail ("Was not able to load any corlib test");
485 public void GetObjectData_Info_Null ()
487 Assembly corlib = typeof (int).Assembly;
489 corlib.GetObjectData (null, new StreamingContext (
490 StreamingContextStates.All));
492 } catch (ArgumentNullException ex) {
493 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
494 Assert.IsNull (ex.InnerException, "#3");
495 Assert.IsNotNull (ex.Message, "#4");
496 Assert.IsNotNull (ex.ParamName, "#5");
497 Assert.AreEqual ("info", ex.ParamName, "#6");
502 public void GetReferencedAssemblies ()
504 Assembly corlib_test = Assembly.GetExecutingAssembly ();
505 AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
506 foreach (AssemblyName an in names) {
507 Assert.IsNull (an.CodeBase, "CodeBase");
508 Assert.IsNotNull (an.CultureInfo, "CultureInfo");
509 Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
510 Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
511 Assert.IsNotNull (an.FullName, "FullName");
512 Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
513 Assert.IsNull (an.KeyPair, "KeyPair");
514 Assert.IsNotNull (an.Name, "Name");
515 Assert.IsNotNull (an.Version, "Version");
516 Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
517 an.VersionCompatibility, "VersionCompatibility");
521 #if !MONOTOUCH && !FULL_AOT_RUNTIME // Reflection.Emit is not supported.
523 public void Location_Empty() {
524 string assemblyFileName = Path.Combine (
525 TempFolder, "AssemblyLocation.dll");
527 AssemblyName assemblyName = new AssemblyName ();
528 assemblyName.Name = "AssemblyLocation";
530 AssemblyBuilder ab = AppDomain.CurrentDomain
531 .DefineDynamicAssembly (assemblyName,
532 AssemblyBuilderAccess.Save,
534 AppDomain.CurrentDomain.Evidence);
535 ab.Save (Path.GetFileName (assemblyFileName));
537 using (FileStream fs = File.OpenRead (assemblyFileName)) {
538 byte[] buffer = new byte[fs.Length];
539 fs.Read (buffer, 0, buffer.Length);
540 Assembly assembly = Assembly.Load (buffer);
541 Assert.AreEqual (string.Empty, assembly.Location);
547 public void SateliteAssemblyForInMemoryAssembly ()
549 string assemblyFileName = Path.Combine (
550 TempFolder, "AssemblyLocation1.dll");
552 AssemblyName assemblyName = new AssemblyName ();
553 assemblyName.Name = "AssemblyLocation1";
555 AssemblyBuilder ab = AppDomain.CurrentDomain
556 .DefineDynamicAssembly (assemblyName,
557 AssemblyBuilderAccess.Save,
560 ModuleBuilder moduleBuilder = ab.DefineDynamicModule (assemblyName.Name, assemblyName.Name + ".dll");
561 TypeBuilder typeBuilder = moduleBuilder.DefineType ("Program", TypeAttributes.Public);
563 MethodBuilder methodBuilder = typeBuilder.DefineMethod ("TestCall", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
564 ILGenerator gen = methodBuilder.GetILGenerator ();
567 // var resourceManager = new ResourceManager (typeof (Program));
568 // resourceManager.GetString ("test");
570 gen.Emit (OpCodes.Ldtoken, typeBuilder);
571 gen.Emit (OpCodes.Call, typeof(Type).GetMethod ("GetTypeFromHandle"));
572 gen.Emit (OpCodes.Newobj, typeof(ResourceManager).GetConstructor (new Type[] { typeof(Type) }));
573 gen.Emit (OpCodes.Ldstr, "test");
574 gen.Emit (OpCodes.Callvirt, typeof(ResourceManager).GetMethod ("GetString", new Type[] { typeof(string) }));
575 gen.Emit (OpCodes.Pop);
576 gen.Emit (OpCodes.Ret);
578 typeBuilder.CreateType ();
580 ab.Save (Path.GetFileName (assemblyFileName));
582 using (FileStream fs = File.OpenRead (assemblyFileName)) {
583 byte[] buffer = new byte[fs.Length];
584 fs.Read (buffer, 0, buffer.Length);
585 Assembly assembly = Assembly.Load (buffer);
587 var mm = assembly.GetType ("Program").GetMethod ("TestCall");
589 mm.Invoke (null, null);
591 } catch (TargetInvocationException e) {
592 Assert.IsTrue (e.InnerException is MissingManifestResourceException);
600 [Category ("NotWorking")]
601 public void bug78464 ()
603 string assemblyFileName = Path.Combine (
604 TempFolder, "bug78464.dll");
606 // execute test in separate appdomain to allow assembly to be unloaded
607 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
608 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
610 crossDomainTester.bug78464 (assemblyFileName);
612 AppDomain.Unload (testDomain);
617 [Category("MobileNotWorking")]
618 public void bug78465 ()
620 string assemblyFileName = Path.Combine (
621 TempFolder, "bug78465.dll");
623 AssemblyName assemblyName = new AssemblyName ();
624 assemblyName.Name = "bug78465";
626 AssemblyBuilder ab = AppDomain.CurrentDomain
627 .DefineDynamicAssembly (assemblyName,
628 AssemblyBuilderAccess.Save,
629 Path.GetDirectoryName (assemblyFileName),
630 AppDomain.CurrentDomain.Evidence);
631 ab.Save (Path.GetFileName (assemblyFileName));
633 using (FileStream fs = File.OpenRead (assemblyFileName)) {
634 byte[] buffer = new byte[fs.Length];
635 fs.Read (buffer, 0, buffer.Length);
636 Assembly assembly = Assembly.Load (buffer);
637 Assert.AreEqual (string.Empty, assembly.Location, "#1");
641 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
642 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
644 crossDomainTester.bug78465 (assemblyFileName);
646 AppDomain.Unload (testDomain);
651 [Category("MobileNotWorking")]
652 public void bug78468 ()
654 string assemblyFileNameA = Path.Combine (TempFolder,
656 string resourceFileName = Path.Combine (TempFolder,
659 using (StreamWriter sw = File.CreateText (resourceFileName)) {
660 sw.WriteLine ("FOO");
664 AssemblyName assemblyName = new AssemblyName ();
665 assemblyName.Name = "bug78468a";
667 AssemblyBuilder ab = AppDomain.CurrentDomain
668 .DefineDynamicAssembly (assemblyName,
669 AssemblyBuilderAccess.Save,
671 AppDomain.CurrentDomain.Evidence);
672 ab.AddResourceFile ("read", "readme.txt");
673 ab.Save (Path.GetFileName (assemblyFileNameA));
677 using (FileStream fs = File.OpenRead (assemblyFileNameA)) {
678 byte[] buffer = new byte[fs.Length];
679 fs.Read (buffer, 0, buffer.Length);
680 assembly = Assembly.Load (buffer);
684 Assert.AreEqual (string.Empty, assembly.Location, "#A1");
685 string[] resNames = assembly.GetManifestResourceNames ();
686 Assert.IsNotNull (resNames, "#A2");
687 Assert.AreEqual (1, resNames.Length, "#A3");
688 Assert.AreEqual ("read", resNames[0], "#A4");
689 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
690 Assert.IsNotNull (resInfo, "#A5");
691 Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6");
692 Assert.IsNull (resInfo.ReferencedAssembly, "#A7");
693 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8");
695 assembly.GetManifestResourceStream ("read");
697 } catch (FileNotFoundException) {
700 assembly.GetFile ("readme.txt");
701 Assert.Fail ("#A10");
702 } catch (FileNotFoundException) {
705 string assemblyFileNameB = Path.Combine (TempFolder,
708 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
709 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
711 crossDomainTester.bug78468 (assemblyFileNameB);
713 AppDomain.Unload (testDomain);
718 [Category ("NotWorking")]
719 public void ReflectionOnlyLoad ()
721 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
723 Assert.IsNotNull (assembly);
724 Assert.IsTrue (assembly.ReflectionOnly);
728 [Category ("AndroidNotWorking")] // Xamarin.Android assemblies are bundled so they don't exist in the file system.
729 public void ReflectionOnlyLoadFrom ()
731 string loc = typeof (AssemblyTest).Assembly.Location;
732 string filename = Path.GetFileName (loc);
733 Assembly assembly = Assembly.ReflectionOnlyLoadFrom (loc);
735 Assert.IsNotNull (assembly);
736 Assert.IsTrue (assembly.ReflectionOnly);
740 [ExpectedException (typeof (ArgumentException))]
741 public void CreateInstanceOnRefOnly ()
743 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
744 assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
748 [Category ("NotWorking")] // patch for bug #79720 must be committed first
749 public void Load_Culture ()
751 string tempDir = TempFolder;
752 string cultureTempDir = Path.Combine (tempDir, "nl-BE");
753 if (!Directory.Exists (cultureTempDir))
754 Directory.CreateDirectory (cultureTempDir);
755 cultureTempDir = Path.Combine (tempDir, "en-US");
756 if (!Directory.Exists (cultureTempDir))
757 Directory.CreateDirectory (cultureTempDir);
760 AppDomain ad = CreateTestDomain (tempDir, true);
762 CrossDomainTester cdt = CreateCrossDomainTester (ad);
766 AssemblyName aname = new AssemblyName ();
767 aname.Name = "culturea";
768 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll"));
770 aname = new AssemblyName ();
771 aname.Name = "culturea";
772 Assert.IsTrue (cdt.AssertLoad(aname), "#A1");
774 aname = new AssemblyName ();
775 aname.Name = "culturea";
776 aname.CultureInfo = new CultureInfo ("nl-BE");
777 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2");
779 aname = new AssemblyName ();
780 aname.Name = "culturea";
781 aname.CultureInfo = CultureInfo.InvariantCulture;
782 Assert.IsTrue (cdt.AssertLoad(aname), "#A3");
786 aname = new AssemblyName ();
787 aname.Name = "cultureb";
788 aname.CultureInfo = new CultureInfo ("nl-BE");
789 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll"));
791 aname = new AssemblyName ();
792 aname.Name = "cultureb";
793 aname.CultureInfo = new CultureInfo ("nl-BE");
794 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
796 aname = new AssemblyName ();
797 aname.Name = "cultureb";
798 Assert.IsTrue (cdt.AssertLoad (aname), "#B2");
800 aname = new AssemblyName ();
801 aname.Name = "cultureb";
802 aname.CultureInfo = new CultureInfo ("en-US");
803 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3");
807 aname = new AssemblyName ();
808 aname.Name = "culturec";
809 aname.CultureInfo = new CultureInfo ("nl-BE");
810 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll"));
812 aname = new AssemblyName ();
813 aname.Name = "culturec";
814 aname.CultureInfo = new CultureInfo ("nl-BE");
815 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
817 aname = new AssemblyName ();
818 aname.Name = "culturec";
819 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2");
821 aname = new AssemblyName ();
822 aname.Name = "culturec";
823 aname.CultureInfo = CultureInfo.InvariantCulture;
824 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3");
828 aname = new AssemblyName ();
829 aname.Name = "cultured";
830 aname.CultureInfo = new CultureInfo ("nl-BE");
831 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll"));
833 aname = new AssemblyName ();
834 aname.Name = "cultured";
835 aname.CultureInfo = new CultureInfo ("nl-BE");
836 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1");
838 aname = new AssemblyName ();
839 aname.Name = "cultured";
840 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2");
842 aname = new AssemblyName ();
843 aname.Name = "cultured";
844 aname.CultureInfo = CultureInfo.InvariantCulture;
845 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3");
847 AppDomain.Unload (ad);
852 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException
853 public void Load_Culture_Mismatch ()
855 string tempDir = TempFolder;
856 string cultureTempDir = Path.Combine (tempDir, "en-US");
857 if (!Directory.Exists (cultureTempDir))
858 Directory.CreateDirectory (cultureTempDir);
860 AppDomain ad = CreateTestDomain (tempDir, true);
862 CrossDomainTester cdt = CreateCrossDomainTester (ad);
866 AssemblyName aname = new AssemblyName ();
867 aname.Name = "bug79712a";
868 aname.CultureInfo = new CultureInfo ("nl-BE");
869 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll"));
871 aname = new AssemblyName ();
872 aname.Name = "bug79712a";
873 aname.CultureInfo = CultureInfo.InvariantCulture;
874 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1");
878 aname = new AssemblyName ();
879 aname.Name = "bug79712b";
880 aname.CultureInfo = new CultureInfo ("nl-BE");
881 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll"));
883 aname = new AssemblyName ();
884 aname.Name = "bug79712b";
885 aname.CultureInfo = new CultureInfo ("en-US");
886 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
888 AppDomain.Unload (ad);
894 [Category("MobileNotWorking")]
895 public void Load_PartialVersion ()
897 string tempDir = TempFolder;
899 AppDomain ad = CreateTestDomain (tempDir, true);
901 CrossDomainTester cdt = CreateCrossDomainTester (ad);
903 AssemblyName aname = new AssemblyName ();
904 aname.Name = "bug79715";
905 aname.Version = new Version (1, 2, 3, 4);
906 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll"));
908 aname = new AssemblyName ();
909 aname.Name = "bug79715";
910 aname.Version = new Version (1, 2);
911 Assert.IsTrue (cdt.AssertLoad (aname), "#A1");
912 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2");
914 aname = new AssemblyName ();
915 aname.Name = "bug79715";
916 aname.Version = new Version (1, 2, 3);
917 Assert.IsTrue (cdt.AssertLoad (aname), "#B1");
918 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2");
920 aname = new AssemblyName ();
921 aname.Name = "bug79715";
922 aname.Version = new Version (1, 2, 3, 4);
923 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
924 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2");
926 AppDomain.Unload (ad);
930 private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
932 AppDomainSetup setup = new AppDomainSetup ();
933 setup.ApplicationBase = baseDirectory;
934 setup.ApplicationName = "testdomain";
936 AppDomain ad = AppDomain.CreateDomain ("testdomain",
937 AppDomain.CurrentDomain.Evidence, setup);
939 if (assemblyResolver) {
940 Assembly ea = Assembly.GetExecutingAssembly ();
941 ad.CreateInstanceFrom (ea.CodeBase,
942 typeof (AssemblyResolveHandler).FullName,
944 BindingFlags.Public | BindingFlags.Instance,
946 new object [] { ea.Location, ea.FullName },
947 CultureInfo.InvariantCulture,
955 private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
957 Type testerType = typeof (CrossDomainTester);
958 return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
959 testerType.Assembly.FullName, testerType.FullName, false,
960 BindingFlags.Public | BindingFlags.Instance, null, new object[0],
961 CultureInfo.InvariantCulture, new object[0], null);
964 private class CrossDomainTester : MarshalByRefObject
966 public void GenerateAssembly (AssemblyName aname, string path)
968 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
969 aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path));
970 ab.Save (Path.GetFileName (path));
973 public void Load (AssemblyName assemblyRef)
975 Assembly.Load (assemblyRef);
978 public void LoadFrom (string assemblyFile)
980 Assembly.LoadFrom (assemblyFile);
983 public bool AssertLoad (AssemblyName assemblyRef)
986 Assembly.Load (assemblyRef);
993 public bool AssertLoad (string assemblyString)
996 Assembly.Load (assemblyString);
1003 public bool AssertFileLoadException (AssemblyName assemblyRef)
1006 Assembly.Load (assemblyRef);
1008 } catch (FileLoadException) {
1013 public bool AssertFileNotFoundException (AssemblyName assemblyRef)
1016 Assembly.Load (assemblyRef);
1018 } catch (FileNotFoundException) {
1023 public void bug78464 (string assemblyFileName)
1025 AssemblyName assemblyName = new AssemblyName ();
1026 assemblyName.Name = "bug78464";
1028 AssemblyBuilder ab = AppDomain.CurrentDomain
1029 .DefineDynamicAssembly (assemblyName,
1030 AssemblyBuilderAccess.Save,
1031 Path.GetDirectoryName (assemblyFileName),
1032 AppDomain.CurrentDomain.Evidence);
1033 ab.Save (Path.GetFileName (assemblyFileName));
1037 using (FileStream fs = File.OpenRead (assemblyFileName)) {
1038 byte[] buffer = new byte[fs.Length];
1039 fs.Read (buffer, 0, buffer.Length);
1040 assembly = Assembly.Load (buffer);
1044 Assert.AreEqual (string.Empty, assembly.Location, "#1");
1046 assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1047 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1048 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3");
1049 // note: we cannot check if directory names match, as MS.NET seems to
1050 // convert directory part of assembly location to lowercase
1051 Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4");
1054 public void bug78465 (string assemblyFileName)
1056 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1057 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1058 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3");
1059 // note: we cannot check if directory names match, as MS.NET seems to
1060 // convert directory part of assembly location to lowercase
1061 Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4");
1064 public void bug78468 (string assemblyFileName)
1066 AssemblyName assemblyName = new AssemblyName ();
1067 assemblyName.Name = "bug78468b";
1069 AssemblyBuilder ab = AppDomain.CurrentDomain
1070 .DefineDynamicAssembly (assemblyName,
1071 AssemblyBuilderAccess.Save,
1072 Path.GetDirectoryName (assemblyFileName),
1073 AppDomain.CurrentDomain.Evidence);
1074 ab.AddResourceFile ("read", "readme.txt");
1075 ab.Save (Path.GetFileName (assemblyFileName));
1077 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1078 Assert.IsTrue (assembly.Location != string.Empty, "#B1");
1079 string[] resNames = assembly.GetManifestResourceNames ();
1080 Assert.IsNotNull (resNames, "#B2");
1081 Assert.AreEqual (1, resNames.Length, "#B3");
1082 Assert.AreEqual ("read", resNames[0], "#B4");
1083 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
1084 Assert.IsNotNull (resInfo, "#B5");
1085 Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6");
1086 Assert.IsNull (resInfo.ReferencedAssembly, "#B7");
1087 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8");
1088 Stream s = assembly.GetManifestResourceStream ("read");
1089 Assert.IsNotNull (s, "#B9");
1091 s = assembly.GetFile ("readme.txt");
1092 Assert.IsNotNull (s, "#B10");
1098 public void bug79872 ()
1100 string outdir = TempFolder;
1102 AssemblyName an = new AssemblyName ();
1103 an.Name = "bug79872";
1104 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir);
1105 string dllname = "bug79872.dll";
1106 ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname);
1107 string netmodule = "bug79872.netmodule";
1108 ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule);
1109 TypeBuilder a1 = mb2.DefineType ("A");
1115 Assembly.LoadFrom (Path.Combine (outdir, dllname));
1119 Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest");
1123 Assembly.LoadFrom (Path.Combine (outdir, netmodule));
1124 } catch (BadImageFormatException) {
1125 ok = true; // mono and .net 2.0 throw this
1126 } catch (FileLoadException) {
1127 ok = true; // .net 1.1 throws this
1131 Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest");
1136 public void ManifestModule ()
1138 Assembly assembly = typeof (int).Assembly;
1139 Module module = assembly.ManifestModule;
1140 Assert.IsNotNull (module, "#1");
1142 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
1144 #if !MONOTOUCH && !FULL_AOT_RUNTIME
1145 Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
1147 Assert.IsFalse (module.IsResource (), "#4");
1148 Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
1149 Assert.AreSame (module, assembly.GetModules () [0], "#6");
1150 Assert.AreSame (module, assembly.ManifestModule, "#7");
1155 private class AssemblyResolveHandler
1157 public AssemblyResolveHandler (string assemblyFile, string assemblyName)
1159 _assemblyFile = assemblyFile;
1160 _assemblyName = assemblyName;
1162 AppDomain.CurrentDomain.AssemblyResolve +=
1163 new ResolveEventHandler (ResolveAssembly);
1166 private Assembly ResolveAssembly (Object sender, ResolveEventArgs args)
1168 if (args.Name == _assemblyName)
1169 return Assembly.LoadFrom (_assemblyFile);
1174 private readonly string _assemblyFile;
1175 private readonly string _assemblyName;
1178 protected internal class Bug328812_NestedFamORAssem { };
1181 public void bug328812 ()
1183 Assembly corlib_test = Assembly.GetExecutingAssembly ();
1184 Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem"));
1185 // Just a sanity check, in case the above passed for some other reason
1186 Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem"));
1190 public void GetCustomAttributes_AttributeType_Null ()
1192 Assembly a = typeof (int).Assembly;
1194 a.GetCustomAttributes (null, false);
1196 } catch (ArgumentNullException ex) {
1197 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
1198 Assert.IsNull (ex.InnerException, "#3");
1199 Assert.IsNotNull (ex.Message, "#4");
1200 Assert.IsNotNull (ex.ParamName, "#5");
1201 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
1206 public void GetTypeWithEmptyStringShouldThrow ()
1209 typeof (string).Assembly.GetType ("");
1211 } catch (ArgumentException) {}
1214 class GetCallingAssemblyCallee {
1217 static void sideEffect () {
1221 // GetCallingAssembly may see an unpredictable
1222 // view of the stack if it's called in tail
1223 // position, or if its caller or the caller's
1224 // caller is inlined. So we put in a side
1225 // effect to get out of tail position, and we
1226 // tag the methods NoInlining to discourage
1228 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1229 public static Assembly Leaf () {
1230 var a = Assembly.GetCallingAssembly ();
1235 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1236 public static Assembly DirectCall () {
1242 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1243 public static Assembly InvokeCall () {
1244 var ty = typeof (GetCallingAssemblyCallee);
1245 var mi = ty.GetMethod("Leaf");
1246 var o = mi.Invoke(null, null);
1253 public void GetCallingAssembly_Direct() {
1254 var a = GetCallingAssemblyCallee.DirectCall ();
1255 Assert.IsNotNull (a);
1257 Assert.AreEqual (GetType().Assembly, a);
1261 public void GetCallingAssembly_SkipsReflection () {
1262 // check that the calling assembly is this
1263 // one, not mscorlib (aka, the reflection
1265 var a = GetCallingAssemblyCallee.InvokeCall ();
1266 Assert.IsNotNull (a);
1268 var invokeAssembly =
1269 typeof (MethodInfo).Assembly;
1270 Assert.AreNotEqual (invokeAssembly, a);
1272 Assert.AreEqual (GetType().Assembly, a);
1276 public void DefinedTypes_Equality ()
1278 var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1279 var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1281 Assert.AreSame (x1, x2, "#1");
1284 class MyAssembly : Assembly { }
1287 public void CustomAssemblyImplThrows ()
1289 var ma = new MyAssembly();
1292 Assert.Fail ("must throw");
1293 } catch (NotImplementedException){
1298 public class TestDefinedTypes