From 7f0542b133e5f1eee15f337e0263c14406091a7e Mon Sep 17 00:00:00 2001 From: Martin Baulig Date: Wed, 27 Feb 2002 09:38:21 +0000 Subject: [PATCH] Importing NUnit 1.11. svn path=/branches/NUNIT/mcs/; revision=2713 --- mcs/nunit/src/NUnitConsole/AssemblyInfo.cs | 8 +- .../src/NUnitConsole/NUnitConsoleMain.cs | 65 +- mcs/nunit/src/NUnitConsole/TestRunner.cs | 481 ++++++++------- mcs/nunit/src/NUnitCore/ActiveTestSuite.cs | 188 +++--- mcs/nunit/src/NUnitCore/AssemblyInfo.cs | 6 +- mcs/nunit/src/NUnitCore/Assertion.cs | 380 ++++++------ .../src/NUnitCore/AssertionFailedError.cs | 38 +- mcs/nunit/src/NUnitCore/BaseTestRunner.cs | 584 ++++++++++-------- .../src/NUnitCore/ClassPathTestCollector.cs | 32 +- mcs/nunit/src/NUnitCore/ExceptionTestCase.cs | 98 +-- mcs/nunit/src/NUnitCore/IProtectable.cs | 23 +- mcs/nunit/src/NUnitCore/ITest.cs | 30 +- mcs/nunit/src/NUnitCore/ITestCollector.cs | 29 +- mcs/nunit/src/NUnitCore/ITestListener.cs | 135 ++-- mcs/nunit/src/NUnitCore/ITestSuiteLoader.cs | 30 +- .../src/NUnitCore/LoadingTestCollector.cs | 113 ++-- mcs/nunit/src/NUnitCore/NUnitException.cs | 71 ++- mcs/nunit/src/NUnitCore/ReflectionUtils.cs | 154 +++-- .../src/NUnitCore/ReloadingTestSuiteLoader.cs | 55 +- .../src/NUnitCore/StandardTestSuiteLoader.cs | 80 +-- mcs/nunit/src/NUnitCore/TestCase.cs | 421 +++++++------ .../src/NUnitCore/TestCaseClassLoader.cs | 58 +- mcs/nunit/src/NUnitCore/TestDecorator.cs | 125 ++-- mcs/nunit/src/NUnitCore/TestFailure.cs | 87 +-- mcs/nunit/src/NUnitCore/TestResult.cs | 420 +++++++------ mcs/nunit/src/NUnitCore/TestSetup.cs | 122 ++-- mcs/nunit/src/NUnitCore/TestSuite.cs | 528 +++++++++------- mcs/nunit/src/NUnitCore/Version.cs | 33 +- 28 files changed, 2373 insertions(+), 2021 deletions(-) diff --git a/mcs/nunit/src/NUnitConsole/AssemblyInfo.cs b/mcs/nunit/src/NUnitConsole/AssemblyInfo.cs index 066fd632d58d7..be984e5c03962 100644 --- a/mcs/nunit/src/NUnitConsole/AssemblyInfo.cs +++ b/mcs/nunit/src/NUnitConsole/AssemblyInfo.cs @@ -30,7 +30,7 @@ // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly:AssemblyVersion("1.10.*")] +[assembly:AssemblyVersion("1.11.*")] // // In order to sign your assembly you must specify a key to use. Refer to the @@ -50,6 +50,6 @@ // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile(@"..\..\..\..\NUnit.key")] -//[assembly: AssemblyKeyName("")] +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile(@"..\..\..\..\NUnit.key")] +[assembly: AssemblyKeyName("")] diff --git a/mcs/nunit/src/NUnitConsole/NUnitConsoleMain.cs b/mcs/nunit/src/NUnitConsole/NUnitConsoleMain.cs index 179742eb10b71..cf6091319d3dc 100644 --- a/mcs/nunit/src/NUnitConsole/NUnitConsoleMain.cs +++ b/mcs/nunit/src/NUnitConsole/NUnitConsoleMain.cs @@ -1,30 +1,35 @@ -namespace NUnit { - - using System; - using System.Collections; - - using NUnit.Framework; - using NUnit.Runner; - using NUnit.TextUI; - /// - /// - /// - public class Top { - /// - /// - /// - /// - public static void Main(string[] args) { - TestRunner aTestRunner = new NUnit.TextUI.TestRunner(); - try { - TestResult r = aTestRunner.Start(args); - if (!r.WasSuccessful) - Environment.Exit(1); - Environment.Exit(0); - } catch(Exception e) { - Console.Error.WriteLine(e.Message); - Environment.Exit(2); - } - } - } -} +namespace NUnit +{ + using System; + using System.Collections; + using NUnit.Framework; + using NUnit.Runner; + using NUnit.TextUI; + + /// + /// + /// + public class Top + { + /// + /// + /// + /// + public static void Main(string[] args) + { + TestRunner aTestRunner = new NUnit.TextUI.TestRunner(); + try + { + TestResult r = aTestRunner.Start(args); + if (!r.WasSuccessful) + Environment.Exit(1); + Environment.Exit(0); + } + catch(Exception e) + { + Console.Error.WriteLine(e.Message); + Environment.Exit(2); + } + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitConsole/TestRunner.cs b/mcs/nunit/src/NUnitConsole/TestRunner.cs index d773b0b31b385..77493e48866d2 100644 --- a/mcs/nunit/src/NUnitConsole/TestRunner.cs +++ b/mcs/nunit/src/NUnitConsole/TestRunner.cs @@ -1,238 +1,277 @@ -namespace NUnit.TextUI { +namespace NUnit.TextUI +{ + using System; + using System.IO; + using System.Reflection; + using NUnit.Framework; + using NUnit.Runner; - using System; - using System.IO; - using System.Reflection; + /// A command line based tool to run tests. + /// + /// C:\NUnitConsole.exe /t [/wait] TestCaseClass + /// + /// TestRunner expects the name of a TestCase class as argument. + /// If this class defines a static Suite property it + /// will be invoked and the returned test is run. Otherwise all + /// the methods starting with "Test" having no arguments are run. + /// + /// When the wait command line argument is given TestRunner + /// waits until the users types RETURN. + /// + /// TestRunner prints a trace as the tests are executed followed by a + /// summary at the end. + public class TestRunner : BaseTestRunner + { + int fColumn = 0; + TextWriter fWriter = Console.Out; - using NUnit.Framework; - using NUnit.Runner; + /// + /// Constructs a TestRunner. + /// + public TestRunner() {} - /// A command line based tool to run tests. - /// - /// C:\NUnitConsole.exe /t [/wait] TestCaseClass - /// - /// TestRunner expects the name of a TestCase class as argument. - /// If this class defines a static Suite property it - /// will be invoked and the returned test is run. Otherwise all - /// the methods starting with "Test" having no arguments are run. - /// - /// When the wait command line argument is given TestRunner - /// waits until the users types RETURN. - /// - /// TestRunner prints a trace as the tests are executed followed by a - /// summary at the end. - public class TestRunner: BaseTestRunner { - int fColumn = 0; - TextWriter fWriter = Console.Out; + /// + /// Constructs a TestRunner using the given stream for all the output + /// + public TestRunner(TextWriter writer) : this() + { + if (writer != null) + { + fWriter= writer; + } + else + { + throw new ArgumentNullException("writer"); + } + } + /// + /// + /// + /// + /// + public override void AddError(ITest test, Exception t) + { + lock(this) + this.Writer.Write("E"); + } + /// + /// + /// + /// + /// + public override void AddFailure(ITest test, AssertionFailedError t) + { + lock (this) + this.Writer.Write("F"); + } - /// - /// Constructs a TestRunner. - /// - public TestRunner() { - } + /// Creates the TestResult to be used for the test run. + protected TestResult CreateTestResult() + { + return new TestResult(); + } + /// + /// + /// + /// + /// + /// + protected TestResult DoRun(ITest suite, bool wait) + { + TestResult result= CreateTestResult(); + result.AddListener(this); + long startTime= System.DateTime.Now.Ticks; + suite.Run(result); + long endTime= System.DateTime.Now.Ticks; + long runTime= (endTime-startTime) / 10000; + Writer.WriteLine(); + Writer.WriteLine("Time: "+ElapsedTimeAsString(runTime)); + Print(result); - /// - /// Constructs a TestRunner using the given stream for all the output - /// - public TestRunner(TextWriter writer) : this() { - if (writer == null) - throw new ArgumentException("Writer can't be null"); - fWriter= writer; - } -/// -/// -/// -/// -/// - public override void AddError(ITest test, Exception t) { - lock(this) - Writer.Write("E"); - } -/// -/// -/// -/// -/// - public override void AddFailure(ITest test, AssertionFailedError t) { - lock (this) - Writer.Write("F"); - } - - /// Creates the TestResult to be used for the test run. - protected TestResult CreateTestResult() { - return new TestResult(); - } -/// -/// -/// -/// -/// -/// - protected TestResult DoRun(ITest suite, bool wait) { - TestResult result= CreateTestResult(); - result.AddListener(this); - long startTime= System.DateTime.Now.Ticks; - suite.Run(result); - long endTime= System.DateTime.Now.Ticks; - long runTime= (endTime-startTime) / 10000; - Writer.WriteLine(); - Writer.WriteLine("Time: "+ElapsedTimeAsString(runTime)); - Print(result); - - Writer.WriteLine(); + Writer.WriteLine(); - if (wait) { - Writer.WriteLine(" to continue"); - try { - Console.ReadLine(); - } - catch(Exception) { - } - } - return result; - } - /// - /// - /// - /// + if (wait) + { + Writer.WriteLine(" to continue"); + try + { + Console.ReadLine(); + } + catch(Exception) + { + } + } + return result; + } + /// + /// + /// + /// - public override void EndTest(ITest test) { - } -/// -/// -/// -/// - public override ITestSuiteLoader GetLoader() { - return new StandardTestSuiteLoader(); - } -/// -/// -/// -/// - public void Print(TestResult result) { - lock(this) { - PrintErrors(result); - PrintFailures(result); - PrintHeader(result); - } - } + public override void EndTest(ITest test) + { + } + /// + /// + /// + /// + public override ITestLoader GetLoader() + { + return new StandardLoader(); + } + /// + /// + /// + /// + public void Print(TestResult result) + { + lock(this) + { + PrintErrors(result); + PrintFailures(result); + PrintHeader(result); + } + } - /// Prints the errors to the standard output. - public void PrintErrors(TestResult result) { - if (result.ErrorCount != 0) { - if (result.ErrorCount == 1) - Writer.WriteLine("There was "+result.ErrorCount+" error:"); - else - Writer.WriteLine("There were "+result.ErrorCount+" errors:"); + /// Prints the errors to the standard output. + public void PrintErrors(TestResult result) + { + if (result.ErrorCount != 0) + { + if (result.ErrorCount == 1) + Writer.WriteLine("There was "+result.ErrorCount+" error:"); + else + Writer.WriteLine("There were "+result.ErrorCount+" errors:"); - int i= 1; - foreach (TestFailure failure in result.Errors) { - Writer.WriteLine(i++ + ") "+failure+"("+failure.ThrownException.GetType().ToString()+")"); - Writer.Write(GetFilteredTrace(failure.ThrownException)); - } - } - } + int i= 1; + foreach (TestFailure failure in result.Errors) + { + Writer.WriteLine(i++ + ") "+failure+"("+failure.ThrownException.GetType().ToString()+")"); + Writer.Write(GetFilteredTrace(failure.ThrownException)); + } + } + } - /// Prints failures to the standard output. - public void PrintFailures(TestResult result) { - if (result.FailureCount != 0) { - if (result.FailureCount == 1) - Writer.WriteLine("There was " + result.FailureCount + " failure:"); - else - Writer.WriteLine("There were " + result.FailureCount + " failures:"); - int i = 1; - foreach (TestFailure failure in result.Failures) { - Writer.Write(i++ + ") " + failure.FailedTest); - Exception t= failure.ThrownException; - if (t.Message != "") - Writer.WriteLine(" \"" + Truncate(t.Message) + "\""); - else { - Writer.WriteLine(); - Writer.Write(GetFilteredTrace(failure.ThrownException)); - } - } - } - } + /// Prints failures to the standard output. + public void PrintFailures(TestResult result) + { + if (result.FailureCount != 0) + { + if (result.FailureCount == 1) + Writer.WriteLine("There was " + result.FailureCount + " failure:"); + else + Writer.WriteLine("There were " + result.FailureCount + " failures:"); + int i = 1; + foreach (TestFailure failure in result.Failures) + { + Writer.Write(i++ + ") " + failure.FailedTest); + Exception t= failure.ThrownException; + if (t.Message != "") + Writer.WriteLine(" \"" + Truncate(t.Message) + "\""); + else + { + Writer.WriteLine(); + Writer.Write(GetFilteredTrace(failure.ThrownException)); + } + } + } + } - /// Prints the header of the report. - public void PrintHeader(TestResult result) { - if (result.WasSuccessful) { - Writer.WriteLine(); - Writer.Write("OK"); - Writer.WriteLine (" (" + result.RunCount + " tests)"); + /// Prints the header of the report. + public void PrintHeader(TestResult result) + { + if (result.WasSuccessful) + { + Writer.WriteLine(); + Writer.Write("OK"); + Writer.WriteLine (" (" + result.RunCount + " tests)"); - } else { - Writer.WriteLine(); - Writer.WriteLine("FAILURES!!!"); - Writer.WriteLine("Tests Run: "+result.RunCount+ - ", Failures: "+result.FailureCount+ - ", Errors: "+result.ErrorCount); - } - } + } + else + { + Writer.WriteLine(); + Writer.WriteLine("FAILURES!!!"); + Writer.WriteLine("Tests Run: "+result.RunCount+ + ", Failures: "+result.FailureCount+ + ", Errors: "+result.ErrorCount); + } + } - /// Runs a Suite extracted from a TestCase subclass. - static public void Run(Type testClass) { - Run(new TestSuite(testClass)); - } -/// -/// -/// -/// - static public void Run(ITest suite) { - TestRunner aTestRunner= new TestRunner(); - aTestRunner.DoRun(suite, false); - } + /// Runs a Suite extracted from a TestCase subclass. + static public void Run(Type testClass) + { + Run(new TestSuite(testClass)); + } + /// + /// + /// + /// + static public void Run(ITest suite) + { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.DoRun(suite, false); + } - /// Runs a single test and waits until the user - /// types RETURN. - static public void RunAndWait(ITest suite) { - TestRunner aTestRunner= new TestRunner(); - aTestRunner.DoRun(suite, true); - } -/// -/// -/// -/// - protected override void RunFailed(string message) { - Console.Error.WriteLine(message); - Environment.ExitCode = 1; - throw new ApplicationException(message); - } + /// Runs a single test and waits until the user + /// types RETURN. + static public void RunAndWait(ITest suite) + { + TestRunner aTestRunner= new TestRunner(); + aTestRunner.DoRun(suite, true); + } + /// + /// + /// + /// + protected override void RunFailed(string message) + { + Console.Error.WriteLine(message); + Environment.ExitCode = 1; + throw new ApplicationException(message); + } - /// Starts a test run. Analyzes the command line arguments - /// and runs the given test suite. - public TestResult Start(string[] args) { - bool wait = false; - string testCase = ProcessArguments(args, ref wait); - if (testCase.Equals("")) - throw new ApplicationException("Usage: NUnitConsole.exe [/wait] testCaseName, where\n" - + "name is the name of the TestCase class"); + /// Starts a test run. Analyzes the command line arguments + /// and runs the given test suite. + public TestResult Start(string[] args) + { + bool wait = false; + string testCase = ProcessArguments(args, ref wait); + if (testCase.Equals("")) + throw new ApplicationException("Usage: NUnitConsole.exe [/wait] testCaseName, where\n" + + "name is the name of the TestCase class"); - try { - ITest suite = GetTest(testCase); - return DoRun(suite, wait); - } catch (Exception e) { - throw new ApplicationException("Could not create and run test suite.", e); - } - } -/// -/// -/// -/// - public override void StartTest(ITest test) { - lock (this) { - Writer.Write("."); - if (fColumn++ >= 40) { - Writer.WriteLine(); - fColumn = 0; - } - } - } -/// -/// -/// - protected TextWriter Writer { - get { return fWriter; } - } - } + try + { + ITest suite = GetTest(testCase); + return DoRun(suite, wait); + } + catch (Exception e) + { + throw new ApplicationException("Could not create and run test suite.", e); + } + } + /// + /// + /// + /// + public override void StartTest(ITest test) + { + lock (this) + { + Writer.Write("."); + if (fColumn++ >= 40) + { + Writer.WriteLine(); + fColumn = 0; + } + } + } + /// + /// + /// + protected TextWriter Writer + { + get { return fWriter; } + } + } } diff --git a/mcs/nunit/src/NUnitCore/ActiveTestSuite.cs b/mcs/nunit/src/NUnitCore/ActiveTestSuite.cs index 605911d233c7d..cdba3b0ed9b32 100644 --- a/mcs/nunit/src/NUnitCore/ActiveTestSuite.cs +++ b/mcs/nunit/src/NUnitCore/ActiveTestSuite.cs @@ -1,93 +1,113 @@ -namespace NUnit.Extensions { - - using System; - using System.Threading; +namespace NUnit.Extensions +{ + using System; + using System.Threading; + using NUnit.Framework; - using NUnit.Framework; - - /// A TestSuite for active Tests. It runs each - /// test in a separate thread and until all - /// threads have terminated. - /// -- Aarhus Radisson Scandinavian Center 11th floor - public class ActiveTestSuite: TestSuite { - private int fActiveTestDeathCount; /// - /// + /// A TestSuite for active Tests. It runs each test in a + /// separate thread and until all threads have terminated. + /// -- Aarhus Radisson Scandinavian Center 11th floor /// - /// - public override void Run(TestResult result) { - fActiveTestDeathCount= 0; - base.Run(result); - WaitUntilFinished(); - } - /// - /// - /// - public class ThreadLittleHelper { - private ITest fTest; - private TestResult fResult; - private ActiveTestSuite fSuite; + public class ActiveTestSuite: TestSuite + { + private int fActiveTestDeathCount; + /// + /// + /// + /// + public override void Run(TestResult result) + { + fActiveTestDeathCount= 0; + base.Run(result); + WaitUntilFinished(); + } /// /// /// /// /// - /// - public ThreadLittleHelper(ITest test, TestResult result, - ActiveTestSuite suite) { - fSuite = suite; - fTest = test; - fResult = result; - } - /// - /// - /// - public void Run() { - try { - fSuite.BaseRunTest(fTest, fResult); - } finally { - fSuite.RunFinished(fTest); - } - } - } - /// - /// - /// - /// - /// - public void BaseRunTest(ITest test, TestResult result) { - base.RunTest(test, result); - } - /// - /// - /// - /// - /// - public override void RunTest(ITest test, TestResult result) { - ThreadLittleHelper tlh = new ThreadLittleHelper(test, result, this); - Thread t = new Thread(new ThreadStart(tlh.Run)); - t.Start(); - } - void WaitUntilFinished() { - lock(this) { - while (fActiveTestDeathCount < TestCount) { - try { - Monitor.Wait(this); - } catch (ThreadInterruptedException) { - return; // TBD - } - } - } - } - /// - /// - /// - /// - public void RunFinished(ITest test) { - lock(this) { - fActiveTestDeathCount++; - Monitor.PulseAll(this); - } - } - } + public void BaseRunTest(ITest test, TestResult result) + { + base.RunTest(test, result); + } + /// + /// + /// + /// + /// + public override void RunTest(ITest test, TestResult result) + { + ThreadLittleHelper tlh = new ThreadLittleHelper(test, result, this); + Thread t = new Thread(new ThreadStart(tlh.Run)); + t.Start(); + } + /// + /// + /// + /// + public void RunFinished(ITest test) + { + lock(this) + { + fActiveTestDeathCount++; + Monitor.PulseAll(this); + } + } + private void WaitUntilFinished() + { + lock(this) + { + while (fActiveTestDeathCount < TestCount) + { + try + { + Monitor.Wait(this); + } + catch (ThreadInterruptedException) + { + return; // TBD + } + } + } + } + #region Nested Classes + /// + /// + /// + public class ThreadLittleHelper + { + private ITest fTest; + private TestResult fResult; + private ActiveTestSuite fSuite; + /// + /// + /// + /// + /// + /// + public ThreadLittleHelper(ITest test, TestResult result, + ActiveTestSuite suite) + { + fSuite = suite; + fTest = test; + fResult = result; + } + /// + /// + /// + public void Run() + { + try + { + fSuite.BaseRunTest(fTest, fResult); + } + finally + { + fSuite.RunFinished(fTest); + } + } + } + #endregion + } } diff --git a/mcs/nunit/src/NUnitCore/AssemblyInfo.cs b/mcs/nunit/src/NUnitCore/AssemblyInfo.cs index a07e95f973623..6f48173a95a24 100644 --- a/mcs/nunit/src/NUnitCore/AssemblyInfo.cs +++ b/mcs/nunit/src/NUnitCore/AssemblyInfo.cs @@ -30,7 +30,7 @@ // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly:AssemblyVersion("1.10.*")] +[assembly:AssemblyVersion("1.11.*")] // // In order to sign your assembly you must specify a key to use. Refer to the @@ -51,5 +51,5 @@ // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile(@"..\..\..\..\NUnit.key")] -[assembly: AssemblyKeyName("")] +[assembly: AssemblyKeyFile(@"..\..\..\..\NUnit.key")] +[assembly: AssemblyKeyName("")] \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/Assertion.cs b/mcs/nunit/src/NUnitCore/Assertion.cs index cc626daa47bbf..f9dbff904576f 100644 --- a/mcs/nunit/src/NUnitCore/Assertion.cs +++ b/mcs/nunit/src/NUnitCore/Assertion.cs @@ -1,204 +1,184 @@ -namespace NUnit.Framework { +namespace NUnit.Framework +{ + using System; - using System; + /// A set of Assert methods. + public class Assertion : MarshalByRefObject + { - /// A set of Assert methods. - public class Assertion { + /// + /// Protect constructor since it is a static only class + /// + protected Assertion():base(){} + /// + /// Asserts that a condition is true. If it isn't it throws + /// an . + /// + /// The message to display is the condition + /// is false + /// The evaluated condition + static public void Assert(string message, bool condition) + { + if (!condition) + Assertion.Fail(message); + } + + /// + /// Asserts that a condition is true. If it isn't it throws + /// an . + /// + /// The evaluated condition + static public void Assert(bool condition) + { + Assertion.Assert(string.Empty, condition); + } + /// + /// /// Asserts that two doubles are equal concerning a delta. If the + /// expected value is infinity then the delta value is ignored. + /// + /// The expected value + /// The actual value + /// The maximum acceptable difference between the + /// the expected and the actual + static public void AssertEquals(double expected, double actual, double delta) + { + Assertion.AssertEquals(string.Empty, expected, actual, delta); + } + /// + /// /// Asserts that two singles are equal concerning a delta. If the + /// expected value is infinity then the delta value is ignored. + /// + /// The expected value + /// The actual value + /// The maximum acceptable difference between the + /// the expected and the actual + static public void AssertEquals(float expected, float actual, float delta) + { + Assertion.AssertEquals(string.Empty, expected, actual, delta); + } - /// Protect constructor since it is a static only class - protected Assertion() { - } - - /// Asserts that a condition is true. If it isn't it throws - /// an . - static public void Assert(string message, bool condition) { - if (!condition) - Fail(message); - } - - /// Asserts that a condition is true. If it isn't it throws - /// an . - static public void Assert(bool condition) { - Assert(null, condition); - } - - /// Asserts that two booleans are equal. - static public void AssertEquals(bool expected, bool actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two bytes are equal. - static public void AssertEquals(byte expected, byte actual) { - AssertEquals(null, expected, actual); - } + /// Asserts that two objects are equal. If they are not + /// an is thrown. + static public void AssertEquals(Object expected, Object actual) + { + Assertion.AssertEquals(string.Empty, expected, actual); + } + + /// Asserts that two doubles are equal concerning a delta. + /// If the expected value is infinity then the delta value is ignored. + /// + static public void AssertEquals(string message, double expected, + double actual, double delta) + { + // handle infinity specially since subtracting two infinite values gives + // NaN and the following test fails + if (double.IsInfinity(expected)) + { + if (!(expected == actual)) + Assertion.FailNotEquals(message, expected, actual); + } + else if (!(Math.Abs(expected-actual) <= delta)) + Assertion.FailNotEquals(message, expected, actual); + } + + /// Asserts that two floats are equal concerning a delta. + /// If the expected value is infinity then the delta value is ignored. + /// + static public void AssertEquals(string message, float expected, + float actual, float delta) + { + // handle infinity specially since subtracting two infinite values gives + // NaN and the following test fails + if (float.IsInfinity(expected)) + { + if (!(expected == actual)) + Assertion.FailNotEquals(message, expected, actual); + } + else if (!(Math.Abs(expected-actual) <= delta)) + Assertion.FailNotEquals(message, expected, actual); + } - /// Asserts that two chars are equal. - static public void AssertEquals(char expected, char actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two doubles are equal concerning a delta. If the expected - /// value is infinity then the delta value is ignored. - static public void AssertEquals(double expected, double actual, double delta) { - AssertEquals(null, expected, actual, delta); - } - - /// Asserts that two floats are equal concerning a delta. If the expected - /// value is infinity then the delta value is ignored. - static public void AssertEquals(float expected, float actual, float delta) { - AssertEquals(null, expected, actual, delta); - } - - /// Asserts that two ints are equal. - static public void AssertEquals(int expected, int actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two longs are equal. - static public void AssertEquals(long expected, long actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two objects are equal. If they are not - /// an is thrown. - static public void AssertEquals(Object expected, Object actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two shorts are equal. - static public void AssertEquals(short expected, short actual) { - AssertEquals(null, expected, actual); - } - - /// Asserts that two bools are equal. - static public void AssertEquals(string message, bool expected, bool actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that two bytes are equal. - static public void AssertEquals(string message, byte expected, byte actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that two chars are equal. - static public void AssertEquals(string message, char expected, char actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that two doubles are equal concerning a delta. If the expected - /// value is infinity then the delta value is ignored. - static public void AssertEquals(string message, double expected, - double actual, double delta) { - // handle infinity specially since subtracting two infinite values gives NaN and the - // following test fails - if (double.IsInfinity(expected)) { - if (!(expected == actual)) - FailNotEquals(message, expected, actual); - } else if (!(Math.Abs(expected-actual) <= delta)) - FailNotEquals(message, expected, actual); - } - - /// Asserts that two floats are equal concerning a delta. If the expected - /// value is infinity then the delta value is ignored. - static public void AssertEquals(string message, float expected, - float actual, float delta) { - // handle infinity specially since subtracting two infinite values gives NaN and the - // following test fails - if (double.IsInfinity(expected)) { - if (!(expected == actual)) - FailNotEquals(message, expected, actual); - } else if (!(Math.Abs(expected-actual) <= delta)) - FailNotEquals(message, expected, actual); - } - - /// Asserts that two ints are equal. - static public void AssertEquals(string message, int expected, int actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that two longs are equal. - static public void AssertEquals(string message, long expected, long actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that two objects are equal. If they are not - /// an is thrown. - static public void AssertEquals(string message, Object expected, - Object actual) { - if (expected == null && actual == null) - return; - if (expected != null && expected.Equals(actual)) - return; - FailNotEquals(message, expected, actual); - } - - /// Asserts that two shorts are equal. - static public void AssertEquals(string message, short expected, short actual) { - AssertEquals(message, (object)expected, (object)actual); - } - - /// Asserts that an object isn't null. - static public void AssertNotNull(Object anObject) { - AssertNotNull(null, anObject); - } - - /// Asserts that an object isn't null. - static public void AssertNotNull(string message, Object anObject) { - Assert(message, anObject != null); - } - - /// Asserts that an object is null. - static public void AssertNull(Object anObject) { - AssertNull(null, anObject); - } - - /// Asserts that an object is null. - static public void AssertNull(string message, Object anObject) { - Assert(message, anObject == null); - } - - /// Asserts that two objects refer to the same object. If they - /// are not the same an is thrown. - /// - static public void AssertSame(Object expected, Object actual) { - AssertSame(null, expected, actual); - } - - /// Asserts that two objects refer to the same object. - /// If they are not an is thrown. - /// - static public void AssertSame(string message, Object expected, - Object actual) { - if (expected == actual) - return; - FailNotSame(message, expected, actual); - } - - /// Fails a test with no message. - static public void Fail() { - Fail(null); - } - - /// Fails a test with the given message. - static public void Fail(string message) { - if (message == null) - message = ""; - throw new AssertionFailedError(message); - } - - static private void FailNotEquals(string message, Object expected, - Object actual) { - string formatted= ""; - if (message != null) - formatted= message+" "; - Fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); - } - - static private void FailNotSame(string message, Object expected, Object actual) { - string formatted= ""; - if (message != null) - formatted= message+" "; - Fail(formatted+"expected same"); - } - } -} + /// Asserts that two objects are equal. If they are not + /// an is thrown. + static public void AssertEquals(string message, Object expected, Object actual) + { + if (expected == null && actual == null) + return; + if (expected != null && expected.Equals(actual)) + return; + Assertion.FailNotEquals(message, expected, actual); + } + + /// Asserts that an object isn't null. + static public void AssertNotNull(Object anObject) + { + Assertion.AssertNotNull(string.Empty, anObject); + } + + /// Asserts that an object isn't null. + static public void AssertNotNull(string message, Object anObject) + { + Assertion.Assert(string.Empty, anObject != null); + } + + /// Asserts that an object is null. + static public void AssertNull(Object anObject) + { + Assertion.AssertNull(string.Empty, anObject); + } + + /// Asserts that an object is null. + static public void AssertNull(string message, Object anObject) + { + Assertion.Assert(message, anObject == null); + } + + /// Asserts that two objects refer to the same object. If they + /// are not the same an is thrown. + /// + static public void AssertSame(Object expected, Object actual) + { + Assertion.AssertSame(string.Empty, expected, actual); + } + + /// Asserts that two objects refer to the same object. + /// If they are not an is thrown. + /// + static public void AssertSame(string message, Object expected, Object actual) + { + if (expected == actual) + return; + Assertion.FailNotSame(message, expected, actual); + } + + /// Fails a test with no message. + static public void Fail() + { + Assertion.Fail(string.Empty); + } + + /// Fails a test with the given message. + static public void Fail(string message) + { + if (message == null) + message = string.Empty; + throw new AssertionFailedError(message); + } + + static private void FailNotEquals(string message, Object expected, Object actual) + { + string formatted=string.Empty; + if (message != null) + formatted= message+" "; + Assertion.Fail(formatted+"expected:<"+expected+"> but was:<"+actual+">"); + } + + static private void FailNotSame(string message, Object expected, Object actual) + { + string formatted=string.Empty; + if (message != null) + formatted= message+" "; + Assertion.Fail(formatted+"expected same"); + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/AssertionFailedError.cs b/mcs/nunit/src/NUnitCore/AssertionFailedError.cs index ba1a8fec1b66a..9afebde079cdd 100644 --- a/mcs/nunit/src/NUnitCore/AssertionFailedError.cs +++ b/mcs/nunit/src/NUnitCore/AssertionFailedError.cs @@ -1,13 +1,27 @@ -namespace NUnit.Framework { +namespace NUnit.Framework +{ + using System; + using System.Runtime.Serialization; - using System; - - /// Thrown when an assertion failed. - public class AssertionFailedError: Exception { - /// - /// - /// - /// - public AssertionFailedError (string message) : base(message) {} - } -} + /// + /// Thrown when an assertion failed. + /// + [Serializable] + public class AssertionFailedError : ApplicationException//NUnitException + { + /// + /// Serialization Constructor + /// + protected AssertionFailedError(SerializationInfo info, + StreamingContext context) : base(info,context){} + /// + /// + /// + /// + public AssertionFailedError (string message) : base(message) {} +// public override bool IsAssertionFailure +// { +// get{return true;} +// } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/BaseTestRunner.cs b/mcs/nunit/src/NUnitCore/BaseTestRunner.cs index ac423b17e1717..7f3adfc6733ef 100644 --- a/mcs/nunit/src/NUnitCore/BaseTestRunner.cs +++ b/mcs/nunit/src/NUnitCore/BaseTestRunner.cs @@ -1,279 +1,323 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ + using System; + using System.Collections; + using System.Collections.Specialized; + using System.IO; + using System.IO.IsolatedStorage; + using System.Reflection; + using NUnit.Framework; - using System; - using System.Collections; - using System.Collections.Specialized; - using System.IO; - using System.IO.IsolatedStorage; - using System.Reflection; + /// + /// Base class for all test runners. + /// + /// + /// + /// + public abstract class BaseTestRunner: MarshalByRefObject, ITestListener + { + /// + /// + /// + [Obsolete("Shoud be handled by a loader")] + public static string SUITE_PROPERTYNAME="Suite"; - using NUnit.Framework; + private static NameValueCollection fPreferences = new NameValueCollection(); + private static int fgMaxMessageLength = 500; + private static bool fgFilterStack = true; - /// Base class for all test runners. - /// This class was born live on stage in Sardinia during - /// XP2000. - public abstract class BaseTestRunner: ITestListener { - /// - /// - /// - public static string SUITE_PROPERTYNAME="Suite"; + private bool fLoading = true; + /// + /// + /// + public BaseTestRunner() + { + fPreferences = new NameValueCollection(); + fPreferences.Add("loading", "true"); + fPreferences.Add("filterstack", "true"); + ReadPreferences(); + fgMaxMessageLength = GetPreference("maxmessage", fgMaxMessageLength); + } + + #region ITestListener Methods + /// + /// + /// + /// + /// + public abstract void AddError(ITest test, Exception t); + + /// + /// + /// + /// + /// + public abstract void AddFailure(ITest test, AssertionFailedError t); + + /// + /// + /// + /// + public abstract void EndTest(ITest test); + #endregion - static NameValueCollection fPreferences = new NameValueCollection(); - static int fgMaxMessageLength = 500; - static bool fgFilterStack = true; - bool fLoading = true; - /// - /// - /// - public BaseTestRunner() { - fPreferences = new NameValueCollection(); - fPreferences.Add("loading", "true"); - fPreferences.Add("filterstack", "true"); - ReadPreferences(); - fgMaxMessageLength = GetPreference("maxmessage", fgMaxMessageLength); - } - /// - /// - /// - /// - /// - public abstract void AddError(ITest test, Exception t); - /// - /// - /// - /// - /// - public abstract void AddFailure(ITest test, AssertionFailedError t); - /// - /// Clears the status message. - /// - protected virtual void ClearStatus() { // Belongs in the GUI TestRunner class. - } - /// - /// - /// - /// - public abstract void EndTest(ITest test); - /// - /// Returns the formatted string of the elapsed time. - /// - public static string ElapsedTimeAsString(long runTime) { - return ((double)runTime/1000).ToString(); - } - /// - /// Extract the class name from a string in VA/Java style - /// - public static string ExtractClassName(string className) { - if(className.StartsWith("Default package for")) - return className.Substring(className.LastIndexOf(".")+1); - return className; - } - static bool FilterLine(string line) { - string[] patterns = new string[] { - "NUnit.Framework.TestCase", - "NUnit.Framework.TestResult", - "NUnit.Framework.TestSuite", - "NUnit.Framework.Assertion." // don't filter AssertionFailure - }; - for (int i = 0; i < patterns.Length; i++) { - if (line.IndexOf(patterns[i]) > 0) - return true; - } - return false; - } - /// - /// Filters stack frames from internal NUnit classes - /// - public static string FilterStack(string stack) { - string pref = GetPreference("filterstack"); - if (((pref != null) && !GetPreference("filterstack").Equals("true")) || fgFilterStack == false) - return stack; +#if false + /// + /// Clears the status message. + /// + protected virtual void ClearStatus() + { + // Belongs in the GUI TestRunner class. + } +#endif + /// + /// Returns the formatted string of the elapsed time. + /// + public static string ElapsedTimeAsString(long runTime) + { + return ((double)runTime/1000).ToString(); + } + /// + /// Extract the class name from a string in VA/Java style + /// + public static string ExtractClassName(string className) + { + if(className.StartsWith("Default package for")) + return className.Substring(className.LastIndexOf(".")+1); + return className; + } + + static bool FilterLine(string line) + { + string[] patterns = new string[] + { + "NUnit.Framework.TestCase", + "NUnit.Framework.TestResult", + "NUnit.Framework.TestSuite", + "NUnit.Framework.Assertion." // don't filter AssertionFailure + }; + for (int i = 0; i < patterns.Length; i++) + { + if (line.IndexOf(patterns[i]) > 0) + return true; + } + return false; + } - StringWriter sw = new StringWriter(); - StringReader sr = new StringReader(stack); + /// + /// Filters stack frames from internal NUnit classes + /// + public static string FilterStack(string stack) + { + string pref = GetPreference("filterstack"); + if (((pref != null) && !GetPreference("filterstack").Equals("true")) + || fgFilterStack == false) + return stack; - string line; - try { - while ((line = sr.ReadLine()) != null) { - if (!FilterLine(line)) - sw.WriteLine(line); - } - } catch (Exception) { - return stack; // return the stack unfiltered - } - return sw.ToString(); - } - /// - /// - /// - /// - /// - public static string GetFilteredTrace(Exception t) { - return BaseTestRunner.FilterStack(t.StackTrace); - } + StringWriter sw = new StringWriter(); + StringReader sr = new StringReader(stack); - /// - /// - /// - /// - /// - public static string GetPreference(string key) { - return fPreferences.Get(key); - } - private static int GetPreference(String key, int dflt) - { - String value= GetPreference(key); - int intValue= dflt; - if (value == null) - return intValue; - try { - intValue= int.Parse(value); - } - catch (FormatException) { - } - return intValue; - } - private static FileStream GetPreferencesFile() { - return new IsolatedStorageFileStream("NUnit.Prefs", - FileMode.OpenOrCreate); - } - /// - /// - /// - /// - public virtual ITestSuiteLoader GetLoader() { - if (UseReloadingTestSuiteLoader()) - return new ReloadingTestSuiteLoader(); - return new StandardTestSuiteLoader(); - } + try + { + string line; + while ((line = sr.ReadLine()) != null) + { + if (!FilterLine(line)) + sw.WriteLine(line); + } + } + catch (Exception) + { + return stack; // return the stack unfiltered + } + return sw.ToString(); + } + + /// + /// + /// + /// + /// + public static string GetFilteredTrace(Exception t) + { + return BaseTestRunner.FilterStack(t.StackTrace); + } - /// - /// Returns the ITest corresponding to the given suite. This is - /// a template method, subclasses override RunFailed(), ClearStatus(). - /// - public ITest GetTest(string suiteClassName) { - if (suiteClassName.Length <= 0) { - ClearStatus(); - return null; - } - Type testClass= null; - try { - testClass = LoadSuiteClass(suiteClassName); - } catch (TypeLoadException e) { - RunFailed(e.Message); - return null; - } catch (Exception e) { - RunFailed("Error: " + e.ToString()); - return null; - } - PropertyInfo suiteProperty= null; - suiteProperty = testClass.GetProperty(SUITE_PROPERTYNAME, new Type[0]); - if (suiteProperty == null ) { - // try to extract a test suite automatically - ClearStatus(); - return new TestSuite(testClass); - } - ITest test= null; - try { - // static property - test= (ITest)suiteProperty.GetValue(null, new Type[0]); - if (test == null) - return test; - } catch(Exception e) { - RunFailed("Could not get the Suite property. " + e); - return null; - } - ClearStatus(); - return test; - } - /// - /// - /// - /// - public static bool InVAJava() { - return false; - } - /// - /// Returns the loaded Class for a suite name. - /// - protected Type LoadSuiteClass(string suiteClassName) { - return GetLoader().Load(suiteClassName); - } - private static void ReadPreferences() { - FileStream fs= null; - try { - fs= GetPreferencesFile(); - fPreferences= new NameValueCollection(fPreferences); - ReadPrefsFromFile(ref fPreferences, fs); - } catch (IOException) { - try { - if (fs != null) - fs.Close(); - } catch (IOException) { - } - } - } - private static void ReadPrefsFromFile(ref NameValueCollection prefs, FileStream fs) { - // Real method reads name/value pairs, populates, or maybe just - // deserializes... - } - /// - /// Override to define how to handle a failed loading of a test suite. - /// - protected abstract void RunFailed(String message); - /// - /// Truncates a String to the maximum length. - /// - public static String Truncate(String s) { - if (fgMaxMessageLength != -1 && s.Length > fgMaxMessageLength) - s= s.Substring(0, fgMaxMessageLength)+"..."; - return s; - } - /// - /// - /// - /// - public abstract void StartTest(ITest test); - /// - /// - /// - /// - /// - /// - protected string ProcessArguments(string[] args, ref bool wait) { - string suiteName=""; - wait = false; - foreach (string arg in args) { - if (arg.Equals("/noloading")) - SetLoading(false); - else if (arg.Equals("/nofilterstack")) - fgFilterStack = false; - else if (arg.Equals("/wait")) - wait = true; - else if (arg.Equals("/c")) - suiteName= ExtractClassName(arg); - else if (arg.Equals("/v")){ - Console.Error.WriteLine("NUnit "+NUnit.Runner.Version.id() - + " by Philip Craig"); - Console.Error.WriteLine("ported from JUnit 3.6 by Kent Beck" - + " and Erich Gamma"); - } else - suiteName = arg; - } - return suiteName; - } - /// - /// Sets the loading behaviour of the test runner - /// - protected void SetLoading(bool enable) { - fLoading = false; - } - /// - /// - /// - /// - protected bool UseReloadingTestSuiteLoader() { - return GetPreference("loading").Equals("true") && fLoading; - } - } + /// + /// + /// + /// + /// + public static string GetPreference(string key) + { + return fPreferences.Get(key); + } + + private static int GetPreference(String key, int dflt) + { + String value= GetPreference(key); + int intValue= dflt; + if (value != null) + { + try + { + intValue= int.Parse(value); + } + catch (FormatException) {} + } + return intValue; + } + + private static FileStream GetPreferencesFile() + { + return new IsolatedStorageFileStream("NUnit.Prefs", FileMode.OpenOrCreate); + } + /// + /// + /// + /// + public virtual ITestLoader GetLoader() + { + if (UseReloadingTestSuiteLoader()) + return new UnloadingLoader(); + return new StandardLoader(); + } + + /// + /// Returns the ITest corresponding to the given suite. This is + /// a template method, subclasses override RunFailed(), ClearStatus(). + /// + public ITest GetTest(string suiteClassName) + { + ITest test = null; + try + { + test = LoadSuiteClass(suiteClassName); + } + catch (TypeLoadException e) + { + RunFailed(e.Message); + return null; + } + catch (Exception e) + { + RunFailed("Error: " + e.ToString()); + return null; + } + //ClearStatus(); + return test; + } + + /// + /// Returns the loaded Class for a suite name. + /// + protected ITest LoadSuiteClass(string suiteClassName) + { + return GetLoader().LoadTest(suiteClassName); + } + + private static void ReadPreferences() + { + FileStream fs= null; + try + { + fs= GetPreferencesFile(); + fPreferences= new NameValueCollection(fPreferences); + ReadPrefsFromFile(ref fPreferences, fs); + } + catch (IOException) + { + try + { + if (fs != null) + fs.Close(); + } + catch (IOException) + { + } + } + } + + /// + /// Real method reads name/value pairs, populates, or maybe just + /// deserializes... + /// + /// + /// + private static void ReadPrefsFromFile(ref NameValueCollection prefs, FileStream fs) + { + } + + /// + /// Override to define how to handle a failed loading of a test suite. + /// + protected abstract void RunFailed(string message); + + /// + /// Truncates a String to the maximum length. + /// + /// + /// + public static string Truncate(string message) + { + if (fgMaxMessageLength != -1 && message.Length > fgMaxMessageLength) + message = message.Substring(0, fgMaxMessageLength)+"..."; + return message; + } + /// + /// + /// + /// + public abstract void StartTest(ITest test); + + /// + /// + /// + /// + /// + /// + protected string ProcessArguments(string[] args, ref bool wait) + { + string suiteName=""; + wait = false; + foreach (string arg in args) + { + if (arg.Equals("/noloading")) + SetLoading(false); + else if (arg.Equals("/nofilterstack")) + fgFilterStack = false; + else if (arg.Equals("/wait")) + wait = true; + else if (arg.Equals("/c")) + suiteName= ExtractClassName(arg); + else if (arg.Equals("/v")) + { + Console.Error.WriteLine("NUnit "+NUnit.Runner.Version.id() + + " by Philip Craig"); + Console.Error.WriteLine("ported from JUnit 3.6 by Kent Beck" + + " and Erich Gamma"); + } + else + suiteName = arg; + } + return suiteName; + } + + /// + /// Sets the loading behaviour of the test runner + /// + protected void SetLoading(bool enable) + { + fLoading = enable; + } + + /// + /// + /// + /// + protected bool UseReloadingTestSuiteLoader() + { + return bool.TrueString.Equals( GetPreference("loading")) && fLoading; + } + } } diff --git a/mcs/nunit/src/NUnitCore/ClassPathTestCollector.cs b/mcs/nunit/src/NUnitCore/ClassPathTestCollector.cs index 437cdaab977e0..0669a285c0739 100644 --- a/mcs/nunit/src/NUnitCore/ClassPathTestCollector.cs +++ b/mcs/nunit/src/NUnitCore/ClassPathTestCollector.cs @@ -1,37 +1,37 @@ namespace NUnit.Runner { - using System; using System.Collections; + using System.Collections.Specialized; using System.IO; /// - /// An implementation of a TestCollector that consults the + /// A TestCollector that consults the /// class path. It considers all classes on the class path /// excluding classes in JARs. It leaves it up to subclasses /// to decide whether a class is a runnable Test. - /// /// /// - public abstract class ClassPathTestCollector: ITestCollector + [Obsolete("Use StandardLoader or UnloadingLoader")] + public abstract class ClassPathTestCollector : ITestCollector { /// /// /// - public ClassPathTestCollector() - { - } + public ClassPathTestCollector() {} /// /// /// /// - public Hashtable CollectTests() + public string[] CollectTestsClassNames() { - string classPath= Environment.GetEnvironmentVariable("Path"); + string classPath = Environment.GetEnvironmentVariable("Path"); char separator= Path.PathSeparator; - Hashtable result= new Hashtable(100); + ArrayList result = new ArrayList(); CollectFilesInRoots(classPath.Split(separator), result); - return result; + string[] retVal = new string[result.Count]; + result.CopyTo(retVal); + return retVal; } /// /// @@ -42,7 +42,8 @@ protected string ClassNameFromFile(string classFileName) { return classFileName; } - void CollectFilesInRoots(string[] roots, Hashtable result) + + private void CollectFilesInRoots(string[] roots, IList result) { foreach (string directory in roots) { @@ -55,7 +56,7 @@ void CollectFilesInRoots(string[] roots, Hashtable result) if (IsTestClass(file)) { string className=ClassNameFromFile(file); - result.Add(className, className); + result.Add(className); } } } @@ -69,8 +70,9 @@ void CollectFilesInRoots(string[] roots, Hashtable result) protected virtual bool IsTestClass(string classFileName) { return - (classFileName.EndsWith(".dll") || classFileName.EndsWith(".exe")) && - classFileName.IndexOf("Test") > 0; + ( classFileName.EndsWith(".dll") + || classFileName.EndsWith(".exe")) + && classFileName.IndexOf("Test") > 0; } } } \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/ExceptionTestCase.cs b/mcs/nunit/src/NUnitCore/ExceptionTestCase.cs index 8af9414d4fe40..a5ae174fd613b 100644 --- a/mcs/nunit/src/NUnitCore/ExceptionTestCase.cs +++ b/mcs/nunit/src/NUnitCore/ExceptionTestCase.cs @@ -1,51 +1,53 @@ -namespace NUnit.Extensions { +namespace NUnit.Extensions +{ + using System; + using NUnit.Framework; - using System; + /// A TestCase that expects an Exception of class fExpected + /// to be thrown. + /// The other way to check that an expected exception is thrown is: + /// + /// try { + /// ShouldThrow(); + /// }catch (SpecialException) { + /// return; + /// } + /// Assertion.Fail("Expected SpecialException"); + /// + /// + /// To use ExceptionTestCase, create a TestCase like: + /// + /// new ExceptionTestCase("TestShouldThrow", typeof(SpecialException)); + /// + public class ExceptionTestCase: TestCase + { + private readonly Type fExpected; + /// + /// + /// + /// + /// + public ExceptionTestCase(string name, Type exception) : base(name) + { + fExpected= exception; + } - using NUnit.Framework; - - /// A TestCase that expects an Exception of class fExpected - /// to be thrown. - /// The other way to check that an expected exception is thrown is: - /// - /// try { - /// ShouldThrow(); - /// } - /// catch (SpecialException) { - /// return; - /// } - /// Fail("Expected SpecialException"); - /// - /// - /// To use ExceptionTestCase, create a TestCase like: - /// - /// new ExceptionTestCase("TestShouldThrow", typeof(SpecialException)); - /// - public class ExceptionTestCase: TestCase { - - readonly Type fExpected; -/// -/// -/// -/// -/// - public ExceptionTestCase(string name, Type exception) : base(name) { - fExpected= exception; - } - - /// Execute the test method expecting that an Exception of - /// class fExpected or one of its subclasses will be thrown. - protected override void RunTest() { - try { - base.RunTest(); - } - catch (Exception e) { - if (fExpected.IsAssignableFrom(e.InnerException.GetType())) - return; - else - throw e.InnerException; - } - Fail("Expected exception " + fExpected); - } - } + /// Execute the test method expecting that an Exception of + /// class fExpected or one of its subclasses will be thrown. + protected override void RunTest() + { + try + { + base.RunTest(); + } + catch (Exception e) + { + if (fExpected.IsAssignableFrom(e.InnerException.GetType())) + return; + else + throw e.InnerException; + } + Assertion.Fail("Expected exception " + fExpected); + } + } } diff --git a/mcs/nunit/src/NUnitCore/IProtectable.cs b/mcs/nunit/src/NUnitCore/IProtectable.cs index 3186ee57e8ecd..ad86136602f53 100644 --- a/mcs/nunit/src/NUnitCore/IProtectable.cs +++ b/mcs/nunit/src/NUnitCore/IProtectable.cs @@ -1,11 +1,12 @@ -namespace NUnit.Framework { - - /// An IProtectable can be run and can throw an Exception. - /// - /// - public interface IProtectable { - - /// Run the the following method protected. - void Protect(); - } -} +namespace NUnit.Framework +{ + /// + /// An IProtectable can be run and can throw an Exception. + /// + /// + public interface IProtectable + { + /// Run the the following method protected. + void Protect(); + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/ITest.cs b/mcs/nunit/src/NUnitCore/ITest.cs index 91ee9826715ca..098f4c0f23f53 100644 --- a/mcs/nunit/src/NUnitCore/ITest.cs +++ b/mcs/nunit/src/NUnitCore/ITest.cs @@ -1,14 +1,18 @@ -namespace NUnit.Framework { - - /// An ITest can be run and collect its results. - /// - public interface ITest { - /// Counts the number of test cases that will be run by this - /// test. - int CountTestCases { get; } - - /// Runs a test and collects its result in a - /// instance. - void Run(TestResult result); - } +namespace NUnit.Framework +{ + /// An ITest can be run and collect its results. + /// + public interface ITest + { + /// + /// Counts the number of test cases that will be run by this test. + /// + int CountTestCases { get; } + /// + /// Runs a test and collects its result in a + /// instance. + /// + /// + void Run(TestResult result); + } } diff --git a/mcs/nunit/src/NUnitCore/ITestCollector.cs b/mcs/nunit/src/NUnitCore/ITestCollector.cs index 920ff19a59037..40bf089be8376 100644 --- a/mcs/nunit/src/NUnitCore/ITestCollector.cs +++ b/mcs/nunit/src/NUnitCore/ITestCollector.cs @@ -1,15 +1,16 @@ -namespace NUnit.Runner { - using System.Collections; - - /// - /// Collects Test class names to be presented by the TestSelector. - /// - /// - public interface ITestCollector { - - /// - /// Returns a StringCollection of qualified class names. - /// - Hashtable CollectTests(); - } +namespace NUnit.Runner +{ + using System; + + /// + /// Collects Test classes to be presented by the TestSelector. + /// + /// + public interface ITestCollector + { + /// + /// Returns an array of FullNames for classes that are tests. + /// + string[] CollectTestsClassNames(); + } } diff --git a/mcs/nunit/src/NUnitCore/ITestListener.cs b/mcs/nunit/src/NUnitCore/ITestListener.cs index 175814b5d32be..87726ea95d48e 100644 --- a/mcs/nunit/src/NUnitCore/ITestListener.cs +++ b/mcs/nunit/src/NUnitCore/ITestListener.cs @@ -1,78 +1,65 @@ -namespace NUnit.Framework { - - using System; +namespace NUnit.Framework +{ + using System; - /// A Listener for test progress - public interface ITestListener { - /// An error occurred. - void AddError(ITest test, Exception t); - - /// A failure occurred. - void AddFailure(ITest test, AssertionFailedError t); + /// A Listener for test progress + public interface ITestListener + { + /// An error occurred. + void AddError(ITest test, Exception ex); - /// A test ended. - void EndTest(ITest test); + /// A failure occurred. + void AddFailure(ITest test, AssertionFailedError ex); - /// A test started. - void StartTest(ITest test); - } - /// - /// - /// - public delegate void TestEventHandler(Object source, TestEventArgs e); - /// - /// - /// - public class TestEventArgs : EventArgs{ - /// - /// - /// - protected ITest fTest; - /// - /// - /// - protected TestEventArgs (){} - /// - /// - /// - /// - public TestEventArgs (ITest test){ - fTest = test; - } - /// - /// - /// - public ITest Test{ - get{return fTest;} - } - } - /// - /// - /// - public delegate void TestExceptionEventHandler(Object source, - TestExceptionEventArgs e); - /// - /// - /// - public class TestExceptionEventArgs : TestEventArgs{ - private TestExceptionEventArgs(){} + /// A test ended. + void EndTest(ITest test); - private Exception fThrownException; - /// - /// - /// - /// - /// - public TestExceptionEventArgs(ITest test, Exception e){ - //this(test); - fTest = test; - fThrownException = e; - } - /// - /// - /// - public Exception ThrownException{ - get{return fThrownException;} - } - } -} + /// A test started. + void StartTest(ITest test); + } +#if false + public class TestEventArgs : System.EventArgs + { + private readonly ITest fTest; + public TestEventArgs(ITest test) : base() + { + fTest = test; + } + public ITest Test + { + get { return fTest;} + } + } + public class TestErrorArgs : TestEventArgs + { + private readonly Exception fThrownException; + + public TestErrorArgs(ITest test, Exception thrownException) : base(test) + { + fThrownException = thrownException; + } + + public TestErrorArgs(TestFailure error) + : this(error.FailedTest,error.ThrownException){} + + public Exception ThrownException + { + get { return fThrownException;} + + } + } + + public delegate void TestErrorHandler(TestFailure failure); + public delegate void TestEventHandler(ITest test); + + public interface ITestEvents + { + event TestErrorHandler TestErred; + event TestErrorHandler TestFailed; + event TestEventHandler TestStarted; + event TestEventHandler TestEnded; + event TestEventHandler RunStarted; + event TestEventHandler RunEnded; + } +#endif +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/ITestSuiteLoader.cs b/mcs/nunit/src/NUnitCore/ITestSuiteLoader.cs index f7bc5bdc1f05e..71f7da29f6e79 100644 --- a/mcs/nunit/src/NUnitCore/ITestSuiteLoader.cs +++ b/mcs/nunit/src/NUnitCore/ITestSuiteLoader.cs @@ -1,17 +1,17 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ + using System; - using System; - - /// An interface to define how a test suite should be - /// loaded. - public interface ITestSuiteLoader { - /// - /// - /// - Type Load(string suiteClassName); - /// - /// - /// - Type Reload(Type aType); - } + /// + /// An interface to define how a test suite should be loaded. + /// + [Obsolete("Use ILoader")] + public interface ITestSuiteLoader + { + /// + /// + /// + Type Load(string suiteClassName); + //Type Reload(Type aType); + } } diff --git a/mcs/nunit/src/NUnitCore/LoadingTestCollector.cs b/mcs/nunit/src/NUnitCore/LoadingTestCollector.cs index 63ac74ef5f007..4938ee952e920 100644 --- a/mcs/nunit/src/NUnitCore/LoadingTestCollector.cs +++ b/mcs/nunit/src/NUnitCore/LoadingTestCollector.cs @@ -1,71 +1,54 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ + using System; + using System.Reflection; + using NUnit.Framework; - using System; - using System.Reflection; - - using NUnit.Framework; - - /// - /// An implementation of a TestCollector that loads - /// all classes on the class path and tests whether - /// it is assignable from ITest or provides a static Suite property. - /// - /// - public class LoadingClassPathTestCollector: ClassPathTestCollector { - - TestCaseClassLoader fLoader; /// - /// + /// An implementation of a TestCollector that loads + /// all classes on the class path and tests whether + /// it is assignable from ITest or provides a static Suite property. + /// /// - public LoadingClassPathTestCollector() { - fLoader= new TestCaseClassLoader(); - } - /// - /// - /// - /// - /// - protected override bool IsTestClass(string classFileName) { - try { - if (classFileName.EndsWith(".dll") || classFileName.EndsWith(".exe")) { - Type testClass= ClassFromFile(classFileName); - return (testClass != null) && IsTestClass(testClass); - } - } catch (TypeLoadException) { - } - return false; - } - - Type ClassFromFile(string classFileName) { - string className= ClassNameFromFile(classFileName); - if (!fLoader.IsExcluded(className)) - return fLoader.LoadClass(className, false); - return null; - } - - bool IsTestClass(Type testClass) { - if (HasSuiteMethod(testClass)) - return true; - if (typeof(ITest).IsAssignableFrom(testClass) && - testClass.IsPublic && - HasPublicConstructor(testClass)) - return true; - return false; - } + [Obsolete("Use StandardLoader or UnloadingLoader")] + public class LoadingClassPathTestCollector: ClassPathTestCollector + { - bool HasSuiteMethod(Type testClass) { - return (testClass.GetProperty(BaseTestRunner.SUITE_PROPERTYNAME, new Type[0]) == null); - } + TestCaseClassLoader fLoader; + /// + /// + /// + public LoadingClassPathTestCollector() + { + fLoader= new TestCaseClassLoader(); + } + /// + /// + /// + /// + /// + protected override bool IsTestClass(string classFileName) + { + try + { + if (classFileName.EndsWith(".dll") || classFileName.EndsWith(".exe")) + { + Type testClass= ClassFromFile(classFileName); + return (testClass != null); //HACK: && TestCase.IsTest(testClass); + } + } + catch (TypeLoadException) + { + } + return false; + } - bool HasPublicConstructor(Type testClass) { - Type[] args= { typeof(string) }; - ConstructorInfo c= null; - try { - c= testClass.GetConstructor(args); - } catch(Exception) { - return false; - } - return true; - } - } + private Type ClassFromFile(string classFileName) + { + string className = base.ClassNameFromFile(classFileName); + if (!fLoader.IsExcluded(className)) + return fLoader.LoadClass(className, false); + return null; + } + } } \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/NUnitException.cs b/mcs/nunit/src/NUnitCore/NUnitException.cs index 155fe74154753..f0273ef791f3d 100644 --- a/mcs/nunit/src/NUnitCore/NUnitException.cs +++ b/mcs/nunit/src/NUnitCore/NUnitException.cs @@ -1,24 +1,51 @@ -namespace NUnit.Framework { - - using System; - using System.Diagnostics; +namespace NUnit.Framework +{ + using System; + using System.Diagnostics; + using System.Runtime.Serialization; - /// Thrown when an assertion failed. Here to preserve the inner - /// exception and hence its stack trace. - public class NUnitException: ApplicationException { - /// - /// - /// - /// - /// - public NUnitException(string message, Exception inner) : - base(message, inner) { } - /// - /// - /// - public bool IsAssertionFailure { - get { return InnerException.GetType() == typeof(AssertionFailedError); } - } - } -} + /// + /// Thrown when an assertion failed. Here to preserve the inner + /// exception and hence its stack trace. + /// + [Serializable] + public class NUnitException : ApplicationException + { + /// + /// Serialization Constructor + /// + protected NUnitException(SerializationInfo info, + StreamingContext context) : base(info,context){} + /// + /// Standard constructor + /// + /// The error message that explains + /// the reason for the exception + public NUnitException(string message) : base (message){} + /// + /// Standard constructor + /// + /// The error message that explains + /// the reason for the exception + /// The exception that caused the + /// current exception + public NUnitException(string message, Exception inner) : + base(message, inner) {} + /// + /// Indicates that this exception wraps an AssertionFailedError + /// exception + /// + public virtual bool IsAssertionFailure + { + get + { + AssertionFailedError inner = this.InnerException + as AssertionFailedError; + if(inner != null) + return true; + return false; + } + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/ReflectionUtils.cs b/mcs/nunit/src/NUnitCore/ReflectionUtils.cs index 19f656f04c421..491e0e7ec9169 100644 --- a/mcs/nunit/src/NUnitCore/ReflectionUtils.cs +++ b/mcs/nunit/src/NUnitCore/ReflectionUtils.cs @@ -1,74 +1,94 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ - using System; - using System.Collections; - using System.Collections.Specialized; - using System.IO; - using System.Reflection; + using System; + using System.Collections; + using System.Collections.Specialized; + using System.IO; + using System.Reflection; - using NUnit.Framework; -/// -/// -/// - public class ReflectionUtils{ -/// -/// -/// -/// -/// - public static bool HasTests(Type testClass) { + using NUnit.Framework; + /// + /// + /// + [Obsolete("Use Standar Loader")] + public class ReflectionUtils + { + /// + /// + /// + /// + /// + [Obsolete("Use Standar Loader")] + public static bool HasTests(Type testClass) + { - PropertyInfo suiteProperty= null; - suiteProperty = testClass.GetProperty("Suite", new Type[0]); - if (suiteProperty == null ) { - // try to extract a test suite automatically - bool result = false; - TestSuite dummy = new TestSuite(testClass, ref result); - return result; - } - ITest test= null; - try { - // static property - test= (ITest)suiteProperty.GetValue(null, new Type[0]); - if (test == null) - return false; - } catch(Exception) { - return false; - } - return true; - } -/// -/// -/// -/// -/// - public static StringCollection GetAssemblyClasses(string assemblyName){ - StringCollection classNames = new StringCollection (); - try { - Assembly testAssembly = Assembly.LoadFrom(assemblyName); + PropertyInfo suiteProperty= null; + suiteProperty = testClass.GetProperty("Suite", new Type[0]); + if (suiteProperty == null ) + { + // try to extract a test suite automatically + TestSuite dummy = new TestSuite(testClass, true); + return (dummy.CountTestCases > 0); + } + ITest test= null; + try + { + // static property + test= (ITest)suiteProperty.GetValue(null, new Type[0]); + if (test == null) + return false; + } + catch(Exception) + { + return false; + } + return true; + } + /// + /// + /// + /// + /// + [Obsolete("Use Standar Loader")] + public static StringCollection GetAssemblyClasses(string assemblyName) + { + StringCollection classNames = new StringCollection (); + try + { + Assembly testAssembly = Assembly.LoadFrom(assemblyName); - foreach(Type testType in testAssembly.GetExportedTypes()){ - if(testType.IsClass && HasTests(testType)){ - classNames.Add(testType.FullName); - } - } - }catch(ReflectionTypeLoadException rcle){ + foreach(Type testType in testAssembly.GetExportedTypes()) + { + if(testType.IsClass && HasTests(testType)) + { + classNames.Add(testType.FullName); + } + } + } + catch(ReflectionTypeLoadException rcle) + { - Type[] loadedTypes = rcle.Types; - Exception[] exceptions = rcle.LoaderExceptions; + Type[] loadedTypes = rcle.Types; + Exception[] exceptions = rcle.LoaderExceptions; - int exceptionCount = 0; + int exceptionCount = 0; - for ( int i =0; i < loadedTypes.Length; i++ ){ - Console.Error.WriteLine("Unable to load a type because {0}", exceptions[exceptionCount] ); - exceptionCount++; - } - }catch(FileNotFoundException fnfe){ - Console.Error.WriteLine(fnfe.Message); - }catch(Exception e){ - Console.Error.WriteLine("Error reading file {0}: {1}", assemblyName, e.Message); - } - return classNames; - } - } -} + for ( int i =0; i < loadedTypes.Length; i++ ) + { + Console.Error.WriteLine("Unable to load a type because {0}", exceptions[exceptionCount] ); + exceptionCount++; + } + } + catch(FileNotFoundException fnfe) + { + Console.Error.WriteLine(fnfe.Message); + } + catch(Exception e) + { + Console.Error.WriteLine("Error reading file {0}: {1}", assemblyName, e.Message); + } + return classNames; + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/ReloadingTestSuiteLoader.cs b/mcs/nunit/src/NUnitCore/ReloadingTestSuiteLoader.cs index 14aaac27b5db9..de222ed9d77b1 100644 --- a/mcs/nunit/src/NUnitCore/ReloadingTestSuiteLoader.cs +++ b/mcs/nunit/src/NUnitCore/ReloadingTestSuiteLoader.cs @@ -1,28 +1,33 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ - using System; + using System; - /// A TestSuite loader that can reload classes. - public class ReloadingTestSuiteLoader: ITestSuiteLoader { - /// - /// - /// - /// - /// - public Type Load(string suiteClassName) { - // TestCaseClassLoader loader= new TestCaseClassLoader(); - // return loader.LoadClass(suiteClassName, true); - return Type.GetType(suiteClassName, true); - } - /// - /// - /// - /// - /// - public Type Reload(Type aClass) { - // TestCaseClassLoader loader= new TestCaseClassLoader(); - // return loader.LoadClass(aClass.ToString(), true); - return aClass; - } - } + /// A TestSuite loader that can reload classes. + [Obsolete("Use StandardLoader or UnloadingLoader")] + public class ReloadingTestSuiteLoader: ITestSuiteLoader + { + /// + /// + /// + /// + /// + public Type Load(string suiteClassName) + { + // TestCaseClassLoader loader= new TestCaseClassLoader(); + // return loader.LoadClass(suiteClassName, true); + return Type.GetType(suiteClassName, true); + } + /// + /// + /// + /// + /// + public Type Reload(Type aClass) + { + // TestCaseClassLoader loader= new TestCaseClassLoader(); + // return loader.LoadClass(aClass.ToString(), true); + return aClass; + } + } } diff --git a/mcs/nunit/src/NUnitCore/StandardTestSuiteLoader.cs b/mcs/nunit/src/NUnitCore/StandardTestSuiteLoader.cs index 7ea7071e7c666..ebdd956576052 100644 --- a/mcs/nunit/src/NUnitCore/StandardTestSuiteLoader.cs +++ b/mcs/nunit/src/NUnitCore/StandardTestSuiteLoader.cs @@ -1,39 +1,47 @@ -namespace NUnit.Runner { +namespace NUnit.Runner +{ + using System; + using System.Reflection; + using System.IO; + using System.Security; - using System; - using System.Reflection; - using System.IO; - using System.Security; + /// + /// The standard test suite loader. It can only load the same + /// class once. + /// + [Obsolete("Use StandardLoader or UnloadingLoader")] + public class StandardTestSuiteLoader: ITestSuiteLoader + { + /// + /// Loads + /// + /// + /// + public Type Load(string testClassName) + { + Type testClass; + string[] classSpec=testClassName.Split(','); + if (classSpec.Length > 1) + { + FileInfo dll=new FileInfo(classSpec[1]); + if (!dll.Exists) + throw new FileNotFoundException("File " + dll.FullName + " not found", dll.FullName); + Assembly a = Assembly.LoadFrom(dll.FullName); + testClass=a.GetType(classSpec[0], true); + } + else + testClass = Type.GetType(testClassName, true); + return testClass; + } - /// The standard test suite loader. It can only load the same - /// class once. - public class StandardTestSuiteLoader: ITestSuiteLoader { - /// - /// - /// - /// - /// - public Type Load(string suiteClassName) { - Type testClass; - string[] classSpec=suiteClassName.Split(','); - if (classSpec.Length > 1) { - FileInfo dll=new FileInfo(classSpec[1]); - if (!dll.Exists) - throw new FileNotFoundException("File " + dll.FullName + " not found", dll.FullName); - Assembly a = Assembly.LoadFrom(dll.FullName); - testClass=a.GetType(classSpec[0], true); - } - else - testClass = Type.GetType(suiteClassName, true); - return testClass; - } - /// - /// - /// - /// - /// - public Type Reload(Type aClass) { - return aClass; - } - } + /// + /// + /// + /// + /// + public Type Reload(Type aClass) + { + return aClass; + } + } } \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/TestCase.cs b/mcs/nunit/src/NUnitCore/TestCase.cs index 45f54d6d0bb0c..e2e746394bf95 100644 --- a/mcs/nunit/src/NUnitCore/TestCase.cs +++ b/mcs/nunit/src/NUnitCore/TestCase.cs @@ -1,196 +1,241 @@ -namespace NUnit.Framework { - - using System; - using System.Reflection; - /// A test case defines the fixture to run multiple Tests. - /// To define a test case - /// - /// implement a subclass of TestCase - /// define instance variables that store the state - /// of the fixture - /// initialize the fixture state by overriding - /// SetUp - /// clean-up after a test by overriding - /// TearDown - /// - /// Each test runs in its own fixture so there - /// can be no side effects among test runs. - /// Here is an example: - /// - /// public class MathTest: TestCase { - /// protected double fValue1; - /// protected double fValue2; - /// - /// public MathTest(string name) : base(name) {} - /// - /// protected override void SetUp() { - /// fValue1= 2.0; - /// fValue2= 3.0; - /// } - /// } - /// - /// - /// For each test implement a method which interacts - /// with the fixture. Verify the expected results with Assertions specified - /// by calling Assert with a bool. - /// - /// protected void TestAdd() { - /// double result= fValue1 + fValue2; - /// Assert(result == 5.0); - /// } - /// - /// Once the methods are defined you can run them. The framework supports - /// both a static type safe and more dynamic way to run a test. - /// In the static way you override the runTest method and define the method - /// to be invoked. - /// - /// protected class AddMathTest: TestCase { - /// public void AddMathTest(string name) : base(name) {} - /// protected override void RunTest() { TestAdd(); } - /// } - /// - /// test test= new AddMathTest("Add"); - /// test.Run(); - /// - /// The dynamic way uses reflection to implement RunTest. It - /// dynamically finds and invokes a method. In this case the name of the - /// test case has to correspond to the test method to be run. - /// - /// test= new MathTest("TestAdd"); - /// test.Run(); - /// - /// The Tests to be run can be collected into a . - /// NUnit provides different test runners which can run a test suite - /// and collect the results. - /// A test runner either expects a static property Suite as the entry - /// point to get a test to run or it will extract the suite automatically. - /// - /// public static ITest Suite { - /// get { - /// suite.AddTest(new MathTest("TestAdd")); - /// suite.AddTest(new MathTest("TestDivideByZero")); - /// return suite; - /// } - /// } - /// - /// - /// - public abstract class TestCase: Assertion, ITest { - - /// the name of the test case. - private readonly string name; - - /// Constructs a test case with the given name. - public TestCase(string TestName) { - name = TestName; - } - - /// Counts the number of test cases executed by - /// Run(TestResult result). - public int CountTestCases { - get { return 1; } - } - - /// Creates a default object. - protected TestResult CreateResult() { - return new TestResult(); - } - - /// The name of the test case. - public string Name { - get { return name; } - } - - /// A convenience method to run this test, collecting the - /// results with a default object. - public TestResult Run() { - TestResult result= CreateResult(); - Run(result); - return result; - } - - /// Runs the test case and collects the results in - /// TestResult. - public void Run(TestResult result) { - result.Run(this); - } - - /// Runs the bare test sequence. - public void RunBare() { - SetUp(); - try { - RunTest(); - } - finally { - TearDown(); - } - } - - /// Override to run the test and Assert its state. - protected virtual void RunTest() { - MethodInfo runMethod= GetType().GetMethod(name, new Type[0]); - if (runMethod == null) - Fail("Method \""+name+"\" not found"); +namespace NUnit.Framework +{ + using System; + using System.Reflection; + + /// A test case defines the fixture to run multiple Tests. + /// To define a test case + /// + /// implement a subclass of TestCase + /// define instance variables that store the state + /// of the fixture + /// initialize the fixture state by overriding + /// SetUp + /// clean-up after a test by overriding + /// TearDown + /// + /// Each test runs in its own fixture so there can be no side effects + /// among test runs. + /// Here is an example: + /// + /// public class MathTest: TestCase { + /// protected double fValue1; + /// protected double fValue2; + /// + /// public MathTest(string name) : base(name) {} + /// + /// protected override void SetUp() { + /// fValue1= 2.0; + /// fValue2= 3.0; + /// } + /// } + /// + /// + /// For each test implement a method which interacts with the fixture. + /// Verify the expected results with Assertions specified by calling + /// Assert with a bool. + /// + /// protected void TestAdd() { + /// double result= fValue1 + fValue2; + /// Assert(result == 5.0); + /// } + /// + /// Once the methods are defined you can run them. The framework supports + /// both a static type safe and more dynamic way to run a test. + /// In the static way you override the runTest method and define the method + /// to be invoked. + /// + /// protected class AddMathTest: TestCase { + /// public void AddMathTest(string name) : base(name) {} + /// protected override void RunTest() { TestAdd(); } + /// } + /// + /// test test= new AddMathTest("Add"); + /// test.Run(); + /// + /// The dynamic way uses reflection to implement RunTest. It + /// dynamically finds and invokes a method. In this case the name of the + /// test case has to correspond to the test method to be run. + /// + /// test= new MathTest("TestAdd"); + /// test.Run(); + /// + /// The Tests to be run can be collected into a . + /// NUnit provides different test runners which can run a test suite + /// and collect the results. + /// A test runner either expects a static property Suite as the entry + /// point to get a test to run or it will extract the suite automatically. + /// + /// public static ITest Suite { + /// get { + /// suite.AddTest(new MathTest("TestAdd")); + /// suite.AddTest(new MathTest("TestDivideByZero")); + /// return suite; + /// } + /// } + /// + /// + /// + public abstract class TestCase: Assertion, ITest + { + #region Instance Variables + /// the name of the test case. + private readonly string fName; + #endregion + + #region Constructors + /// Constructs a test case with no name. + public TestCase() : this(String.Empty){} + + /// Constructs a test case with the given name. + public TestCase(string testName) + { + this.fName = testName; + } + #endregion + + #region Properties + /// Counts the number of test cases executed by + /// Run(TestResult result). + public int CountTestCases + { + get { return 1; } + } + + /// The name of the test case. + public string Name + { + get { return this.fName; } + } + #endregion + + #region Utility Methods + /// Creates a default object. + protected TestResult CreateResult() + { + return new TestResult(); + } + #endregion + + #region Run Methods + /// A convenience method to run this test, collecting the + /// results with a default object. + public TestResult Run() + { + TestResult result = this.CreateResult(); + this.Run(result); + return result; + } + + /// Runs the test case and collects the results in + /// TestResult. + public void Run(TestResult result) + { + result.Run(this); + } + + /// Runs the bare test sequence. + public void RunBare() + { + this.SetUp(); + try + { + this.RunTest(); + } + finally + { + this.TearDown(); + } + } + + /// Override to run the test and Assert its state. + protected virtual void RunTest() + { + MethodInfo runMethod = GetType().GetMethod(this.Name, new Type[0]); + if (runMethod == null) + Assertion.Fail("Method \""+this.Name+"\" not found"); - if (runMethod != null && !runMethod.IsPublic) { - Fail("Method \""+name+"\" should be public"); - } + if (runMethod != null && !runMethod.IsPublic) + { + Assertion.Fail("Method \""+this.Name+"\" should be public"); + } object[] exa = - runMethod.GetCustomAttributes(typeof(ExpectExceptionAttribute),true); - - try { - runMethod.Invoke(this, null); - } - catch (TargetInvocationException e) { - Exception i = e.InnerException; - if (i is AssertionFailedError) { - throw new NUnitException("", i); - } + runMethod.GetCustomAttributes(typeof(ExpectExceptionAttribute),true); - if (exa.Length > 0) { - foreach (ExpectExceptionAttribute ex in exa) { - if (ex.ExceptionExpected.IsAssignableFrom(i.GetType())) - return; - } - Fail("Wrong exception: " + i); - } else - throw new NUnitException("", i); - } - catch (MemberAccessException e) + try + { + runMethod.Invoke(this, null); + } + catch (AssertionFailedError e) + { + throw new NUnitException("Run Error: ", e); + } + catch (TargetInvocationException e) + { + Exception inner = e.InnerException; + if (inner is AssertionFailedError) + { + throw new NUnitException("Run Error: ", inner); + } + if (exa.Length>0) + { + foreach (ExpectExceptionAttribute ex in exa) + { + if (ex.ExceptionExpected.IsAssignableFrom(inner.GetType())) + return; + } + Assertion.Fail("Unexpected Exception thrown: " + inner); + } + else + { + throw new NUnitException("Run Error: ", inner); + } + } + catch (MemberAccessException e) { throw new NUnitException("", e); } - if (exa.Length > 0) { - System.Text.StringBuilder sb = - new System.Text.StringBuilder - ("One of these exceptions should have been thrown: "); - bool first = true; - foreach (ExpectExceptionAttribute ex in exa) { - if (first) - first = false; - else - sb.Append(", "); - sb.Append(ex); - } - Fail(sb.ToString()); - } - } - - /// Sets up the fixture, for example, open a network connection. - /// This method is called before a test is executed. - protected virtual void SetUp() { - } - - /// Tears down the fixture, for example, close a network - /// connection. This method is called after a test is executed. - protected virtual void TearDown() { - } - - /// Returns a string representation of the test case. - public override string ToString() { - return name+"("+GetType().ToString()+")"; - } - } -} + if (exa.Length > 0) + { + System.Text.StringBuilder sb = + new System.Text.StringBuilder + ("One of these exceptions should have been thrown: "); + bool first = true; + foreach (ExpectExceptionAttribute ex in exa) + { + if(first) + first = false; + else + sb.Append(", "); + sb.Append(ex); + } + Assertion.Fail(sb.ToString()); + } + } + + /// + /// Sets up the fixture, for example, open a network connection. + /// This method is called before a test is executed. + /// + protected virtual void SetUp() {} + /// + /// Tears down the fixture, for example, close a network + /// connection. This method is called after a test is executed. + /// + protected virtual void TearDown() {} + #endregion + + #region Overrides + /// + /// Returns a string representation of the test case. + /// + public override string ToString() + { + return this.Name+"("+this.GetType().ToString()+")"; + } + #endregion + + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/TestCaseClassLoader.cs b/mcs/nunit/src/NUnitCore/TestCaseClassLoader.cs index 52a73b6855e12..80fc7e891001b 100644 --- a/mcs/nunit/src/NUnitCore/TestCaseClassLoader.cs +++ b/mcs/nunit/src/NUnitCore/TestCaseClassLoader.cs @@ -1,37 +1,42 @@ -namespace NUnit.Runner { - using System; -/// -/// -/// - public class TestCaseClassLoader : StandardTestSuiteLoader { - /// - /// - /// - /// - /// - /// - public Type LoadClass(string name, bool resolve) { - return Load(name); - } -/// -/// -/// -/// -/// - public bool IsExcluded(string name) { - return false; - } - } +namespace NUnit.Runner +{ + using System; + + /// + /// + /// + [Obsolete("Use StandardLoader or UnloadingLoader")] + public class TestCaseClassLoader : StandardTestSuiteLoader + { + /// + /// + /// + /// + /// + /// + public Type LoadClass(string name, bool resolve) + { + return Load(name); + } + /// + /// + /// + /// + /// + public bool IsExcluded(string name) + { + return false; + } + } } #if false - // commented out till figure out .net class reloading namespace NUnit.Runner { - /** + /** * A custom class loader which enables the reloading * of classes for each test run. The class loader * can be configured with a list of package paths that @@ -200,5 +205,4 @@ public class TestCaseClassLoader: ClassLoader { return excluded; } } - #endif diff --git a/mcs/nunit/src/NUnitCore/TestDecorator.cs b/mcs/nunit/src/NUnitCore/TestDecorator.cs index 0275391235037..eded1c24ba5e7 100644 --- a/mcs/nunit/src/NUnitCore/TestDecorator.cs +++ b/mcs/nunit/src/NUnitCore/TestDecorator.cs @@ -1,56 +1,71 @@ -namespace NUnit.Extensions { +namespace NUnit.Extensions +{ + using System; + using NUnit.Framework; - using System; - - using NUnit.Framework; - - /// A Decorator for Tests. - /// Use TestDecorator as the base class - /// for defining new test decorators. TestDecorator subclasses - /// can be introduced to add behaviour before or after a test - /// is run. - public class TestDecorator: Assertion, ITest { - /// - /// - /// - protected readonly ITest fTest; - /// - /// - /// - /// - public TestDecorator(ITest test) { - fTest= test; - } - - /// The basic run behaviour. - public void BasicRun(TestResult result) { - fTest.Run(result); - } - /// - /// - /// - public virtual int CountTestCases { - get { return fTest.CountTestCases; } - } - /// - /// - /// - public ITest GetTest { - get { return fTest; } - } - /// - /// - /// - /// - public virtual void Run(TestResult result) { - BasicRun(result); - } - /// - /// - /// - /// - public override string ToString() { - return fTest.ToString(); - } - } -} + /// A Decorator for Tests. + /// Use TestDecorator as the base class + /// for defining new test decorators. TestDecorator subclasses + /// can be introduced to add behaviour before or after a test + /// is run. + public class TestDecorator: Assertion, ITest + { + /// + /// A reference to the test that is being decorated + /// + protected readonly ITest fTest; + /// + /// Creates a decorator for the supplied test + /// + /// The test to be decorated + public TestDecorator(ITest test) + { + if(test!= null) + { + this.fTest= test; + } + else + throw new ArgumentNullException("test"); + } + /// + /// + /// + /// + public virtual void Run(TestResult result) + { + this.BasicRun(result); + } + /// The basic run behaviour. + public void BasicRun(TestResult result) + { + this.fTest.Run(result); + } + /// + /// + /// + public virtual int CountTestCases + { + get { return fTest.CountTestCases; } + } + /// + /// + /// + public ITest GetTest + { + get { return fTest; } + } + //public string Name + //{ + // get{return fTest.Name;} + //} + + /// + /// + /// + /// + public override string ToString() + { + return fTest.ToString(); + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/TestFailure.cs b/mcs/nunit/src/NUnitCore/TestFailure.cs index 7d768b494bac6..4dad5bd02bd04 100644 --- a/mcs/nunit/src/NUnitCore/TestFailure.cs +++ b/mcs/nunit/src/NUnitCore/TestFailure.cs @@ -1,44 +1,55 @@ -namespace NUnit.Framework { - - using System; - using System.Diagnostics; - using System.IO; - using System.Text; +namespace NUnit.Framework +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Text; - /// A TestFailure collects a failed test together with - /// the caught exception. - /// - public class TestFailure { - private readonly ITest failedTest; - private readonly Exception thrownException; + /// + /// A TestFailure collects a failed test together with + /// the caught exception. + /// + /// + public class TestFailure : MarshalByRefObject + { + private readonly ITest fFailedTest; + private readonly Exception fThrownException; - /// Constructs a TestFailure with the given test and - /// exception. - public TestFailure(ITest theFailedTest, Exception theThrownException) { - failedTest= theFailedTest; - thrownException= theThrownException; - } + /// + /// Constructs a TestFailure with the given test and exception. + /// + public TestFailure(ITest theFailedTest, Exception theThrownException) + { + if(theFailedTest==null) + throw new ArgumentNullException("theFailedTest"); + if(theThrownException==null) + throw new ArgumentNullException("theThrownException"); + this.fFailedTest = theFailedTest; + this.fThrownException = theThrownException; + } - /// Gets the failed test. - public ITest FailedTest { - get { return failedTest; } - } + /// Gets the failed test. + public ITest FailedTest + { + get { return this.fFailedTest; } + } - /// True if it's a failure, false if error. - public bool IsFailure { - get { return thrownException is AssertionFailedError; } - } + /// True if it's a failure, false if error. + public bool IsFailure + { + get { return this.fThrownException is AssertionFailedError; } + } - /// Gets the thrown exception. - public Exception ThrownException { - get { return thrownException; } - } + /// Gets the thrown exception. + public Exception ThrownException + { + get { return this.fThrownException; } + } - /// Returns a short description of the failure. - public override string ToString() { - StringBuilder buffer= new StringBuilder(); - buffer.Append(failedTest+": "+thrownException.Message); - return buffer.ToString(); - } - } -} + /// Returns a short description of the failure. + public override string ToString() + { + return this.fFailedTest + ": " + this.fThrownException.Message; + } + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/TestResult.cs b/mcs/nunit/src/NUnitCore/TestResult.cs index 9b0bfb7590d48..ff274a8c4ff22 100644 --- a/mcs/nunit/src/NUnitCore/TestResult.cs +++ b/mcs/nunit/src/NUnitCore/TestResult.cs @@ -1,181 +1,249 @@ -namespace NUnit.Framework { - - using System; - using System.Collections; - using System.Threading; - - /// A TestResult collects the results of executing - /// a test case. It is an instance of the Collecting Parameter pattern. - /// - /// The test framework distinguishes between failures and errors. - /// A failure is anticipated and checked for with assertions. Errors are - /// unanticipated problems like an ArgumentOutOfRangeException. - /// - public class TestResult { - private ArrayList fFailures; - private ArrayList fErrors; - private ArrayList fListeners; - private int fRunTests; - private bool fStop; - /// - /// - /// - public TestResult() { - fFailures= new ArrayList(); - fErrors= new ArrayList(); - fListeners= new ArrayList(); - } - - /// Adds an error to the list of errors. The passed in exception - /// caused the error. - public void AddError(ITest test, Exception t) { - lock(this) { - fErrors.Add(new TestFailure(test, t)); - foreach (ITestListener l in CloneListeners()) { - l.AddError(test, t); - } - } - } - - /// Adds a failure to the list of failures. The passed in - /// exception caused the failure. - public void AddFailure(ITest test, AssertionFailedError t) { - lock(this) - { - fFailures.Add(new TestFailure(test, t)); - foreach (ITestListener l in CloneListeners()) { - l.AddFailure(test, t); - } - } - } - - /// Registers a TestListener. - public void AddListener(ITestListener listener) { - lock(this) - fListeners.Add(listener); - } - - /// Returns a copy of the listeners. - private ArrayList CloneListeners() { - lock(this) - return (ArrayList)fListeners.Clone(); - } - - /// Informs the result that a test was completed. - public void EndTest(ITest test) { - foreach (ITestListener l in CloneListeners()) { - l.EndTest(test); - } - } - - /// Gets the number of detected errors. - public int ErrorCount { - get {return fErrors.Count; } - } - - /// Returns an IEnumerable for the errors. - public IEnumerable Errors { - get { return fErrors; } - } - - /// Gets the number of detected failures. - public int FailureCount { - get {return fFailures.Count; } - } - - /// Returns an IEnumerable for the failures. - public IEnumerable Failures { - get { return fFailures; } - } - - /// Runs a TestCase. - protected class ProtectedProtect: IProtectable { - private TestCase fTest; +namespace NUnit.Framework +{ + using System; + using System.Collections; + using System.Threading; + + /// A TestResult collects the results of executing + /// a test case. It is an instance of the Collecting Parameter pattern. + /// + /// The test framework distinguishes between failures and errors. + /// A failure is anticipated and checked for with assertions. Errors are + /// unanticipated problems like an ArgumentOutOfRangeException. + /// + public class TestResult : MarshalByRefObject + { + #region Instance Variables + private ArrayList fFailures; + private ArrayList fErrors; + private ArrayList fListeners; + private int fRunTests; + private bool fStop; + #endregion + + #region Constructors /// /// /// - /// - public ProtectedProtect(TestCase test) { - fTest = test; - } + public TestResult() + { + fFailures= new ArrayList(); + fErrors= new ArrayList(); + fListeners= new ArrayList(); + } + #endregion + + #region Collection Methods /// - /// + /// Adds an error to the list of errors. The passed in exception + /// caused the error. /// - public void Protect() { - fTest.RunBare(); - } - } - - /// Unregisters a TestListener - public void RemoveListener(ITestListener listener) { - lock(this) { - fListeners.Remove(listener); - } - } - - /// Runs a TestCase. - internal void Run(TestCase test) { - StartTest(test); - IProtectable p = new ProtectedProtect(test); - RunProtected(test, p); - - EndTest(test); - } - - /// Gets the number of run tests. - public int RunCount { - get {return fRunTests; } - } - - /// Runs a TestCase. - public void RunProtected(ITest test, IProtectable p) { - try { - p.Protect(); - } - catch (NUnitException e) { - if (e.IsAssertionFailure) - AddFailure(test, (AssertionFailedError)e.InnerException); - else - AddError(test, e.InnerException); - } - catch (ThreadAbortException e) { // don't catch by accident - throw e; - } - catch (AssertionFailedError e) { - AddFailure(test, e); - } - catch (System.Exception e) { - AddError(test, e); - } - } - - /// Checks whether the test run should stop. - public bool ShouldStop { - get {return fStop; } - } - - /// Informs the result that a test will be started. - public void StartTest(ITest test) { - int count = test.CountTestCases; - lock(this) - fRunTests += count; - foreach (ITestListener l in CloneListeners()) { - l.StartTest(test); - } - } - - /// Marks that the test run should stop. - public void Stop() { - fStop= true; - } - - /// Returns whether the entire test was successful or not. - public bool WasSuccessful { - get { - lock(this) - return (FailureCount == 0) && (ErrorCount == 0); - } - } - } -} - + public void AddError(ITest test, Exception error) + { + lock(this) + { + this.fErrors.Add(new TestFailure(test, error)); + foreach (ITestListener listner in CloneListeners()) + { + listner.AddError(test, error); + } + } + } + /// + /// Adds a failure to the list of failures. The passed in + /// exception caused the failure. + /// + public void AddFailure(ITest test, AssertionFailedError failure) + { + lock(this) + { + fFailures.Add(new TestFailure(test, failure)); + foreach (ITestListener listner in CloneListeners()) + { + listner.AddFailure(test, failure); + } + } + } + #endregion + + #region Events + /// Registers a TestListener. + public void AddListener(ITestListener listener) + { + lock(this) + this.fListeners.Add(listener); + } + /// Unregisters a TestListener + public void RemoveListener(ITestListener listener) + { + lock(this) + { + fListeners.Remove(listener); + } + } + /// Returns a copy of the listeners. + private ArrayList CloneListeners() + { + lock(this) + { + return (ArrayList)fListeners.Clone(); + } + } + /// Informs the result that a test was completed. + public void EndTest(ITest test) + { + foreach (ITestListener listner in CloneListeners()) + { + listner.EndTest(test); + } + } + /// Informs the result that a test will be started. + public void StartTest(ITest test) + { + lock(this) + { + this.fRunTests += test.CountTestCases; + } + foreach (ITestListener listner in CloneListeners()) + { + listner.StartTest(test); + } + } + #endregion + + #region Properties + /// Gets the number of run tests. + public int RunCount + { + get {lock(this)return this.fRunTests; } + } + /// Gets the number of detected errors. + public int ErrorCount + { + get {lock(this)return this.fErrors.Count; } + } + /// Gets the number of detected failures. + public int FailureCount + { + get {lock(this)return this.fFailures.Count; } + } + /// Checks whether the test run should stop. + public bool ShouldStop + { + get {lock(this)return this.fStop; } + } + /// Returns whether the entire test was successful or not. + public bool WasSuccessful + { + get + { + lock(this) + { + return (this.FailureCount == 0) + && (this.ErrorCount == 0); + } + } + } + /// Returns a TestFailure[] for the errors. + public TestFailure[] Errors + { + get + { + lock(this) + { + TestFailure[] retVal = new TestFailure[this.fErrors.Count]; + this.fErrors.CopyTo(retVal); + return retVal; + } + } + } + /// Returns a TestFauiler[] for the failures. + public TestFailure[] Failures + { + get + { + lock(this) + { + TestFailure[] retVal = new TestFailure[this.fFailures.Count]; + this.fFailures.CopyTo(retVal); + return retVal; + } + } + } + #endregion + + #region Nested Classes + /// Runs a TestCase. + protected class ProtectedProtect: IProtectable + { + private TestCase fTest; + /// + /// + /// + /// + public ProtectedProtect(TestCase test) + { + if(test != null) + { + this.fTest = test; + } + else + { + throw new ArgumentNullException("test"); + } + } + /// + /// + /// + public void Protect() + { + this.fTest.RunBare(); + } + } + #endregion + + #region Run Methods + /// Runs a TestCase. + internal void Run(TestCase test) + { + StartTest(test); + IProtectable p = new ProtectedProtect(test); + RunProtected(test, p); + EndTest(test); + } + + /// Runs a TestCase. + public void RunProtected(ITest test, IProtectable p) + { + try + { + p.Protect(); + } + catch (AssertionFailedError e) + { + AddFailure(test, e); + } + catch (NUnitException e) + { + if (e.IsAssertionFailure) + AddFailure(test, (AssertionFailedError)e.InnerException); + else + AddError(test, e.InnerException); + } + catch (ThreadAbortException e) + { // don't catch by accident + throw e; + } + catch (System.Exception e) + { + AddError(test, e); + } + } + /// Marks that the test run should stop. + public void Stop() + { + fStop= true; + } + #endregion + } +} \ No newline at end of file diff --git a/mcs/nunit/src/NUnitCore/TestSetup.cs b/mcs/nunit/src/NUnitCore/TestSetup.cs index fb360a6035156..9582350401572 100644 --- a/mcs/nunit/src/NUnitCore/TestSetup.cs +++ b/mcs/nunit/src/NUnitCore/TestSetup.cs @@ -1,58 +1,70 @@ -namespace NUnit.Extensions { +namespace NUnit.Extensions +{ + using System; + using NUnit.Framework; + + /// A Decorator to set up and tear down additional fixture state. + /// + /// Subclass TestSetup and insert it into your tests when you want + /// to set up additional state once before the tests are run. + public class TestSetup: TestDecorator + { + #region Constructors + /// + /// + /// + /// + public TestSetup(ITest test) : base(test) {} + #endregion - using System; + #region Nested Classes + /// + /// + /// + protected class ProtectedProtect: IProtectable + { + private readonly TestSetup fTestSetup; + private readonly TestResult fTestResult; + /// + /// + /// + /// + /// + public ProtectedProtect(TestSetup testSetup, TestResult testResult) + { + if(testSetup == null) + throw new ArgumentNullException("testSetup"); + if(testResult == null) + throw new ArgumentNullException("testResult"); + this.fTestSetup = testSetup; + this.fTestResult = testResult; + } + /// + /// + /// + void IProtectable.Protect() + { + this.fTestSetup.SetUp(); + this.fTestSetup.BasicRun(fTestResult); + this.fTestSetup.TearDown(); + } + } + #endregion - using NUnit.Framework; - - /// A Decorator to set up and tear down additional fixture state. - /// - /// Subclass TestSetup and insert it into your tests when you want - /// to set up additional state once before the tests are run. - public class TestSetup: TestDecorator { - /// - /// - /// - /// - public TestSetup(ITest test) : base(test) {} - /// - /// - /// - protected class ProtectedProtect: IProtectable { - private readonly TestSetup fTestSetup; - private readonly TestResult fTestResult; - /// - /// - /// - /// - /// - public ProtectedProtect(TestSetup testSetup, TestResult testResult) { - fTestSetup = testSetup; - fTestResult = testResult; - } - /// - /// - /// - public void Protect() { - fTestSetup.SetUp(); - fTestSetup.BasicRun(fTestResult); - fTestSetup.TearDown(); - } - } - /// - /// - /// - /// - public override void Run(TestResult result) { - IProtectable p= new ProtectedProtect(this, result); - result.RunProtected(this, p); - } - /// Sets up the fixture. Override to set up additional fixture - /// state. - protected virtual void SetUp() { - } - /// Tears down the fixture. Override to tear down the additional - /// fixture state. - protected virtual void TearDown() { - } - } + /// + /// + /// + /// + public override void Run(TestResult result) + { + IProtectable p = new ProtectedProtect(this, result); + result.RunProtected(this, p); + } + /// Sets up the fixture. Override to set up additional fixture + /// state. + protected virtual void SetUp() {} + /// Tears down the fixture. Override to tear down the additional + /// fixture state. + protected virtual void TearDown() {} + } } diff --git a/mcs/nunit/src/NUnitCore/TestSuite.cs b/mcs/nunit/src/NUnitCore/TestSuite.cs index 558060ee4d181..7febc1150f598 100644 --- a/mcs/nunit/src/NUnitCore/TestSuite.cs +++ b/mcs/nunit/src/NUnitCore/TestSuite.cs @@ -1,243 +1,293 @@ -namespace NUnit.Framework { - - using System; - using System.Collections; - using System.Reflection; - - /// A TestSuite is a Composite of Tests. - /// It runs a collection of test cases. Here is an example using - /// the dynamic test definition. - /// - /// TestSuite suite= new TestSuite(); - /// suite.AddTest(new MathTest("TestAdd")); - /// suite.AddTest(new MathTest("TestDivideByZero")); - /// - /// Alternatively, a TestSuite can extract the Tests to be run automatically. - /// To do so you pass the class of your TestCase class to the - /// TestSuite constructor. - /// - /// TestSuite suite= new TestSuite(typeof(MathTest)); - /// - /// This constructor creates a suite with all the methods - /// starting with "Test" that take no arguments. - /// - public class TestSuite: MarshalByRefObject, ITest { - - private ArrayList fTests= new ArrayList(10); - private string fName; - private bool fHasWarnings = false; - - /// Constructs an empty TestSuite. - public TestSuite() { - } - - /// Constructs a TestSuite from the given class. - /// Adds all the methods - /// starting with "Test" as test cases to the suite. - /// Parts of this method was written at 2337 meters in the Hüffihütte, - /// Kanton Uri - public TestSuite(Type theClass) { - fName= theClass.Name; - ConstructorInfo constructor = GetConstructor(theClass); - if (constructor == null) { - AddTest(Warning("Class "+theClass.Name+" has no public constructor TestCase(String name)")); - return; - } - if (theClass.IsNotPublic) { - AddTest(Warning("Class "+theClass.Name+" is not public")); - return; - } - - Type superClass= theClass; - ArrayList names= new ArrayList(); - while (typeof(ITest).IsAssignableFrom(superClass)) { - MethodInfo[] methods= superClass.GetMethods(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); - for (int i= 0; i < methods.Length; i++) { - AddTestMethod(methods[i], names, constructor); - } - superClass= superClass.BaseType; - } - if (fTests.Count == 0) - AddTest(Warning("No Tests found in "+theClass.ToString())); - } - /// - /// - /// - /// - /// - public TestSuite(Type theClass, ref bool hasNonWarningTests) { - hasNonWarningTests = false; - fName= theClass.ToString(); - ConstructorInfo constructor= GetConstructor(theClass); - if (constructor == null) { - return; - } - if (theClass.IsNotPublic) { - return; - } - - Type superClass= theClass; - ArrayList names= new ArrayList(); - while (typeof(ITest).IsAssignableFrom(superClass)) { - MethodInfo[] methods= superClass.GetMethods(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance); - for (int i= 0; i < methods.Length; i++) { - AddTestMethod(methods[i], names, constructor); - } - superClass= superClass.BaseType; - } - if (fHasWarnings) { - hasNonWarningTests = false; - } else { - hasNonWarningTests = (fTests.Count != 0); - } - } - - /// Constructs an empty TestSuite. - public TestSuite(string name) { - fName= name; - } - - /// Adds a test to the suite. - public void AddTest(ITest test) { - fTests.Add(test); - } - - private void AddTestMethod(MethodInfo m, ArrayList names, - ConstructorInfo constructor) { - string name= m.Name; - if (names.Contains(name)) - return; - if (IsPublicTestMethod(m)) { - names.Add(name); - - Object[] args= new Object[]{name}; - try { - AddTest((ITest)constructor.Invoke(args)); - } catch (TypeLoadException e) { - AddTest(Warning("Cannot instantiate test case: "+name + "( " + e.ToString() + ")")); - } catch (TargetInvocationException e) { - AddTest(Warning("Exception in constructor: "+name + "( " + e.ToString() + ")")); - } - catch (MemberAccessException e) - { - AddTest(Warning("Cannot access test case: "+name + "( " + e.ToString() + ")")); - } - - } else { // almost a test method - if (IsTestMethod(m)) - AddTest(Warning("test method isn't public: "+m.Name)); - } - } - - /// Adds the tests from the given class to the suite - public void AddTestSuite(Type testClass) { - AddTest(new TestSuite(testClass)); - } - - /// The number of test cases that will be run by this test. - public int CountTestCases { - get { - int count= 0; - foreach (ITest test in Tests) { - count += test.CountTestCases; - } - return count; - } - } - - /// Gets a constructor which takes a single string as - /// its argument. - private ConstructorInfo GetConstructor(Type theClass) { - Type[] args= { typeof(string) }; - return theClass.GetConstructor(args); - } - - /// - /// Returns the name of the suite. Not all test suites have a name - /// and this method can return null. - /// - public string Name { - get { return fName; } - } - - private bool IsPublicTestMethod(MethodInfo m) { - return IsTestMethod(m) && m.IsPublic; - } - - private bool IsTestMethod(MethodInfo m) { - string name= m.Name; - - ParameterInfo[] parameters= m.GetParameters(); - Type returnType= m.ReturnType; - return parameters.Length == 0 && name.ToLower().StartsWith("test") - && returnType.Equals(typeof(void)); - } - - /// Runs the Tests and collects their result in a - /// TestResult. - public virtual void Run(TestResult result) { - foreach (ITest test in Tests) { - if (result.ShouldStop ) - break; - RunTest(test, result); - } - } - /// - /// - /// - /// - /// - public virtual void RunTest(ITest test, TestResult result) { - test.Run(result); - } +namespace NUnit.Framework +{ + using System; + using System.Collections; + using System.Collections.Specialized; + using System.Reflection; + + /// A TestSuite is a Composite of Tests. + /// It runs a collection of test cases. Here is an example using + /// the dynamic test definition. + /// + /// TestSuite suite= new TestSuite(); + /// suite.AddTest(new MathTest("TestAdd")); + /// suite.AddTest(new MathTest("TestDivideByZero")); + /// + /// Alternatively, a TestSuite can extract the Tests to be run automatically. + /// To do so you pass the class of your TestCase class to the + /// TestSuite constructor. + /// + /// TestSuite suite= new TestSuite(typeof(MathTest)); + /// + /// This constructor creates a suite with all the methods + /// starting with "Test" that take no arguments. + /// + public class TestSuite: MarshalByRefObject, ITest + { + #region Instance Variables + private ArrayList fTests= new ArrayList(10); + private string fName; + private bool fSupressWarnings = false; + private string fDynamicConstructionQualifiedName= string.Empty; + + #endregion + + #region Constructors + /// Constructs an empty TestSuite with a name. + public TestSuite(string name) + { + if(name==null) + this.fName=String.Empty; + this.fName = name; + } + + /// Constructs an empty TestSuite with no name. + public TestSuite() : this(String.Empty){} + + /// Constructs a TestSuite from the given class. + /// Adds all the methods starting with "Test" as test cases + /// to the suite. Parts of this method was written at 2337 meters in + /// the Hüffihütte, Kanton Uri + /// + /// + public TestSuite(Type theClass, bool supressWarnings) : + this(theClass.FullName) + { + this.fSupressWarnings = supressWarnings; + //REFACTOR: these checks are also found in AssemblyTestCollector + if( theClass.IsClass + && (theClass.IsPublic || theClass.IsNestedPublic) + && !theClass.IsAbstract + && typeof(ITest).IsAssignableFrom(theClass) + ) + { + ConstructorInfo FixtureConstructor = GetConstructor(theClass); + if(FixtureConstructor != null) + { + { + MethodInfo[] methods = theClass.GetMethods( + BindingFlags.Public + |BindingFlags.NonPublic + |BindingFlags.Instance + ); + foreach (MethodInfo method in methods) + { + AddTestMethod(method, FixtureConstructor); + } + if (this.fTests.Count == 0) + AddWarning("No Tests found in "+theClass.ToString()); + } + } + else + { + AddWarning("Class "+theClass.Name + +" has no public constructor TestCase(String name)"); + } + } + else + { + AddWarning("Type '" + theClass.Name + +"' must be a public, not abstract class that" + +" implements ITest."); + } + } + + /// + /// + /// + /// + public TestSuite(Type theClass) : this(theClass,false){} + #endregion + + #region Collection Methods + /// Adds a test to the suite. + public void AddTest(ITest test) + { + fTests.Add(test); + } - /// The test at the given index. - /// Formerly TestAt(int). - public ITest this[int index] { - get {return (ITest)fTests[index]; } - } + /// Adds the tests from the given class to the suite + public void AddTestSuite(Type testClass) + { + AddTest(new TestSuite(testClass)); + } + #endregion + + #region Dynamic Test Case Creation + //private void AddTestMethod(MethodInfo m, StringCollection names, + private void AddTestMethod(MethodInfo m, + ConstructorInfo constructor) + { + string name = m.Name; + if (IsPublicTestMethod(m)) + { + Object[] args= new Object[]{name}; + try + { + AddTest((ITest)constructor.Invoke(args)); + } + catch (TypeLoadException e) + { + AddWarning("Cannot instantiate test case: "+name + "( " + e.ToString() + ")"); + } + catch (TargetInvocationException e) + { + AddWarning("Exception in constructor: "+name + "( " + e.ToString() + ")"); + } + catch (MemberAccessException e) + { + AddWarning("Cannot access test case: "+name + "( " + e.ToString() + ")"); + } + } + else + { // almost a test method + if (IsTestMethod(m)) + AddWarning("test method isn't public: "+m.Name); + } + } + + /// Gets a constructor which takes a single string as + /// its argument. + private ConstructorInfo GetConstructor(Type theClass) + { + //REFACTOR: these checks are also found in AssemblyTestCollector + return theClass.GetConstructor(new Type[]{typeof(string)}); + } + + private bool IsPublicTestMethod(MethodInfo methodToCheck) + { + return methodToCheck.IsPublic + && IsTestMethod(methodToCheck); + } + + private bool IsTestMethod(MethodInfo methodToCheck) + { + return + !methodToCheck.IsAbstract + && methodToCheck.GetParameters().Length == 0 + && methodToCheck.ReturnType.Equals(typeof(void)) + && methodToCheck.Name.ToLower().StartsWith("test") + ; + } + #endregion + + #region Properties + /// + /// Returns the name of the suite. Not all test suites have a name + /// and this method can return null. + /// + public string Name + { + get { return this.fName; } + } + + /// + /// The number of test cases that will be run by this test. + /// + public int CountTestCases + { + get + { + int count= 0; + foreach (ITest test in this.Tests) + { + count += test.CountTestCases; + } + return count; + } + } + + /// The number of Tests in this suite. + public int TestCount + { + get {return this.fTests.Count; } + } + + /// The test at the given index. + /// Formerly TestAt(int). + public ITest this[int index] + { + get {return (ITest)this.fTests[index]; } + } - /// The number of Tests in this suite. - public int TestCount { - get {return fTests.Count; } - } + /// The Tests as a Test[]. + public ITest[] Tests + { + get { + ITest[] ret = new ITest[this.fTests.Count]; + this.fTests.CopyTo(ret); + return ret; + } + } + #endregion + + #region Utility Methods + private void AddWarning(string message) + { + if(!this.fSupressWarnings) + AddTest(new WarningFail(message)); + } + #endregion + + #region Run Methods + /// Runs the Tests and collects their result in a + /// TestResult. + public virtual void Run(TestResult result) + { + foreach (ITest test in Tests) + { + if (result.ShouldStop ) + break; + RunTest(test, result); + } + } + /// + /// + /// + /// + /// + public virtual void RunTest(ITest test, TestResult result) + { + test.Run(result); + } - /// The Tests as an ArrayList. - public ArrayList Tests { - get { return fTests; } - } - /// - /// - /// - /// - public override string ToString() { - if (Name != null) - return Name; - return base.ToString(); - } - - private ITest Warning(string message) { - fHasWarnings = true; - return new WarningFail(message); - } - - /// Returns a test which will fail and log a warning - /// message. - public class WarningFail: TestCase { - private string fMessage; - /// - /// - /// - /// - public WarningFail(string message): base("warning") { - fMessage = message; - } - /// - /// - /// - protected override void RunTest() { - Fail(fMessage); - } - } - } + /// + /// + /// + /// + #endregion + + #region Overrides + public override string ToString() + { + return this.Name; + } + #endregion + + #region Nested Classes + /// A test which will fail and log a warning + /// message. + public class WarningFail : TestCase + { + private string fMessage; + + /// + /// + /// + /// + public WarningFail(string message): base("warning") + { + this.fMessage = message; + } + + /// + /// + /// + protected override void RunTest() + { + Assertion.Fail(fMessage); + } + } + #endregion + } } diff --git a/mcs/nunit/src/NUnitCore/Version.cs b/mcs/nunit/src/NUnitCore/Version.cs index 64a5a7a23c25d..bc7770df126e9 100644 --- a/mcs/nunit/src/NUnitCore/Version.cs +++ b/mcs/nunit/src/NUnitCore/Version.cs @@ -1,18 +1,23 @@ -namespace NUnit.Runner { - +namespace NUnit.Runner +{ + using System.Reflection; /// /// This class defines the current version of NUnit /// - public class Version { - private Version() { - // don't instantiate - } - /// - /// - /// - /// - public static string id() { - return "1.10"; - } - } + public class Version + { + private Version() + { + // don't instantiate + } + /// + /// + /// + /// + public static string id() + { + return Assembly.GetExecutingAssembly().GetName().Version.ToString(); + //return "1.10"; + } + } }