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");
268 } else if (p.ExitCode != expectedExitCode) {
269 var end = DateTime.UtcNow;
275 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
277 var end = DateTime.UtcNow;
283 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
289 Console.WriteLine (output.ToString ());
296 threads.Add (thread);
299 for (int j = 0; j < threads.Count; ++j)
302 TimeSpan test_time = DateTime.UtcNow - test_start_time;
304 int npassed = passed.Count;
305 int nfailed = failed.Count;
306 int ntimedout = timedout.Count;
308 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
309 xmlWriterSettings.NewLineOnAttributes = true;
310 xmlWriterSettings.Indent = true;
311 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
312 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
313 writer.WriteStartDocument ();
314 // <!--This file represents the results of running a test suite-->
315 writer.WriteComment ("This file represents the results of running a test suite");
316 // <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">
317 writer.WriteStartElement ("test-results");
318 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
319 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
320 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
321 writer.WriteAttributeString ("not-run", "0");
322 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
323 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
324 // <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" />
325 writer.WriteStartElement ("environment");
326 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
327 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
328 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
329 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
330 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
331 writer.WriteAttributeString ("machine-name", Environment.MachineName );
332 writer.WriteAttributeString ("user", Environment.UserName );
333 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
334 writer.WriteEndElement ();
335 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
336 writer.WriteStartElement ("culture-info");
337 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
338 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
339 writer.WriteEndElement ();
340 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
341 writer.WriteStartElement ("test-suite");
342 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
343 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
344 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
345 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
347 writer.WriteStartElement ("results");
348 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
349 writer.WriteStartElement ("test-suite");
350 writer.WriteAttributeString ("name","MonoTests");
351 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
352 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
353 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
355 writer.WriteStartElement ("results");
356 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
357 writer.WriteStartElement ("test-suite");
358 writer.WriteAttributeString ("name", testsuiteName);
359 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
360 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
361 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
363 writer.WriteStartElement ("results");
364 // Dump all passing tests first
365 foreach (ProcessData pd in passed) {
366 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
367 writer.WriteStartElement ("test-case");
368 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
369 writer.WriteAttributeString ("executed", "True");
370 writer.WriteAttributeString ("success", "True");
371 writer.WriteAttributeString ("time", "0");
372 writer.WriteAttributeString ("asserts", "0");
373 writer.WriteEndElement ();
375 // Now dump all failing tests
376 foreach (ProcessData pd in failed) {
377 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
378 writer.WriteStartElement ("test-case");
379 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
380 writer.WriteAttributeString ("executed", "True");
381 writer.WriteAttributeString ("success", "False");
382 writer.WriteAttributeString ("time", "0");
383 writer.WriteAttributeString ("asserts", "1");
384 writer.WriteStartElement ("failure");
385 writer.WriteStartElement ("message");
386 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
387 writer.WriteEndElement ();
388 writer.WriteStartElement ("stack-trace");
389 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
390 writer.WriteEndElement ();
391 writer.WriteEndElement ();
392 writer.WriteEndElement ();
394 // Then dump all timing out tests
395 foreach (ProcessData pd in timedout) {
396 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
397 writer.WriteStartElement ("test-case");
398 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
399 writer.WriteAttributeString ("executed", "True");
400 writer.WriteAttributeString ("success", "False");
401 writer.WriteAttributeString ("time", "0");
402 writer.WriteAttributeString ("asserts", "1");
403 writer.WriteStartElement ("failure");
404 writer.WriteStartElement ("message");
405 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
406 writer.WriteEndElement ();
407 writer.WriteStartElement ("stack-trace");
408 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
409 writer.WriteEndElement ();
410 writer.WriteEndElement ();
411 writer.WriteEndElement ();
414 writer.WriteEndElement ();
416 writer.WriteEndElement ();
418 writer.WriteEndElement ();
420 writer.WriteEndElement ();
422 writer.WriteEndElement ();
424 writer.WriteEndElement ();
426 writer.WriteEndElement ();
427 writer.WriteEndDocument ();
430 Console.WriteLine ();
431 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
432 Console.WriteLine ();
433 Console.WriteLine ("{0,4} test(s) passed", npassed);
434 Console.WriteLine ("{0,4} test(s) failed", nfailed);
435 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
438 Console.WriteLine ();
439 Console.WriteLine ("Failed test(s):");
440 foreach (ProcessData pd in failed) {
441 Console.WriteLine ();
442 Console.WriteLine (pd.test);
443 DumpFile (pd.stdoutFile);
444 DumpFile (pd.stderrFile);
449 Console.WriteLine ();
450 Console.WriteLine ("Timed out test(s):");
451 foreach (ProcessData pd in timedout) {
452 Console.WriteLine ();
453 Console.WriteLine (pd.test);
454 DumpFile (pd.stdoutFile);
455 DumpFile (pd.stderrFile);
459 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
462 static void DumpFile (string filename) {
463 if (File.Exists (filename)) {
464 Console.WriteLine ("=============== {0} ===============", filename);
465 Console.WriteLine (File.ReadAllText (filename));
466 Console.WriteLine ("=============== EOF ===============");
470 static string DumpPseudoTrace (string filename) {
471 if (File.Exists (filename))
472 return FilterInvalidXmlChars (File.ReadAllText (filename));
477 static string FilterInvalidXmlChars (string text) {
478 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
479 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
480 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");