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
45 public StreamWriter stdout, stderr;
46 public string stdoutFile, stderrFile;
50 public string test, opt_set;
53 public static int Main (String[] args) {
56 int timeout = 2 * 60; // in seconds
57 int expectedExitCode = 0;
58 string testsuiteName = null;
60 DateTime test_start_time = DateTime.UtcNow;
62 // FIXME: Add support for runtime arguments + env variables
64 string disabled_tests = null;
65 string runtime = "mono";
66 var opt_sets = new List<string> ();
70 while (i < args.Length) {
71 if (args [i].StartsWith ("-")) {
72 if (args [i] == "-j") {
73 if (i + i >= args.Length) {
74 Console.WriteLine ("Missing argument to -j command line option.");
77 if (args [i + 1] == "a")
78 concurrency = Environment.ProcessorCount;
80 concurrency = Int32.Parse (args [i + 1]);
82 } else if (args [i] == "--timeout") {
83 if (i + i >= args.Length) {
84 Console.WriteLine ("Missing argument to --timeout command line option.");
87 timeout = Int32.Parse (args [i + 1]);
89 } else if (args [i] == "--disabled") {
90 if (i + i >= args.Length) {
91 Console.WriteLine ("Missing argument to --disabled command line option.");
94 disabled_tests = args [i + 1];
96 } else if (args [i] == "--runtime") {
97 if (i + i >= args.Length) {
98 Console.WriteLine ("Missing argument to --runtime command line option.");
101 runtime = args [i + 1];
103 } else if (args [i] == "--opt-sets") {
104 if (i + i >= args.Length) {
105 Console.WriteLine ("Missing argument to --opt-sets command line option.");
108 foreach (var s in args [i + 1].Split ())
111 } else if (args [i] == "--expected-exit-code") {
112 if (i + i >= args.Length) {
113 Console.WriteLine ("Missing argument to --expected-exit-code command line option.");
116 expectedExitCode = Int32.Parse (args [i + 1]);
118 } else if (args [i] == "--testsuite-name") {
119 if (i + i >= args.Length) {
120 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
123 testsuiteName = args [i + 1];
126 Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
134 if (String.IsNullOrEmpty (testsuiteName)) {
135 Console.WriteLine ("Missing the required --testsuite-name command line option.");
139 var disabled = new Dictionary <string, string> ();
141 if (disabled_tests != null) {
142 foreach (string test in disabled_tests.Split ())
143 disabled [test] = test;
146 // The remaining arguments are the tests
147 var tests = new List<string> ();
148 for (int j = i; j < args.Length; ++j)
149 if (!disabled.ContainsKey (args [j]))
150 tests.Add (args [j]);
152 var passed = new List<ProcessData> ();
153 var failed = new List<ProcessData> ();
154 var timedout = new List<ProcessData> ();
156 object monitor = new object ();
158 if (concurrency != 1)
159 Console.WriteLine ("Running tests: ");
161 var test_info = new Queue<TestInfo> ();
162 if (opt_sets.Count == 0) {
163 foreach (string s in tests)
164 test_info.Enqueue (new TestInfo { test = s });
166 foreach (string opt in opt_sets) {
167 foreach (string s in tests)
168 test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
172 List<Thread> threads = new List<Thread> (concurrency);
174 for (int j = 0; j < concurrency; ++j) {
175 Thread thread = new Thread (() => {
180 if (test_info.Count == 0)
182 ti = test_info.Dequeue ();
185 string test = ti.test;
186 string opt_set = ti.opt_set;
188 if (concurrency == 1)
189 Console.Write ("Testing " + test + "... ");
191 /* Spawn a new process */
196 process_args = "-O=" + opt_set + " " + test;
197 ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
198 info.UseShellExecute = false;
199 info.RedirectStandardOutput = true;
200 info.RedirectStandardError = true;
201 Process p = new Process ();
204 ProcessData data = new ProcessData ();
207 string log_prefix = "";
209 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
211 data.stdoutFile = test + log_prefix + ".stdout";
212 data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
214 data.stderrFile = test + log_prefix + ".stderr";
215 data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
217 p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
218 if (e.Data != null) {
219 data.stdout.WriteLine (e.Data);
221 data.stdout.Flush ();
222 data.stdout.Close ();
226 p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
227 if (e.Data != null) {
228 data.stderr.WriteLine (e.Data);
230 data.stderr.Flush ();
231 data.stderr.Close ();
237 p.BeginOutputReadLine ();
238 p.BeginErrorReadLine ();
240 if (!p.WaitForExit (timeout * 1000)) {
245 if (concurrency == 1)
246 Console.WriteLine ("timed out.");
251 } else if (p.ExitCode != expectedExitCode) {
256 if (concurrency == 1)
257 Console.WriteLine ("failed.");
265 if (concurrency == 1)
266 Console.WriteLine ("passed.");
277 threads.Add (thread);
280 for (int j = 0; j < threads.Count; ++j)
283 int npassed = passed.Count;
284 int nfailed = failed.Count;
285 int ntimedout = timedout.Count;
287 TimeSpan test_time = DateTime.UtcNow - test_start_time;
288 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
289 xmlWriterSettings.NewLineOnAttributes = true;
290 xmlWriterSettings.Indent = true;
291 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResults_{0}.xml", testsuiteName), xmlWriterSettings)) {
292 // <?xml version="1.0" encoding="utf-8" standalone="no"?>
293 writer.WriteStartDocument ();
294 // <!--This file represents the results of running a test suite-->
295 writer.WriteComment ("This file represents the results of running a test suite");
296 // <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">
297 writer.WriteStartElement ("test-results");
298 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
299 writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
300 writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
301 writer.WriteAttributeString ("not-run", "0");
302 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
303 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
304 // <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" />
305 writer.WriteStartElement ("environment");
306 writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
307 writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
308 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
309 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
310 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
311 writer.WriteAttributeString ("machine-name", Environment.MachineName );
312 writer.WriteAttributeString ("user", Environment.UserName );
313 writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
314 writer.WriteEndElement ();
315 // <culture-info current-culture="en-GB" current-uiculture="en-GB" />
316 writer.WriteStartElement ("culture-info");
317 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
318 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
319 writer.WriteEndElement ();
320 // <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
321 writer.WriteStartElement ("test-suite");
322 writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
323 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
324 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
325 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
327 writer.WriteStartElement ("results");
328 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
329 writer.WriteStartElement ("test-suite");
330 writer.WriteAttributeString ("name","MonoTests");
331 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
332 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
333 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
335 writer.WriteStartElement ("results");
336 // <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
337 writer.WriteStartElement ("test-suite");
338 writer.WriteAttributeString ("name", testsuiteName);
339 writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
340 writer.WriteAttributeString ("time", test_time.Seconds.ToString());
341 writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
343 writer.WriteStartElement ("results");
344 // Dump all passing tests first
345 foreach (ProcessData pd in passed) {
346 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
347 writer.WriteStartElement ("test-case");
348 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
349 writer.WriteAttributeString ("executed", "True");
350 writer.WriteAttributeString ("success", "True");
351 writer.WriteAttributeString ("time", "0");
352 writer.WriteAttributeString ("asserts", "0");
353 writer.WriteEndElement ();
355 // Now dump all failing tests
356 foreach (ProcessData pd in failed) {
357 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
358 writer.WriteStartElement ("test-case");
359 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
360 writer.WriteAttributeString ("executed", "True");
361 writer.WriteAttributeString ("success", "False");
362 writer.WriteAttributeString ("time", "0");
363 writer.WriteAttributeString ("asserts", "1");
364 writer.WriteStartElement ("failure");
365 writer.WriteStartElement ("message");
366 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
367 writer.WriteEndElement ();
368 writer.WriteStartElement ("stack-trace");
369 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
370 writer.WriteEndElement ();
371 writer.WriteEndElement ();
372 writer.WriteEndElement ();
374 // Then dump all timing out tests
375 foreach (ProcessData pd in timedout) {
376 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
377 writer.WriteStartElement ("test-case");
378 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
379 writer.WriteAttributeString ("executed", "True");
380 writer.WriteAttributeString ("success", "False");
381 writer.WriteAttributeString ("time", "0");
382 writer.WriteAttributeString ("asserts", "1");
383 writer.WriteStartElement ("failure");
384 writer.WriteStartElement ("message");
385 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
386 writer.WriteEndElement ();
387 writer.WriteStartElement ("stack-trace");
388 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
389 writer.WriteEndElement ();
390 writer.WriteEndElement ();
391 writer.WriteEndElement ();
394 writer.WriteEndElement ();
396 writer.WriteEndElement ();
398 writer.WriteEndElement ();
400 writer.WriteEndElement ();
402 writer.WriteEndElement ();
404 writer.WriteEndElement ();
406 writer.WriteEndElement ();
407 writer.WriteEndDocument ();
410 Console.WriteLine ();
411 Console.WriteLine ("{0,4} test(s) passed", npassed);
412 Console.WriteLine ("{0,4} test(s) failed", nfailed);
413 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
416 Console.WriteLine ();
417 Console.WriteLine ("Failed test(s):");
418 foreach (ProcessData pd in failed) {
419 Console.WriteLine ();
420 Console.WriteLine (pd.test);
421 DumpFile (pd.stdoutFile);
422 DumpFile (pd.stderrFile);
427 Console.WriteLine ();
428 Console.WriteLine ("Timed out test(s):");
429 foreach (ProcessData pd in timedout) {
430 Console.WriteLine ();
431 Console.WriteLine (pd.test);
432 DumpFile (pd.stdoutFile);
433 DumpFile (pd.stderrFile);
437 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
440 static void DumpFile (string filename) {
441 if (File.Exists (filename)) {
442 Console.WriteLine ("=============== {0} ===============", filename);
443 Console.WriteLine (File.ReadAllText (filename));
444 Console.WriteLine ("=============== EOF ===============");
448 static string DumpPseudoTrace (string filename) {
449 if (File.Exists (filename))
450 return FilterInvalidXmlChars (File.ReadAllText (filename));
455 static string FilterInvalidXmlChars (string text) {
456 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
457 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
458 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");