Merge pull request #2820 from kumpera/license-change-rebased
[mono.git] / mono / tests / test-runner.cs
1 //
2 // test-runner.cs
3 //
4 // Author:
5 //   Zoltan Varga (vargaz@gmail.com)
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 //
9 // Licensed under the MIT license. See LICENSE file in the project root for full license information.
10 //
11 using System;
12 using System.IO;
13 using System.Threading;
14 using System.Diagnostics;
15 using System.Collections.Generic;
16 using System.Globalization;
17 using System.Xml;
18 using System.Text.RegularExpressions;
19 using Mono.Unix.Native;
20
21 //
22 // This is a simple test runner with support for parallel execution
23 //
24
25 public class TestRunner
26 {
27         const string TEST_TIME_FORMAT = "mm\\:ss\\.fff";
28         const string ENV_TIMEOUT = "TEST_DRIVER_TIMEOUT_SEC";
29
30         class ProcessData {
31                 public string test;
32                 public StreamWriter stdout, stderr;
33                 public string stdoutFile, stderrFile;
34         }
35
36         class TestInfo {
37                 public string test, opt_set;
38         }
39
40         public static int Main (String[] args) {
41                 // Defaults
42                 int concurrency = 1;
43                 int timeout = 2 * 60; // in seconds
44                 int expectedExitCode = 0;
45                 string testsuiteName = null;
46                 string inputFile = null;
47
48                 // FIXME: Add support for runtime arguments + env variables
49
50                 string disabled_tests = null;
51                 string runtime = "mono";
52                 var opt_sets = new List<string> ();
53
54                 // Process options
55                 int i = 0;
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.");
61                                                 return 1;
62                                         }
63                                         if (args [i + 1] == "a")
64                                                 concurrency = Environment.ProcessorCount;
65                                         else
66                                                 concurrency = Int32.Parse (args [i + 1]);
67                                         i += 2;
68                                 } else if (args [i] == "--timeout") {
69                                         if (i + 1 >= args.Length) {
70                                                 Console.WriteLine ("Missing argument to --timeout command line option.");
71                                                 return 1;
72                                         }
73                                         timeout = Int32.Parse (args [i + 1]);
74                                         i += 2;
75                                 } else if (args [i] == "--disabled") {
76                                         if (i + 1 >= args.Length) {
77                                                 Console.WriteLine ("Missing argument to --disabled command line option.");
78                                                 return 1;
79                                         }
80                                         disabled_tests = args [i + 1];
81                                         i += 2;
82                                 } else if (args [i] == "--runtime") {
83                                         if (i + 1 >= args.Length) {
84                                                 Console.WriteLine ("Missing argument to --runtime command line option.");
85                                                 return 1;
86                                         }
87                                         runtime = args [i + 1];
88                                         i += 2;
89                                 } else if (args [i] == "--opt-sets") {
90                                         if (i + 1 >= args.Length) {
91                                                 Console.WriteLine ("Missing argument to --opt-sets command line option.");
92                                                 return 1;
93                                         }
94                                         foreach (var s in args [i + 1].Split ())
95                                                 opt_sets.Add (s);
96                                         i += 2;
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.");
100                                                 return 1;
101                                         }
102                                         expectedExitCode = Int32.Parse (args [i + 1]);
103                                         i += 2;
104                                 } else if (args [i] == "--testsuite-name") {
105                                         if (i + 1 >= args.Length) {
106                                                 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
107                                                 return 1;
108                                         }
109                                         testsuiteName = args [i + 1];
110                                         i += 2;
111                                 } else if (args [i] == "--input-file") {
112                                         if (i + 1 >= args.Length) {
113                                                 Console.WriteLine ("Missing argument to --input-file command line option.");
114                                                 return 1;
115                                         }
116                                         inputFile = args [i + 1];
117                                         i += 2;
118                                 } else {
119                                         Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
120                                         return 1;
121                                 }
122                         } else {
123                                 break;
124                         }
125                 }
126
127                 if (String.IsNullOrEmpty (testsuiteName)) {
128                         Console.WriteLine ("Missing the required --testsuite-name command line option.");
129                         return 1;
130                 }
131
132                 var disabled = new Dictionary <string, string> ();
133
134                 if (disabled_tests != null) {
135                         foreach (string test in disabled_tests.Split ())
136                                 disabled [test] = test;
137                 }
138
139                 var tests = new List<string> ();
140
141                 if (!String.IsNullOrEmpty (inputFile)) {
142                         tests.AddRange (File.ReadAllLines (inputFile));
143                 } else {
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]);
148                 }
149
150                 var passed = new List<ProcessData> ();
151                 var failed = new List<ProcessData> ();
152                 var timedout = new List<ProcessData> ();
153
154                 object monitor = new object ();
155
156                 Console.WriteLine ("Running tests: ");
157
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 });
162                 } else {
163                         foreach (string opt in opt_sets) {
164                                 foreach (string s in tests)
165                                         test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
166                         }
167                 }
168
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);
174                 }
175
176                 List<Thread> threads = new List<Thread> (concurrency);
177
178                 DateTime test_start_time = DateTime.UtcNow;
179
180                 for (int j = 0; j < concurrency; ++j) {
181                         Thread thread = new Thread (() => {
182                                 while (true) {
183                                         TestInfo ti;
184
185                                         lock (monitor) {
186                                                 if (test_info.Count == 0)
187                                                         break;
188                                                 ti = test_info.Dequeue ();
189                                         }
190
191                                         var output = new StringWriter ();
192
193                                         string test = ti.test;
194                                         string opt_set = ti.opt_set;
195
196                                         output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
197
198                                         /* Spawn a new process */
199                                         string process_args;
200                                         if (opt_set == null)
201                                                 process_args = test;
202                                         else
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 ();
210                                         p.StartInfo = info;
211
212                                         ProcessData data = new ProcessData ();
213                                         data.test = test;
214
215                                         string log_prefix = "";
216                                         if (opt_set != null)
217                                                 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
218
219                                         data.stdoutFile = test + log_prefix + ".stdout";
220                                         data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
221
222                                         data.stderrFile = test + log_prefix + ".stderr";
223                                         data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
224
225                                         p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
226                                                 if (e.Data != null) {
227                                                         data.stdout.WriteLine (e.Data);
228                                                 } else {
229                                                         data.stdout.Flush ();
230                                                         data.stdout.Close ();
231                                                 }
232                                         };
233
234                                         p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
235                                                 if (e.Data != null) {
236                                                         data.stderr.WriteLine (e.Data);
237                                                 } else {
238                                                         data.stderr.Flush ();
239                                                         data.stderr.Close ();
240                                                 }
241                                         };
242
243                                         var start = DateTime.UtcNow;
244
245                                         p.Start ();
246
247                                         p.BeginOutputReadLine ();
248                                         p.BeginErrorReadLine ();
249
250                                         if (!p.WaitForExit (timeout * 1000)) {
251                                                 lock (monitor) {
252                                                         timedout.Add (data);
253                                                 }
254
255                                                 // Force the process to print a thread dump
256                                                 try {
257                                                         Syscall.kill (p.Id, Signum.SIGQUIT);
258                                                         Thread.Sleep (1000);
259                                                 } catch {
260                                                 }
261
262                                                 output.Write ("timed out");
263
264                                                 p.Kill ();
265                                         } else if (p.ExitCode != expectedExitCode) {
266                                                 var end = DateTime.UtcNow;
267
268                                                 lock (monitor) {
269                                                         failed.Add (data);
270                                                 }
271
272                                                 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
273                                         } else {
274                                                 var end = DateTime.UtcNow;
275
276                                                 lock (monitor) {
277                                                         passed.Add (data);
278                                                 }
279
280                                                 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
281                                         }
282
283                                         p.Close ();
284
285                                         lock (monitor) {
286                                                 Console.WriteLine (output.ToString ());
287                                         }
288                                 }
289                         });
290
291                         thread.Start ();
292
293                         threads.Add (thread);
294                 }
295
296                 for (int j = 0; j < threads.Count; ++j)
297                         threads [j].Join ();
298
299                 TimeSpan test_time = DateTime.UtcNow - test_start_time;
300
301                 int npassed = passed.Count;
302                 int nfailed = failed.Count;
303                 int ntimedout = timedout.Count;
304
305                 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
306                 xmlWriterSettings.NewLineOnAttributes = true;
307                 xmlWriterSettings.Indent = true;
308                 using (XmlWriter writer = XmlWriter.Create (String.Format ("TestResult-{0}.xml", testsuiteName), xmlWriterSettings)) {
309                         // <?xml version="1.0" encoding="utf-8" standalone="no"?>
310                         writer.WriteStartDocument ();
311                         // <!--This file represents the results of running a test suite-->
312                         writer.WriteComment ("This file represents the results of running a test suite");
313                         // <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">
314                         writer.WriteStartElement ("test-results");
315                         writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
316                         writer.WriteAttributeString ("total", (npassed + nfailed + ntimedout).ToString());
317                         writer.WriteAttributeString ("failures", (nfailed + ntimedout).ToString());
318                         writer.WriteAttributeString ("not-run", "0");
319                         writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
320                         writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
321                         //   <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" />
322                         writer.WriteStartElement ("environment");
323                         writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
324                         writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
325                         writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
326                         writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
327                         writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
328                         writer.WriteAttributeString ("machine-name", Environment.MachineName );
329                         writer.WriteAttributeString ("user", Environment.UserName );
330                         writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
331                         writer.WriteEndElement ();
332                         //   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
333                         writer.WriteStartElement ("culture-info");
334                         writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
335                         writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
336                         writer.WriteEndElement ();
337                         //   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
338                         writer.WriteStartElement ("test-suite");
339                         writer.WriteAttributeString ("name", String.Format ("{0}-tests.dummy", testsuiteName));
340                         writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
341                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
342                         writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
343                         //     <results>
344                         writer.WriteStartElement ("results");
345                         //       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
346                         writer.WriteStartElement ("test-suite");
347                         writer.WriteAttributeString ("name","MonoTests");
348                         writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
349                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
350                         writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
351                         //         <results>
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", testsuiteName);
356                         writer.WriteAttributeString ("success", (nfailed + ntimedout == 0).ToString());
357                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
358                         writer.WriteAttributeString ("asserts", (nfailed + ntimedout).ToString());
359                         //             <results>
360                         writer.WriteStartElement ("results");
361                         // Dump all passing tests first
362                         foreach (ProcessData pd in passed) {
363                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
364                                 writer.WriteStartElement ("test-case");
365                                 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
366                                 writer.WriteAttributeString ("executed", "True");
367                                 writer.WriteAttributeString ("success", "True");
368                                 writer.WriteAttributeString ("time", "0");
369                                 writer.WriteAttributeString ("asserts", "0");
370                                 writer.WriteEndElement ();
371                         }
372                         // Now dump all failing tests
373                         foreach (ProcessData pd in failed) {
374                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
375                                 writer.WriteStartElement ("test-case");
376                                 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}", testsuiteName, pd.test));
377                                 writer.WriteAttributeString ("executed", "True");
378                                 writer.WriteAttributeString ("success", "False");
379                                 writer.WriteAttributeString ("time", "0");
380                                 writer.WriteAttributeString ("asserts", "1");
381                                 writer.WriteStartElement ("failure");
382                                 writer.WriteStartElement ("message");
383                                 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
384                                 writer.WriteEndElement ();
385                                 writer.WriteStartElement ("stack-trace");
386                                 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
387                                 writer.WriteEndElement ();
388                                 writer.WriteEndElement ();
389                                 writer.WriteEndElement ();
390                         }
391                         // Then dump all timing out tests
392                         foreach (ProcessData pd in timedout) {
393                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
394                                 writer.WriteStartElement ("test-case");
395                                 writer.WriteAttributeString ("name", String.Format ("MonoTests.{0}.{1}_timedout", testsuiteName, pd.test));
396                                 writer.WriteAttributeString ("executed", "True");
397                                 writer.WriteAttributeString ("success", "False");
398                                 writer.WriteAttributeString ("time", "0");
399                                 writer.WriteAttributeString ("asserts", "1");
400                                 writer.WriteStartElement ("failure");
401                                 writer.WriteStartElement ("message");
402                                 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
403                                 writer.WriteEndElement ();
404                                 writer.WriteStartElement ("stack-trace");
405                                 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
406                                 writer.WriteEndElement ();
407                                 writer.WriteEndElement ();
408                                 writer.WriteEndElement ();
409                         }
410                         //             </results>
411                         writer.WriteEndElement ();
412                         //           </test-suite>
413                         writer.WriteEndElement ();
414                         //         </results>
415                         writer.WriteEndElement ();
416                         //       </test-suite>
417                         writer.WriteEndElement ();
418                         //     </results>
419                         writer.WriteEndElement ();
420                         //   </test-suite>
421                         writer.WriteEndElement ();
422                         // </test-results>
423                         writer.WriteEndElement ();
424                         writer.WriteEndDocument ();
425                 }
426
427                 Console.WriteLine ();
428                 Console.WriteLine ("Time: {0}", test_time.ToString (TEST_TIME_FORMAT));
429                 Console.WriteLine ();
430                 Console.WriteLine ("{0,4} test(s) passed", npassed);
431                 Console.WriteLine ("{0,4} test(s) failed", nfailed);
432                 Console.WriteLine ("{0,4} test(s) timed out", ntimedout);
433
434                 if (nfailed > 0) {
435                         Console.WriteLine ();
436                         Console.WriteLine ("Failed test(s):");
437                         foreach (ProcessData pd in failed) {
438                                 Console.WriteLine ();
439                                 Console.WriteLine (pd.test);
440                                 DumpFile (pd.stdoutFile);
441                                 DumpFile (pd.stderrFile);
442                         }
443                 }
444
445                 if (ntimedout > 0) {
446                         Console.WriteLine ();
447                         Console.WriteLine ("Timed out test(s):");
448                         foreach (ProcessData pd in timedout) {
449                                 Console.WriteLine ();
450                                 Console.WriteLine (pd.test);
451                                 DumpFile (pd.stdoutFile);
452                                 DumpFile (pd.stderrFile);
453                         }
454                 }
455
456                 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
457         }
458         
459         static void DumpFile (string filename) {
460                 if (File.Exists (filename)) {
461                         Console.WriteLine ("=============== {0} ===============", filename);
462                         Console.WriteLine (File.ReadAllText (filename));
463                         Console.WriteLine ("=============== EOF ===============");
464                 }
465         }
466
467         static string DumpPseudoTrace (string filename) {
468                 if (File.Exists (filename))
469                         return FilterInvalidXmlChars (File.ReadAllText (filename));
470                 else
471                         return string.Empty;
472         }
473
474         static string FilterInvalidXmlChars (string text) {
475                 // Spec at http://www.w3.org/TR/2008/REC-xml-20081126/#charsets says only the following chars are valid in XML:
476                 // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]      /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
477                 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", "");
478         }
479 }