3 using System.Diagnostics;
4 using System.Reflection;
6 using System.Collections;
12 string Output { get; }
13 bool Invoke (string[] args);
14 bool IsWarning (int warningNumber);
17 class ReflectionTester: ITester {
23 public ReflectionTester (Assembly a)
25 Type t = a.GetType ("Mono.CSharp.CompilerCallableEntryPoint");
26 ep = t.GetMethod ("InvokeCompiler",
27 BindingFlags.Static | BindingFlags.Public);
29 throw new MissingMethodException ("static InvokeCompiler");
30 method_arg = new object [2];
32 PropertyInfo pi = t.GetProperty ("AllWarningNumbers");
33 all_warnings = (int[])pi.GetValue (null, null);
34 Array.Sort (all_warnings);
37 public string Output {
39 return output.GetStringBuilder ().ToString ();
43 public bool Invoke(string[] args)
45 output = new StringWriter ();
46 method_arg [0] = args;
47 method_arg [1] = output;
48 return (bool)ep.Invoke (null, method_arg);
51 public bool IsWarning (int warningNumber)
53 return Array.BinarySearch (all_warnings, warningNumber) >= 0;
57 class ProcessTester: ITester
62 public ProcessTester (string p_path)
64 pi = new ProcessStartInfo ();
66 pi.CreateNoWindow = true;
67 pi.WindowStyle = ProcessWindowStyle.Hidden;
68 pi.RedirectStandardOutput = true;
69 pi.RedirectStandardError = true;
70 pi.UseShellExecute = false;
73 public string Output {
79 public bool Invoke(string[] args)
81 StringBuilder sb = new StringBuilder ("/nologo ");
82 foreach (string s in args) {
86 pi.Arguments = sb.ToString ();
87 Process p = Process.Start (pi);
88 output = p.StandardError.ReadToEnd ();
89 if (output.Length == 0)
90 output = p.StandardOutput.ReadToEnd ();
92 return p.ExitCode == 0;
95 public bool IsWarning (int warningNumber)
97 throw new NotImplementedException ();
103 public readonly string FileName;
104 public readonly string[] CompilerOptions;
105 public readonly string[] Dependencies;
107 public TestCase (string filename, string[] options, string[] deps)
109 this.FileName = filename;
110 this.CompilerOptions = options;
111 this.Dependencies = deps;
115 class Checker: IDisposable
117 protected ITester tester;
118 protected int success;
120 protected int ignored;
122 StreamWriter log_file;
123 // protected string[] compiler_options;
124 // protected string[] dependencies;
126 protected ArrayList tests = new ArrayList ();
127 protected Hashtable test_hash = new Hashtable ();
128 protected ArrayList regression = new ArrayList ();
129 protected ArrayList know_issues = new ArrayList ();
130 protected ArrayList ignore_list = new ArrayList ();
131 protected ArrayList no_error_list = new ArrayList ();
133 int total_known_issues;
135 protected Checker (ITester tester, string log_file, string issue_file)
137 this.tester = tester;
138 this.issue_file = issue_file;
139 ReadWrongErrors (issue_file);
140 this.log_file = new StreamWriter (log_file, false);
143 protected virtual bool GetExtraOptions (string file, out string[] compiler_options,
144 out string[] dependencies)
147 compiler_options = null;
150 using (StreamReader sr = new StreamReader (file)) {
152 while (row++ < 3 && (line = sr.ReadLine()) != null) {
153 if (!AnalyzeTestFile (ref row, line, ref compiler_options,
164 protected virtual bool AnalyzeTestFile (ref int row, string line,
165 ref string[] compiler_options,
166 ref string[] dependencies)
168 const string options = "// Compiler options:";
169 const string depends = "// Dependencies:";
172 compiler_options = null;
176 int index = line.IndexOf (options);
178 compiler_options = line.Substring (index + options.Length).Trim().Split (' ');
179 for (int i = 0; i < compiler_options.Length; i++)
180 compiler_options[i] = compiler_options[i].TrimStart ();
182 index = line.IndexOf (depends);
184 dependencies = line.Substring (index + depends.Length).Trim().Split (' ');
185 for (int i = 0; i < dependencies.Length; i++)
186 dependencies[i] = dependencies[i].TrimStart ();
192 public bool Do (string filename)
194 if (test_hash.Contains (filename))
197 if (ignore_list.Contains (filename)) {
199 LogLine (filename + "...\tNOT TESTED");
203 string[] compiler_options, dependencies;
204 if (!GetExtraOptions (filename, out compiler_options, out dependencies)) {
205 LogLine (filename + "...\tERROR");
209 TestCase test = new TestCase (filename, compiler_options, dependencies);
210 test_hash.Add (filename, test);
213 if (dependencies != null) {
214 foreach (string dependency in dependencies) {
215 if (!Do (dependency)) {
216 LogLine (filename + "...\tDEPENDENCY FAILED");
230 protected virtual bool Check (TestCase test)
234 if (test.CompilerOptions != null) {
235 test_args = new string [1 + test.CompilerOptions.Length];
236 test.CompilerOptions.CopyTo (test_args, 0);
238 test_args = new string [1];
240 test_args [test_args.Length - 1] = test.FileName;
242 return tester.Invoke (test_args);
246 void ReadWrongErrors (string file)
248 const string ignored = "IGNORE";
249 const string no_error = "NO ERROR";
251 using (StreamReader sr = new StreamReader (file)) {
253 while ((line = sr.ReadLine()) != null) {
254 if (line.StartsWith ("#"))
257 ArrayList active_cont = know_issues;
259 if (line.IndexOf (ignored) > 0)
260 active_cont = ignore_list;
261 else if (line.IndexOf (no_error) > 0)
262 active_cont = no_error_list;
264 string file_name = line.Split (' ')[0];
265 if (file_name.Length == 0)
268 active_cont.Add (file_name);
271 total_known_issues = know_issues.Count;
274 public virtual void PrintSummary ()
276 LogLine ("Done" + Environment.NewLine);
277 LogLine ("{0} test cases passed ({1:.##%})", success, (float) (success) / (float)total);
280 LogLine ("{0} test cases ignored", ignored);
282 if (total_known_issues - know_issues.Count > 0)
283 LogLine ("{0} known issues", total_known_issues - know_issues.Count);
285 know_issues.AddRange (no_error_list);
286 if (know_issues.Count > 0) {
288 LogLine (issue_file + " contains {0} already fixed issues. Please remove", know_issues.Count);
289 foreach (string s in know_issues)
292 if (regression.Count > 0) {
294 LogLine ("The latest changes caused regression in {0} file(s)", regression.Count);
295 foreach (string s in regression)
300 public int ResultCode
303 return regression.Count == 0 ? 0 : 1;
307 protected void Log (string msg, params object [] rest)
309 Console.Write (msg, rest);
310 log_file.Write (msg, rest);
313 protected void LogLine (string msg, params object [] rest)
315 Console.WriteLine (msg, rest);
316 log_file.WriteLine (msg, rest);
319 #region IDisposable Members
321 public void Dispose()
329 class PositiveChecker: Checker {
330 readonly string files_folder;
331 readonly static object[] default_args = new object[1] { new string[] {} };
334 // When we cannot load assembly to domain we are automaticaly switching to process calling
335 bool appdomain_limit_reached;
338 readonly string mono;
340 // This is really pain
341 // This number is highly experimental on my box I am not able to load more than 1000 files to domain
342 // Every files is there twice and we need some space for tests which reference assemblies
343 const int MAX_TESTS_IN_DOMAIN = 420;
346 protected enum TestResult {
354 public PositiveChecker (ITester tester, string log_file, string issue_file):
355 base (tester, log_file, issue_file)
357 files_folder = Directory.GetCurrentDirectory ();
359 pi = new ProcessStartInfo ();
360 pi.CreateNoWindow = true;
361 pi.WindowStyle = ProcessWindowStyle.Hidden;
362 pi.RedirectStandardOutput = true;
363 pi.RedirectStandardError = true;
364 pi.UseShellExecute = false;
366 mono = Environment.GetEnvironmentVariable ("MONO_RUNTIME");
372 protected override bool GetExtraOptions(string file, out string[] compiler_options,
373 out string[] dependencies) {
374 if (!base.GetExtraOptions (file, out compiler_options, out dependencies))
378 if (compiler_options == null)
381 foreach (string one_opt in compiler_options) {
382 if (one_opt.StartsWith ("-doc:")) {
383 doc_output = one_opt.Split (':')[1];
389 protected override bool Check(TestCase test)
391 string filename = test.FileName;
393 if (!base.Check (test)) {
394 HandleFailure (filename, TestResult.CompileError, tester.Output);
398 catch (Exception e) {
399 HandleFailure (filename, TestResult.CompileError, e.ToString ());
404 if (filename.EndsWith ("-lib.cs") || filename.EndsWith ("-mod.cs")) {
410 MethodInfo mi = null;
411 string file = Path.Combine (files_folder, Path.GetFileNameWithoutExtension (filename) + ".exe");
412 if (!appdomain_limit_reached) {
414 mi = Assembly.LoadFile (file).EntryPoint;
415 if (test_counter++ > MAX_TESTS_IN_DOMAIN)
416 appdomain_limit_reached = true;
418 catch (FileNotFoundException) {
419 if (File.Exists (file)) {
420 Console.WriteLine ("APPDOMAIN LIMIT REACHED");
421 appdomain_limit_reached = true;
424 catch (Exception e) {
425 HandleFailure (filename, TestResult.LoadError, e.ToString ());
430 if (appdomain_limit_reached) {
431 if (!ExecuteFile (file, filename))
434 if (!ExecuteFile (mi, file, filename))
438 if (doc_output != null) {
439 string ref_file = filename.Replace (".cs", "-ref.xml");
441 XmlComparer.Compare (ref_file, doc_output);
443 catch (Exception e) {
444 HandleFailure (filename, TestResult.XmlError, e.Message);
449 HandleFailure (filename, TestResult.Success, null);
453 int ExecFile (string exe_name, string filename)
456 pi.FileName = exe_name;
458 pi.Arguments = exe_name;
460 Process p = Process.Start (pi);
465 bool ExecuteFile (string exe_name, string filename)
467 int exit_code = ExecFile (exe_name, filename);
471 HandleFailure (filename, TestResult.ExecError, "Wrong return code: " + exit_code);
475 bool ExecuteFile (MethodInfo entry_point, string exe_name, string filename)
477 TextWriter stdout = Console.Out;
478 TextWriter stderr = Console.Error;
479 Console.SetOut (TextWriter.Null);
480 Console.SetError (TextWriter.Null);
481 ParameterInfo[] pi = entry_point.GetParameters ();
482 object[] args = pi.Length == 0 ? null : default_args;
484 object result = null;
487 result = entry_point.Invoke (null, args);
489 Console.SetOut (stdout);
490 Console.SetError (stderr);
493 catch (Exception e) {
494 int exit_code = ExecFile (exe_name, filename);
495 if (exit_code == 0) {
496 LogLine ("(appdomain method failed, external executable succeeded)");
497 LogLine (e.ToString ());
500 HandleFailure (filename, TestResult.ExecError, e.ToString ());
504 if (result is int && (int)result != 0) {
505 HandleFailure (filename, TestResult.ExecError, "Wrong return code: " + result.ToString ());
511 void HandleFailure (string file, TestResult status, string extra)
514 case TestResult.Success:
516 if (know_issues.Contains (file)) {
517 LogLine ("FIXED ISSUE");
523 case TestResult.CompileError:
524 if (know_issues.Contains (file)) {
525 LogLine ("KNOWN ISSUE (Compilation error)");
526 know_issues.Remove (file);
529 LogLine ("REGRESSION (SUCCESS -> COMPILATION ERROR)");
532 case TestResult.ExecError:
533 if (know_issues.Contains (file)) {
534 LogLine ("KNOWN ISSUE (Execution error)");
535 know_issues.Remove (file);
538 LogLine ("REGRESSION (SUCCESS -> EXECUTION ERROR)");
541 case TestResult.XmlError:
542 if (know_issues.Contains (file)) {
543 LogLine ("KNOWN ISSUE (Xml comparision error)");
544 know_issues.Remove (file);
547 LogLine ("REGRESSION (SUCCESS -> DOCUMENTATION ERROR)");
550 case TestResult.LoadError:
551 LogLine ("REGRESSION (SUCCESS -> LOAD ERROR)");
558 regression.Add (file);
562 class NegativeChecker: Checker
564 string expected_message;
565 string error_message;
567 bool check_error_line;
569 IDictionary wrong_warning;
571 protected enum CompilerError {
580 public NegativeChecker (ITester tester, string log_file, string issue_file, bool check_msg):
581 base (tester, log_file, issue_file)
583 this.check_msg = check_msg;
584 wrong_warning = new Hashtable ();
587 protected override bool AnalyzeTestFile (ref int row, string line,
588 ref string[] compiler_options,
589 ref string[] dependencies)
592 expected_message = null;
594 int index = line.IndexOf (':');
595 if (index == -1 || index > 15) {
596 LogLine ("IGNORING: Wrong test file syntax (missing error mesage text)");
598 base.AnalyzeTestFile (ref row, line, ref compiler_options,
603 expected_message = line.Substring (index + 1).Trim ();
607 string filtered = line.Replace(" ", "");
609 // Some error tests require to have different error text for different runtimes.
610 if (filtered.StartsWith ("//GMCS")) {
615 return AnalyzeTestFile(ref row, line, ref compiler_options, ref dependencies);
619 check_error_line = !filtered.StartsWith ("//Line:0");
621 if (!filtered.StartsWith ("//Line:")) {
622 LogLine ("IGNORING: Wrong test syntax (following line after an error messsage must have `// Line: xx' syntax");
628 if (!base.AnalyzeTestFile (ref row, line, ref compiler_options, ref dependencies))
632 if (compiler_options != null) {
633 foreach (string s in compiler_options) {
634 if (s.EndsWith ("warnaserror"))
642 protected override bool Check (TestCase test)
644 string filename = test.FileName;
647 while (Char.IsLetter (filename, start_char))
650 int end_char = filename.IndexOfAny (new char [] { '-', '.' } );
651 string expected = filename.Substring (start_char, end_char - start_char);
654 if (base.Check (test)) {
655 HandleFailure (filename, CompilerError.Missing);
659 catch (Exception e) {
660 HandleFailure (filename, CompilerError.Missing);
665 int err_id = int.Parse (expected, System.Globalization.CultureInfo.InvariantCulture);
666 if (tester.IsWarning (err_id)) {
668 wrong_warning [err_id] = true;
671 wrong_warning [err_id] = false;
674 CompilerError result_code = GetCompilerError (expected, tester.Output);
675 if (HandleFailure (filename, result_code)) {
680 if (result_code == CompilerError.Wrong)
681 LogLine (tester.Output);
686 CompilerError GetCompilerError (string expected, string buffer)
688 const string error_prefix = "CS";
689 const string ignored_error = "error CS5001";
690 string tested_text = "error " + error_prefix + expected;
691 StringReader sr = new StringReader (buffer);
692 string line = sr.ReadLine ();
693 ArrayList ld = new ArrayList ();
694 CompilerError result = CompilerError.Missing;
695 while (line != null) {
696 if (ld.Contains (line)) {
697 if (line.IndexOf ("Location of the symbol related to previous") == -1)
698 return CompilerError.Duplicate;
702 if (result != CompilerError.Expected) {
703 if (line.IndexOf (tested_text) != -1) {
705 int first = line.IndexOf (':');
706 int second = line.IndexOf (':', first + 1);
707 if (second == -1 || !check_error_line)
710 string msg = line.Substring (second + 1).TrimEnd ('.').Trim ();
711 if (msg != expected_message && msg != expected_message.Replace ('`', '\'')) {
713 return CompilerError.WrongMessage;
716 if (check_error_line && line.IndexOf (".cs(") == -1)
717 return CompilerError.MissingLocation;
719 result = CompilerError.Expected;
720 } else if (line.IndexOf (error_prefix) != -1 &&
721 line.IndexOf (ignored_error) == -1)
722 result = CompilerError.Wrong;
725 line = sr.ReadLine ();
731 bool HandleFailure (string file, CompilerError status)
734 case CompilerError.Expected:
735 if (know_issues.Contains (file) || no_error_list.Contains (file)) {
736 LogLine ("FIXED ISSUE");
742 case CompilerError.Wrong:
743 if (know_issues.Contains (file)) {
744 LogLine ("KNOWN ISSUE (Wrong error reported)");
745 know_issues.Remove (file);
748 if (no_error_list.Contains (file)) {
749 LogLine ("REGRESSION (NO ERROR -> WRONG ERROR CODE)");
750 no_error_list.Remove (file);
753 LogLine ("REGRESSION (CORRECT ERROR -> WRONG ERROR CODE)");
757 case CompilerError.WrongMessage:
758 if (know_issues.Contains (file)) {
759 LogLine ("KNOWN ISSUE (Wrong error message reported)");
760 know_issues.Remove (file);
763 if (no_error_list.Contains (file)) {
764 LogLine ("REGRESSION (NO ERROR -> WRONG ERROR MESSAGE)");
765 no_error_list.Remove (file);
768 LogLine ("REGRESSION (CORRECT ERROR -> WRONG ERROR MESSAGE)");
769 LogLine ("Exp: {0}", expected_message);
770 LogLine ("Was: {0}", error_message);
774 case CompilerError.Missing:
775 if (no_error_list.Contains (file)) {
776 LogLine ("KNOWN ISSUE (No error reported)");
777 no_error_list.Remove (file);
781 if (know_issues.Contains (file)) {
782 LogLine ("REGRESSION (WRONG ERROR -> NO ERROR)");
783 know_issues.Remove (file);
786 LogLine ("REGRESSION (CORRECT ERROR -> NO ERROR)");
791 case CompilerError.MissingLocation:
792 if (know_issues.Contains (file)) {
793 LogLine ("KNOWN ISSUE (Missing error location)");
794 know_issues.Remove (file);
797 if (no_error_list.Contains (file)) {
798 LogLine ("REGRESSION (NO ERROR -> MISSING ERROR LOCATION)");
799 no_error_list.Remove (file);
802 LogLine ("REGRESSION (CORRECT ERROR -> MISSING ERROR LOCATION)");
806 case CompilerError.Duplicate:
807 // Will become an error soon
808 LogLine("WARNING: EXACTLY SAME ERROR HAS BEEN ISSUED MULTIPLE TIMES");
812 regression.Add (file);
816 public override void PrintSummary()
818 base.PrintSummary ();
820 if (wrong_warning.Count > 0) {
822 LogLine ("List of incorectly defined warnings (they should be either defined in the compiler as a warning or a test-case has redundant `warnaserror' option)");
824 foreach (DictionaryEntry de in wrong_warning)
825 LogLine ("CS{0:0000} : {1}", de.Key, (bool)de.Value ? "incorrect warning definition" : "missing warning definition");
833 static int Main(string[] args) {
834 if (args.Length != 5) {
835 Console.Error.WriteLine ("Usage: TestRunner [negative|positive] test-pattern compiler know-issues log-file");
839 string mode = args[0].ToLower ();
841 string test_pattern = args [1] == "0" ? "*cs*.cs" : "*test-*.cs"; //args [1];
843 string test_pattern = args [1] == "0" ? "cs*.cs" : "test-*.cs"; //args [1];
845 string mcs = args [2];
846 string issue_file = args [3];
847 string log_fname = args [4];
849 string[] files = Directory.GetFiles (".", test_pattern);
853 Console.WriteLine ("Loading: " + mcs);
854 tester = new ReflectionTester (Assembly.LoadFile (mcs));
857 Console.Error.WriteLine ("Switching to command line mode (compiler entry point was not found)");
858 if (!File.Exists (mcs)) {
859 Console.Error.WriteLine ("ERROR: Tested compiler was not found");
862 tester = new ProcessTester (mcs);
868 checker = new NegativeChecker (tester, log_fname, issue_file, true);
871 checker = new PositiveChecker (tester, log_fname, issue_file);
874 Console.Error.WriteLine ("You must specify testing mode (positive or negative)");
878 foreach (string s in files) {
879 string filename = Path.GetFileName (s);
880 if (Char.IsUpper (filename, 0)) { // Windows hack
884 if (filename.EndsWith ("-p2.cs"))
887 checker.Do (filename);
890 checker.PrintSummary ();
894 return checker.ResultCode;