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;
15 using System.Diagnostics;
16 using System.Collections.Generic;
17 using System.Globalization;
19 using System.Text.RegularExpressions;
20 using Mono.Unix.Native;
23 // This is a simple test runner with support for parallel execution
26 public class TestRunner
28 const string TEST_TIME_FORMAT = "mm\\:ss\\.fff";
29 const string ENV_TIMEOUT = "TEST_DRIVER_TIMEOUT_SEC";
33 public StringBuilder stdout, stderr;
34 public string stdoutName, stderrName;
38 public string test, opt_set;
41 public static int Main (String[] args) {
44 int timeout = 2 * 60; // in seconds
45 int expectedExitCode = 0;
46 string testsuiteName = null;
47 string inputFile = null;
49 // FIXME: Add support for runtime arguments + env variables
51 string disabled_tests = null;
52 string runtime = "mono";
54 var opt_sets = new List<string> ();
58 while (i < args.Length) {
59 if (args [i].StartsWith ("-")) {
60 if (args [i] == "-j") {
61 if (i + 1 >= args.Length) {
62 Console.WriteLine ("Missing argument to -j command line option.");
65 if (args [i + 1] == "a")
66 concurrency = Environment.ProcessorCount;
68 concurrency = Int32.Parse (args [i + 1]);
70 } else if (args [i] == "--timeout") {
71 if (i + 1 >= args.Length) {
72 Console.WriteLine ("Missing argument to --timeout command line option.");
75 timeout = Int32.Parse (args [i + 1]);
77 } else if (args [i] == "--disabled") {
78 if (i + 1 >= args.Length) {
79 Console.WriteLine ("Missing argument to --disabled command line option.");
82 disabled_tests = args [i + 1];
84 } else if (args [i] == "--runtime") {
85 if (i + 1 >= args.Length) {
86 Console.WriteLine ("Missing argument to --runtime command line option.");
89 runtime = args [i + 1];
91 } else if (args [i] == "--config") {
92 if (i + 1 >= args.Length) {
93 Console.WriteLine ("Missing argument to --config command line option.");
96 config = args [i + 1];
98 } else if (args [i] == "--opt-sets") {
99 if (i + 1 >= args.Length) {
100 Console.WriteLine ("Missing argument to --opt-sets command line option.");
103 foreach (var s in args [i + 1].Split ())
106 } else if (args [i] == "--expected-exit-code") {
107 if (i + 1 >= args.Length) {
108 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
111 expectedExitCode = Int32.Parse (args [i + 1]);
113 } else if (args [i] == "--testsuite-name") {
114 if (i + 1 >= args.Length) {
115 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
118 testsuiteName = args [i + 1];
120 } else if (args [i] == "--input-file") {
121 if (i + 1 >= args.Length) {
122 Console.WriteLine ("Missing argument to --input-file command line option.");
125 inputFile = args [i + 1];
128 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
136 if (String.IsNullOrEmpty (testsuiteName)) {
137 Console.WriteLine ("Missing the required --testsuite-name command line option.");
141 var disabled = new Dictionary <string, string> ();
143 if (disabled_tests != null) {
144 foreach (string test in disabled_tests.Split ())
145 disabled [test] = test;
148 var tests = new List<string> ();
150 if (!String.IsNullOrEmpty (inputFile)) {
151 tests.AddRange (File.ReadAllLines (inputFile));
153 // The remaining arguments are the tests
154 for (int j = i; j < args.Length; ++j)
155 if (!disabled.ContainsKey (args [j]))
156 tests.Add (args [j]);
159 var passed = new List<ProcessData> ();
160 var failed = new List<ProcessData> ();
161 var timedout = new List<ProcessData> ();
163 object monitor = new object ();
165 Console.WriteLine ("Running tests: ");
167 var test_info = new Queue<TestInfo> ();
168 if (opt_sets.Count == 0) {
169 foreach (string s in tests)
170 test_info.Enqueue (new TestInfo { test = s });
172 foreach (string opt in opt_sets) {
173 foreach (string s in tests)
174 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
178 /* compute the max length of test names, to have an optimal output width */
179 int output_width = -1;
180 foreach (TestInfo ti in test_info) {
181 if (ti.test.Length > output_width)
182 output_width = Math.Min (120, ti.test.Length);
185 List<Thread> threads = new List<Thread> (concurrency);
187 DateTime test_start_time = DateTime.UtcNow;
189 for (int j = 0; j < concurrency; ++j) {
190 Thread thread = new Thread (() => {
195 if (test_info.Count == 0)
197 ti = test_info.Dequeue ();
200 var output = new StringWriter ();
202 string test = ti.test;
203 string opt_set = ti.opt_set;
205 output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
207 /* Spawn a new process */
212 process_args = "-O=" + opt_set + " " + test;
213 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
214 info.UseShellExecute = false;
215 info.RedirectStandardOutput = true;
216 info.RedirectStandardError = true;
217 info.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
219 info.EnvironmentVariables["MONO_CONFIG"] = config;
220 Process p = new Process ();
223 ProcessData data = new ProcessData ();
226 string log_prefix = "";
228 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
230 data.stdoutName = test + log_prefix + ".stdout";
231 data.stdout = new StringBuilder ();
233 data.stderrName = test + log_prefix + ".stderr";
234 data.stderr = new StringBuilder ();
236 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
237 if (e.Data != null) {
238 data.stdout.AppendLine (e.Data);
242 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
243 if (e.Data != null) {
244 data.stderr.AppendLine (e.Data);
248 var start = DateTime.UtcNow;
252 p.BeginOutputReadLine ();
253 p.BeginErrorReadLine ();
255 if (!p.WaitForExit (timeout * 1000)) {
260 // Force the process to print a thread dump
262 Syscall.kill (p.Id, Signum.SIGQUIT);
267 output.Write ($"timed out ({timeout}s)");
273 } else if (p.ExitCode != expectedExitCode) {
274 var end = DateTime.UtcNow;
280 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
282 var end = DateTime.UtcNow;
288 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
294 Console.WriteLine (output.ToString ());
301 threads.Add (thread);
304 for (int j = 0; j < threads.Count; ++j)
307 TimeSpan test_time = DateTime.UtcNow - test_start_time;
309 int npassed = passed.Count;
310 int nfailed = failed.Count;
311 int ntimedout = timedout.Count;
313 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
314 xmlWriterSettings.NewLineOnAttributes = true;
315 xmlWriterSettings.Indent = true;
316 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
317 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
318 writer.WriteStartDocument ();
319 // <!--This file represents the results of running a test suite-->
320 writer.WriteComment ("This file represents the results of running a test suite");
321 // <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">
322 writer.WriteStartElement ("test-results");
323 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
324 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
325 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
326 writer.WriteAttributeString ("not-run", "0");
327 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
328 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
329 // <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" />
330 writer.WriteStartElement ("environment");
331 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
332 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
333 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
334 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
335 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
336 writer.WriteAttributeString ("machine-name", Environment.MachineName );
337 writer.WriteAttributeString ("user", Environment.UserName );
338 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
339 writer.WriteEndElement ();
340 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
341 writer.WriteStartElement ("culture-info");
342 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
343 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
344 writer.WriteEndElement ();
345 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
346 writer.WriteStartElement ("test-suite");
347 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
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","MonoTests");
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 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
362 writer.WriteStartElement ("test-suite");
363 writer.WriteAttributeString ("name", testsuiteName);
364 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
365 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
366 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
368 writer.WriteStartElement ("results");
369 // Dump all passing tests first
370 foreach (ProcessData pd in passed) {
371 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
372 writer.WriteStartElement ("test-case");
373 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
374 writer.WriteAttributeString ("executed", "True");
375 writer.WriteAttributeString ("success", "True");
376 writer.WriteAttributeString ("time", "0");
377 writer.WriteAttributeString ("asserts", "0");
378 writer.WriteEndElement ();
380 // Now dump all failing tests
381 foreach (ProcessData pd in failed) {
382 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
383 writer.WriteStartElement ("test-case");
384 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
385 writer.WriteAttributeString ("executed", "True");
386 writer.WriteAttributeString ("success", "False");
387 writer.WriteAttributeString ("time", "0");
388 writer.WriteAttributeString ("asserts", "1");
389 writer.WriteStartElement ("failure");
390 writer.WriteStartElement ("message");
391 writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
392 writer.WriteEndElement ();
393 writer.WriteStartElement ("stack-trace");
394 writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
395 writer.WriteEndElement ();
396 writer.WriteEndElement ();
397 writer.WriteEndElement ();
399 // Then dump all timing out tests
400 foreach (ProcessData pd in timedout) {
401 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
402 writer.WriteStartElement ("test-case");
403 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
404 writer.WriteAttributeString ("executed", "True");
405 writer.WriteAttributeString ("success", "False");
406 writer.WriteAttributeString ("time", "0");
407 writer.WriteAttributeString ("asserts", "1");
408 writer.WriteStartElement ("failure");
409 writer.WriteStartElement ("message");
410 writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
411 writer.WriteEndElement ();
412 writer.WriteStartElement ("stack-trace");
413 writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
414 writer.WriteEndElement ();
415 writer.WriteEndElement ();
416 writer.WriteEndElement ();
419 writer.WriteEndElement ();
421 writer.WriteEndElement ();
423 writer.WriteEndElement ();
425 writer.WriteEndElement ();
427 writer.WriteEndElement ();
429 writer.WriteEndElement ();
431 writer.WriteEndElement ();
432 writer.WriteEndDocument ();
435 Console.WriteLine ();
436 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
437 Console.WriteLine ();
438 Console.WriteLine ("{0,4} test(s) passed", npassed);
439 Console.WriteLine ("{0,4} test(s) failed", nfailed);
440 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
443 Console.WriteLine ();
444 Console.WriteLine ("Failed test(s):");
445 foreach (ProcessData pd in failed) {
446 Console.WriteLine ();
447 Console.WriteLine (pd.test);
448 DumpFile (pd.stdoutName, pd.stdout.ToString ());
449 DumpFile (pd.stderrName, pd.stderr.ToString ());
454 Console.WriteLine ();
455 Console.WriteLine ("Timed out test(s):");
456 foreach (ProcessData pd in timedout) {
457 Console.WriteLine ();
458 Console.WriteLine (pd.test);
459 DumpFile (pd.stdoutName, pd.stdout.ToString ());
460 DumpFile (pd.stderrName, pd.stderr.ToString ());
464 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
467 static void DumpFile (string filename, string text) {
468 Console.WriteLine ("=============== {0} ===============", filename);
469 Console.WriteLine (text);
470 Console.WriteLine ("=============== EOF ===============");
473 static string FilterInvalidXmlChars (string text) {
474 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
475 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
476 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");