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 [Category ("StaticLinkedAotNotWorking")] // Can't find .dll files when bundled in .exe
326 public void GetFiles_False ()
328 Assembly corlib = typeof (int).Assembly;
329 FileStream[] fss = corlib.GetFiles ();
330 Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)");
332 Assembly corlib_test = Assembly.GetExecutingAssembly ();
333 fss = corlib_test.GetFiles ();
334 Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)");
338 [Category ("AndroidNotWorking")] // Assemblies in Xamarin.Android cannot be accessed as FileStream
339 [Category ("StaticLinkedAotNotWorking")] // Can't find .dll files when bundled in .exe
340 public void GetFiles_True ()
342 Assembly corlib = typeof (int).Assembly;
343 FileStream[] fss = corlib.GetFiles ();
344 Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)");
346 Assembly corlib_test = Assembly.GetExecutingAssembly ();
347 fss = corlib_test.GetFiles ();
348 Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)");
352 public void GetManifestResourceStream_Name_Empty ()
354 Assembly corlib = typeof (int).Assembly;
357 corlib.GetManifestResourceStream (string.Empty);
359 } catch (ArgumentException ex) {
360 // String cannot have zero length
361 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2");
362 Assert.IsNull (ex.InnerException, "#A3");
363 Assert.IsNotNull (ex.Message, "#A4");
366 corlib.GetManifestResourceStream (typeof (int), string.Empty);
369 corlib.GetManifestResourceStream ((Type) null, string.Empty);
371 } catch (ArgumentException ex) {
372 // String cannot have zero length
373 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2");
374 Assert.IsNull (ex.InnerException, "#B3");
375 Assert.IsNotNull (ex.Message, "#B4");
380 public void GetManifestResourceStream_Name_Null ()
382 Assembly corlib = typeof (int).Assembly;
385 corlib.GetManifestResourceStream ((string) null);
387 } catch (ArgumentNullException ex) {
388 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
389 Assert.IsNull (ex.InnerException, "#A3");
390 Assert.IsNotNull (ex.Message, "#A4");
393 corlib.GetManifestResourceStream (typeof (int), (string) null);
396 corlib.GetManifestResourceStream ((Type) null, (string) null);
398 } catch (ArgumentNullException ex) {
399 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
400 Assert.IsNull (ex.InnerException, "#B3");
401 Assert.IsNotNull (ex.Message, "#B4");
402 Assert.IsNotNull (ex.ParamName, "#B5");
403 Assert.AreEqual ("type", ex.ParamName, "#B6");
408 public void IsDefined_AttributeType_Null ()
410 Assembly corlib = typeof (int).Assembly;
413 corlib.IsDefined ((Type) null, false);
415 } catch (ArgumentNullException ex) {
416 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
417 Assert.IsNull (ex.InnerException, "#3");
418 Assert.IsNotNull (ex.Message, "#4");
419 Assert.IsNotNull (ex.ParamName, "#5");
420 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
425 public void LoadFrom_Empty_Assembly ()
427 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
428 File.CreateText (tempFile).Close ();
431 Assembly.LoadFrom (tempFile);
433 } catch (BadImageFormatException ex) {
434 Assert.IsNull (ex.InnerException, "#2");
439 public void LoadFrom_Invalid_Assembly ()
441 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
442 using (StreamWriter sw = File.CreateText (tempFile)) {
443 sw.WriteLine ("foo");
448 Assembly.LoadFrom (tempFile);
450 } catch (BadImageFormatException ex) {
451 Assert.IsNull (ex.InnerException, "#2");
456 public void LoadFrom_NonExisting_Assembly ()
458 string tempFile = Path.Combine (TempFolder, Path.GetRandomFileName ());
461 Assembly.LoadFrom (tempFile);
463 } catch (FileNotFoundException ex) {
464 Assert.IsNull (ex.InnerException, "#2");
469 public void LoadWithPartialName ()
472 // So the problem here is that if we load an assembly
473 // in a fully aot mode and then cannot load the
474 // dylib, we will assert. This test is incompatible
475 // with the semantics of aot'ed assembly loading, as
476 // aot may assert when loading. This assumes that it's
477 // safe to greedly load everything.
478 var names = new string[] { Assembly.GetCallingAssembly ().GetName ().Name };
480 foreach (string s in names)
481 if (Assembly.LoadWithPartialName (s) != null)
483 Assert.Fail ("Was not able to load any corlib test");
487 public void GetObjectData_Info_Null ()
489 Assembly corlib = typeof (int).Assembly;
491 corlib.GetObjectData (null, new StreamingContext (
492 StreamingContextStates.All));
494 } catch (ArgumentNullException ex) {
495 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
496 Assert.IsNull (ex.InnerException, "#3");
497 Assert.IsNotNull (ex.Message, "#4");
498 Assert.IsNotNull (ex.ParamName, "#5");
499 Assert.AreEqual ("info", ex.ParamName, "#6");
504 public void GetReferencedAssemblies ()
506 Assembly corlib_test = Assembly.GetExecutingAssembly ();
507 AssemblyName[] names = corlib_test.GetReferencedAssemblies ();
508 foreach (AssemblyName an in names) {
509 Assert.IsNull (an.CodeBase, "CodeBase");
510 Assert.IsNotNull (an.CultureInfo, "CultureInfo");
511 Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase");
512 Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags");
513 Assert.IsNotNull (an.FullName, "FullName");
514 Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm");
515 Assert.IsNull (an.KeyPair, "KeyPair");
516 Assert.IsNotNull (an.Name, "Name");
517 Assert.IsNotNull (an.Version, "Version");
518 Assert.AreEqual (AssemblyVersionCompatibility.SameMachine,
519 an.VersionCompatibility, "VersionCompatibility");
523 #if !MONOTOUCH && !FULL_AOT_RUNTIME // Reflection.Emit is not supported.
525 public void Location_Empty() {
526 string assemblyFileName = Path.Combine (
527 TempFolder, "AssemblyLocation.dll");
529 AssemblyName assemblyName = new AssemblyName ();
530 assemblyName.Name = "AssemblyLocation";
532 AssemblyBuilder ab = AppDomain.CurrentDomain
533 .DefineDynamicAssembly (assemblyName,
534 AssemblyBuilderAccess.Save,
536 AppDomain.CurrentDomain.Evidence);
537 ab.Save (Path.GetFileName (assemblyFileName));
539 using (FileStream fs = File.OpenRead (assemblyFileName)) {
540 byte[] buffer = new byte[fs.Length];
541 fs.Read (buffer, 0, buffer.Length);
542 Assembly assembly = Assembly.Load (buffer);
543 Assert.AreEqual (string.Empty, assembly.Location);
549 public void SateliteAssemblyForInMemoryAssembly ()
551 string assemblyFileName = Path.Combine (
552 TempFolder, "AssemblyLocation1.dll");
554 AssemblyName assemblyName = new AssemblyName ();
555 assemblyName.Name = "AssemblyLocation1";
557 AssemblyBuilder ab = AppDomain.CurrentDomain
558 .DefineDynamicAssembly (assemblyName,
559 AssemblyBuilderAccess.Save,
562 ModuleBuilder moduleBuilder = ab.DefineDynamicModule (assemblyName.Name, assemblyName.Name + ".dll");
563 TypeBuilder typeBuilder = moduleBuilder.DefineType ("Program", TypeAttributes.Public);
565 MethodBuilder methodBuilder = typeBuilder.DefineMethod ("TestCall", MethodAttributes.Public | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
566 ILGenerator gen = methodBuilder.GetILGenerator ();
569 // var resourceManager = new ResourceManager (typeof (Program));
570 // resourceManager.GetString ("test");
572 gen.Emit (OpCodes.Ldtoken, typeBuilder);
573 gen.Emit (OpCodes.Call, typeof(Type).GetMethod ("GetTypeFromHandle"));
574 gen.Emit (OpCodes.Newobj, typeof(ResourceManager).GetConstructor (new Type[] { typeof(Type) }));
575 gen.Emit (OpCodes.Ldstr, "test");
576 gen.Emit (OpCodes.Callvirt, typeof(ResourceManager).GetMethod ("GetString", new Type[] { typeof(string) }));
577 gen.Emit (OpCodes.Pop);
578 gen.Emit (OpCodes.Ret);
580 typeBuilder.CreateType ();
582 ab.Save (Path.GetFileName (assemblyFileName));
584 using (FileStream fs = File.OpenRead (assemblyFileName)) {
585 byte[] buffer = new byte[fs.Length];
586 fs.Read (buffer, 0, buffer.Length);
587 Assembly assembly = Assembly.Load (buffer);
589 var mm = assembly.GetType ("Program").GetMethod ("TestCall");
591 mm.Invoke (null, null);
593 } catch (TargetInvocationException e) {
594 Assert.IsTrue (e.InnerException is MissingManifestResourceException);
602 [Category ("NotWorking")]
603 public void bug78464 ()
605 string assemblyFileName = Path.Combine (
606 TempFolder, "bug78464.dll");
608 // execute test in separate appdomain to allow assembly to be unloaded
609 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
610 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
612 crossDomainTester.bug78464 (assemblyFileName);
614 AppDomain.Unload (testDomain);
619 [Category("MobileNotWorking")]
620 public void bug78465 ()
622 string assemblyFileName = Path.Combine (
623 TempFolder, "bug78465.dll");
625 AssemblyName assemblyName = new AssemblyName ();
626 assemblyName.Name = "bug78465";
628 AssemblyBuilder ab = AppDomain.CurrentDomain
629 .DefineDynamicAssembly (assemblyName,
630 AssemblyBuilderAccess.Save,
631 Path.GetDirectoryName (assemblyFileName),
632 AppDomain.CurrentDomain.Evidence);
633 ab.Save (Path.GetFileName (assemblyFileName));
635 using (FileStream fs = File.OpenRead (assemblyFileName)) {
636 byte[] buffer = new byte[fs.Length];
637 fs.Read (buffer, 0, buffer.Length);
638 Assembly assembly = Assembly.Load (buffer);
639 Assert.AreEqual (string.Empty, assembly.Location, "#1");
643 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
644 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
646 crossDomainTester.bug78465 (assemblyFileName);
648 AppDomain.Unload (testDomain);
653 [Category("MobileNotWorking")]
654 public void bug78468 ()
656 string assemblyFileNameA = Path.Combine (TempFolder,
658 string resourceFileName = Path.Combine (TempFolder,
661 using (StreamWriter sw = File.CreateText (resourceFileName)) {
662 sw.WriteLine ("FOO");
666 AssemblyName assemblyName = new AssemblyName ();
667 assemblyName.Name = "bug78468a";
669 AssemblyBuilder ab = AppDomain.CurrentDomain
670 .DefineDynamicAssembly (assemblyName,
671 AssemblyBuilderAccess.Save,
673 AppDomain.CurrentDomain.Evidence);
674 ab.AddResourceFile ("read", "readme.txt");
675 ab.Save (Path.GetFileName (assemblyFileNameA));
679 using (FileStream fs = File.OpenRead (assemblyFileNameA)) {
680 byte[] buffer = new byte[fs.Length];
681 fs.Read (buffer, 0, buffer.Length);
682 assembly = Assembly.Load (buffer);
686 Assert.AreEqual (string.Empty, assembly.Location, "#A1");
687 string[] resNames = assembly.GetManifestResourceNames ();
688 Assert.IsNotNull (resNames, "#A2");
689 Assert.AreEqual (1, resNames.Length, "#A3");
690 Assert.AreEqual ("read", resNames[0], "#A4");
691 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
692 Assert.IsNotNull (resInfo, "#A5");
693 Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6");
694 Assert.IsNull (resInfo.ReferencedAssembly, "#A7");
695 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8");
697 assembly.GetManifestResourceStream ("read");
699 } catch (FileNotFoundException) {
702 assembly.GetFile ("readme.txt");
703 Assert.Fail ("#A10");
704 } catch (FileNotFoundException) {
707 string assemblyFileNameB = Path.Combine (TempFolder,
710 AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false);
711 CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain);
713 crossDomainTester.bug78468 (assemblyFileNameB);
715 AppDomain.Unload (testDomain);
720 [Category ("NotWorking")]
721 public void ReflectionOnlyLoad ()
723 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
725 Assert.IsNotNull (assembly);
726 Assert.IsTrue (assembly.ReflectionOnly);
730 [Category ("AndroidNotWorking")] // Xamarin.Android assemblies are bundled so they don't exist in the file system.
731 public void ReflectionOnlyLoadFrom ()
733 string loc = typeof (AssemblyTest).Assembly.Location;
734 string filename = Path.GetFileName (loc);
735 Assembly assembly = Assembly.ReflectionOnlyLoadFrom (loc);
737 Assert.IsNotNull (assembly);
738 Assert.IsTrue (assembly.ReflectionOnly);
742 [ExpectedException (typeof (ArgumentException))]
743 public void CreateInstanceOnRefOnly ()
745 Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName);
746 assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest");
750 [Category ("NotWorking")] // patch for bug #79720 must be committed first
751 public void Load_Culture ()
753 string tempDir = TempFolder;
754 string cultureTempDir = Path.Combine (tempDir, "nl-BE");
755 if (!Directory.Exists (cultureTempDir))
756 Directory.CreateDirectory (cultureTempDir);
757 cultureTempDir = Path.Combine (tempDir, "en-US");
758 if (!Directory.Exists (cultureTempDir))
759 Directory.CreateDirectory (cultureTempDir);
762 AppDomain ad = CreateTestDomain (tempDir, true);
764 CrossDomainTester cdt = CreateCrossDomainTester (ad);
768 AssemblyName aname = new AssemblyName ();
769 aname.Name = "culturea";
770 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll"));
772 aname = new AssemblyName ();
773 aname.Name = "culturea";
774 Assert.IsTrue (cdt.AssertLoad(aname), "#A1");
776 aname = new AssemblyName ();
777 aname.Name = "culturea";
778 aname.CultureInfo = new CultureInfo ("nl-BE");
779 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2");
781 aname = new AssemblyName ();
782 aname.Name = "culturea";
783 aname.CultureInfo = CultureInfo.InvariantCulture;
784 Assert.IsTrue (cdt.AssertLoad(aname), "#A3");
788 aname = new AssemblyName ();
789 aname.Name = "cultureb";
790 aname.CultureInfo = new CultureInfo ("nl-BE");
791 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll"));
793 aname = new AssemblyName ();
794 aname.Name = "cultureb";
795 aname.CultureInfo = new CultureInfo ("nl-BE");
796 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
798 aname = new AssemblyName ();
799 aname.Name = "cultureb";
800 Assert.IsTrue (cdt.AssertLoad (aname), "#B2");
802 aname = new AssemblyName ();
803 aname.Name = "cultureb";
804 aname.CultureInfo = new CultureInfo ("en-US");
805 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3");
809 aname = new AssemblyName ();
810 aname.Name = "culturec";
811 aname.CultureInfo = new CultureInfo ("nl-BE");
812 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll"));
814 aname = new AssemblyName ();
815 aname.Name = "culturec";
816 aname.CultureInfo = new CultureInfo ("nl-BE");
817 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
819 aname = new AssemblyName ();
820 aname.Name = "culturec";
821 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2");
823 aname = new AssemblyName ();
824 aname.Name = "culturec";
825 aname.CultureInfo = CultureInfo.InvariantCulture;
826 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3");
830 aname = new AssemblyName ();
831 aname.Name = "cultured";
832 aname.CultureInfo = new CultureInfo ("nl-BE");
833 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll"));
835 aname = new AssemblyName ();
836 aname.Name = "cultured";
837 aname.CultureInfo = new CultureInfo ("nl-BE");
838 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1");
840 aname = new AssemblyName ();
841 aname.Name = "cultured";
842 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2");
844 aname = new AssemblyName ();
845 aname.Name = "cultured";
846 aname.CultureInfo = CultureInfo.InvariantCulture;
847 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3");
849 AppDomain.Unload (ad);
854 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException
855 public void Load_Culture_Mismatch ()
857 string tempDir = TempFolder;
858 string cultureTempDir = Path.Combine (tempDir, "en-US");
859 if (!Directory.Exists (cultureTempDir))
860 Directory.CreateDirectory (cultureTempDir);
862 AppDomain ad = CreateTestDomain (tempDir, true);
864 CrossDomainTester cdt = CreateCrossDomainTester (ad);
868 AssemblyName aname = new AssemblyName ();
869 aname.Name = "bug79712a";
870 aname.CultureInfo = new CultureInfo ("nl-BE");
871 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll"));
873 aname = new AssemblyName ();
874 aname.Name = "bug79712a";
875 aname.CultureInfo = CultureInfo.InvariantCulture;
876 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1");
880 aname = new AssemblyName ();
881 aname.Name = "bug79712b";
882 aname.CultureInfo = new CultureInfo ("nl-BE");
883 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll"));
885 aname = new AssemblyName ();
886 aname.Name = "bug79712b";
887 aname.CultureInfo = new CultureInfo ("en-US");
888 Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1");
890 AppDomain.Unload (ad);
896 [Category("MobileNotWorking")]
897 public void Load_PartialVersion ()
899 string tempDir = TempFolder;
901 AppDomain ad = CreateTestDomain (tempDir, true);
903 CrossDomainTester cdt = CreateCrossDomainTester (ad);
905 AssemblyName aname = new AssemblyName ();
906 aname.Name = "bug79715";
907 aname.Version = new Version (1, 2, 3, 4);
908 cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll"));
910 aname = new AssemblyName ();
911 aname.Name = "bug79715";
912 aname.Version = new Version (1, 2);
913 Assert.IsTrue (cdt.AssertLoad (aname), "#A1");
914 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2");
916 aname = new AssemblyName ();
917 aname.Name = "bug79715";
918 aname.Version = new Version (1, 2, 3);
919 Assert.IsTrue (cdt.AssertLoad (aname), "#B1");
920 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2");
922 aname = new AssemblyName ();
923 aname.Name = "bug79715";
924 aname.Version = new Version (1, 2, 3, 4);
925 Assert.IsTrue (cdt.AssertLoad (aname), "#C1");
926 Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2");
928 AppDomain.Unload (ad);
932 private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver)
934 AppDomainSetup setup = new AppDomainSetup ();
935 setup.ApplicationBase = baseDirectory;
936 setup.ApplicationName = "testdomain";
938 AppDomain ad = AppDomain.CreateDomain ("testdomain",
939 AppDomain.CurrentDomain.Evidence, setup);
941 if (assemblyResolver) {
942 Assembly ea = Assembly.GetExecutingAssembly ();
943 ad.CreateInstanceFrom (ea.CodeBase,
944 typeof (AssemblyResolveHandler).FullName,
946 BindingFlags.Public | BindingFlags.Instance,
948 new object [] { ea.Location, ea.FullName },
949 CultureInfo.InvariantCulture,
957 private static CrossDomainTester CreateCrossDomainTester (AppDomain domain)
959 Type testerType = typeof (CrossDomainTester);
960 return (CrossDomainTester) domain.CreateInstanceAndUnwrap (
961 testerType.Assembly.FullName, testerType.FullName, false,
962 BindingFlags.Public | BindingFlags.Instance, null, new object[0],
963 CultureInfo.InvariantCulture, new object[0], null);
966 private class CrossDomainTester : MarshalByRefObject
968 public void GenerateAssembly (AssemblyName aname, string path)
970 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
971 aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path));
972 ab.Save (Path.GetFileName (path));
975 public void Load (AssemblyName assemblyRef)
977 Assembly.Load (assemblyRef);
980 public void LoadFrom (string assemblyFile)
982 Assembly.LoadFrom (assemblyFile);
985 public bool AssertLoad (AssemblyName assemblyRef)
988 Assembly.Load (assemblyRef);
995 public bool AssertLoad (string assemblyString)
998 Assembly.Load (assemblyString);
1005 public bool AssertFileLoadException (AssemblyName assemblyRef)
1008 Assembly.Load (assemblyRef);
1010 } catch (FileLoadException) {
1015 public bool AssertFileNotFoundException (AssemblyName assemblyRef)
1018 Assembly.Load (assemblyRef);
1020 } catch (FileNotFoundException) {
1025 public void bug78464 (string assemblyFileName)
1027 AssemblyName assemblyName = new AssemblyName ();
1028 assemblyName.Name = "bug78464";
1030 AssemblyBuilder ab = AppDomain.CurrentDomain
1031 .DefineDynamicAssembly (assemblyName,
1032 AssemblyBuilderAccess.Save,
1033 Path.GetDirectoryName (assemblyFileName),
1034 AppDomain.CurrentDomain.Evidence);
1035 ab.Save (Path.GetFileName (assemblyFileName));
1039 using (FileStream fs = File.OpenRead (assemblyFileName)) {
1040 byte[] buffer = new byte[fs.Length];
1041 fs.Read (buffer, 0, buffer.Length);
1042 assembly = Assembly.Load (buffer);
1046 Assert.AreEqual (string.Empty, assembly.Location, "#1");
1048 assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1049 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1050 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3");
1051 // note: we cannot check if directory names match, as MS.NET seems to
1052 // convert directory part of assembly location to lowercase
1053 Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4");
1056 public void bug78465 (string assemblyFileName)
1058 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1059 Assert.IsFalse (assembly.Location == string.Empty, "#2");
1060 Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3");
1061 // note: we cannot check if directory names match, as MS.NET seems to
1062 // convert directory part of assembly location to lowercase
1063 Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4");
1066 public void bug78468 (string assemblyFileName)
1068 AssemblyName assemblyName = new AssemblyName ();
1069 assemblyName.Name = "bug78468b";
1071 AssemblyBuilder ab = AppDomain.CurrentDomain
1072 .DefineDynamicAssembly (assemblyName,
1073 AssemblyBuilderAccess.Save,
1074 Path.GetDirectoryName (assemblyFileName),
1075 AppDomain.CurrentDomain.Evidence);
1076 ab.AddResourceFile ("read", "readme.txt");
1077 ab.Save (Path.GetFileName (assemblyFileName));
1079 Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence);
1080 Assert.IsTrue (assembly.Location != string.Empty, "#B1");
1081 string[] resNames = assembly.GetManifestResourceNames ();
1082 Assert.IsNotNull (resNames, "#B2");
1083 Assert.AreEqual (1, resNames.Length, "#B3");
1084 Assert.AreEqual ("read", resNames[0], "#B4");
1085 ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read");
1086 Assert.IsNotNull (resInfo, "#B5");
1087 Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6");
1088 Assert.IsNull (resInfo.ReferencedAssembly, "#B7");
1089 Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8");
1090 Stream s = assembly.GetManifestResourceStream ("read");
1091 Assert.IsNotNull (s, "#B9");
1093 s = assembly.GetFile ("readme.txt");
1094 Assert.IsNotNull (s, "#B10");
1100 public void bug79872 ()
1102 string outdir = TempFolder;
1104 AssemblyName an = new AssemblyName ();
1105 an.Name = "bug79872";
1106 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir);
1107 string dllname = "bug79872.dll";
1108 ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname);
1109 string netmodule = "bug79872.netmodule";
1110 ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule);
1111 TypeBuilder a1 = mb2.DefineType ("A");
1117 Assembly.LoadFrom (Path.Combine (outdir, dllname));
1121 Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest");
1125 Assembly.LoadFrom (Path.Combine (outdir, netmodule));
1126 } catch (BadImageFormatException) {
1127 ok = true; // mono and .net 2.0 throw this
1128 } catch (FileLoadException) {
1129 ok = true; // .net 1.1 throws this
1133 Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest");
1138 public void ManifestModule ()
1140 Assembly assembly = typeof (int).Assembly;
1141 Module module = assembly.ManifestModule;
1142 Assert.IsNotNull (module, "#1");
1144 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
1146 #if !MONOTOUCH && !FULL_AOT_RUNTIME
1147 Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
1149 Assert.IsFalse (module.IsResource (), "#4");
1150 Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
1151 Assert.AreSame (module, assembly.GetModules () [0], "#6");
1152 Assert.AreSame (module, assembly.ManifestModule, "#7");
1157 private class AssemblyResolveHandler
1159 public AssemblyResolveHandler (string assemblyFile, string assemblyName)
1161 _assemblyFile = assemblyFile;
1162 _assemblyName = assemblyName;
1164 AppDomain.CurrentDomain.AssemblyResolve +=
1165 new ResolveEventHandler (ResolveAssembly);
1168 private Assembly ResolveAssembly (Object sender, ResolveEventArgs args)
1170 if (args.Name == _assemblyName)
1171 return Assembly.LoadFrom (_assemblyFile);
1176 private readonly string _assemblyFile;
1177 private readonly string _assemblyName;
1180 protected internal class Bug328812_NestedFamORAssem { };
1183 public void bug328812 ()
1185 Assembly corlib_test = Assembly.GetExecutingAssembly ();
1186 Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem"));
1187 // Just a sanity check, in case the above passed for some other reason
1188 Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem"));
1192 public void GetCustomAttributes_AttributeType_Null ()
1194 Assembly a = typeof (int).Assembly;
1196 a.GetCustomAttributes (null, false);
1198 } catch (ArgumentNullException ex) {
1199 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
1200 Assert.IsNull (ex.InnerException, "#3");
1201 Assert.IsNotNull (ex.Message, "#4");
1202 Assert.IsNotNull (ex.ParamName, "#5");
1203 Assert.AreEqual ("attributeType", ex.ParamName, "#6");
1208 public void GetTypeWithEmptyStringShouldThrow ()
1211 typeof (string).Assembly.GetType ("");
1213 } catch (ArgumentException) {}
1216 class GetCallingAssemblyCallee {
1219 static void sideEffect () {
1223 // GetCallingAssembly may see an unpredictable
1224 // view of the stack if it's called in tail
1225 // position, or if its caller or the caller's
1226 // caller is inlined. So we put in a side
1227 // effect to get out of tail position, and we
1228 // tag the methods NoInlining to discourage
1230 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1231 public static Assembly Leaf () {
1232 var a = Assembly.GetCallingAssembly ();
1237 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1238 public static Assembly DirectCall () {
1244 [MethodImplAttribute (MethodImplOptions.NoInlining)]
1245 public static Assembly InvokeCall () {
1246 var ty = typeof (GetCallingAssemblyCallee);
1247 var mi = ty.GetMethod("Leaf");
1248 var o = mi.Invoke(null, null);
1255 public void GetCallingAssembly_Direct() {
1256 var a = GetCallingAssemblyCallee.DirectCall ();
1257 Assert.IsNotNull (a);
1259 Assert.AreEqual (GetType().Assembly, a);
1263 public void GetCallingAssembly_SkipsReflection () {
1264 // check that the calling assembly is this
1265 // one, not mscorlib (aka, the reflection
1267 var a = GetCallingAssemblyCallee.InvokeCall ();
1268 Assert.IsNotNull (a);
1270 var invokeAssembly =
1271 typeof (MethodInfo).Assembly;
1272 Assert.AreNotEqual (invokeAssembly, a);
1274 Assert.AreEqual (GetType().Assembly, a);
1278 public void DefinedTypes_Equality ()
1280 var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1281 var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single ();
1283 Assert.AreSame (x1, x2, "#1");
1286 class MyAssembly : Assembly { }
1289 public void CustomAssemblyImplThrows ()
1291 var ma = new MyAssembly();
1294 Assert.Fail ("must throw");
1295 } catch (NotImplementedException){
1300 public class TestDefinedTypes