1 #region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig
2 /************************************************************************************
4 ' Copyright © 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole
5 ' Copyright © 2000-2003 Philip A. Craig
7 ' This software is provided 'as-is', without any express or implied warranty. In no
8 ' event will the authors be held liable for any damages arising from the use of this
11 ' Permission is granted to anyone to use this software for any purpose, including
12 ' commercial applications, and to alter it and redistribute it freely, subject to the
13 ' following restrictions:
15 ' 1. The origin of this software must not be misrepresented; you must not claim that
16 ' you wrote the original software. If you use this software in a product, an
17 ' acknowledgment (see the following) in the product documentation is required.
19 ' Portions Copyright © 2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole
20 ' or Copyright © 2000-2003 Philip A. Craig
22 ' 2. Altered source versions must be plainly marked as such, and must not be
23 ' misrepresented as being the original software.
25 ' 3. This notice may not be removed or altered from any source distribution.
27 '***********************************************************************************/
30 namespace NUnit.Console
33 using System.Collections;
34 using System.Collections.Specialized;
36 using System.Reflection;
39 using System.Xml.XPath;
40 using System.Resources;
42 using System.Text.RegularExpressions;
43 using System.Diagnostics;
49 /// Summary description for ConsoleUi.
51 public class ConsoleUi
54 public static int Main(string[] args)
56 ConsoleOptions options = new ConsoleOptions(args);
68 Console.Error.WriteLine("fatal error: no inputs specified");
73 if(!options.Validate())
75 Console.Error.WriteLine("fatal error: invalid arguments");
82 ConsoleUi consoleUi = new ConsoleUi();
83 return consoleUi.Execute( options );
85 catch( FileNotFoundException ex )
87 Console.WriteLine( ex.Message );
90 catch( BadImageFormatException ex )
92 Console.WriteLine( ex.Message );
97 Console.WriteLine( "Unhandled Exception:\n{0}", ex.ToString() );
104 Console.Out.WriteLine("\nHit <enter> key to continue");
110 private static XmlTextReader GetTransformReader(ConsoleOptions parser)
112 XmlTextReader reader = null;
113 if(!parser.IsTransform)
115 Assembly assembly = Assembly.GetAssembly(typeof(XmlResultVisitor));
116 ResourceManager resourceManager = new ResourceManager("NUnit.Util.Transform",assembly);
117 string xmlData = (string)resourceManager.GetObject("Summary.xslt");
119 reader = new XmlTextReader(new StringReader(xmlData));
123 FileInfo xsltInfo = new FileInfo(parser.transform);
126 Console.Error.WriteLine("Transform file: {0} does not exist", xsltInfo.FullName);
131 reader = new XmlTextReader(xsltInfo.FullName);
138 private static void WriteCopyright()
140 Assembly executingAssembly = Assembly.GetExecutingAssembly();
141 System.Version version = executingAssembly.GetName().Version;
143 object[] objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
144 AssemblyProductAttribute productAttr = (AssemblyProductAttribute)objectAttrs[0];
146 objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
147 AssemblyCopyrightAttribute copyrightAttr = (AssemblyCopyrightAttribute)objectAttrs[0];
149 Console.WriteLine(String.Format("{0} version {1}", productAttr.Product, version.ToString(3)));
150 Console.WriteLine(copyrightAttr.Copyright);
153 string clrPlatform = Type.GetType("Mono.Runtime", false) == null ? ".NET" : "Mono";
154 Console.WriteLine( string.Format("OS Version: {0} {1} Version: {2}",
155 Environment.OSVersion, clrPlatform, Environment.Version ) );
159 private static Test MakeTestFromCommandLine(TestDomain testDomain, ConsoleOptions parser)
161 NUnitProject project;
163 if ( parser.IsTestProject )
165 project = NUnitProject.LoadProject( (string)parser.Parameters[0] );
166 string configName = (string) parser.config;
167 if ( configName != null )
168 project.SetActiveConfig( configName );
171 project = NUnitProject.FromAssemblies( (string[])parser.Parameters.ToArray( typeof( string ) ) );
173 return testDomain.Load( project, parser.fixture );
180 public int Execute( ConsoleOptions options )
182 XmlTextReader transformReader = GetTransformReader(options);
183 if(transformReader == null) return 3;
185 ConsoleWriter outStream = options.isOut
186 ? new ConsoleWriter( new StreamWriter( options.output ) )
187 : new ConsoleWriter(Console.Out);
189 ConsoleWriter errorStream = options.isErr
190 ? new ConsoleWriter( new StreamWriter( options.err ) )
191 : new ConsoleWriter(Console.Error);
193 TestDomain testDomain = new TestDomain(outStream, errorStream);
194 if ( options.noshadow ) testDomain.ShadowCopyFiles = false;
196 Test test = MakeTestFromCommandLine(testDomain, options);
200 Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture);
204 Directory.SetCurrentDirectory(new FileInfo((string)options.Parameters[0]).DirectoryName);
206 EventCollector collector = new EventCollector( options, outStream );
208 string savedDirectory = Environment.CurrentDirectory;
210 if (options.HasInclude)
212 Console.WriteLine( "Included categories: " + options.include );
213 testDomain.SetFilter( new CategoryFilter( options.IncludedCategories ) );
215 else if ( options.HasExclude )
217 Console.WriteLine( "Excluded categories: " + options.exclude );
218 testDomain.SetFilter( new CategoryFilter( options.ExcludedCategories, true ) );
221 TestResult result = null;
222 if ( options.thread )
224 testDomain.RunTest( collector );
226 result = testDomain.Result;
230 result = testDomain.Run( collector );
233 Directory.SetCurrentDirectory( savedDirectory );
237 collector.PrintSummary( result );
240 string xmlOutput = CreateXmlOutput( result );
242 if (options.xmlConsole)
243 Console.WriteLine(xmlOutput);
245 CreateSummaryDocument(xmlOutput, transformReader, outStream);
247 // Write xml output here
248 string xmlResultFile = options.IsXml ? options.xml : "TestResult.xml";
250 using ( StreamWriter writer = new StreamWriter( xmlResultFile ) )
252 writer.Write(xmlOutput);
255 if ( testDomain != null )
258 return result.IsFailure ? 1 : 0;
261 private string CreateXmlOutput( TestResult result )
263 StringBuilder builder = new StringBuilder();
264 XmlResultVisitor resultVisitor = new XmlResultVisitor(new StringWriter( builder ), result);
265 result.Accept(resultVisitor);
266 resultVisitor.Write();
268 return builder.ToString();
271 private void CreateSummaryDocument(string xmlOutput, XmlTextReader transformReader,
272 ConsoleWriter outStream)
274 XPathDocument originalXPathDocument = new XPathDocument(new StringReader(xmlOutput));
275 XslTransform summaryXslTransform = new XslTransform();
277 // Using obsolete form for now, remove warning suppression from project after changing
278 summaryXslTransform.Load(transformReader);
280 // Using obsolete form for now, remove warning suppression from project after changing
281 summaryXslTransform.Transform(originalXPathDocument,null,outStream);
284 #region Nested Class to Handle Events
286 private class EventCollector : LongLivingMarshalByRefObject, EventListener
288 private int testRunCount;
289 private int testIgnoreCount;
290 private int failureCount;
293 private ConsoleOptions options;
294 private ConsoleWriter writer;
296 StringCollection messages;
298 private bool debugger = false;
299 private string currentTestName;
301 public EventCollector( ConsoleOptions options, ConsoleWriter writer )
303 debugger = Debugger.IsAttached;
305 this.options = options;
306 this.writer = writer;
307 this.currentTestName = string.Empty;
310 public void RunStarted(Test[] tests)
314 public void RunFinished(TestResult[] results)
318 public void RunFinished(Exception exception)
322 public void TestFinished(TestCaseResult testResult)
324 if ( !options.xmlConsole && !options.labels )
326 if(testResult.Executed)
330 if(testResult.IsFailure)
336 messages.Add( string.Format( "{0}) {1} :", failureCount, testResult.Test.FullName ) );
337 messages.Add( testResult.Message.Trim( Environment.NewLine.ToCharArray() ) );
339 string stackTrace = StackTraceFilter.Filter( testResult.StackTrace );
340 string[] trace = stackTrace.Split( System.Environment.NewLine.ToCharArray() );
341 foreach( string s in trace )
343 if ( s != string.Empty )
345 string link = Regex.Replace( s.Trim(), @".* in (.*):line (.*)", "$1($2)");
346 messages.Add( string.Format( "at\n{0}", link ) );
359 currentTestName = string.Empty;
362 public void TestStarted(TestCase testCase)
364 currentTestName = testCase.FullName;
366 if ( options.labels )
367 writer.WriteLine("***** {0}", testCase.FullName );
368 else if ( !options.xmlConsole )
372 public void SuiteStarted(TestSuite suite)
374 if ( debugger && level++ == 0 )
376 messages = new StringCollection();
380 Trace.WriteLine( "################################ UNIT TESTS ################################" );
381 Trace.WriteLine( "Running tests in '" + suite.FullName + "'..." );
385 public void SuiteFinished(TestSuiteResult suiteResult)
387 if ( debugger && --level == 0)
389 Trace.WriteLine( "############################################################################" );
391 if (messages.Count == 0)
393 Trace.WriteLine( "############## S U C C E S S #################" );
397 Trace.WriteLine( "############## F A I L U R E S #################" );
399 foreach ( string s in messages )
405 Trace.WriteLine( "############################################################################" );
406 Trace.WriteLine( "Executed tests : " + testRunCount );
407 Trace.WriteLine( "Ignored tests : " + testIgnoreCount );
408 Trace.WriteLine( "Failed tests : " + failureCount );
409 Trace.WriteLine( "Total time : " + suiteResult.Time + " seconds" );
410 Trace.WriteLine( "############################################################################");
414 public void PrintSummary (TestResult suiteResult)
416 Console.WriteLine("Tests run: {0}, Failures: {1}, Not run: {2}, Time: {3} seconds",
417 testRunCount, failureCount, testIgnoreCount, suiteResult.Time);
420 public void UnhandledException( Exception exception )
422 string msg = string.Format( "##### Unhandled Exception while running {0}", currentTestName );
424 // If we do labels, we already have a newline
425 if ( !options.labels ) writer.WriteLine();
426 writer.WriteLine( msg );
427 writer.WriteLine( exception.ToString() );
431 Trace.WriteLine( msg );
432 Trace.WriteLine( exception.ToString() );