Merge pull request #853 from echampet/onclick
[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                         p.EnableRaisingEvents = true;
205
206                         ProcessData data = new ProcessData ();
207                         data.test = test;
208
209                         p.Exited += delegate (object sender, EventArgs e) {
210                                 // Anon methods share some of their state, so we can't use
211                                 // variables which change during the loop (test, p)
212                                 Process dead = (Process)sender;
213
214                                 lock (monitor) {
215                                         if (dead.ExitCode == 0) {
216                                                 if (concurrency == 1)
217                                                         Console.WriteLine ("passed.");
218                                                 else
219                                                         Console.Write (".");
220                                                 passed.Add(process_data [dead]);
221                                                 npassed ++;
222                                         } else {
223                                                 if (concurrency == 1)
224                                                         Console.WriteLine ("failed.");
225                                                 else
226                                                         Console.Write ("F");
227                                                 failed.Add (process_data [dead]);
228                                                 nfailed ++;
229                                         }
230                                         processes.Remove (dead);
231                                         terminated.Add (dead);
232                                         Monitor.Pulse (monitor);
233                                 }
234                         };
235
236                         string log_prefix = "";
237                         if (opt_set != null)
238                                 log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
239
240                         data.stdoutFile = test + log_prefix + ".stdout";
241                         data.stdout = new StreamWriter (new FileStream (data.stdoutFile, FileMode.Create));
242
243                         data.stderrFile = test + log_prefix + ".stderr";
244                         data.stderr = new StreamWriter (new FileStream (data.stderrFile, FileMode.Create));
245
246                         p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
247                                 Process p2 = (Process)sender;
248
249                                 StreamWriter fs;
250
251                                 lock (monitor) {
252                                         fs = process_data [p2].stdout;
253
254                                         if (String.IsNullOrEmpty (e.Data))
255                                                 process_data [p2].stdout = null;
256                                 }
257
258                                 if (String.IsNullOrEmpty (e.Data)) {
259                                         fs.Close ();
260                                 } else {
261                                         fs.WriteLine (e.Data);
262                                         fs.Flush ();
263                                 }
264                         };
265
266                         p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e) {
267                                 Process p2 = (Process)sender;
268
269                                 StreamWriter fs;
270
271                                 lock (monitor) {
272                                         fs = process_data [p2].stderr;
273
274                                         if (String.IsNullOrEmpty (e.Data))
275                                                 process_data [p2].stderr = null;
276
277                                 }
278
279                                 if (String.IsNullOrEmpty (e.Data)) {
280                                         fs.Close ();
281
282                                         lock (monitor) {
283                                                 process_data [p2].stderr = null;
284                                         }
285                                 } else {
286                                         fs.WriteLine (e.Data);
287                                         fs.Flush ();
288                                 }
289                         };
290
291                         lock (monitor) {
292                                 processes.Add (p);
293                                 process_data [p] = data;
294                         }
295                         p.Start ();
296
297                         p.BeginOutputReadLine ();
298                         p.BeginErrorReadLine ();
299                 }
300
301                 bool timed_out = false;
302
303                 /* Wait for all processes to terminate */
304                 while (true) {
305                         lock (monitor) {
306                                 int nprocesses = processes.Count;
307
308                                 if (nprocesses == 0)
309                                         break;
310
311                                 bool res = Monitor.Wait (monitor, 1000 * timeout);
312                                 if (!res) {
313                                         timed_out = true;
314                                         break;
315                                 }
316                         }
317                 }
318
319                 TimeSpan test_time = DateTime.UtcNow - test_start_time;
320                 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings ();
321                 xmlWriterSettings.NewLineOnAttributes = true;
322                 xmlWriterSettings.Indent = true;
323                 using (XmlWriter writer = XmlWriter.Create ("TestResults_runtime.xml", xmlWriterSettings)) {
324                         // <?xml version="1.0" encoding="utf-8" standalone="no"?>
325                         writer.WriteStartDocument ();
326                         // <!--This file represents the results of running a test suite-->
327                         writer.WriteComment ("This file represents the results of running a test suite");
328                         // <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">
329                         writer.WriteStartElement ("test-results");
330                         writer.WriteAttributeString ("name", "runtime-tests.dummy");
331                         writer.WriteAttributeString ("total", (npassed + nfailed).ToString());
332                         writer.WriteAttributeString ("failures", nfailed.ToString());
333                         writer.WriteAttributeString ("not-run", "0");
334                         writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
335                         writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
336                         //   <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" />
337                         writer.WriteStartElement ("environment");
338                         writer.WriteAttributeString ("nunit-version", "2.4.8.0" );
339                         writer.WriteAttributeString ("clr-version", Environment.Version.ToString() );
340                         writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString() );
341                         writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString() );
342                         writer.WriteAttributeString ("cwd", Environment.CurrentDirectory );
343                         writer.WriteAttributeString ("machine-name", Environment.MachineName );
344                         writer.WriteAttributeString ("user", Environment.UserName );
345                         writer.WriteAttributeString ("user-domain", Environment.UserDomainName );
346                         writer.WriteEndElement ();
347                         //   <culture-info current-culture="en-GB" current-uiculture="en-GB" />
348                         writer.WriteStartElement ("culture-info");
349                         writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name );
350                         writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name );
351                         writer.WriteEndElement ();
352                         //   <test-suite name="corlib_test_net_4_5.dll" success="True" time="114.318" asserts="0">
353                         writer.WriteStartElement ("test-suite");
354                         writer.WriteAttributeString ("name","runtime-tests.dummy");
355                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
356                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
357                         writer.WriteAttributeString ("asserts", nfailed.ToString());
358                         //     <results>
359                         writer.WriteStartElement ("results");
360                         //       <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
361                         writer.WriteStartElement ("test-suite");
362                         writer.WriteAttributeString ("name","MonoTests");
363                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
364                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
365                         writer.WriteAttributeString ("asserts", nfailed.ToString());
366                         //         <results>
367                         writer.WriteStartElement ("results");
368                         //           <test-suite name="MonoTests" success="True" time="114.318" asserts="0">
369                         writer.WriteStartElement ("test-suite");
370                         writer.WriteAttributeString ("name","runtime");
371                         writer.WriteAttributeString ("success", (nfailed == 0).ToString());
372                         writer.WriteAttributeString ("time", test_time.Seconds.ToString());
373                         writer.WriteAttributeString ("asserts", nfailed.ToString());
374                         //             <results>
375                         writer.WriteStartElement ("results");
376                         // Dump all passing tests first
377                         foreach (ProcessData pd in passed) {
378                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
379                                 writer.WriteStartElement ("test-case");
380                                 writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
381                                 writer.WriteAttributeString ("executed", "True");
382                                 writer.WriteAttributeString ("success", "True");
383                                 writer.WriteAttributeString ("time", "0");
384                                 writer.WriteAttributeString ("asserts", "0");
385                                 writer.WriteEndElement ();
386                         }
387                         // Now dump all failing tests
388                         foreach (ProcessData pd in failed) {
389                                 // <test-case name="MonoTests.Microsoft.Win32.RegistryKeyTest.bug79051" executed="True" success="True" time="0.063" asserts="0" />
390                                 writer.WriteStartElement ("test-case");
391                                 writer.WriteAttributeString ("name", "MonoTests.runtime." + pd.test);
392                                 writer.WriteAttributeString ("executed", "True");
393                                 writer.WriteAttributeString ("success", "False");
394                                 writer.WriteAttributeString ("time", "0");
395                                 writer.WriteAttributeString ("asserts", "1");
396                                 writer.WriteStartElement ("failure");
397                                 writer.WriteStartElement ("message");
398                                 writer.WriteCData (DumpPseudoTrace (pd.stdoutFile));
399                                 writer.WriteEndElement ();
400                                 writer.WriteStartElement ("stack-trace");
401                                 writer.WriteCData (DumpPseudoTrace (pd.stderrFile));
402                                 writer.WriteEndElement ();
403                                 writer.WriteEndElement ();
404                                 writer.WriteEndElement ();
405                         }
406                         //             </results>
407                         writer.WriteEndElement ();
408                         //           </test-suite>
409                         writer.WriteEndElement ();
410                         //         </results>
411                         writer.WriteEndElement ();
412                         //       </test-suite>
413                         writer.WriteEndElement ();
414                         //     </results>
415                         writer.WriteEndElement ();
416                         //   </test-suite>
417                         writer.WriteEndElement ();
418                         // </test-results>
419                         writer.WriteEndElement ();
420                         writer.WriteEndDocument ();
421                 }
422
423                 Console.WriteLine ();
424
425                 if (timed_out) {
426                         Console.WriteLine ("\nrunning tests timed out:\n");
427                         Console.WriteLine (npassed + nfailed);
428                         lock (monitor) {
429                                 foreach (Process p in processes) {
430                                         ProcessData pd = process_data [p];
431                                         pd.CloseStreams ();
432                                         Console.WriteLine (pd.test);
433                                         p.Kill ();
434                                         DumpFile (pd.stdoutFile);
435                                         DumpFile (pd.stderrFile);
436                                 }
437                         }
438                         return 1;
439                 }
440
441                 Console.WriteLine ("" + npassed + " test(s) passed. " + nfailed + " test(s) did not pass.");
442                 if (nfailed > 0) {
443                         Console.WriteLine ("\nFailed tests:\n");
444                         foreach (ProcessData pd in failed) {
445                                 Console.WriteLine (pd.test);
446                                 DumpFile (pd.stdoutFile);
447                                 DumpFile (pd.stderrFile);
448                         }
449                         return 1;
450                 } else {
451                         return 0;
452                 }
453         }
454         
455         static void DumpFile (string filename) {
456                 if (File.Exists (filename)) {
457                         Console.WriteLine ("=============== {0} ===============", filename);
458                         Console.WriteLine (File.ReadAllText (filename));
459                         Console.WriteLine ("=============== EOF ===============");
460                 }
461         }
462
463         static string DumpPseudoTrace (string filename) {
464                 if (File.Exists (filename))
465                         return File.ReadAllText (filename);
466                 else
467                         return string.Empty;
468         }
469 }