5 // Zoltan Varga (vargaz@gmail.com)
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Threading;
31 using System.Diagnostics;
32 using System.Collections.Generic;
33 using System.Globalization;
35 using System.Text.RegularExpressions;
38 // This is a simple test runner with support for parallel execution
41 public class TestRunner
43 const string TEST_TIME_FORMAT = "mm\\:ss\\.fff";
47 public StreamWriter stdout, stderr;
48 public string stdoutFile, stderrFile;
52 public string test, opt_set;
55 public static int Main (String[] args) {
58 int timeout = 2 * 60; // in seconds
59 int expectedExitCode = 0;
60 string testsuiteName = null;
61 string inputFile = null;
63 // FIXME: Add support for runtime arguments + env variables
65 string disabled_tests = null;
66 string runtime = "mono";
67 var opt_sets = new List<string> ();
71 while (i < args.Length) {
72 if (args [i].StartsWith ("-")) {
73 if (args [i] == "-j") {
74 if (i + 1 >= args.Length) {
75 Console.WriteLine ("Missing argument to -j command line option.");
78 if (args [i + 1] == "a")
79 concurrency = Environment.ProcessorCount;
81 concurrency = Int32.Parse (args [i + 1]);
83 } else if (args [i] == "--timeout") {
84 if (i + 1 >= args.Length) {
85 Console.WriteLine ("Missing argument to --timeout command line option.");
88 timeout = Int32.Parse (args [i + 1]);
90 } else if (args [i] == "--disabled") {
91 if (i + 1 >= args.Length) {
92 Console.WriteLine ("Missing argument to --disabled command line option.");
95 disabled_tests = args [i + 1];
97 } else if (args [i] == "--runtime") {
98 if (i + 1 >= args.Length) {
99 Console.WriteLine ("Missing argument to --runtime command line option.");
102 runtime = args [i + 1];
104 } else if (args [i] == "--opt-sets") {
105 if (i + 1 >= args.Length) {
106 Console.WriteLine ("Missing argument to --opt-sets command line option.");
109 foreach (var s in args [i + 1].Split ())
112 } else if (args [i] == "--expected-exit-code") {
113 if (i + 1 >= args.Length) {
114 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
117 expectedExitCode = Int32.Parse (args [i + 1]);
119 } else if (args [i] == "--testsuite-name") {
120 if (i + 1 >= args.Length) {
121 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
124 testsuiteName = args [i + 1];
126 } else if (args [i] == "--input-file") {
127 if (i + 1 >= args.Length) {
128 Console.WriteLine ("Missing argument to --input-file command line option.");
131 inputFile = args [i + 1];
134 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
142 if (String.IsNullOrEmpty (testsuiteName)) {
143 Console.WriteLine ("Missing the required --testsuite-name command line option.");
147 var disabled = new Dictionary <string, string> ();
149 if (disabled_tests != null) {
150 foreach (string test in disabled_tests.Split ())
151 disabled [test] = test;
154 var tests = new List<string> ();
156 if (!String.IsNullOrEmpty (inputFile)) {
157 tests.AddRange (File.ReadAllLines (inputFile));
159 // The remaining arguments are the tests
160 for (int j = i; j < args.Length; ++j)
161 if (!disabled.ContainsKey (args [j]))
162 tests.Add (args [j]);
165 var passed = new List<ProcessData> ();
166 var failed = new List<ProcessData> ();
167 var timedout = new List<ProcessData> ();
169 object monitor = new object ();
171 Console.WriteLine ("Running tests: ");
173 var test_info = new Queue<TestInfo> ();
174 if (opt_sets.Count == 0) {
175 foreach (string s in tests)
176 test_info.Enqueue (new TestInfo { test = s });
178 foreach (string opt in opt_sets) {
179 foreach (string s in tests)
180 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
184 /* compute the max length of test names, to have an optimal output width */
185 int output_width = -1;
186 foreach (TestInfo ti in test_info) {
187 if (ti.test.Length > output_width)
188 output_width = Math.Min (120, ti.test.Length);
191 List<Thread> threads = new List<Thread> (concurrency);
193 DateTime test_start_time = DateTime.UtcNow;
195 for (int j = 0; j < concurrency; ++j) {
196 Thread thread = new Thread (() => {
201 if (test_info.Count == 0)
203 ti = test_info.Dequeue ();
206 var output = new StringWriter ();
208 string test = ti.test;
209 string opt_set = ti.opt_set;
211 output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
213 /* Spawn a new process */
218 process_args = "-O=" + opt_set + " " + test;
219 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
220 info.UseShellExecute = false;
221 info.RedirectStandardOutput = true;
222 info.RedirectStandardError = true;
223 Process p = new Process ();
226 ProcessData data = new ProcessData ();
229 string log_prefix = "";
231 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
233 data.stdoutFile = test + log_prefix + ".stdout";
234 data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
236 data.stderrFile = test + log_prefix + ".stderr";
237 data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
239 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
240 if (e.Data != null) {
241 data.stdout.WriteLine (e.Data);
243 data.stdout.Flush ();
244 data.stdout.Close ();
248 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
249 if (e.Data != null) {
250 data.stderr.WriteLine (e.Data);
252 data.stderr.Flush ();
253 data.stderr.Close ();
257 var start = DateTime.UtcNow;
261 p.BeginOutputReadLine ();
262 p.BeginErrorReadLine ();
264 if (!p.WaitForExit (timeout * 1000)) {
269 output.Write ("timed out");
272 } else if (p.ExitCode != expectedExitCode) {
273 var end = DateTime.UtcNow;
279 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
281 var end = DateTime.UtcNow;
287 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
293 Console.WriteLine (output.ToString ());
300 threads.Add (thread);
303 for (int j = 0; j < threads.Count; ++j)
306 TimeSpan test_time = DateTime.UtcNow - test_start_time;
308 int npassed = passed.Count;
309 int nfailed = failed.Count;
310 int ntimedout = timedout.Count;
312 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
313 xmlWriterSettings.NewLineOnAttributes = true;
314 xmlWriterSettings.Indent = true;
315 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
316 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
317 writer.WriteStartDocument ();
318 // <!--This file represents the results of running a test suite-->
319 writer.WriteComment ("This file represents the results of running a test suite");
320 // <test-results name="/home/charlie/Dev/NUnit/nunit-2.5/work/src/bin/Debug/tests/mock-assembly.dll" total="21" errors="1" failures="1" not-run="7" inconclusive="1" ignored="4" skipped="0" invalid="3" date="2010-10-18" time="13:23:35">
321 writer.WriteStartElement ("test-results");
322 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
323 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
324 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
325 writer.WriteAttributeString ("not-run", "0");
326 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
327 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
328 // <environment nunit-version="2.4.8.0" clr-version="4.0.30319.17020" os-version="Unix 3.13.0.45" platform="Unix" cwd="/home/directhex/Projects/mono/mcs/class/corlib" machine-name="marceline" user="directhex" user-domain="marceline" />
329 writer.WriteStartElement ("environment");
330 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
331 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
332 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
333 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
334 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
335 writer.WriteAttributeString ("machine-name", Environment.MachineName );
336 writer.WriteAttributeString ("user", Environment.UserName );
337 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
338 writer.WriteEndElement ();
339 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
340 writer.WriteStartElement ("culture-info");
341 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
342 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
343 writer.WriteEndElement ();
344 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
345 writer.WriteStartElement ("test-suite");
346 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
347 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
348 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
349 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
351 writer.WriteStartElement ("results");
352 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
353 writer.WriteStartElement ("test-suite");
354 writer.WriteAttributeString ("name","MonoTests");
355 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
356 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
357 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
359 writer.WriteStartElement ("results");
360 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
361 writer.WriteStartElement ("test-suite");
362 writer.WriteAttributeString ("name", testsuiteName);
363 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
364 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
365 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
367 writer.WriteStartElement ("results");
368 // Dump all passing tests first
369 foreach (ProcessData pd in passed) {
370 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
371 writer.WriteStartElement ("test-case");
372 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
373 writer.WriteAttributeString ("executed", "True");
374 writer.WriteAttributeString ("success", "True");
375 writer.WriteAttributeString ("time", "0");
376 writer.WriteAttributeString ("asserts", "0");
377 writer.WriteEndElement ();
379 // Now dump all failing tests
380 foreach (ProcessData pd in failed) {
381 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
382 writer.WriteStartElement ("test-case");
383 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
384 writer.WriteAttributeString ("executed", "True");
385 writer.WriteAttributeString ("success", "False");
386 writer.WriteAttributeString ("time", "0");
387 writer.WriteAttributeString ("asserts", "1");
388 writer.WriteStartElement ("failure");
389 writer.WriteStartElement ("message");
390 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
391 writer.WriteEndElement ();
392 writer.WriteStartElement ("stack-trace");
393 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
394 writer.WriteEndElement ();
395 writer.WriteEndElement ();
396 writer.WriteEndElement ();
398 // Then dump all timing out tests
399 foreach (ProcessData pd in timedout) {
400 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
401 writer.WriteStartElement ("test-case");
402 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
403 writer.WriteAttributeString ("executed", "True");
404 writer.WriteAttributeString ("success", "False");
405 writer.WriteAttributeString ("time", "0");
406 writer.WriteAttributeString ("asserts", "1");
407 writer.WriteStartElement ("failure");
408 writer.WriteStartElement ("message");
409 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
410 writer.WriteEndElement ();
411 writer.WriteStartElement ("stack-trace");
412 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
413 writer.WriteEndElement ();
414 writer.WriteEndElement ();
415 writer.WriteEndElement ();
418 writer.WriteEndElement ();
420 writer.WriteEndElement ();
422 writer.WriteEndElement ();
424 writer.WriteEndElement ();
426 writer.WriteEndElement ();
428 writer.WriteEndElement ();
430 writer.WriteEndElement ();
431 writer.WriteEndDocument ();
434 Console.WriteLine ();
435 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
436 Console.WriteLine ();
437 Console.WriteLine ("{0,4} test(s) passed", npassed);
438 Console.WriteLine ("{0,4} test(s) failed", nfailed);
439 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
442 Console.WriteLine ();
443 Console.WriteLine ("Failed test(s):");
444 foreach (ProcessData pd in failed) {
445 Console.WriteLine ();
446 Console.WriteLine (pd.test);
447 DumpFile (pd.stdoutFile);
448 DumpFile (pd.stderrFile);
453 Console.WriteLine ();
454 Console.WriteLine ("Timed out test(s):");
455 foreach (ProcessData pd in timedout) {
456 Console.WriteLine ();
457 Console.WriteLine (pd.test);
458 DumpFile (pd.stdoutFile);
459 DumpFile (pd.stderrFile);
463 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
466 static void DumpFile (string filename) {
467 if (File.Exists (filename)) {
468 Console.WriteLine ("=============== {0} ===============", filename);
469 Console.WriteLine (File.ReadAllText (filename));
470 Console.WriteLine ("=============== EOF ===============");
474 static string DumpPseudoTrace (string filename) {
475 if (File.Exists (filename))
476 return FilterInvalidXmlChars (File.ReadAllText (filename));
481 static string FilterInvalidXmlChars (string text) {
482 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
483 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
484 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");