5 // Zoltan Varga (vargaz@gmail.com)
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
9 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 using System.Threading;
14 using System.Diagnostics;
15 using System.Collections.Generic;
16 using System.Globalization;
18 using System.Text.RegularExpressions;
19 using Mono.Unix.Native;
22 // This is a simple test runner with support for parallel execution
25 public class TestRunner
27 const string TEST_TIME_FORMAT = "mm\\:ss\\.fff";
28 const string ENV_TIMEOUT = "TEST_DRIVER_TIMEOUT_SEC";
32 public StreamWriter stdout, stderr;
33 public string stdoutFile, stderrFile;
37 public string test, opt_set;
40 public static int Main (String[] args) {
43 int timeout = 2 * 60; // in seconds
44 int expectedExitCode = 0;
45 string testsuiteName = null;
46 string inputFile = null;
48 // FIXME: Add support for runtime arguments + env variables
50 string disabled_tests = null;
51 string runtime = "mono";
52 var opt_sets = new List<string> ();
56 while (i < args.Length) {
57 if (args [i].StartsWith ("-")) {
58 if (args [i] == "-j") {
59 if (i + 1 >= args.Length) {
60 Console.WriteLine ("Missing argument to -j command line option.");
63 if (args [i + 1] == "a")
64 concurrency = Environment.ProcessorCount;
66 concurrency = Int32.Parse (args [i + 1]);
68 } else if (args [i] == "--timeout") {
69 if (i + 1 >= args.Length) {
70 Console.WriteLine ("Missing argument to --timeout command line option.");
73 timeout = Int32.Parse (args [i + 1]);
75 } else if (args [i] == "--disabled") {
76 if (i + 1 >= args.Length) {
77 Console.WriteLine ("Missing argument to --disabled command line option.");
80 disabled_tests = args [i + 1];
82 } else if (args [i] == "--runtime") {
83 if (i + 1 >= args.Length) {
84 Console.WriteLine ("Missing argument to --runtime command line option.");
87 runtime = args [i + 1];
89 } else if (args [i] == "--opt-sets") {
90 if (i + 1 >= args.Length) {
91 Console.WriteLine ("Missing argument to --opt-sets command line option.");
94 foreach (var s in args [i + 1].Split ())
97 } else if (args [i] == "--expected-exit-code") {
98 if (i + 1 >= args.Length) {
99 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
102 expectedExitCode = Int32.Parse (args [i + 1]);
104 } else if (args [i] == "--testsuite-name") {
105 if (i + 1 >= args.Length) {
106 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
109 testsuiteName = args [i + 1];
111 } else if (args [i] == "--input-file") {
112 if (i + 1 >= args.Length) {
113 Console.WriteLine ("Missing argument to --input-file command line option.");
116 inputFile = args [i + 1];
119 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
127 if (String.IsNullOrEmpty (testsuiteName)) {
128 Console.WriteLine ("Missing the required --testsuite-name command line option.");
132 var disabled = new Dictionary <string, string> ();
134 if (disabled_tests != null) {
135 foreach (string test in disabled_tests.Split ())
136 disabled [test] = test;
139 var tests = new List<string> ();
141 if (!String.IsNullOrEmpty (inputFile)) {
142 tests.AddRange (File.ReadAllLines (inputFile));
144 // The remaining arguments are the tests
145 for (int j = i; j < args.Length; ++j)
146 if (!disabled.ContainsKey (args [j]))
147 tests.Add (args [j]);
150 var passed = new List<ProcessData> ();
151 var failed = new List<ProcessData> ();
152 var timedout = new List<ProcessData> ();
154 object monitor = new object ();
156 Console.WriteLine ("Running tests: ");
158 var test_info = new Queue<TestInfo> ();
159 if (opt_sets.Count == 0) {
160 foreach (string s in tests)
161 test_info.Enqueue (new TestInfo { test = s });
163 foreach (string opt in opt_sets) {
164 foreach (string s in tests)
165 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
169 /* compute the max length of test names, to have an optimal output width */
170 int output_width = -1;
171 foreach (TestInfo ti in test_info) {
172 if (ti.test.Length > output_width)
173 output_width = Math.Min (120, ti.test.Length);
176 List<Thread> threads = new List<Thread> (concurrency);
178 DateTime test_start_time = DateTime.UtcNow;
180 for (int j = 0; j < concurrency; ++j) {
181 Thread thread = new Thread (() => {
186 if (test_info.Count == 0)
188 ti = test_info.Dequeue ();
191 var output = new StringWriter ();
193 string test = ti.test;
194 string opt_set = ti.opt_set;
196 output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
198 /* Spawn a new process */
203 process_args = "-O=" + opt_set + " " + test;
204 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
205 info.UseShellExecute = false;
206 info.RedirectStandardOutput = true;
207 info.RedirectStandardError = true;
208 info.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
209 Process p = new Process ();
212 ProcessData data = new ProcessData ();
215 string log_prefix = "";
217 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
219 data.stdoutFile = test + log_prefix + ".stdout";
220 data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
222 data.stderrFile = test + log_prefix + ".stderr";
223 data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
225 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
226 if (e.Data != null) {
227 data.stdout.WriteLine (e.Data);
229 data.stdout.Flush ();
230 data.stdout.Close ();
234 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
235 if (e.Data != null) {
236 data.stderr.WriteLine (e.Data);
238 data.stderr.Flush ();
239 data.stderr.Close ();
243 var start = DateTime.UtcNow;
247 p.BeginOutputReadLine ();
248 p.BeginErrorReadLine ();
250 if (!p.WaitForExit (timeout * 1000)) {
255 // Force the process to print a thread dump
257 Syscall.kill (p.Id, Signum.SIGQUIT);
262 output.Write ("timed out");
265 } else if (p.ExitCode != expectedExitCode) {
266 var end = DateTime.UtcNow;
272 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
274 var end = DateTime.UtcNow;
280 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
286 Console.WriteLine (output.ToString ());
293 threads.Add (thread);
296 for (int j = 0; j < threads.Count; ++j)
299 TimeSpan test_time = DateTime.UtcNow - test_start_time;
301 int npassed = passed.Count;
302 int nfailed = failed.Count;
303 int ntimedout = timedout.Count;
305 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
306 xmlWriterSettings.NewLineOnAttributes = true;
307 xmlWriterSettings.Indent = true;
308 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
309 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
310 writer.WriteStartDocument ();
311 // <!--This file represents the results of running a test suite-->
312 writer.WriteComment ("This file represents the results of running a test suite");
313 // <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">
314 writer.WriteStartElement ("test-results");
315 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
316 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
317 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
318 writer.WriteAttributeString ("not-run", "0");
319 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
320 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
321 // <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" />
322 writer.WriteStartElement ("environment");
323 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
324 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
325 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
326 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
327 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
328 writer.WriteAttributeString ("machine-name", Environment.MachineName );
329 writer.WriteAttributeString ("user", Environment.UserName );
330 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
331 writer.WriteEndElement ();
332 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
333 writer.WriteStartElement ("culture-info");
334 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
335 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
336 writer.WriteEndElement ();
337 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
338 writer.WriteStartElement ("test-suite");
339 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
340 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
341 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
342 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
344 writer.WriteStartElement ("results");
345 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
346 writer.WriteStartElement ("test-suite");
347 writer.WriteAttributeString ("name","MonoTests");
348 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
349 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
350 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
352 writer.WriteStartElement ("results");
353 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
354 writer.WriteStartElement ("test-suite");
355 writer.WriteAttributeString ("name", testsuiteName);
356 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
357 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
358 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
360 writer.WriteStartElement ("results");
361 // Dump all passing tests first
362 foreach (ProcessData pd in passed) {
363 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
364 writer.WriteStartElement ("test-case");
365 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
366 writer.WriteAttributeString ("executed", "True");
367 writer.WriteAttributeString ("success", "True");
368 writer.WriteAttributeString ("time", "0");
369 writer.WriteAttributeString ("asserts", "0");
370 writer.WriteEndElement ();
372 // Now dump all failing tests
373 foreach (ProcessData pd in failed) {
374 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
375 writer.WriteStartElement ("test-case");
376 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
377 writer.WriteAttributeString ("executed", "True");
378 writer.WriteAttributeString ("success", "False");
379 writer.WriteAttributeString ("time", "0");
380 writer.WriteAttributeString ("asserts", "1");
381 writer.WriteStartElement ("failure");
382 writer.WriteStartElement ("message");
383 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
384 writer.WriteEndElement ();
385 writer.WriteStartElement ("stack-trace");
386 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
387 writer.WriteEndElement ();
388 writer.WriteEndElement ();
389 writer.WriteEndElement ();
391 // Then dump all timing out tests
392 foreach (ProcessData pd in timedout) {
393 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
394 writer.WriteStartElement ("test-case");
395 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
396 writer.WriteAttributeString ("executed", "True");
397 writer.WriteAttributeString ("success", "False");
398 writer.WriteAttributeString ("time", "0");
399 writer.WriteAttributeString ("asserts", "1");
400 writer.WriteStartElement ("failure");
401 writer.WriteStartElement ("message");
402 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
403 writer.WriteEndElement ();
404 writer.WriteStartElement ("stack-trace");
405 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
406 writer.WriteEndElement ();
407 writer.WriteEndElement ();
408 writer.WriteEndElement ();
411 writer.WriteEndElement ();
413 writer.WriteEndElement ();
415 writer.WriteEndElement ();
417 writer.WriteEndElement ();
419 writer.WriteEndElement ();
421 writer.WriteEndElement ();
423 writer.WriteEndElement ();
424 writer.WriteEndDocument ();
427 Console.WriteLine ();
428 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
429 Console.WriteLine ();
430 Console.WriteLine ("{0,4} test(s) passed", npassed);
431 Console.WriteLine ("{0,4} test(s) failed", nfailed);
432 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
435 Console.WriteLine ();
436 Console.WriteLine ("Failed test(s):");
437 foreach (ProcessData pd in failed) {
438 Console.WriteLine ();
439 Console.WriteLine (pd.test);
440 DumpFile (pd.stdoutFile);
441 DumpFile (pd.stderrFile);
446 Console.WriteLine ();
447 Console.WriteLine ("Timed out test(s):");
448 foreach (ProcessData pd in timedout) {
449 Console.WriteLine ();
450 Console.WriteLine (pd.test);
451 DumpFile (pd.stdoutFile);
452 DumpFile (pd.stderrFile);
456 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
459 static void DumpFile (string filename) {
460 if (File.Exists (filename)) {
461 Console.WriteLine ("=============== {0} ===============", filename);
462 Console.WriteLine (File.ReadAllText (filename));
463 Console.WriteLine ("=============== EOF ===============");
467 static string DumpPseudoTrace (string filename) {
468 if (File.Exists (filename))
469 return FilterInvalidXmlChars (File.ReadAllText (filename));
474 static string FilterInvalidXmlChars (string text) {
475 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
476 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
477 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");