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