Merge pull request #2139 from akoeplinger/symbolicate-test-fix
[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
36 //
37 // This is a simple test runner with support for parallel execution
38 //
39
40 public class TestRunner
41 {
42         class ProcessData {
43                 public string test;
44                 public StreamWriter stdout, stderr;
45                 public string stdoutFile, stderrFile;
46
47                 public void CloseStreams () {
48                         if (stdout != null) {
49                                 stdout.Close ();
50                                 stdout = null;
51                         }
52                         if (stderr != null) {
53                                 stderr.Close ();
54                                 stderr = null;
55                         }
56                 }
57         }
58
59         class TestInfo {
60                 public string test, opt_set;
61         }
62
63         public static int Main (String[] args) {
64                 // Defaults
65                 int concurrency = 1;
66                 int timeout = 2 * 60; // in seconds
67
68                 DateTime test_start_time = DateTime.UtcNow;
69
70                 // FIXME: Add support for runtime arguments + env variables
71
72                 string disabled_tests = null;
73                 string runtime = "mono";
74                 var opt_sets = new List<string> ();
75
76                 // Process options
77                 int i = 0;
78                 while (i < args.Length) {
79                         if (args [i].StartsWith ("-")) {
80                                 if (args [i] == "-j") {
81                                         if (i + i >= args.Length) {
82                                                 Console.WriteLine ("Missing argument to -j command line option.");
83                                                 return 1;
84                                         }
85                                         if (args [i + 1] == "a")
86                                                 concurrency = Environment.ProcessorCount;
87                                         else
88                                                 concurrency = Int32.Parse (args [i + 1]);
89                                         i += 2;
90                                 } else if (args [i] == "--timeout") {
91                                         if (i + i >= args.Length) {
92                                                 Console.WriteLine ("Missing argument to --timeout command line option.");
93                                                 return 1;
94                                         }
95                                         timeout = Int32.Parse (args [i + 1]);
96                                         i += 2;
97                                 } else if (args [i] == "--disabled") {
98                                         if (i + i >= args.Length) {
99                                                 Console.WriteLine ("Missing argument to --disabled command line option.");
100                                                 return 1;
101                                         }
102                                         disabled_tests = args [i + 1];
103                                         i += 2;
104                                 } else if (args [i] == "--runtime") {
105                                         if (i + i >= args.Length) {
106                                                 Console.WriteLine ("Missing argument to --runtime command line option.");
107                                                 return 1;
108                                         }
109                                         runtime = args [i + 1];
110                                         i += 2;
111                                 } else if (args [i] == "--opt-sets") {
112                                         if (i + i >= args.Length) {
113                                                 Console.WriteLine ("Missing argument to --opt-sets command line option.");
114                                                 return 1;
115                                         }
116                                         foreach (var s in args [i + 1].Split ())
117                                                 opt_sets.Add (s);
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                 var disabled = new Dictionary <string, string> ();
129
130                 if (disabled_tests != null) {
131                         foreach (string test in disabled_tests.Split ())
132                                 disabled [test] = test;
133                 }
134
135                 // The remaining arguments are the tests
136                 var tests = new List<string> ();
137                 for (int j = i; j < args.Length; ++j)
138                         if (!disabled.ContainsKey (args [j]))
139                                 tests.Add (args [j]);
140
141                 int npassed = 0;
142                 int nfailed = 0;
143
144                 var processes = new List<Process> ();
145                 var passed = new List<ProcessData> ();
146                 var failed = new List<ProcessData> ();
147                 var process_data = new Dictionary<Process, ProcessData> ();
148
149                 object monitor = new object ();
150
151                 var terminated = new List<Process> ();
152
153                 if (concurrency != 1)
154                         Console.WriteLine ("Running tests: ");
155
156                 var test_info = new List<TestInfo> ();
157                 if (opt_sets.Count == 0) {
158                         foreach (string s in tests)
159                                 test_info.Add (new TestInfo { test = s });
160                 } else {
161                         foreach (string opt in opt_sets) {
162                                 foreach (string s in tests)
163                                         test_info.Add (new TestInfo { test = s, opt_set = opt });
164                         }
165                 }               
166
167                 foreach (TestInfo ti in test_info) {
168                         lock (monitor) {
169                                 while (processes.Count == concurrency) {
170                                         /* Wait for one process to terminate */
171                                         Monitor.Wait (monitor);
172                                 }
173
174                                 /* Cleaup terminated processes */
175                                 foreach (Process dead in terminated) {
176                                         if (process_data [dead].stdout != null)
177                                                 process_data [dead].stdout.Close ();
178                                         if (process_data [dead].stderr != null)
179                                                 process_data [dead].stderr.Close ();
180                                         // This is needed to avoid CreateProcess failed errors :(
181                                         dead.Close ();
182                                 }
183                                 terminated.Clear ();
184                         }
185
186                         string test = ti.test;
187                         string opt_set = ti.opt_set;
188
189                         if (concurrency == 1)
190                                 Console.Write ("Testing " + test + "... ");
191
192                         /* Spawn a new process */
193                         string process_args;
194                         if (opt_set == null)
195                                 process_args = test;
196                         else
197                                 process_args = "-O=" + opt_set + " " + test;
198                         ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
199                         info.UseShellExecute = false;
200                         info.RedirectStandardOutput = true;
201                         info.RedirectStandardError = true;
202                         Process p = new Process ();
203                         p.StartInfo = info;
204
205                         ProcessData data = new ProcessData ();
206                         data.test = test;
207
208                         string log_prefix = "";
209                         if (opt_set != null)
210                                 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
211
212                         data.stdoutFile = test + log_prefix + ".stdout";
213                         data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
214
215                         data.stderrFile = test + log_prefix + ".stderr";
216                         data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
217
218                         p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
219                                 Process p2 = (Process)sender;
220
221                                 StreamWriter fs;
222
223                                 lock (monitor) {
224                                         fs = process_data [p2].stdout;
225
226                                         if (e.Data == null)
227                                                 process_data [p2].stdout = null;
228                                 }
229
230                                 if (e.Data == null) {
231                                         fs.Close ();
232                                 } else {
233                                         fs.WriteLine (e.Data);
234                                         fs.Flush ();
235                                 }
236                         };
237
238                         p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
239                                 Process p2 = (Process)sender;
240
241                                 StreamWriter fs;
242
243                                 lock (monitor) {
244                                         fs = process_data [p2].stderr;
245
246                                         if (e.Data == null)
247                                                 process_data [p2].stderr = null;
248
249                                 }
250
251                                 if (e.Data == null) {
252                                         fs.Close ();
253
254                                         lock (monitor) {
255                                                 process_data [p2].stderr = null;
256                                         }
257                                 } else {
258                                         fs.WriteLine (e.Data);
259                                         fs.Flush ();
260                                 }
261                         };
262
263                         lock (monitor) {
264                                 processes.Add (p);
265                                 process_data [p] = data;
266                         }
267                         p.Start ();
268
269                         p.BeginOutputReadLine ();
270                         p.BeginErrorReadLine ();
271
272                         ThreadPool.QueueUserWorkItem (o => {
273                                 Process process = (Process) o;
274
275                                 process.WaitForExit ();
276
277                                 lock (monitor) {
278                                         if (process.ExitCode == 0) {
279                                                 if (concurrency == 1)
280                                                         Console.WriteLine ("passed.");
281                                                 else
282                                                         Console.Write (".");
283                                                 passed.Add(process_data [process]);
284                                                 npassed ++;
285                                         } else {
286                                                 if (concurrency == 1)
287                                                         Console.WriteLine ("failed.");
288                                                 else
289                                                         Console.Write ("F");
290                                                 failed.Add (process_data [process]);
291                                                 nfailed ++;
292                                         }
293                                         processes.Remove (process);
294                                         terminated.Add (process);
295                                         Monitor.Pulse (monitor);
296                                 }
297                         }, p);
298                 }
299
300                 bool timed_out = false;
301
302                 /* Wait for all processes to terminate */
303                 while (true) {
304                         lock (monitor) {
305                                 int nprocesses = processes.Count;
306
307                                 if (nprocesses == 0)
308                                         break;
309
310                                 bool res = Monitor.Wait (monitor, 1000 * timeout);
311                                 if (!res) {
312                                         timed_out = true;
313                                         break;
314                                 }
315                         }
316                 }
317
318                 TimeSpan test_time = DateTime.UtcNow - test_start_time;
319                 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
320                 xmlWriterSettings.NewLineOnAttributes = true;
321                 xmlWriterSettings.Indent = true;
322                 using (XmlWriter writer = XmlWriter.Create ("TestResults_runtime.xml", xmlWriterSettings)) {
323                         // <?xml version="1.0" encoding="utf-8" standalone="no"?>
324                         writer.WriteStartDocument ();
325                         // <!--This file represents the results of running a test suite-->
326                         writer.WriteComment ("This file represents the results of running a test suite");
327                         // <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">
328                         writer.WriteStartElement ("test-results");
329                         writer.WriteAttributeString ("name", "runtime-tests.dummy");
330                         writer.WriteAttributeString ("total", (npassed + nfailed).ToString());
331                         writer.WriteAttributeString ("failures", nfailed.ToString());
332                         writer.WriteAttributeString ("not-run", "0");
333                         writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
334                         writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
335                         //   <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" />
336                         writer.WriteStartElement ("environment");
337                         writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
338                         writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
339                         writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
340                         writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
341                         writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
342                         writer.WriteAttributeString ("machine-name", Environment.MachineName );
343                         writer.WriteAttributeString ("user", Environment.UserName );
344                         writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
345                         writer.WriteEndElement ();
346                         //   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
347                         writer.WriteStartElement ("culture-info");
348                         writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
349                         writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
350                         writer.WriteEndElement ();
351                         //   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
352                         writer.WriteStartElement ("test-suite");
353                         writer.WriteAttributeString ("name","runtime-tests.dummy");
354                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
355                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
356                         writer.WriteAttributeString ("asserts", nfailed.ToString());
357                         //     <results>
358                         writer.WriteStartElement ("results");
359                         //       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
360                         writer.WriteStartElement ("test-suite");
361                         writer.WriteAttributeString ("name","MonoTests");
362                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
363                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
364                         writer.WriteAttributeString ("asserts", nfailed.ToString());
365                         //         <results>
366                         writer.WriteStartElement ("results");
367                         //           <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
368                         writer.WriteStartElement ("test-suite");
369                         writer.WriteAttributeString ("name","runtime");
370                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
371                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
372                         writer.WriteAttributeString ("asserts", nfailed.ToString());
373                         //             <results>
374                         writer.WriteStartElement ("results");
375                         // Dump all passing tests first
376                         foreach (ProcessData pd in passed) {
377                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
378                                 writer.WriteStartElement ("test-case");
379                                 writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
380                                 writer.WriteAttributeString ("executed", "True");
381                                 writer.WriteAttributeString ("success", "True");
382                                 writer.WriteAttributeString ("time", "0");
383                                 writer.WriteAttributeString ("asserts", "0");
384                                 writer.WriteEndElement ();
385                         }
386                         // Now dump all failing tests
387                         foreach (ProcessData pd in failed) {
388                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
389                                 writer.WriteStartElement ("test-case");
390                                 writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
391                                 writer.WriteAttributeString ("executed", "True");
392                                 writer.WriteAttributeString ("success", "False");
393                                 writer.WriteAttributeString ("time", "0");
394                                 writer.WriteAttributeString ("asserts", "1");
395                                 writer.WriteStartElement ("failure");
396                                 writer.WriteStartElement ("message");
397                                 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
398                                 writer.WriteEndElement ();
399                                 writer.WriteStartElement ("stack-trace");
400                                 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
401                                 writer.WriteEndElement ();
402                                 writer.WriteEndElement ();
403                                 writer.WriteEndElement ();
404                         }
405                         //             </results>
406                         writer.WriteEndElement ();
407                         //           </test-suite>
408                         writer.WriteEndElement ();
409                         //         </results>
410                         writer.WriteEndElement ();
411                         //       </test-suite>
412                         writer.WriteEndElement ();
413                         //     </results>
414                         writer.WriteEndElement ();
415                         //   </test-suite>
416                         writer.WriteEndElement ();
417                         // </test-results>
418                         writer.WriteEndElement ();
419                         writer.WriteEndDocument ();
420                 }
421
422                 Console.WriteLine ();
423
424                 if (timed_out) {
425                         Console.WriteLine ("\nrunning tests timed out:\n");
426                         Console.WriteLine (npassed + nfailed);
427                         lock (monitor) {
428                                 foreach (Process p in processes) {
429                                         ProcessData pd = process_data [p];
430                                         pd.CloseStreams ();
431                                         Console.WriteLine (pd.test);
432                                         p.Kill ();
433                                         DumpFile (pd.stdoutFile);
434                                         DumpFile (pd.stderrFile);
435                                 }
436                         }
437                         return 1;
438                 }
439
440                 Console.WriteLine ("" + npassed + " test(s) passed. " + nfailed + " test(s) did not pass.");
441                 if (nfailed > 0) {
442                         Console.WriteLine ("\nFailed tests:\n");
443                         foreach (ProcessData pd in failed) {
444                                 Console.WriteLine (pd.test);
445                                 DumpFile (pd.stdoutFile);
446                                 DumpFile (pd.stderrFile);
447                         }
448                         return 1;
449                 } else {
450                         return 0;
451                 }
452         }
453         
454         static void DumpFile (string filename) {
455                 if (File.Exists (filename)) {
456                         Console.WriteLine ("=============== {0} ===============", filename);
457                         Console.WriteLine (File.ReadAllText (filename));
458                         Console.WriteLine ("=============== EOF ===============");
459                 }
460         }
461
462         static string DumpPseudoTrace (string filename) {
463                 if (File.Exists (filename))
464                         return File.ReadAllText (filename);
465                 else
466                         return string.Empty;
467         }
468 }