File: TestLoader.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (786 lines) | stat: -rw-r--r-- 19,073 bytes parent folder | download
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
// ****************************************************************
// Copyright 2002-2003, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org/?p=license&r=2.4
// ****************************************************************

namespace NUnit.Util
{
	using System;
	using System.IO;
	using System.Collections;
	using System.Threading;
	using System.Configuration;
	using NUnit.Core;
	using NUnit.Core.Filters;


	/// <summary>
	/// TestLoader handles interactions between a test runner and a 
	/// client program - typically the user interface - for the 
	/// purpose of loading, unloading and running tests.
	/// 
	/// It implemements the EventListener interface which is used by 
	/// the test runner and repackages those events, along with
	/// others as individual events that clients may subscribe to
	/// in collaboration with a TestEventDispatcher helper object.
	/// 
	/// TestLoader is quite handy for use with a gui client because
	/// of the large number of events it supports. However, it has
	/// no dependencies on ui components and can be used independently.
	/// </summary>
	public class TestLoader : MarshalByRefObject, NUnit.Core.EventListener, ITestLoader, IService
	{
		#region Instance Variables

		/// <summary>
		/// Our event dispatching helper object
		/// </summary>
		private TestEventDispatcher events;

		/// <summary>
		/// Use MuiltipleTestDomainRunner if true
		/// </summary>
		private bool multiDomain;

		/// <summary>
		/// Merge namespaces across multiple assemblies
		/// </summary>
		private bool mergeAssemblies;

		/// <summary>
		/// Generate suites for each level of namespace containing tests
		/// </summary>
		private bool autoNamespaceSuites;

		private bool shadowCopyFiles;

		/// <summary>
		/// Loads and executes tests. Non-null when
		/// we have loaded a test.
		/// </summary>
		private TestRunner testRunner = null;

		/// <summary>
		/// Our current test project, if we have one.
		/// </summary>
		private NUnitProject testProject = null;

		/// <summary>
		/// The currently loaded test, returned by the testrunner
		/// </summary>
		private ITest loadedTest = null;

		/// <summary>
		/// The test name that was specified when loading
		/// </summary>
		private string loadedTestName = null;

		/// <summary>
		/// The currently executing test
		/// </summary>
		private string currentTestName;

		/// <summary>
		/// Result of the last test run
		/// </summary>
		private TestResult testResult = null;

		/// <summary>
		/// The last exception received when trying to load, unload or run a test
		/// </summary>
		private Exception lastException = null;

		/// <summary>
		/// Watcher fires when the assembly changes
		/// </summary>
		private AssemblyWatcher watcher;

		/// <summary>
		/// Assembly changed during a test and
		/// needs to be reloaded later
		/// </summary>
		private bool reloadPending = false;

		/// <summary>
		/// Indicates whether to watch for changes
		/// and reload the tests when a change occurs.
		/// </summary>
		private bool reloadOnChange = false;

		/// <summary>
		/// Indicates whether to automatically rerun
		/// the tests when a change occurs.
		/// </summary>
		private bool rerunOnChange = false;

		/// <summary>
		/// The last filter used for a run - used to 
		/// rerun tests when a change occurs
		/// </summary>
		private ITestFilter lastFilter;

		/// <summary>
		/// Indicates whether to reload the tests
		/// before each run.
		/// </summary>
		private bool reloadOnRun = false;

		#endregion

		#region Constructors

		public TestLoader()
			: this( new TestEventDispatcher() ) { }

		public TestLoader(TestEventDispatcher eventDispatcher )
		{
			this.events = eventDispatcher;

			ISettings settings = Services.UserSettings;
			this.ReloadOnRun = settings.GetSetting( "Options.TestLoader.ReloadOnRun", true );
			this.ReloadOnChange = settings.GetSetting( "Options.TestLoader.ReloadOnChange", true );
			this.RerunOnChange = settings.GetSetting( "Options.TestLoader.RerunOnChange", false );
			this.MultiDomain = settings.GetSetting( "Options.TestLoader.MultiDomain", false );
			this.MergeAssemblies = settings.GetSetting( "Options.TestLoader.MergeAssemblies", false );
			this.AutoNamespaceSuites = settings.GetSetting( "Options.TestLoader.AutoNamespaceSuites", true );
			this.ShadowCopyFiles = settings.GetSetting( "Options.TestLoader.ShadowCopyFiles", true );

			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( OnUnhandledException );
		}

		#endregion

		#region Properties
		public bool IsProjectLoaded
		{
			get { return testProject != null; }
		}

		public bool IsTestLoaded
		{
			get { return loadedTest != null; }
		}

		public bool Running
		{
			get { return testRunner != null && testRunner.Running; }
		}

