~nunit-core/nunitv2/2.5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************

using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Configuration;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using NUnit.Core;

namespace NUnit.Util
{
	/// <summary>
	/// The DomainManager class handles the creation and unloading
	/// of domains as needed and keeps track of all existing domains.
	/// </summary>
	public class DomainManager : IService
	{
        static Logger log = InternalTrace.GetLogger(typeof(DomainManager));

		#region Properties
		private static string shadowCopyPath;
		public static string ShadowCopyPath
		{
			get
			{
				if ( shadowCopyPath == null )
				{
                    shadowCopyPath = Services.UserSettings.GetSetting("Options.TestLoader.ShadowCopyPath", "");
                    if (shadowCopyPath == "")
                        shadowCopyPath = Path.Combine(Path.GetTempPath(), @"nunit20\ShadowCopyCache");
					else
						shadowCopyPath = Environment.ExpandEnvironmentVariables(shadowCopyPath);
				}

				return shadowCopyPath;
			}
		}
		#endregion

		#region Create and Unload Domains
		/// <summary>
		/// Construct an application domain for running a test package
		/// </summary>
		/// <param name="package">The TestPackage to be run</param>
		public AppDomain CreateDomain( TestPackage package )
		{
			AppDomainSetup setup = new AppDomainSetup();
			 
			//For paralell tests, we need to use distinct application name
        	setup.ApplicationName = "Tests" + "_" + Environment.TickCount;

            FileInfo testFile = package.FullName != null && package.FullName != string.Empty
                ? new FileInfo(package.FullName)
                : null;

            string appBase = package.BasePath;
            string configFile = package.ConfigurationFile;
            string binPath = package.PrivateBinPath;

            if (testFile != null)
            {
                if (appBase == null || appBase == string.Empty)
                    appBase = testFile.DirectoryName;

                if (configFile == null || configFile == string.Empty)
                    configFile = Services.ProjectService.CanLoadProject(testFile.Name)
                        ? Path.GetFileNameWithoutExtension(testFile.Name) + ".config"
                        : testFile.Name + ".config";
            }
            else if (appBase == null || appBase == string.Empty)
                appBase = GetCommonAppBase(package.Assemblies);

            setup.ApplicationBase = appBase;
            // TODO: Check whether Mono still needs full path to config file...
            setup.ConfigurationFile = appBase != null && configFile != null
                ? Path.Combine(appBase, configFile)
                : configFile;

            if (package.AutoBinPath)
				binPath = GetPrivateBinPath( appBase, package.Assemblies );

			setup.PrivateBinPath = binPath;

            if (package.GetSetting("ShadowCopyFiles", true))
            {
                setup.ShadowCopyFiles = "true";
                setup.ShadowCopyDirectories = appBase;
                setup.CachePath = GetCachePath();
            }
            else
                setup.ShadowCopyFiles = "false";

			string domainName = "test-domain-" + package.Name;
            // Setup the Evidence
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            if (evidence.Count == 0)
            {
                Zone zone = new Zone(SecurityZone.MyComputer);
                evidence.AddHost(zone);
                Assembly assembly = Assembly.GetExecutingAssembly();
                Url url = new Url(assembly.CodeBase);
                evidence.AddHost(url);
                Hash hash = new Hash(assembly);
                evidence.AddHost(hash);
            }

            log.Info("Creating AppDomain " + domainName);

			AppDomain runnerDomain;
			
			// TODO: Try to eliminate this test. Currently, running on
			// Linux with the permission set specified causes an
			// unexplained crash when unloading the domain.
#if NET_2_0
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
			{
            	PermissionSet permissionSet = new PermissionSet( PermissionState.Unrestricted );	
           		runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup, permissionSet, null);
			}
			else
#endif
            	runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);

			// HACK: Only pass down our AddinRegistry one level so that tests of NUnit
			// itself start without any addins defined.
			if ( !IsTestDomain( AppDomain.CurrentDomain ) )
				runnerDomain.SetData("AddinRegistry", Services.AddinRegistry);

            // Inject DomainInitializer into the remote domain - there are other
            // approaches, but this works for all CLR versions.
            DomainInitializer initializer = DomainInitializer.CreateInstance(runnerDomain);

            // HACK: Under nunit-console, direct use of the enum fails
            int traceLevel = IsTestDomain(AppDomain.CurrentDomain)
                ? (int)InternalTraceLevel.Off : (int)InternalTrace.Level;

            initializer.InitializeDomain(traceLevel);

