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";
53 var opt_sets = new List<string> ();
57 while (i < args.Length) {
58 if (args [i].StartsWith ("-")) {
59 if (args [i] == "-j") {
60 if (i + 1 >= args.Length) {
61 Console.WriteLine ("Missing argument to -j command line option.");
64 if (args [i + 1] == "a")
65 concurrency = Environment.ProcessorCount;
67 concurrency = Int32.Parse (args [i + 1]);
69 } else if (args [i] == "--timeout") {
70 if (i + 1 >= args.Length) {
71 Console.WriteLine ("Missing argument to --timeout command line option.");
74 timeout = Int32.Parse (args [i + 1]);
76 } else if (args [i] == "--disabled") {
77 if (i + 1 >= args.Length) {
78 Console.WriteLine ("Missing argument to --disabled command line option.");
81 disabled_tests = args [i + 1];
83 } else if (args [i] == "--runtime") {
84 if (i + 1 >= args.Length) {
85 Console.WriteLine ("Missing argument to --runtime command line option.");
88 runtime = args [i + 1];
90 } else if (args [i] == "--opt-sets") {
91 if (i + 1 >= args.Length) {
92 Console.WriteLine ("Missing argument to --opt-sets command line option.");
95 foreach (var s in args [i + 1].Split ())
98 } else if (args [i] == "--expected-exit-code") {
99 if (i + 1 >= args.Length) {
100 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
103 expectedExitCode = Int32.Parse (args [i + 1]);
105 } else if (args [i] == "--testsuite-name") {
106 if (i + 1 >= args.Length) {
107 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
110 testsuiteName = args [i + 1];
112 } else if (args [i] == "--input-file") {
113 if (i + 1 >= args.Length) {
114 Console.WriteLine ("Missing argument to --input-file command line option.");
117 inputFile = args [i + 1];
120 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
128 if (String.IsNullOrEmpty (testsuiteName)) {
129 Console.WriteLine ("Missing the required --testsuite-name command line option.");
133 var disabled = new Dictionary <string, string> ();
135 if (disabled_tests != null) {
136 foreach (string test in disabled_tests.Split ())
137 disabled [test] = test;
140 var tests = new List<string> ();
142 if (!String.IsNullOrEmpty (inputFile)) {
143 tests.AddRange (File.ReadAllLines (inputFile));
145 // The remaining arguments are the tests
146 for (int j = i; j < args.Length; ++j)
147 if (!disabled.ContainsKey (args [j]))
148 tests.Add (args [j]);
151 var passed = new List<ProcessData> ();
152 var failed = new List<ProcessData> ();
153 var timedout = new List<ProcessData> ();
155 object monitor = new object ();
157 Console.WriteLine ("Running tests: ");
159 var test_info = new Queue<TestInfo> ();
160 if (opt_sets.Count == 0) {
161 foreach (string s in tests)
162 test_info.Enqueue (new TestInfo { test = s });
164 foreach (string opt in opt_sets) {
165 foreach (string s in tests)
166 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
170 /* compute the max length of test names, to have an optimal output width */
171 int output_width = -1;
172 foreach (TestInfo ti in test_info) {
173 if (ti.test.Length > output_width)
174 output_width = Math.Min (120, ti.test.Length);
177 List<Thread> threads = new List<Thread> (concurrency);
179 DateTime test_start_time = DateTime.UtcNow;
181 for (int j = 0; j < concurrency; ++j) {
182 Thread thread = new Thread (() => {
187 if (test_info.Count == 0)
189 ti = test_info.Dequeue ();
192 var output = new StringWriter ();
194 string test = ti.test;
195 string opt_set = ti.opt_set;
197 output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
199 /* Spawn a new process */
204 process_args = "-O=" + opt_set + " " + test;
205 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
206 info.UseShellExecute = false;
207 info.RedirectStandardOutput = true;
208 info.RedirectStandardError = true;
209 info.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
210 Process p = new Process ();
213 ProcessData data = new ProcessData ();
216 string log_prefix = "";
218 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
220 data.stdoutName = test + log_prefix + ".stdout";
221 data.stdout = new StringBuilder ();
223 data.stderrName = test + log_prefix + ".stderr";
224 data.stderr = new StringBuilder ();
226 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
227 if (e.Data != null) {
228 data.stdout.AppendLine (e.Data);
232 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
233 if (e.Data != null) {
234 data.stderr.AppendLine (e.Data);
238 var start = DateTime.UtcNow;
242 p.BeginOutputReadLine ();
243 p.BeginErrorReadLine ();
245 if (!p.WaitForExit (timeout * 1000)) {
250 // Force the process to print a thread dump
252 Syscall.kill (p.Id, Signum.SIGQUIT);
257 output.Write ($"timed out ({timeout}s)");
263 } else if (p.ExitCode != expectedExitCode) {
264 var end = DateTime.UtcNow;
270 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
272 var end = DateTime.UtcNow;
278 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
284 Console.WriteLine (output.ToString ());
291 threads.Add (thread);
294 for (int j = 0; j < threads.Count; ++j)
297 TimeSpan test_time = DateTime.UtcNow - test_start_time;
299 int npassed = passed.Count;
300 int nfailed = failed.Count;
301 int ntimedout = timedout.Count;
303 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
304 xmlWriterSettings.NewLineOnAttributes = true;
305 xmlWriterSettings.Indent = true;
306 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
307 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
308 writer.WriteStartDocument ();
309 // <!--This file represents the results of running a test suite-->
310 writer.WriteComment ("This file represents the results of running a test suite");
311 // <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">
312 writer.WriteStartElement ("test-results");
313 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
314 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
315 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
316 writer.WriteAttributeString ("not-run", "0");
317 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
318 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
319 // <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" />
320 writer.WriteStartElement ("environment");
321 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
322 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
323 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
324 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
325 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
326 writer.WriteAttributeString ("machine-name", Environment.MachineName );
327 writer.WriteAttributeString ("user", Environment.UserName );
328 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
329 writer.WriteEndElement ();
330 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
331 writer.WriteStartElement ("culture-info");
332 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
333 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
334 writer.WriteEndElement ();
335 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
336 writer.WriteStartElement ("test-suite");
337 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
338 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
339 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
340 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
342 writer.WriteStartElement ("results");
343 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
344 writer.WriteStartElement ("test-suite");
345 writer.WriteAttributeString ("name","MonoTests");
346 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
347 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
348 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
350 writer.WriteStartElement ("results");
351 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
352 writer.WriteStartElement ("test-suite");
353 writer.WriteAttributeString ("name", testsuiteName);
354 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
355 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
356 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
358 writer.WriteStartElement ("results");
359 // Dump all passing tests first
360 foreach (ProcessData pd in passed) {
361 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
362 writer.WriteStartElement ("test-case");
363 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
364 writer.WriteAttributeString ("executed", "True");
365 writer.WriteAttributeString ("success", "True");
366 writer.WriteAttributeString ("time", "0");
367 writer.WriteAttributeString ("asserts", "0");
368 writer.WriteEndElement ();
370 // Now dump all failing tests
371 foreach (ProcessData pd in failed) {
372 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
373 writer.WriteStartElement ("test-case");
374 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
375 writer.WriteAttributeString ("executed", "True");
376 writer.WriteAttributeString ("success", "False");
377 writer.WriteAttributeString ("time", "0");
378 writer.WriteAttributeString ("asserts", "1");
379 writer.WriteStartElement ("failure");
380 writer.WriteStartElement ("message");
381 writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
382 writer.WriteEndElement ();
383 writer.WriteStartElement ("stack-trace");
384 writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
385 writer.WriteEndElement ();
386 writer.WriteEndElement ();
387 writer.WriteEndElement ();
389 // Then dump all timing out tests
390 foreach (ProcessData pd in timedout) {
391 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
392 writer.WriteStartElement ("test-case");
393 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
394 writer.WriteAttributeString ("executed", "True");
395 writer.WriteAttributeString ("success", "False");
396 writer.WriteAttributeString ("time", "0");
397 writer.WriteAttributeString ("asserts", "1");
398 writer.WriteStartElement ("failure");
399 writer.WriteStartElement ("message");
400 writer.WriteCData (FilterInvalidXmlChars (pd.stdout.ToString ()));
401 writer.WriteEndElement ();
402 writer.WriteStartElement ("stack-trace");
403 writer.WriteCData (FilterInvalidXmlChars (pd.stderr.ToString ()));
404 writer.WriteEndElement ();
405 writer.WriteEndElement ();
406 writer.WriteEndElement ();
409 writer.WriteEndElement ();
411 writer.WriteEndElement ();
413 writer.WriteEndElement ();
415 writer.WriteEndElement ();
417 writer.WriteEndElement ();
419 writer.WriteEndElement ();
421 writer.WriteEndElement ();
422 writer.WriteEndDocument ();
425 Console.WriteLine ();
426 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
427 Console.WriteLine ();
428 Console.WriteLine ("{0,4} test(s) passed", npassed);
429 Console.WriteLine ("{0,4} test(s) failed", nfailed);
430 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
433 Console.WriteLine ();
434 Console.WriteLine ("Failed test(s):");
435 foreach (ProcessData pd in failed) {
436 Console.WriteLine ();
437 Console.WriteLine (pd.test);
438 DumpFile (pd.stdoutName, pd.stdout.ToString ());
439 DumpFile (pd.stderrName, pd.stderr.ToString ());
444 Console.WriteLine ();
445 Console.WriteLine ("Timed out test(s):");
446 foreach (ProcessData pd in timedout) {
447 Console.WriteLine ();
448 Console.WriteLine (pd.test);
449 DumpFile (pd.stdoutName, pd.stdout.ToString ());
450 DumpFile (pd.stderrName, pd.stderr.ToString ());
454 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
457 static void DumpFile (string filename, string text) {
458 Console.WriteLine ("=============== {0} ===============", filename);
459 Console.WriteLine (text);
460 Console.WriteLine ("=============== EOF ===============");
463 static string FilterInvalidXmlChars (string text) {
464 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
465 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
466 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");