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";
44 const string ENV_TIMEOUT = "TEST_DRIVER_TIMEOUT_SEC";
48 public StreamWriter stdout, stderr;
49 public string stdoutFile, stderrFile;
53 public string test, opt_set;
56 public static int Main (String[] args) {
59 int timeout = 2 * 60; // in seconds
60 int expectedExitCode = 0;
61 string testsuiteName = null;
62 string inputFile = null;
64 // FIXME: Add support for runtime arguments + env variables
66 string disabled_tests = null;
67 string runtime = "mono";
68 var opt_sets = new List<string> ();
72 while (i < args.Length) {
73 if (args [i].StartsWith ("-")) {
74 if (args [i] == "-j") {
75 if (i + 1 >= args.Length) {
76 Console.WriteLine ("Missing argument to -j command line option.");
79 if (args [i + 1] == "a")
80 concurrency = Environment.ProcessorCount;
82 concurrency = Int32.Parse (args [i + 1]);
84 } else if (args [i] == "--timeout") {
85 if (i + 1 >= args.Length) {
86 Console.WriteLine ("Missing argument to --timeout command line option.");
89 timeout = Int32.Parse (args [i + 1]);
91 } else if (args [i] == "--disabled") {
92 if (i + 1 >= args.Length) {
93 Console.WriteLine ("Missing argument to --disabled command line option.");
96 disabled_tests = args [i + 1];
98 } else if (args [i] == "--runtime") {
99 if (i + 1 >= args.Length) {
100 Console.WriteLine ("Missing argument to --runtime command line option.");
103 runtime = args [i + 1];
105 } else if (args [i] == "--opt-sets") {
106 if (i + 1 >= args.Length) {
107 Console.WriteLine ("Missing argument to --opt-sets command line option.");
110 foreach (var s in args [i + 1].Split ())
113 } else if (args [i] == "--expected-exit-code") {
114 if (i + 1 >= args.Length) {
115 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
118 expectedExitCode = Int32.Parse (args [i + 1]);
120 } else if (args [i] == "--testsuite-name") {
121 if (i + 1 >= args.Length) {
122 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
125 testsuiteName = args [i + 1];
127 } else if (args [i] == "--input-file") {
128 if (i + 1 >= args.Length) {
129 Console.WriteLine ("Missing argument to --input-file command line option.");
132 inputFile = args [i + 1];
135 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
143 if (String.IsNullOrEmpty (testsuiteName)) {
144 Console.WriteLine ("Missing the required --testsuite-name command line option.");
148 var disabled = new Dictionary <string, string> ();
150 if (disabled_tests != null) {
151 foreach (string test in disabled_tests.Split ())
152 disabled [test] = test;
155 var tests = new List<string> ();
157 if (!String.IsNullOrEmpty (inputFile)) {
158 tests.AddRange (File.ReadAllLines (inputFile));
160 // The remaining arguments are the tests
161 for (int j = i; j < args.Length; ++j)
162 if (!disabled.ContainsKey (args [j]))
163 tests.Add (args [j]);
166 var passed = new List<ProcessData> ();
167 var failed = new List<ProcessData> ();
168 var timedout = new List<ProcessData> ();
170 object monitor = new object ();
172 Console.WriteLine ("Running tests: ");
174 var test_info = new Queue<TestInfo> ();
175 if (opt_sets.Count == 0) {
176 foreach (string s in tests)
177 test_info.Enqueue (new TestInfo { test = s });
179 foreach (string opt in opt_sets) {
180 foreach (string s in tests)
181 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
185 /* compute the max length of test names, to have an optimal output width */
186 int output_width = -1;
187 foreach (TestInfo ti in test_info) {
188 if (ti.test.Length > output_width)
189 output_width = Math.Min (120, ti.test.Length);
192 List<Thread> threads = new List<Thread> (concurrency);
194 DateTime test_start_time = DateTime.UtcNow;
196 for (int j = 0; j < concurrency; ++j) {
197 Thread thread = new Thread (() => {
202 if (test_info.Count == 0)
204 ti = test_info.Dequeue ();
207 var output = new StringWriter ();
209 string test = ti.test;
210 string opt_set = ti.opt_set;
212 output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
214 /* Spawn a new process */
219 process_args = "-O=" + opt_set + " " + test;
220 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
221 info.UseShellExecute = false;
222 info.RedirectStandardOutput = true;
223 info.RedirectStandardError = true;
224 info.EnvironmentVariables[ENV_TIMEOUT] = timeout.ToString();
225 Process p = new Process ();
228 ProcessData data = new ProcessData ();
231 string log_prefix = "";
233 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
235 data.stdoutFile = test + log_prefix + ".stdout";
236 data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
238 data.stderrFile = test + log_prefix + ".stderr";
239 data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
241 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
242 if (e.Data != null) {
243 data.stdout.WriteLine (e.Data);
245 data.stdout.Flush ();
246 data.stdout.Close ();
250 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
251 if (e.Data != null) {
252 data.stderr.WriteLine (e.Data);
254 data.stderr.Flush ();
255 data.stderr.Close ();
259 var start = DateTime.UtcNow;
263 p.BeginOutputReadLine ();
264 p.BeginErrorReadLine ();
266 if (!p.WaitForExit (timeout * 1000)) {
271 output.Write ("timed out");
274 } else if (p.ExitCode != expectedExitCode) {
275 var end = DateTime.UtcNow;
281 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
283 var end = DateTime.UtcNow;
289 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
295 Console.WriteLine (output.ToString ());
302 threads.Add (thread);
305 for (int j = 0; j < threads.Count; ++j)
308 TimeSpan test_time = DateTime.UtcNow - test_start_time;
310 int npassed = passed.Count;
311 int nfailed = failed.Count;
312 int ntimedout = timedout.Count;
314 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
315 xmlWriterSettings.NewLineOnAttributes = true;
316 xmlWriterSettings.Indent = true;
317 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
318 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
319 writer.WriteStartDocument ();
320 // <!--This file represents the results of running a test suite-->
321 writer.WriteComment ("This file represents the results of running a test suite");
322 // <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">
323 writer.WriteStartElement ("test-results");
324 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
325 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
326 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
327 writer.WriteAttributeString ("not-run", "0");
328 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
329 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
330 // <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" />
331 writer.WriteStartElement ("environment");
332 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
333 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
334 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
335 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
336 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
337 writer.WriteAttributeString ("machine-name", Environment.MachineName );
338 writer.WriteAttributeString ("user", Environment.UserName );
339 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
340 writer.WriteEndElement ();
341 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
342 writer.WriteStartElement ("culture-info");
343 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
344 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
345 writer.WriteEndElement ();
346 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
347 writer.WriteStartElement ("test-suite");
348 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
349 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
350 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
351 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
353 writer.WriteStartElement ("results");
354 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
355 writer.WriteStartElement ("test-suite");
356 writer.WriteAttributeString ("name","MonoTests");
357 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
358 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
359 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
361 writer.WriteStartElement ("results");
362 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
363 writer.WriteStartElement ("test-suite");
364 writer.WriteAttributeString ("name", testsuiteName);
365 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
366 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
367 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
369 writer.WriteStartElement ("results");
370 // Dump all passing tests first
371 foreach (ProcessData pd in passed) {
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", "True");
377 writer.WriteAttributeString ("time", "0");
378 writer.WriteAttributeString ("asserts", "0");
379 writer.WriteEndElement ();
381 // Now dump all failing tests
382 foreach (ProcessData pd in failed) {
383 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
384 writer.WriteStartElement ("test-case");
385 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
386 writer.WriteAttributeString ("executed", "True");
387 writer.WriteAttributeString ("success", "False");
388 writer.WriteAttributeString ("time", "0");
389 writer.WriteAttributeString ("asserts", "1");
390 writer.WriteStartElement ("failure");
391 writer.WriteStartElement ("message");
392 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
393 writer.WriteEndElement ();
394 writer.WriteStartElement ("stack-trace");
395 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
396 writer.WriteEndElement ();
397 writer.WriteEndElement ();
398 writer.WriteEndElement ();
400 // Then dump all timing out tests
401 foreach (ProcessData pd in timedout) {
402 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
403 writer.WriteStartElement ("test-case");
404 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
405 writer.WriteAttributeString ("executed", "True");
406 writer.WriteAttributeString ("success", "False");
407 writer.WriteAttributeString ("time", "0");
408 writer.WriteAttributeString ("asserts", "1");
409 writer.WriteStartElement ("failure");
410 writer.WriteStartElement ("message");
411 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
412 writer.WriteEndElement ();
413 writer.WriteStartElement ("stack-trace");
414 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
415 writer.WriteEndElement ();
416 writer.WriteEndElement ();
417 writer.WriteEndElement ();
420 writer.WriteEndElement ();
422 writer.WriteEndElement ();
424 writer.WriteEndElement ();
426 writer.WriteEndElement ();
428 writer.WriteEndElement ();
430 writer.WriteEndElement ();
432 writer.WriteEndElement ();
433 writer.WriteEndDocument ();
436 Console.WriteLine ();
437 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
438 Console.WriteLine ();
439 Console.WriteLine ("{0,4} test(s) passed", npassed);
440 Console.WriteLine ("{0,4} test(s) failed", nfailed);
441 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
444 Console.WriteLine ();
445 Console.WriteLine ("Failed test(s):");
446 foreach (ProcessData pd in failed) {
447 Console.WriteLine ();
448 Console.WriteLine (pd.test);
449 DumpFile (pd.stdoutFile);
450 DumpFile (pd.stderrFile);
455 Console.WriteLine ();
456 Console.WriteLine ("Timed out test(s):");
457 foreach (ProcessData pd in timedout) {
458 Console.WriteLine ();
459 Console.WriteLine (pd.test);
460 DumpFile (pd.stdoutFile);
461 DumpFile (pd.stderrFile);
465 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
468 static void DumpFile (string filename) {
469 if (File.Exists (filename)) {
470 Console.WriteLine ("=============== {0} ===============", filename);
471 Console.WriteLine (File.ReadAllText (filename));
472 Console.WriteLine ("=============== EOF ===============");
476 static string DumpPseudoTrace (string filename) {
477 if (File.Exists (filename))
478 return FilterInvalidXmlChars (File.ReadAllText (filename));
483 static string FilterInvalidXmlChars (string text) {
484 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
485 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
486 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");