			return runnerDomain;
		}

        public void Unload(AppDomain domain)
        {
            new DomainUnloader(domain).Unload();
        }

		#endregion

        #region Nested DomainUnloader Class
        class DomainUnloader
        {
            private Thread thread;
            private AppDomain domain;

            public DomainUnloader(AppDomain domain)
            {
                this.domain = domain;
            }

            public void Unload()
            {
                string domainName;
                try
                {
                    domainName = domain.FriendlyName;
                }
                catch (AppDomainUnloadedException)
                {
                    return;
                }

                log.Info("Unloading AppDomain " + domainName);

                thread = new Thread(new ThreadStart(UnloadOnThread));
                thread.Start();
                if (!thread.Join(30000))
                {
                    log.Error("Unable to unload AppDomain {0}, Unload thread timed out", domainName);
                    thread.Abort();
                }
            }

            private void UnloadOnThread()
            {
                bool shadowCopy = false;
                string cachePath = null;
                string domainName = "UNKNOWN";               

                try
                {
                    shadowCopy = domain.ShadowCopyFiles;
                    cachePath = domain.SetupInformation.CachePath;
                    domainName = domain.FriendlyName;

                    AppDomain.Unload(domain);
                }
                catch (Exception ex)
                {
                    // We assume that the tests did something bad and just leave
                    // the orphaned AppDomain "out there". 
                    // TODO: Something useful.
                    log.Error("Unable to unload AppDomain " + domainName, ex);
                }
                finally
                {
                    if (shadowCopy && cachePath != null)
                        DeleteCacheDir(new DirectoryInfo(cachePath));
                }
            }
        }
        #endregion

        #region Helper Methods
        /// <summary>
		/// Get the location for caching and delete any old cache info
		/// </summary>
		private string GetCachePath()
		{
            int processId = Process.GetCurrentProcess().Id;
            long ticks = DateTime.Now.Ticks;
			string cachePath = Path.Combine( ShadowCopyPath, processId.ToString() + "_" + ticks.ToString() ); 
				
			try 
			{
				DirectoryInfo dir = new DirectoryInfo(cachePath);		
				if(dir.Exists) dir.Delete(true);
			}
			catch( Exception ex)
			{
				throw new ApplicationException( 
					string.Format( "Invalid cache path: {0}",cachePath ),
					ex );
			}

			return cachePath;
		}

		/// <summary>
		/// Helper method to delete the cache dir. This method deals 
		/// with a bug that occurs when files are marked read-only
		/// and deletes each file separately in order to give better 
		/// exception information when problems occur.
		/// 
		/// TODO: This entire method is problematic. Should we be doing it?
		/// </summary>
		/// <param name="cacheDir"></param>
		private static void DeleteCacheDir( DirectoryInfo cacheDir )
		{
			//			Debug.WriteLine( "Modules:");
			//			foreach( ProcessModule module in Process.GetCurrentProcess().Modules )
			//				Debug.WriteLine( module.ModuleName );
			

			if(cacheDir.Exists)
			{
				foreach( DirectoryInfo dirInfo in cacheDir.GetDirectories() )
					DeleteCacheDir( dirInfo );

				foreach( FileInfo fileInfo in cacheDir.GetFiles() )
				{
					fileInfo.Attributes = FileAttributes.Normal;
					try 
					{
						fileInfo.Delete();
					}
					catch( Exception ex )
					{
						Debug.WriteLine( string.Format( 
							"Error deleting {0}, {1}", fileInfo.Name, ex.Message ) );
					}
				}

				cacheDir.Attributes = FileAttributes.Normal;

				try
				{
					cacheDir.Delete();
				}
				catch( Exception ex )
				{
					Debug.WriteLine( string.Format( 
						"Error deleting {0}, {1}", cacheDir.Name, ex.Message ) );
				}
			}
		}

		private bool IsTestDomain(AppDomain domain)
		{
			return domain.FriendlyName.StartsWith( "test-domain-" );
		}

        public static string GetCommonAppBase(IList assemblies)
        {
            string commonBase = null;

            foreach (string assembly in assemblies)
            {
                string dir = Path.GetFullPath(Path.GetDirectoryName(assembly));
                if (commonBase == null)
                    commonBase = dir;
                else while (!PathUtils.SamePathOrUnder(commonBase, dir) && commonBase != null)
                        commonBase = Path.GetDirectoryName(commonBase);
            }

            return commonBase;
        }

		public static string GetPrivateBinPath( string basePath, IList assemblies )
		{
			StringBuilder sb = new StringBuilder(200);
			ArrayList dirList = new ArrayList();

			foreach( string assembly in assemblies )
			{
				string dir = PathUtils.RelativePath(
                    Path.GetFullPath(basePath), 
                    Path.GetDirectoryName( Path.GetFullPath(assembly) ) );
				if ( dir != null && dir != "." && !dirList.Contains( dir ) )
				{
					dirList.Add( dir );
					if ( sb.Length > 0 )
						sb.Append( Path.PathSeparator );
					sb.Append( dir );
				}
			}

			return sb.Length == 0 ? null : sb.ToString();
		}

		public static void DeleteShadowCopyPath()
		{
			if ( Directory.Exists( ShadowCopyPath ) )
				Directory.Delete( ShadowCopyPath, true );
		}
		#endregion

		#region IService Members

		public void UnloadService()
		{
            // TODO:  Add DomainManager.UnloadService implementation
        }

		public void InitializeService()
		{
			// TODO:  Add DomainManager.InitializeService implementation
		}

		#endregion
	}
}