		public NUnitProject TestProject
		{
			get { return testProject; }
			set	{ OnProjectLoad( value ); }
		}

		public ITestEvents Events
		{
			get { return events; }
		}

		public string TestFileName
		{
			get { return testProject.ProjectPath; }
		}

		public TestResult TestResult
		{
			get { return testResult; }
		}

		public Exception LastException
		{
			get { return lastException; }
		}

		public bool ReloadOnChange
		{
			get { return reloadOnChange; }
			set { reloadOnChange = value; }
		}

		public bool RerunOnChange
		{
			get { return rerunOnChange; }
			set { rerunOnChange = value; }
		}

		public bool ReloadOnRun
		{
			get { return reloadOnRun; }
			set { reloadOnRun = value; }
		}

		public bool MultiDomain
		{
			get { return multiDomain; }
			set { multiDomain = value; }
		}

		public bool MergeAssemblies
		{
			get { return mergeAssemblies; }
			set { mergeAssemblies = value; }
		}

		public bool AutoNamespaceSuites
		{
			get { return autoNamespaceSuites; }
			set { autoNamespaceSuites = value; }
		}

		public bool ShadowCopyFiles
		{
			get { return shadowCopyFiles; }
			set { shadowCopyFiles = value; }
		}

		public IList AssemblyInfo
		{
			get { return testRunner == null ? null : testRunner.AssemblyInfo; }
		}

		public int TestCount
		{
			get { return loadedTest == null ? 0 : loadedTest.TestCount; }
		}
		#endregion

		#region EventListener Handlers

		void EventListener.RunStarted(string name, int testCount)
		{
			events.FireRunStarting( name, testCount );
		}

		void EventListener.RunFinished(NUnit.Core.TestResult testResult)
		{
			this.testResult = testResult;

			try
			{
				this.SaveLastResult( 
					Path.Combine( Path.GetDirectoryName( this.TestFileName ), "TestResult.xml" ) );
				events.FireRunFinished( testResult );
			}
			catch( Exception ex )
			{
				this.lastException = ex;
				events.FireRunFinished( ex );
			}
		}

		void EventListener.RunFinished(Exception exception)
		{
			this.lastException = exception;
			events.FireRunFinished( exception );
		}

		/// <summary>
		/// Trigger event when each test starts
		/// </summary>
		/// <param name="testCase">TestCase that is starting</param>
		void EventListener.TestStarted(TestName testName)
		{
			this.currentTestName = testName.FullName;
			events.FireTestStarting( testName );
		}

		/// <summary>
		/// Trigger event when each test finishes
		/// </summary>
		/// <param name="result">Result of the case that finished</param>
		void EventListener.TestFinished(TestCaseResult result)
		{
			events.FireTestFinished( result );
		}

		/// <summary>
		/// Trigger event when each suite starts
		/// </summary>
		/// <param name="suite">Suite that is starting</param>
		void EventListener.SuiteStarted(TestName suiteName)
		{
			events.FireSuiteStarting( suiteName );
		}

		/// <summary>
		/// Trigger event when each suite finishes
		/// </summary>
		/// <param name="result">Result of the suite that finished</param>
		void EventListener.SuiteFinished(TestSuiteResult result)
		{
			events.FireSuiteFinished( result );
		}

		/// <summary>
		/// Trigger event when an unhandled exception (other than ThreadAbordException) occurs during a test
		/// </summary>
		/// <param name="exception">The unhandled exception</param>
		void EventListener.UnhandledException(Exception exception)
		{
			events.FireTestException( this.currentTestName, exception );
		}

		void OnUnhandledException( object sender, UnhandledExceptionEventArgs args )
		{
			switch( args.ExceptionObject.GetType().FullName )
			{
				case "System.Threading.ThreadAbortException":
					break;
				case "NUnit.Framework.AssertionException":
				default:
					events.FireTestException( this.currentTestName, (Exception)args.ExceptionObject );
					break;
			}
		}

		/// <summary>
		/// Trigger event when output occurs during a test
		/// </summary>
		/// <param name="testOutput">The test output</param>
		void EventListener.TestOutput(TestOutput testOutput)
		{
			events.FireTestOutput( testOutput );
		}

		#endregion

		#region Methods for Loading and Unloading Projects
		
		/// <summary>
		/// Create a new project with default naming
		/// </summary>
		public void NewProject()
		{
			try
			{
				events.FireProjectLoading( "New Project" );

				OnProjectLoad( NUnitProject.NewProject() );
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireProjectLoadFailed( "New Project", exception );
			}
		}

		/// <summary>
		/// Create a new project using a given path
		/// </summary>
		public void NewProject( string filePath )
		{
			try
			{
				events.FireProjectLoading( filePath );

				NUnitProject project = new NUnitProject( filePath );

				project.Configs.Add( "Debug" );
				project.Configs.Add( "Release" );			
				project.IsDirty = false;

				OnProjectLoad( project );
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireProjectLoadFailed( filePath, exception );
			}
		}

