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;
121 protected int syntax_errors;
123 StreamWriter log_file;
124 // protected string[] compiler_options;
125 // protected string[] dependencies;
127 protected ArrayList tests = new ArrayList ();
128 protected Hashtable test_hash = new Hashtable ();
129 protected ArrayList regression = new ArrayList ();
130 protected ArrayList know_issues = new ArrayList ();
131 protected ArrayList ignore_list = new ArrayList ();
132 protected ArrayList no_error_list = new ArrayList ();
134 protected bool verbose;
136 int total_known_issues;
138 protected Checker (ITester tester, string log_file, string issue_file)
140 this.tester = tester;
141 this.issue_file = issue_file;
142 ReadWrongErrors (issue_file);
143 this.log_file = new StreamWriter (log_file, false);
146 protected virtual bool GetExtraOptions (string file, out string[] compiler_options,
147 out string[] dependencies)
150 compiler_options = null;
153 using (StreamReader sr = new StreamReader (file)) {
155 while (row++ < 3 && (line = sr.ReadLine()) != null) {
156 if (!AnalyzeTestFile (file, ref row, line, ref compiler_options,
167 protected virtual bool AnalyzeTestFile (string file, ref int row, string line,
168 ref string[] compiler_options,
169 ref string[] dependencies)
171 const string options = "// Compiler options:";
172 const string depends = "// Dependencies:";
175 compiler_options = null;
179 int index = line.IndexOf (options);
181 compiler_options = line.Substring (index + options.Length).Trim().Split (' ');
182 for (int i = 0; i < compiler_options.Length; i++)
183 compiler_options[i] = compiler_options[i].TrimStart ();
185 index = line.IndexOf (depends);
187 dependencies = line.Substring (index + depends.Length).Trim().Split (' ');
188 for (int i = 0; i < dependencies.Length; i++)
189 dependencies[i] = dependencies[i].TrimStart ();
195 public bool Do (string filename)
197 if (test_hash.Contains (filename))
200 if (ignore_list.Contains (filename)) {
202 LogFileLine (filename, "NOT TESTED");
206 string[] compiler_options, dependencies;
207 if (!GetExtraOptions (filename, out compiler_options, out dependencies)) {
208 LogFileLine (filename, "ERROR");
212 TestCase test = new TestCase (filename, compiler_options, dependencies);
213 test_hash.Add (filename, test);
216 if (dependencies != null) {
217 foreach (string dependency in dependencies) {
218 if (!Do (dependency)) {
219 LogFileLine (filename, "DEPENDENCY FAILED");
235 protected virtual bool Check (TestCase test)
239 if (test.CompilerOptions != null) {
240 test_args = new string [1 + test.CompilerOptions.Length];
241 test.CompilerOptions.CopyTo (test_args, 0);
243 test_args = new string [1];
245 test_args [test_args.Length - 1] = test.FileName;
247 return tester.Invoke (test_args);
251 void ReadWrongErrors (string file)
253 const string ignored = "IGNORE";
254 const string no_error = "NO ERROR";
256 using (StreamReader sr = new StreamReader (file)) {
258 while ((line = sr.ReadLine()) != null) {
259 if (line.StartsWith ("#"))
262 ArrayList active_cont = know_issues;
264 if (line.IndexOf (ignored) > 0)
265 active_cont = ignore_list;
266 else if (line.IndexOf (no_error) > 0)
267 active_cont = no_error_list;
269 string file_name = line.Split (' ')[0];
270 if (file_name.Length == 0)
273 active_cont.Add (file_name);
276 total_known_issues = know_issues.Count;
279 public virtual void PrintSummary ()
281 LogLine ("Done" + Environment.NewLine);
282 LogLine ("{0} test cases passed ({1:.##%})", success, (float) (success) / (float)total);
284 if (syntax_errors > 0)
285 LogLine ("{0} test(s) ignored because of wrong syntax !", syntax_errors);
288 LogLine ("{0} test(s) ignored", ignored);
290 if (total_known_issues - know_issues.Count > 0)
291 LogLine ("{0} known issue(s)", total_known_issues - know_issues.Count);
293 know_issues.AddRange (no_error_list);
294 if (know_issues.Count > 0) {
296 LogLine (issue_file + " contains {0} already fixed issues. Please remove", know_issues.Count);
297 foreach (string s in know_issues)
300 if (regression.Count > 0) {
302 LogLine ("The latest changes caused regression in {0} file(s)", regression.Count);
303 foreach (string s in regression)
308 public int ResultCode
311 return regression.Count == 0 ? 0 : 1;
315 protected void Log (string msg, params object [] rest)
317 Console.Write (msg, rest);
318 log_file.Write (msg, rest);
321 protected void LogLine (string msg, params object [] rest)
323 Console.WriteLine (msg, rest);
324 log_file.WriteLine (msg, rest);
327 protected void LogFileLine (string file, string msg, params object [] args)
329 string s = file + "...\t" + string.Format (msg, args);
330 Console.WriteLine (s);
331 log_file.WriteLine (s);
334 #region IDisposable Members
336 public void Dispose()
344 class PositiveChecker: Checker
346 readonly string files_folder;
347 readonly static object[] default_args = new object[1] { new string[] {} };
351 readonly string mono;
353 protected enum TestResult {
361 public PositiveChecker (ITester tester, string log_file, string issue_file):
362 base (tester, log_file, issue_file)
364 files_folder = Directory.GetCurrentDirectory ();
366 pi = new ProcessStartInfo ();
367 pi.CreateNoWindow = true;
368 pi.WindowStyle = ProcessWindowStyle.Hidden;
369 pi.RedirectStandardOutput = true;
370 pi.RedirectStandardError = true;
371 pi.UseShellExecute = false;
373 mono = Environment.GetEnvironmentVariable ("MONO_RUNTIME");
379 protected override bool GetExtraOptions(string file, out string[] compiler_options,
380 out string[] dependencies) {
381 if (!base.GetExtraOptions (file, out compiler_options, out dependencies))
385 if (compiler_options == null)
388 foreach (string one_opt in compiler_options) {
389 if (one_opt.StartsWith ("-doc:")) {
390 doc_output = one_opt.Split (':')[1];
396 protected override bool Check(TestCase test)
398 string filename = test.FileName;
400 if (!base.Check (test)) {
401 HandleFailure (filename, TestResult.CompileError, tester.Output);
405 catch (Exception e) {
406 if (e.InnerException != null)
407 e = e.InnerException;
409 HandleFailure (filename, TestResult.CompileError, e.ToString ());
414 if (filename.EndsWith ("-lib.cs") || filename.EndsWith ("-mod.cs")) {
421 MethodInfo mi = null;
422 string file = Path.Combine (files_folder, Path.GetFileNameWithoutExtension (filename) + ".exe");
424 // Enable .dll only tests (no execution required)
425 if (!File.Exists(file)) {
426 HandleFailure (filename, TestResult.Success, null);
431 mi = Assembly.LoadFile (file).EntryPoint;
433 catch (FileNotFoundException) {
434 if (File.Exists (file)) {
435 Console.WriteLine ("APPDOMAIN LIMIT REACHED");
438 catch (Exception e) {
439 HandleFailure (filename, TestResult.LoadError, e.ToString ());
443 if (!ExecuteFile (mi, file, filename))
446 if (doc_output != null) {
447 string ref_file = filename.Replace (".cs", "-ref.xml");
450 XmlComparer.Compare (ref_file, doc_output);
453 catch (Exception e) {
454 HandleFailure (filename, TestResult.XmlError, e.Message);
459 HandleFailure (filename, TestResult.Success, null);
463 int ExecFile (string exe_name, string filename)
466 pi.FileName = exe_name;
468 pi.Arguments = exe_name;
470 Process p = Process.Start (pi);
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 LogFileLine (file, "FIXED ISSUE");
524 case TestResult.CompileError:
525 if (know_issues.Contains (file)) {
526 LogFileLine (file, "KNOWN ISSUE (Compilation error)");
527 know_issues.Remove (file);
530 LogFileLine (file, "REGRESSION (SUCCESS -> COMPILATION ERROR)");
533 case TestResult.ExecError:
534 if (know_issues.Contains (file)) {
535 LogFileLine (file, "KNOWN ISSUE (Execution error)");
536 know_issues.Remove (file);
539 LogFileLine (file, "REGRESSION (SUCCESS -> EXECUTION ERROR)");
542 case TestResult.XmlError:
543 if (know_issues.Contains (file)) {
544 LogFileLine (file, "KNOWN ISSUE (Xml comparision error)");
545 know_issues.Remove (file);
548 LogFileLine (file, "REGRESSION (SUCCESS -> DOCUMENTATION ERROR)");
551 case TestResult.LoadError:
552 LogFileLine (file, "REGRESSION (SUCCESS -> LOAD ERROR)");
557 LogLine ("{0}", extra);
559 regression.Add (file);
563 class NegativeChecker: Checker
565 string expected_message;
566 string error_message;
568 bool check_error_line;
570 IDictionary wrong_warning;
572 protected enum CompilerError {
581 public NegativeChecker (ITester tester, string log_file, string issue_file, bool check_msg):
582 base (tester, log_file, issue_file)
584 this.check_msg = check_msg;
585 wrong_warning = new Hashtable ();
588 protected override bool AnalyzeTestFile (string file, ref int row, string line,
589 ref string[] compiler_options,
590 ref string[] dependencies)
593 expected_message = null;
595 int index = line.IndexOf (':');
596 if (index == -1 || index > 15) {
597 LogFileLine (file, "IGNORING: Wrong test file syntax (missing error mesage text)");
599 base.AnalyzeTestFile (file, ref row, line, ref compiler_options,
604 expected_message = line.Substring (index + 1).Trim ();
608 string filtered = line.Replace(" ", "");
610 // Some error tests require to have different error text for different runtimes.
611 if (filtered.StartsWith ("//GMCS")) {
616 return AnalyzeTestFile(file, ref row, line, ref compiler_options, ref dependencies);
620 check_error_line = !filtered.StartsWith ("//Line:0");
622 if (!filtered.StartsWith ("//Line:")) {
623 LogFileLine (file, "IGNORING: Wrong test syntax (following line after an error messsage must have `// Line: xx' syntax");
629 if (!base.AnalyzeTestFile (file, ref row, line, ref compiler_options, ref dependencies))
633 if (compiler_options != null) {
634 foreach (string s in compiler_options) {
635 if (s.EndsWith ("warnaserror"))
643 protected override bool Check (TestCase test)
645 string filename = test.FileName;
648 while (Char.IsLetter (filename, start_char))
651 int end_char = filename.IndexOfAny (new char [] { '-', '.' } );
652 string expected = filename.Substring (start_char, end_char - start_char);
655 if (base.Check (test)) {
656 HandleFailure (filename, CompilerError.Missing);
660 catch (Exception e) {
661 HandleFailure (filename, CompilerError.Missing);
662 if (e.InnerException != null)
663 e = e.InnerException;
669 int err_id = int.Parse (expected, System.Globalization.CultureInfo.InvariantCulture);
670 if (tester.IsWarning (err_id)) {
672 wrong_warning [err_id] = true;
675 wrong_warning [err_id] = false;
678 CompilerError result_code = GetCompilerError (expected, tester.Output);
679 if (HandleFailure (filename, result_code)) {
684 if (result_code == CompilerError.Wrong)
685 LogLine (tester.Output);
690 CompilerError GetCompilerError (string expected, string buffer)
692 const string error_prefix = "CS";
693 const string ignored_error = "error CS5001";
694 string tested_text = "error " + error_prefix + expected;
695 StringReader sr = new StringReader (buffer);
696 string line = sr.ReadLine ();
697 ArrayList ld = new ArrayList ();
698 CompilerError result = CompilerError.Missing;
699 while (line != null) {
700 if (ld.Contains (line)) {
701 if (line.IndexOf ("Location of the symbol related to previous") == -1)
702 return CompilerError.Duplicate;
706 if (result != CompilerError.Expected) {
707 if (line.IndexOf (tested_text) != -1) {
709 int first = line.IndexOf (':');
710 int second = line.IndexOf (':', first + 1);
711 if (second == -1 || !check_error_line)
714 string msg = line.Substring (second + 1).TrimEnd ('.').Trim ();
715 if (msg != expected_message && msg != expected_message.Replace ('`', '\'')) {
717 return CompilerError.WrongMessage;
720 if (check_error_line && line.IndexOf (".cs(") == -1)
721 return CompilerError.MissingLocation;
723 result = CompilerError.Expected;
724 } else if (line.IndexOf (error_prefix) != -1 &&
725 line.IndexOf (ignored_error) == -1)
726 result = CompilerError.Wrong;
729 line = sr.ReadLine ();
735 bool HandleFailure (string file, CompilerError status)
738 case CompilerError.Expected:
739 if (know_issues.Contains (file) || no_error_list.Contains (file)) {
740 LogFileLine (file, "FIXED ISSUE");
748 case CompilerError.Wrong:
749 if (know_issues.Contains (file)) {
750 LogFileLine (file, "KNOWN ISSUE (Wrong error reported)");
751 know_issues.Remove (file);
754 if (no_error_list.Contains (file)) {
755 LogFileLine (file, "REGRESSION (NO ERROR -> WRONG ERROR CODE)");
756 no_error_list.Remove (file);
759 LogFileLine (file, "REGRESSION (CORRECT ERROR -> WRONG ERROR CODE)");
763 case CompilerError.WrongMessage:
764 if (know_issues.Contains (file)) {
765 LogFileLine (file, "KNOWN ISSUE (Wrong error message reported)");
766 know_issues.Remove (file);
769 if (no_error_list.Contains (file)) {
770 LogFileLine (file, "REGRESSION (NO ERROR -> WRONG ERROR MESSAGE)");
771 no_error_list.Remove (file);
774 LogFileLine (file, "REGRESSION (CORRECT ERROR -> WRONG ERROR MESSAGE)");
775 LogLine ("Exp: {0}", expected_message);
776 LogLine ("Was: {0}", error_message);
780 case CompilerError.Missing:
781 if (no_error_list.Contains (file)) {
782 LogFileLine (file, "KNOWN ISSUE (No error reported)");
783 no_error_list.Remove (file);
787 if (know_issues.Contains (file)) {
788 LogFileLine (file, "REGRESSION (WRONG ERROR -> NO ERROR)");
789 know_issues.Remove (file);
792 LogFileLine (file, "REGRESSION (CORRECT ERROR -> NO ERROR)");
797 case CompilerError.MissingLocation:
798 if (know_issues.Contains (file)) {
799 LogFileLine (file, "KNOWN ISSUE (Missing error location)");
800 know_issues.Remove (file);
803 if (no_error_list.Contains (file)) {
804 LogFileLine (file, "REGRESSION (NO ERROR -> MISSING ERROR LOCATION)");
805 no_error_list.Remove (file);
808 LogFileLine (file, "REGRESSION (CORRECT ERROR -> MISSING ERROR LOCATION)");
812 case CompilerError.Duplicate:
813 // Will become an error soon
814 LogFileLine (file, "WARNING: EXACTLY SAME ERROR HAS BEEN ISSUED MULTIPLE TIMES");
818 regression.Add (file);
822 public override void PrintSummary()
824 base.PrintSummary ();
826 if (wrong_warning.Count > 0) {
828 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)");
830 foreach (DictionaryEntry de in wrong_warning)
831 LogLine ("CS{0:0000} : {1}", de.Key, (bool)de.Value ? "incorrect warning definition" : "missing warning definition");
839 static int Main(string[] args) {
840 if (args.Length != 5) {
841 Console.Error.WriteLine ("Usage: TestRunner [negative|positive] test-pattern compiler know-issues log-file");
845 string mode = args[0].ToLower ();
847 string test_pattern ="fubar";
849 string test_pattern = args [1] == "0" ? "*cs*.cs" : "*test-*.cs"; //args [1];
851 string test_pattern = args [1] == "0" ? "cs*.cs" : "test-*.cs"; //args [1];
853 string mcs = args [2];
854 string issue_file = args [3];
855 string log_fname = args [4];
857 string[] files = Directory.GetFiles (".", test_pattern);
861 Console.WriteLine ("Testing: " + mcs);
862 tester = new ReflectionTester (Assembly.LoadFile (mcs));
865 Console.Error.WriteLine ("Switching to command line mode (compiler entry point was not found)");
866 if (!File.Exists (mcs)) {
867 Console.Error.WriteLine ("ERROR: Tested compiler was not found");
870 tester = new ProcessTester (mcs);
876 checker = new NegativeChecker (tester, log_fname, issue_file, true);
879 checker = new PositiveChecker (tester, log_fname, issue_file);
882 Console.Error.WriteLine ("You must specify testing mode (positive or negative)");
886 foreach (string s in files) {
887 string filename = Path.GetFileName (s);
888 if (Char.IsUpper (filename, 0)) { // Windows hack
892 if (filename.EndsWith ("-p2.cs"))
895 checker.Do (filename);
898 checker.PrintSummary ();
902 return checker.ResultCode;