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