		/// <summary>
		/// Load a new project, optionally selecting the config and fire events
		/// </summary>
		public void LoadProject( string filePath, string configName )
		{
			try
			{
				events.FireProjectLoading( filePath );

				NUnitProject newProject = NUnitProject.LoadProject( filePath );
				if ( configName != null ) 
				{
					newProject.SetActiveConfig( configName );
					newProject.IsDirty = false;
				}

				OnProjectLoad( newProject );
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireProjectLoadFailed( filePath, exception );
			}
		}

		/// <summary>
		/// Load a new project using the default config and fire events
		/// </summary>
		public void LoadProject( string filePath )
		{
			LoadProject( filePath, null );
		}

		/// <summary>
		/// Load a project from a list of assemblies and fire events
		/// </summary>
		public void LoadProject( string[] assemblies )
		{
			try
			{
				events.FireProjectLoading( "New Project" );

				NUnitProject newProject = NUnitProject.FromAssemblies( assemblies );

				OnProjectLoad( newProject );
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireProjectLoadFailed( "New Project", exception );
			}
		}

		/// <summary>
		/// Unload the current project and fire events
		/// </summary>
		public void UnloadProject()
		{
			string testFileName = TestFileName;

			try
			{
				events.FireProjectUnloading( testFileName );

				if ( IsTestLoaded )
					UnloadTest();

				testProject.Changed -= new ProjectEventHandler( OnProjectChanged );
				testProject = null;

				events.FireProjectUnloaded( testFileName );
			}
			catch (Exception exception )
			{
				lastException = exception;
				events.FireProjectUnloadFailed( testFileName, exception );
			}

		}

		/// <summary>
		/// Common operations done each time a project is loaded
		/// </summary>
		/// <param name="testProject">The newly loaded project</param>
		private void OnProjectLoad( NUnitProject testProject )
		{
			if ( IsProjectLoaded )
				UnloadProject();

			this.testProject = testProject;
			testProject.Changed += new ProjectEventHandler( OnProjectChanged );

			events.FireProjectLoaded( TestFileName );
		}

		private void OnProjectChanged( object sender, ProjectEventArgs e )
		{
			switch ( e.type )
			{
				case ProjectChangeType.ActiveConfig:
				case ProjectChangeType.Other:
					if( TestProject.IsLoadable )
						TryToLoadOrReloadTest();
					break;

				case ProjectChangeType.AddConfig:
				case ProjectChangeType.UpdateConfig:
					if ( e.configName == TestProject.ActiveConfigName && TestProject.IsLoadable )
						TryToLoadOrReloadTest();
					break;

				case ProjectChangeType.RemoveConfig:
					if ( IsTestLoaded && TestProject.Configs.Count == 0 )
						UnloadTest();
					break;

				default:
					break;
			}
		}

		private void TryToLoadOrReloadTest()
		{
			if ( IsTestLoaded ) 
				ReloadTest();
			else 
				LoadTest();
		}

		#endregion

		#region Methods for Loading and Unloading Tests

		public void LoadTest()
		{
			LoadTest( null );
		}
		
		public void LoadTest( string testName )
		{
            long startTime = DateTime.Now.Ticks;

			try
			{
				events.FireTestLoading( TestFileName );

				testRunner = CreateRunner();

				bool loaded = testRunner.Load( MakeTestPackage( testName ) );

				loadedTest = testRunner.Test;
				loadedTestName = testName;
				testResult = null;
				reloadPending = false;
			
				if ( ReloadOnChange )
					InstallWatcher( );

				if ( loaded )
					events.FireTestLoaded( TestFileName, loadedTest );
				else
				{
					lastException = new ApplicationException( string.Format ( "Unable to find test {0} in assembly", testName ) );
					events.FireTestLoadFailed( TestFileName, lastException );
				}
			}
			catch( FileNotFoundException exception )
			{
				lastException = exception;

				foreach( string assembly in TestProject.ActiveConfig.Assemblies )
				{
					if ( Path.GetFileNameWithoutExtension( assembly ) == exception.FileName &&
						!PathUtils.SamePathOrUnder( testProject.ActiveConfig.BasePath, assembly ) )
					{
						lastException = new ApplicationException( string.Format( "Unable to load {0} because it is not located under the AppBase", exception.FileName ), exception );
						break;
					}
				}

				events.FireTestLoadFailed( TestFileName, lastException );
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireTestLoadFailed( TestFileName, exception );
			}

            double loadTime = (double)(DateTime.Now.Ticks - startTime) / (double)TimeSpan.TicksPerSecond;
            System.Diagnostics.Trace.WriteLine(string.Format("TestLoader: Loaded in {0} seconds", loadTime)); 
		}

