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