Merge pull request #3142 from henricm/fix-for-win-mono_string_to_utf8
[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.Text;
15 using System.Diagnostics;
16 using System.Collections.Generic;
17 using System.Globalization;
18 using System.Xml;
19 using System.Text.RegularExpressions;
20 using Mono.Unix.Native;
21
22 //
23 // This is a simple test runner with support for parallel execution
24 //
25
26 public class TestRunner
27 {
28         const string TEST_TIME_FORMAT = "mm\\:ss\\.fff";
29         const string ENV_TIMEOUT = "TEST_DRIVER_TIMEOUT_SEC";
30
31         class ProcessData {
32                 public string test;
33                 public StringBuilder stdout, stderr;
34                 public string stdoutName, stderrName;
35         }
36
37         class TestInfo {
38                 public string test, opt_set;
39         }
40
41         public static int Main (String[] args) {
42                 // Defaults
43                 int concurrency = 1;
44                 int timeout = 2 * 60; // in seconds
45                 int expectedExitCode = 0;
46                 string testsuiteName = null;
47                 string inputFile = null;
48
49                 // FIXME: Add support for runtime arguments + env variables
50
51                 string disabled_tests = null;
52                 string runtime = "mono";
53                 var opt_sets = new List<string> ();
54
55                 // Process options
56                 int i = 0;
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.");
62                                                 return 1;
63                                         }
64                                         if (args [i + 1] == "a")
65                                                 concurrency = Environment.ProcessorCount;
66                                         else
67                                                 concurrency = Int32.Parse (args [i + 1]);
68                                         i += 2;
69                                 } else if (args [i] == "--timeout") {
70                                         if (i + 1 >= args.Length) {
71                                                 Console.WriteLine ("Missing argument to --timeout command line option.");
72                                                 return 1;
73                                         }
74                                         timeout = Int32.Parse (args [i + 1]);
75                                         i += 2;
76                                 } else if (args [i] == "--disabled") {
77                                         if (i + 1 >= args.Length) {
78                                                 Console.WriteLine ("Missing argument to --disabled command line option.");
79                                                 return 1;
80                                         }
81                                         disabled_tests = args [i + 1];
82                                         i += 2;
83                                 } else if (args [i] == "--runtime") {
84                                         if (i + 1 >= args.Length) {
85                                                 Console.WriteLine ("Missing argument to --runtime command line option.");
86                                                 return 1;
87                                         }
88                                         runtime = args [i + 1];
89                                         i += 2;
90                                 } else if (args [i] == "--opt-sets") {
91                                         if (i + 1 >= args.Length) {
92                                                 Console.WriteLine ("Missing argument to --opt-sets command line option.");
93                                                 return 1;
94                                         }
95                                         foreach (var s in args [i + 1].Split ())
96                                                 opt_sets.Add (s);
97                                         i += 2;
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.");
101                                                 return 1;
102                                         }
103                                         expectedExitCode = Int32.Parse (args [i + 1]);
104                                         i += 2;
105                                 } else if (args [i] == "--testsuite-name") {
106                                         if (i + 1 >= args.Length) {
107                                                 Console.WriteLine ("Missing argument to --testsuite-name command line option.");
108                                                 return 1;
109                                         }
110                                         testsuiteName = args [i + 1];
111                                         i += 2;
112                                 } else if (args [i] == "--input-file") {
113                                         if (i + 1 >= args.Length) {
114                                                 Console.WriteLine ("Missing argument to --input-file command line option.");
115                                                 return 1;
116                                         }
117                                         inputFile = args [i + 1];
118                                         i += 2;
119                                 } else {
120                                         Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
121                                         return 1;
122                                 }
123                         } else {
124                                 break;
125                         }
126                 }
127
128                 if (String.IsNullOrEmpty (testsuiteName)) {
129                         Console.WriteLine ("Missing the required --testsuite-name command line option.");
130                         return 1;
131                 }
132
133                 var disabled = new Dictionary <string, string> ();
134
135                 if (disabled_tests != null) {
136                         foreach (string test in disabled_tests.Split ())
137                                 disabled [test] = test;
138                 }
139
140                 var tests = new List<string> ();
141
142                 if (!String.IsNullOrEmpty (inputFile)) {
143                         tests.AddRange (File.ReadAllLines (inputFile));
144                 } else {
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]);
149                 }
150
151                 var passed = new List<ProcessData> ();
152                 var failed = new List<ProcessData> ();
153                 var timedout = new List<ProcessData> ();
154
155                 object monitor = new object ();
156
157                 Console.WriteLine ("Running tests: ");
158
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 });
163                 } else {
164                         foreach (string opt in opt_sets) {
165                                 foreach (string s in tests)
166                                         test_info.Enqueue (new TestInfo { test = s, opt_set = opt });
167                         }
168                 }
169
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);
175                 }
176
177                 List<Thread> threads = new List<Thread> (concurrency);
178
179                 DateTime test_start_time = DateTime.UtcNow;
180
181                 for (int j = 0; j < concurrency; ++j) {
182                         Thread thread = new Thread (() => {
183                                 while (true) {
184                                         TestInfo ti;
185
186                                         lock (monitor) {
187                                                 if (test_info.Count == 0)
188                                                         break;
189                                                 ti = test_info.Dequeue ();
190                                         }
191
192                                         var output = new StringWriter ();
193
194                                         string test = ti.test;
195                                         string opt_set = ti.opt_set;
196
197                                         output.Write (String.Format ("{{0,-{0}}} ", output_width), test);
198
199                                         /* Spawn a new process */
200                                         string process_args;
201                                         if (opt_set == null)
202                                                 process_args = test;
203                                         else
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 ();
211                                         p.StartInfo = info;
212
213                                         ProcessData data = new ProcessData ();
214                                         data.test = test;
215
216                                         string log_prefix = "";
217                                         if (opt_set != null)
218                                                 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
219
220                                         data.stdoutName = test + log_prefix + ".stdout";
221                                         data.stdout = new StringBuilder ();
222
223                                         data.stderrName = test + log_prefix + ".stderr";
224                                         data.stderr = new StringBuilder ();
225
226                                         p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
227                                                 if (e.Data != null) {
228                                                         data.stdout.AppendLine (e.Data);
229                                                 }
230                                         };
231
232                                         p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
233                                                 if (e.Data != null) {
234                                                         data.stderr.AppendLine (e.Data);
235                                                 }
236                                         };
237
238                                         var start = DateTime.UtcNow;
239
240                                         p.Start ();
241
242                                         p.BeginOutputReadLine ();
243                                         p.BeginErrorReadLine ();
244
245                                         if (!p.WaitForExit (timeout * 1000)) {
246                                                 lock (monitor) {
247                                                         timedout.Add (data);
248                                                 }
249
250                                                 // Force the process to print a thread dump
251                                                 try {
252                                                         Syscall.kill (p.Id, Signum.SIGQUIT);
253                                                         Thread.Sleep (1000);
254                                                 } catch {
255                                                 }
256
257                                                 output.Write ($"timed out ({timeout}s)");
258
259                                                 try {
260                                                         p.Kill ();
261                                                 } catch {
262                                                 }
263                                         } else if (p.ExitCode != expectedExitCode) {
264                                                 var end = DateTime.UtcNow;
265
266                                                 lock (monitor) {
267                                                         failed.Add (data);
268                                                 }
269
270                                                 output.Write ("failed, time: {0}, exit code: {1}", (end - start).ToString (TEST_TIME_FORMAT), p.ExitCode);
271                                         } else {
272                                                 var end = DateTime.UtcNow;
273
274                                                 lock (monitor) {
275                                                         passed.Add (data);
276                                                 }
277
278                                                 output.Write ("passed, time: {0}", (end - start).ToString (TEST_TIME_FORMAT));
279                                         }
280
281                                         p.Close ();
282
283                                         lock (monitor) {
284                                                 Console.WriteLine (output.ToString ());
285                                         }
286                                 }
287                         });
288
289                         thread.Start ();
290
291                         threads.Add (thread);
292                 }
293
294                 for (int j = 0; j < threads.Count; ++j)
295                         threads [j].Join ();
296
297                 TimeSpan test_time = DateTime.UtcNow - test_start_time;
298
299                 int npassed = passed.Count;
300                 int nfailed = failed.Count;
301                 int ntimedout = timedout.Count;
302
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());
341                         //     <results>
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());
349                         //         <results>
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());
357                         //             <results>
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 ();
369                         }
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 ();
388                         }
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 ();
407                         }
408                         //             </results>
409                         writer.WriteEndElement ();
410                         //           </test-suite>
411                         writer.WriteEndElement ();
412                         //         </results>
413                         writer.WriteEndElement ();
414                         //       </test-suite>
415                         writer.WriteEndElement ();
416                         //     </results>
417                         writer.WriteEndElement ();
418                         //   </test-suite>
419                         writer.WriteEndElement ();
420                         // </test-results>
421                         writer.WriteEndElement ();
422                         writer.WriteEndDocument ();
423                 }
424
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);
431
432                 if (nfailed > 0) {
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 ());
440                         }
441                 }
442
443                 if (ntimedout > 0) {
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 ());
451                         }
452                 }
453
454                 return (ntimedout == 0 && nfailed == 0) ? 0 : 1;
455         }
456         
457         static void DumpFile (string filename, string text) {
458                 Console.WriteLine ("=============== {0} ===============", filename);
459                 Console.WriteLine (text);
460                 Console.WriteLine ("=============== EOF ===============");
461         }
462
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]", "");
467         }
468 }