		/// <summary>
		/// Unload the current test suite and fire the Unloaded event
		/// </summary>
		public void UnloadTest( )
		{
			if( IsTestLoaded )
			{
				// Hold the name for notifications after unload
				string fileName = TestFileName;

				try
				{
					events.FireTestUnloading( fileName );

					RemoveWatcher();

					testRunner.Unload();

					testRunner = null;

					loadedTest = null;
					loadedTestName = null;
					testResult = null;
					reloadPending = false;

					events.FireTestUnloaded( fileName );
				}
				catch( Exception exception )
				{
					lastException = exception;
					events.FireTestUnloadFailed( fileName, exception );
				}
			}
		}

		/// <summary>
		/// Reload the current test on command
		/// </summary>
		public void ReloadTest()
		{
			try
			{
				events.FireTestReloading( TestFileName );

				testRunner.Load( MakeTestPackage( loadedTestName ) );

				loadedTest = testRunner.Test;
				reloadPending = false;

				events.FireTestReloaded( TestFileName, loadedTest );				
			}
			catch( Exception exception )
			{
				lastException = exception;
				events.FireTestReloadFailed( TestFileName, exception );
			}
		}

		/// <summary>
		/// Handle watcher event that signals when the loaded assembly
		/// file has changed. Make sure it's a real change before
		/// firing the SuiteChangedEvent. Since this all happens
		/// asynchronously, we use an event to let ui components
		/// know that the failure happened.
		/// </summary>
		public void OnTestChanged( string testFileName )
		{
			if ( Running )
				reloadPending = true;
			else
			{
				ReloadTest();

				if ( rerunOnChange && lastFilter != null )
					testRunner.BeginRun( this, lastFilter );
			}
		}
		#endregion

		#region Methods for Running Tests
		/// <summary>
		/// Run all the tests
		/// </summary>
		public void RunTests()
		{
			RunTests( TestFilter.Empty );
		}

		/// <summary>
		/// Run selected tests using a filter
		/// </summary>
		/// <param name="filter">The filter to be used</param>
		public void RunTests( ITestFilter filter )
		{
			if ( !Running )
			{
				if ( reloadPending || ReloadOnRun )
					ReloadTest();

				this.lastFilter = filter;
				testRunner.BeginRun( this, filter );
			}
		}

		/// <summary>
		/// Cancel the currently running test.
		/// Fail silently if there is none to
		/// allow for latency in the UI.
		/// </summary>
		public void CancelTestRun()
		{
			if ( Running )
				testRunner.CancelRun();
		}

		public IList GetCategories() 
		{
			CategoryManager categoryManager = new CategoryManager();
			categoryManager.AddAllCategories( this.loadedTest );
			ArrayList list = new ArrayList( categoryManager.Categories );
			list.Sort();
			return list;
		}
		#endregion

		public void SaveLastResult( string fileName )
		{
			XmlResultVisitor resultVisitor 
				= new XmlResultVisitor( fileName, this.testResult );
			this.testResult.Accept(resultVisitor);
			resultVisitor.Write();
		}

		#region Helper Methods

		/// <summary>
		/// Install our watcher object so as to get notifications
		/// about changes to a test.
		/// </summary>
		private void InstallWatcher()
		{
			if(watcher!=null) watcher.Stop();

			watcher = new AssemblyWatcher( 1000, TestProject.ActiveConfig.Assemblies.ToArray() );
			watcher.AssemblyChangedEvent += new AssemblyWatcher.AssemblyChangedHandler( OnTestChanged );
			watcher.Start();
		}

		/// <summary>
		/// Stop and remove our current watcher object.
		/// </summary>
		private void RemoveWatcher()
		{
			if ( watcher != null )
			{
				watcher.Stop();
				watcher = null;
			}
		}

		private TestRunner CreateRunner()
		{
			TestRunner runner = multiDomain
				? (TestRunner)new MultipleTestDomainRunner()
				: (TestRunner)new TestDomain();
				
			return runner;
		}

		private TestPackage MakeTestPackage( string testName )
		{
			TestPackage package = TestProject.ActiveConfig.MakeTestPackage();
			package.TestName = testName;
			package.Settings["MergeAssemblies"] = mergeAssemblies;
			package.Settings["AutoNamespaceSuites"] = autoNamespaceSuites;
			package.Settings["ShadowCopyFiles"] = shadowCopyFiles;
			return package;
		}
		#endregion

		#region InitializeLifetimeService Override
		public override object InitializeLifetimeService()
		{
			return null;
		}
		#endregion

		#region IService Members

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

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

		#endregion
	}
}