[Csmail-patches] CVS: csmail/nunit/src/NUnitCore ActiveTestSuite.cs,NONE,1.1 AssemblyInfo.cs,NONE,1.
Status: Pre-Alpha
Brought to you by:
mastergaurav
Update of /cvsroot/csmail/csmail/nunit/src/NUnitCore In directory usw-pr-cvs1:/tmp/cvs-serv27574/nunit/src/NUnitCore Added Files: ActiveTestSuite.cs AssemblyInfo.cs AssemblyTestCollector.cs Assertion.cs AssertionFailedError.cs BaseTestRunner.cs ClassPathTestCollector.cs ExceptionTestCase.cs ExpectExceptionAttribute.cs IFailureDetailView.cs IProtectable.cs ITest.cs ITestCollector.cs ITestListener.cs ITestLoader.cs ITestSuiteLoader.cs LoadingTestCollector.cs NUnitCore.csproj NUnitException.cs ReflectionUtils.cs ReloadingTestSuiteLoader.cs RepeatedTest.cs SimpleTestCollector.cs StandardLoader.cs StandardTestSuiteLoader.cs TestCase.cs TestCaseClassLoader.cs TestDecorator.cs TestFailure.cs TestResult.cs TestSetup.cs TestSuite.cs Version.cs Log Message: 2002-02-24 Gaurav Vaish <mastergaurav AT users DOT sf DOT net> * NUnit -- Added the sourcecode. I hope there's no problem with license. --- NEW FILE --- namespace NUnit.Extensions { using System; using System.Threading; using NUnit.Framework; /// <summary> /// 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 /// </summary> public class ActiveTestSuite: TestSuite { private int fActiveTestDeathCount; /// <summary> /// /// </summary> /// <param name="result"></param> public override void Run(TestResult result) { fActiveTestDeathCount= 0; base.Run(result); WaitUntilFinished(); } /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="result"></param> public void BaseRunTest(ITest test, TestResult result) { base.RunTest(test, result); } /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="result"></param> 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(); } /// <summary> /// /// </summary> /// <param name="test"></param> 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 /// <summary> /// /// </summary> public class ThreadLittleHelper { private ITest fTest; private TestResult fResult; private ActiveTestSuite fSuite; /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="result"></param> /// <param name="suite"></param> public ThreadLittleHelper(ITest test, TestResult result, ActiveTestSuite suite) { fSuite = suite; fTest = test; fResult = result; } /// <summary> /// /// </summary> public void Run() { try { fSuite.BaseRunTest(fTest, fResult); } finally { fSuite.RunFinished(fTest); } } } #endregion } } --- NEW FILE --- using System; using System.Reflection; using System.Runtime.CompilerServices; // Mark the framework assembly as CLS compliant [assembly:CLSCompliant(true)] // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitle("NUnit Testing Framework")] [assembly:AssemblyDescription("A unit testing framework for the .Net platform, ported from junit by Kent Beck and Erich Gamma.")] [assembly:AssemblyConfiguration("")] [assembly:AssemblyCompany("")] [assembly:AssemblyProduct("NUnit")] [assembly:AssemblyCopyright("")] [assembly:AssemblyTrademark("")] [assembly:AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Revision // Build Number // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersion("1.11.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified - the assembly cannot be signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. // (*) If the key file and a key name attributes are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP - that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the file is installed into the CSP and used. // (*) 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("")] --- NEW FILE --- using System; using NUnit.Framework; namespace NUnit.Runner { /// <summary> /// Collects the names of all classes in an assembly that are tests. /// </summary> public sealed class AssemblyTestCollector : MarshalByRefObject, ITestCollector { #region Instance Variables private string fAssemblyName; private StandardLoader fLoader; #endregion #region Constructors /// <summary> /// Create a new AssemblyTestCollector for the specified /// assembly, and uses the supplied loader to load the tests /// from the assembly. /// </summary> /// <param name="assemblyName">The file name of the assembly /// from which to load classes</param> /// <param name="loader">An instance if the standard loader to /// use for loading tests from the assembly.</param> public AssemblyTestCollector(string assemblyName, StandardLoader loader) { if(loader!=null) fLoader = loader; else throw new ArgumentNullException("loader"); if(assemblyName != null) { fAssemblyName = assemblyName; } else throw new ArgumentNullException("assemblyName"); } /// <summary> /// Create a new AssemblyTestCollector for the specified /// assembly. /// </summary> /// <param name="assemblyName">The file name of the assembly /// from which to load classes.</param> public AssemblyTestCollector(string assemblyName) : this(assemblyName,new StandardLoader()){} /// <summary> /// returns a System.String[] of FullNames for all test classes /// contained within the assembly. /// Implements ITestCollector.CollectTestsClassNames() /// </summary> #endregion #region ITestCollector Methods public string[] CollectTestsClassNames() { Type[] tests = fLoader.GetTestTypes(fAssemblyName); string[] ret = new string[tests.Length]; int i=0; foreach (Type testType in tests) { ret[i] = testType.FullName; i++; } return ret; } #endregion } } --- NEW FILE --- namespace NUnit.Framework { using System; /// <summary>A set of Assert methods.</summary> public class Assertion : MarshalByRefObject { /// <summary> /// Protect constructor since it is a static only class /// </summary> protected Assertion():base(){} /// <summary> /// Asserts that a condition is true. If it isn't it throws /// an <see cref="AssertionFailedError"/>. /// </summary> /// <param name="message">The message to display is the condition /// is false</param> /// <param name="condition">The evaluated condition</param> static public void Assert(string message, bool condition) { if (!condition) Assertion.Fail(message); } /// <summary> /// Asserts that a condition is true. If it isn't it throws /// an <see cref="AssertionFailedError"/>. /// </summary> /// <param name="condition">The evaluated condition</param> static public void Assert(bool condition) { Assertion.Assert(string.Empty, condition); } /// <summary> /// /// Asserts that two doubles are equal concerning a delta. If the /// expected value is infinity then the delta value is ignored. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="delta">The maximum acceptable difference between the /// the expected and the actual</param> static public void AssertEquals(double expected, double actual, double delta) { Assertion.AssertEquals(string.Empty, expected, actual, delta); } /// <summary> /// /// Asserts that two singles are equal concerning a delta. If the /// expected value is infinity then the delta value is ignored. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="delta">The maximum acceptable difference between the /// the expected and the actual</param> static public void AssertEquals(float expected, float actual, float delta) { Assertion.AssertEquals(string.Empty, expected, actual, delta); } /// <summary>Asserts that two objects are equal. If they are not /// an <see cref="AssertionFailedError"/> is thrown.</summary> static public void AssertEquals(Object expected, Object actual) { Assertion.AssertEquals(string.Empty, expected, actual); } /// <summary>Asserts that two doubles are equal concerning a delta. /// If the expected value is infinity then the delta value is ignored. /// </summary> 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); } /// <summary>Asserts that two floats are equal concerning a delta. /// If the expected value is infinity then the delta value is ignored. /// </summary> 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); } /// <summary>Asserts that two objects are equal. If they are not /// an <see cref="AssertionFailedError"/> is thrown.</summary> 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); } /// <summary>Asserts that an object isn't null.</summary> static public void AssertNotNull(Object anObject) { Assertion.AssertNotNull(string.Empty, anObject); } /// <summary>Asserts that an object isn't null.</summary> static public void AssertNotNull(string message, Object anObject) { Assertion.Assert(string.Empty, anObject != null); } /// <summary>Asserts that an object is null.</summary> static public void AssertNull(Object anObject) { Assertion.AssertNull(string.Empty, anObject); } /// <summary>Asserts that an object is null.</summary> static public void AssertNull(string message, Object anObject) { Assertion.Assert(message, anObject == null); } /// <summary>Asserts that two objects refer to the same object. If they /// are not the same an <see cref="AssertionFailedError"/> is thrown. /// </summary> static public void AssertSame(Object expected, Object actual) { Assertion.AssertSame(string.Empty, expected, actual); } /// <summary>Asserts that two objects refer to the same object. /// If they are not an <see cref="AssertionFailedError"/> is thrown. /// </summary> static public void AssertSame(string message, Object expected, Object actual) { if (expected == actual) return; Assertion.FailNotSame(message, expected, actual); } /// <summary>Fails a test with no message.</summary> static public void Fail() { Assertion.Fail(string.Empty); } /// <summary>Fails a test with the given message.</summary> 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"); } } } --- NEW FILE --- namespace NUnit.Framework { using System; using System.Runtime.Serialization; /// <summary> /// Thrown when an assertion failed. /// </summary> [Serializable] public class AssertionFailedError : ApplicationException//NUnitException { /// <summary> /// Serialization Constructor /// </summary> protected AssertionFailedError(SerializationInfo info, StreamingContext context) : base(info,context){} /// <summary> /// /// </summary> /// <param name="message"></param> public AssertionFailedError (string message) : base(message) {} // public override bool IsAssertionFailure // { // get{return true;} // } } } --- NEW FILE --- 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; /// <summary> /// Base class for all test runners. /// </summary> /// <remarks> /// /// </remarks> public abstract class BaseTestRunner: MarshalByRefObject, ITestListener { /// <summary> /// /// </summary> [Obsolete("Shoud be handled by a loader")] public static string SUITE_PROPERTYNAME="Suite"; private static NameValueCollection fPreferences = new NameValueCollection(); private static int fgMaxMessageLength = 500; private static bool fgFilterStack = true; private bool fLoading = true; /// <summary> /// /// </summary> public BaseTestRunner() { fPreferences = new NameValueCollection(); fPreferences.Add("loading", "true"); fPreferences.Add("filterstack", "true"); ReadPreferences(); fgMaxMessageLength = GetPreference("maxmessage", fgMaxMessageLength); } #region ITestListener Methods /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="t"></param> public abstract void AddError(ITest test, Exception t); /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="t"></param> public abstract void AddFailure(ITest test, AssertionFailedError t); /// <summary> /// /// </summary> /// <param name="test"></param> public abstract void EndTest(ITest test); #endregion #if false /// <summary> /// Clears the status message. /// </summary> protected virtual void ClearStatus() { // Belongs in the GUI TestRunner class. } #endif /// <summary> /// Returns the formatted string of the elapsed time. /// </summary> public static string ElapsedTimeAsString(long runTime) { return ((double)runTime/1000).ToString(); } /// <summary> /// Extract the class name from a string in VA/Java style /// </summary> 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; } /// <summary> /// Filters stack frames from internal NUnit classes /// </summary> public static string FilterStack(string stack) { string pref = GetPreference("filterstack"); if (((pref != null) && !GetPreference("filterstack").Equals("true")) || fgFilterStack == false) return stack; StringWriter sw = new StringWriter(); StringReader sr = new StringReader(stack); 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(); } /// <summary> /// /// </summary> /// <param name="t"></param> /// <returns></returns> public static string GetFilteredTrace(Exception t) { return BaseTestRunner.FilterStack(t.StackTrace); } /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> 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); } /// <summary> /// /// </summary> /// <returns></returns> public virtual ITestLoader GetLoader() { if (UseReloadingTestSuiteLoader()) return new UnloadingLoader(); return new StandardLoader(); } /// <summary> /// Returns the ITest corresponding to the given suite. This is /// a template method, subclasses override RunFailed(), ClearStatus(). /// </summary> 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; } /// <summary> /// Returns the loaded Class for a suite name. /// </summary> 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) { } } } /// <summary> /// Real method reads name/value pairs, populates, or maybe just /// deserializes... /// </summary> /// <param name="prefs"></param> /// <param name="fs"></param> private static void ReadPrefsFromFile(ref NameValueCollection prefs, FileStream fs) { } /// <summary> /// Override to define how to handle a failed loading of a test suite. /// </summary> protected abstract void RunFailed(string message); /// <summary> /// Truncates a String to the maximum length. /// </summary> /// <param name="message"></param> /// <returns></returns> public static string Truncate(string message) { if (fgMaxMessageLength != -1 && message.Length > fgMaxMessageLength) message = message.Substring(0, fgMaxMessageLength)+"..."; return message; } /// <summary> /// /// </summary> /// <param name="test"></param> public abstract void StartTest(ITest test); /// <summary> /// /// </summary> /// <param name="args"></param> /// <param name="wait"></param> /// <returns></returns> 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; } /// <summary> /// Sets the loading behaviour of the test runner /// </summary> protected void SetLoading(bool enable) { fLoading = enable; } /// <summary> /// /// </summary> /// <returns></returns> protected bool UseReloadingTestSuiteLoader() { return bool.TrueString.Equals( GetPreference("loading")) && fLoading; } } } --- NEW FILE --- namespace NUnit.Runner { using System; using System.Collections; using System.Collections.Specialized; using System.IO; /// <summary> /// 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. /// <see cref="ITestCollector"/> /// </summary> [Obsolete("Use StandardLoader or UnloadingLoader")] public abstract class ClassPathTestCollector : ITestCollector { /// <summary> /// /// </summary> public ClassPathTestCollector() {} /// <summary> /// /// </summary> /// <returns></returns> public string[] CollectTestsClassNames() { string classPath = Environment.GetEnvironmentVariable("Path"); char separator= Path.PathSeparator; ArrayList result = new ArrayList(); CollectFilesInRoots(classPath.Split(separator), result); string[] retVal = new string[result.Count]; result.CopyTo(retVal); return retVal; } /// <summary> /// /// </summary> /// <param name="classFileName"></param> /// <returns></returns> protected string ClassNameFromFile(string classFileName) { return classFileName; } private void CollectFilesInRoots(string[] roots, IList result) { foreach (string directory in roots) { DirectoryInfo dirInfo=new DirectoryInfo(directory); if (dirInfo.Exists) { string[] files=Directory.GetFiles(dirInfo.FullName); foreach (string file in files) { if (IsTestClass(file)) { string className=ClassNameFromFile(file); result.Add(className); } } } } } /// <summary> /// /// </summary> /// <param name="classFileName"></param> /// <returns></returns> protected virtual bool IsTestClass(string classFileName) { return ( classFileName.EndsWith(".dll") || classFileName.EndsWith(".exe")) && classFileName.IndexOf("Test") > 0; } } } --- NEW FILE --- namespace NUnit.Extensions { using System; using NUnit.Framework; /// <summary>A TestCase that expects an Exception of class fExpected /// to be thrown.</summary> /// <remarks> The other way to check that an expected exception is thrown is: /// <code> /// try { /// ShouldThrow(); /// }catch (SpecialException) { /// return; /// } /// Assertion.Fail("Expected SpecialException"); /// </code> /// /// To use ExceptionTestCase, create a TestCase like: /// <code> /// new ExceptionTestCase("TestShouldThrow", typeof(SpecialException)); /// </code></remarks> public class ExceptionTestCase: TestCase { private readonly Type fExpected; /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="exception"></param> public ExceptionTestCase(string name, Type exception) : base(name) { fExpected= exception; } /// <summary>Execute the test method expecting that an Exception of /// class fExpected or one of its subclasses will be thrown.</summary> 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); } } } --- NEW FILE --- namespace NUnit.Framework { using System; /// <summary> /// The given exception should be thrown by the annotated method. /// </summary> /// <remarks> /// To use this attribute, attach it to a method in a /// <see cref="TestCase"/> subclass. /// <example>Here is an example: /// <code> /// public class FooTest : TestCase { /// public ExpectExceptionTest(string name) : base(name) {} /// [ExpectException(typeof(ArgumentException))] /// [ExpectException(typeof(IndexOutOfRangeException))] /// public void TestBar() { /// throw new ArgumentException("bad argument"); /// } /// } /// </code> /// </example> /// </remarks> [AttributeUsage(AttributeTargets.Method, AllowMultiple=true)] public class ExpectExceptionAttribute : Attribute { private Type expected; /// <summary> /// /// </summary> /// <param name="exceptionExpected"></param> public ExpectExceptionAttribute(Type exceptionExpected) { this.expected = exceptionExpected; } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return expected.ToString(); } /// <summary> /// /// </summary> public Type ExceptionExpected { get { return expected; } } } } --- NEW FILE --- namespace NUnit.Runner { using System; using NUnit.Framework; /// <summary> /// A view to show details about a failure /// </summary> public interface IFailureDetailView { /// <summary> /// Clears the view /// </summary> void Clear(); /// <summary> /// Shows details of a TestFailure /// </summary> void ShowFailure(TestFailure failure); } } --- NEW FILE --- namespace NUnit.Framework { /// <summary> /// An <c>IProtectable</c> can be run and can throw an Exception. /// </summary> /// <seealso cref="TestResult"/> public interface IProtectable { /// <summary>Run the the following method protected.</summary> void Protect(); } } --- NEW FILE --- namespace NUnit.Framework { /// <summary>An <c>ITest</c> can be run and collect its results.</summary> /// <seealso cref="TestResult"/> public interface ITest { /// <summary> /// Counts the number of test cases that will be run by this test. /// </summary> int CountTestCases { get; } /// <summary> /// Runs a test and collects its result in a /// <see cref="TestResult"/> instance. /// </summary> /// <param name="result"></param> void Run(TestResult result); } } --- NEW FILE --- namespace NUnit.Runner { using System; /// <summary> /// Collects Test classes to be presented by the TestSelector. /// <see foocref="TestSelector"/> /// </summary> public interface ITestCollector { /// <summary> /// Returns an array of FullNames for classes that are tests. /// </summary> string[] CollectTestsClassNames(); } } --- NEW FILE --- namespace NUnit.Framework { using System; /// <summary>A Listener for test progress</summary> public interface ITestListener { /// <summary>An error occurred.</summary> void AddError(ITest test, Exception ex); /// <summary>A failure occurred.</summary> void AddFailure(ITest test, AssertionFailedError ex); /// <summary>A test ended.</summary> void EndTest(ITest test); /// <summary>A test started.</summary> 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 } --- NEW FILE --- namespace NUnit.Runner { using System; using NUnit.Framework; using System.Runtime.Serialization; /// <summary> /// Basic contract governing loading of tests /// </summary> public interface ITestLoader { /// <summary> /// Loads an instance of the test class specified by the name. /// Loadable in most cases will be an assembly qualified name. /// /// Other loaders could dynamically construct a test case from /// an XML file or a database record. /// </summary> ITest LoadTest(string loadableName); /// <summary> /// Return the name used by the loader to load an instance /// of the supplied test /// </summary> /// <param name="test"></param> /// <returns></returns> string GetLoadName(ITest test); } /// <summary> /// Error thrown during assembly and class loading problems /// </summary> [Serializable] public class LoaderException : NUnitException { /// <summary> /// Serialization Constructor /// </summary> protected LoaderException(SerializationInfo info, StreamingContext context) : base(info,context){} /// <summary> /// Standard constructor /// </summary> /// <param name="message">The error message that explains /// the reason for the exception</param> /// <param name="innerException">The exception that caused the /// current exception</param> public LoaderException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Standard constructor /// </summary> /// <param name="message">The error message that explains /// the reason for the exception</param> public LoaderException(string message) : base(message) {} } } --- NEW FILE --- namespace NUnit.Runner { using System; /// <summary> /// An interface to define how a test suite should be loaded. /// </summary> [Obsolete("Use ILoader")] public interface ITestSuiteLoader { /// <summary> /// /// </summary> Type Load(string suiteClassName); //Type Reload(Type aType); } } --- NEW FILE --- namespace NUnit.Runner { using System; using System.Reflection; using NUnit.Framework; /// <summary> /// 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. /// <see cref="ITestCollector"/> /// </summary> [Obsolete("Use StandardLoader or UnloadingLoader")] public class LoadingClassPathTestCollector: ClassPathTestCollector { TestCaseClassLoader fLoader; /// <summary> /// /// </summary> public LoadingClassPathTestCollector() { fLoader= new TestCaseClassLoader(); } /// <summary> /// /// </summary> /// <param name="classFileName"></param> /// <returns></returns> 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; } private Type ClassFromFile(string classFileName) { string className = base.ClassNameFromFile(classFileName); if (!fLoader.IsExcluded(className)) return fLoader.LoadClass(className, false); return null; } } } --- NEW FILE --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.0.9466" SchemaVersion = "1.0" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "NUnitCore" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Flow" DefaultTargetSchema = "IE32Nav30" DelaySign = "false" OutputType = "Library" RootNamespace = "NUnitCore" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "0" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "NUnitCore.xml" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "0" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" /> <Reference Name = "SYSTEM.WINDOWS.FORMS" AssemblyName = "System.Windows.Forms" /> <Reference Name = "System.Data" AssemblyName = "System.Data" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" /> </References> </Build> <Files> <Include> <File RelPath = "ActiveTestSuite.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyTestCollector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Assertion.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssertionFailedError.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "BaseTestRunner.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ClassPathTestCollector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ExceptionTestCase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ExpectExceptionAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IFailureDetailView.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IProtectable.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ITest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ITestCollector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ITestListener.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ITestLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ITestSuiteLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "LoadingTestCollector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NUnitException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ReflectionUtils.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ReloadingTestSuiteLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "RepeatedTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "StandardLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "StandardTestSuiteLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestCase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestCaseClassLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestDecorator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestFailure.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestResult.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestSetup.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestSuite.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Version.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE --- namespace NUnit.Framework { using System; using System.Diagnostics; using System.Runtime.Serialization; /// <summary> /// Thrown when an assertion failed. Here to preserve the inner /// exception and hence its stack trace. /// </summary> [Serializable] public class NUnitException : ApplicationException { /// <summary> /// Serialization Constructor /// </summary> protected NUnitException(SerializationInfo info, StreamingContext context) : base(info,context){} /// <summary> /// Standard constructor /// </summary> /// <param name="message">The error message that explains /// the reason for the exception</param> public NUnitException(string message) : base (message){} /// <summary> /// Standard constructor /// </summary> /// <param name="message">The error message that explains /// the reason for the exception</param> /// <param name="inner">The exception that caused the /// current exception</param> public NUnitException(string message, Exception inner) : base(message, inner) {} /// <summary> /// Indicates that this exception wraps an AssertionFailedError /// exception /// </summary> public virtual bool IsAssertionFailure { get { AssertionFailedError inner = this.InnerException as AssertionFailedError; if(inner != null) return true; return false; } } } } --- NEW FILE --- namespace NUnit.Runner { using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using NUnit.Framework; /// <summary> /// /// </summary> [Obsolete("Use Standar Loader")] public class ReflectionUtils { /// <summary> /// /// </summary> /// <param name="testClass"></param> /// <returns></returns> [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 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; } /// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> [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) { Type[] loadedTypes = rcle.Types; Exception[] exceptions = rcle.LoaderExceptions; 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; } } } --- NEW FILE --- namespace NUnit.Runner { using System; /// <summary>A TestSuite loader that can reload classes.</summary> [Obsolete("Use StandardLoader or UnloadingLoader")] public class ReloadingTestSuiteLoader: ITestSuiteLoader { /// <summary> /// /// </summary> /// <param name="suiteClassName"></param> /// <returns></returns> public Type Load(string suiteClassName) { // TestCaseClassLoader loader= new TestCaseClassLoader(); // return loader.LoadClass(suiteClassName, true); return Type.GetType(suiteClassName, true); } /// <summary> /// /// </summary> /// <param name="aClass"></param> /// <returns></returns> public Type Reload(Type aClass) { // TestCaseClassLoader loader= new TestCaseClassLoader(); // return loader.LoadClass(aClass.ToString(), true); return aClass; } } } --- NEW FILE --- namespace NUnit.Extensions { using System; using NUnit.Framework; /// <summary>A Decorator that runs a test repeatedly.</summary> public class RepeatedTest: TestDecorator { private readonly int fTimesRepeat; /// <summary> /// /// </summary> /// <param name="test"></param> /// <param name="repeat"></param> public RepeatedTest(ITest test, int repeat) : base(test) { if (repeat < 0) { throw new ArgumentOutOfRangeException("repeat", "Repetition count must be > 0"); } fTimesRepeat= repeat; } /// <summary> /// /// </summary> public override int CountTestCases { get { return base.CountTestCases * fTimesRepeat; } } /// <summary> /// /// </summary> /// <param name="result"></param> public override void Run(TestResult result) { for (int i= 0; i < fTimesRepeat; i++) { if (result.ShouldStop) break; base.Run(result); } } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return base.ToString()+"(repeated)"; } } } --- NEW FILE --- namespace NUnit.Runner { using System; /// <summary> /// An implementation of a TestCollector that considers /// a class to be a test class when it contains the /// pattern "Test" in its name /// <see cref="ITestCollector"/> /// </summary> public class SimpleTestCollector: ClassPathTestCollector { /// <summary> /// /// </summary> public SimpleTestCollector() { } /// <summary> /// /// </summary> /// <param name="classFileName"></param> /// <returns></returns> protected override bool IsTestClass(string classFileName) { return (classFileName.EndsWith(".dll") || classFileName.EndsWith(".exe")) && classFileName.IndexOf("Test") > 0; } } } --- NEW FILE --- namespace NUnit.Runner { using System; using System.Collections; using System.Reflection; using NUnit.Framework; /// <summary> /// Same as StandardLoader. /// TODO: Clean up "Unloading" concepts in framework /// </summary> public class UnloadingLoader : StandardLoader{} /// <summary> /// TestLoader that /// </summary> public class StandardLoader : ITestLoader { #region Overidable loader implementatioons /// <summary> /// Attempts by all means possible to return a test for the given type. /// Check in the following order: /// 1. For a static Suite property, that implments ITest. /// 2. Tries to dynamically create a suite for the type. /// </summary> /// <param name="testClass"></param> /// <returns></returns> protected virtual ITest CoerceTestFrom(Type testClass) { try { ITest test = GetStaticSuiteProperty(testClass); if (test == null ) { // try to extract a test suite automatically test = new TestSuite(testClass); } return test; } catch (Exception e) { throw new NUnitException("Error building test for class: " + testClass.FullName,e); } } /// <summary> /// Searches for the type specified by the testClassName in the /// specified assembly, and if found, attempts to coerce a test /// from the type. /// </summary> /// <param name="testClassName"></param> /// <param name="assemblyFileName"></param> /// <returns></returns> public virtual ITest LoadTest(string testClassName, string assemblyFileName) { try { return this.CoerceTestFrom( getAssembly(assemblyFileName).GetType(testClassName)); } catch (Exception e) { throw new LoaderException("Error loading test class: " + testClassName + "," + assemblyFileName, e); } } /// <summary> /// Determines if a Type is a test. /// </summary> /// <param name="typeToCheck"></param> protected virtual bool IsTestClass(Type typeToCheck) { if(typeToCheck!=null) { if( typeToCheck.IsClass && typeToCheck.IsPublic && !typeToCheck.IsAbstract) { try { if( (typeof(ITest).IsAssignableFrom(typeToCheck) // Has public single string constructor && (typeToCheck.GetConstructor(new Type[]{typeof(string)})!=null)) || GetStaticSuiteProperty(typeToCheck)!= null) { return true; } } catch(System.Security.SecurityException) { // eat security exceptions, since shouldn't // have errors on classes we can't access } } return false; } else { throw new ArgumentNullException("typeToCheck"); } } /// <summary> /// Uses reflection to obtain the suite property for the Type /// </summary> /// <param name="testClass"></param> /// <returns>The Suite property of the Type, or null if the property /// does not exist</returns> protected virtual TestSuite GetStaticSuiteProperty(Type testClass) { if(testClass!=null) { TestSuite test = null; PropertyInfo suiteProperty = testClass.GetProperty("Suite" ,BindingFlags.Static|BindingFlags.Public ,Type.DefaultBinder // unknown ,typeof(ITest) // Itest return type ,Type.EmptyTypes // no parameters ,new ParameterModifier[0] // unknown ); if (suiteProperty != null ) { test = (TestSuite)suiteProperty.GetValue(null, new Object[0]); } return test; } else { throw new ArgumentNullException ("testClass"); } } private Assembly getAssembly(string assemblyFileName) { try { return Assembly.LoadFrom(assemblyFileName); } catch(ArgumentNullException) { throw new ArgumentNullException("assemblyFileName"); } } #endregion #region ILoader Methods /// <summary> /// Implements ILoader.GetLoadName(). /// </summary> /// <param name="test"></param> /// <returns></returns> public virtual string GetLoadName(ITest test) { Type testType = test.GetType(); if(testType.Equals(typeof(TestSuite))) { string tname = test.ToString(); testType = Type.GetType(tname); } if(testType != null) return testType.FullName+","+testType.Assembly.CodeBase; else return string.Empty; } /// <summary> /// Implements ILoader.LoadTest(). /// Loads an instance of the test class specified by the /// AssemblyQualifiedName. The assembly qualified name /// contains the Full Clas Name, followed by the CodeBase /// (file or url) of the assembly. If the class is found, /// the loader will attempt to return a TestSuite for the /// class. Trying first the static Suite property, followed /// by trying to dynamically create a suite for the class. /// </summary> /// <param name="assemblyQualifiedName">The qualified name /// for the class taking the form /// "Namespace.ClassName,AssemblyFileName" without the quotes. /// Assembly file name can be a fulied qualified path name, or /// a URL.</param> /// <returns></returns> public virtual ITest LoadTest(string assemblyQualifiedName) { if(assemblyQualifiedName==null) throw new ArgumentNullException("assemblyQualifiedName"); string[] nameParts = assemblyQualifiedName.Split(new Char[]{','}); if(nameParts.Length >= 1) { return this.LoadTest(nameParts[0].Trim(),nameParts[1].Trim()); } else { throw new ArgumentException("Expected an Assembly Qualified Class" + " Name, containing the file name of the assembly", "assemblyQualifiedName"); } } #endregion /// <summary> /// Examies all types in the specified assembly and returns a list of those /// types that can be coerced into tests. /// </summary> /// <param name="assemblyFileName"></param> /// <returns></returns> public virtual Type[] GetTestTypes(string assemblyFileName) { Assembly assembly = getAssembly(assemblyFileName); ArrayList Tests = new ArrayList(assembly.GetExportedTypes().Length); foreach(Type typeToCheck in assembly.GetExportedTypes()) { if(this.IsTestClass(typeToCheck)) { Tests.Add(typeToCheck); } } Type[] ret = new Type[Tests.Count]; Tests.CopyTo(ret); return ret; } } } --- NEW FILE --- namespace NUnit.Runner { using System; using System.Reflection; using System.IO; using System.Security; /// <summary> /// The standard test suite loader. It can only load the same /// class once. /// </summary> [Obsolete("Use StandardLoader or UnloadingLoader")] public class StandardTestSuiteLoader: ITestSuiteLoader { /// <summary> /// Loads /// </summary> /// <param name="testClassName"></param> /// <returns></returns> 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; } /// <summary> /// /// </summary> /// <param name="aClass"></param> /// <returns></returns> public Type Reload(Type aClass) { return aClass; } } } --- NEW FILE --- namespace NUnit.Framework { using System; using System.Reflection; /// <summary>A test case defines the fixture to run multiple Tests.</summary> /// <remarks> To define a test case /// <list type="number"> /// <item><description>implement a subclass of TestCase</description></item> /// <item><description>define instance variables that store the state /// of the fixture</description></item> /// <item><description>initialize the fixture state by overriding /// <c>SetUp</c></description></item> /// <item><description>clean-up after a test by overriding /// <c>TearDown</c></description></item> /// </list> /// Each test runs in its own fixture so there can be no side effects /// among test runs. /// <example>Here is an example: /// <code> /// 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; /// } /// }</code> /// </example> /// /// For each test implement a method which interacts with the fixture. /// Verify the expected results with Assertions specified by calling /// <c>Assert</c> with a bool. /// <code> /// protected void TestAdd() { /// double result= fValue1 + fValue2; /// Assert(result == 5.0); /// } /// </code> /// 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. /// <code> /// protected class AddMathTest: TestCase { /// public void AddMathTest(string name) : base(name) {} /// protected override void RunTest() { TestAdd(); } /// } /// /// test test= new AddMathTest("Add"); /// test.Run(); /// </code> /// The dynamic way uses reflection to implement <c>RunTest</c>. 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. /// <code> /// test= new MathTest("TestAdd"); /// test.Run(); /// </code> /// The Tests to be run can be collected into a <see cref="TestSuite"/>. /// NUnit provides different test runners which can run a test suite /// and collect the results. /// A test runner either expects a static property <c>Suite</c> as the entry /// point to get a test to run or it will extract the suite automatically. /// <code> /// public static ITest Suite { /// get { /// suite.AddTest(new MathTest("TestAdd")); /// suite.AddTest(new MathTest("TestDivideByZero")); /// return suite; /// } /// } /// </code></remarks> /// <seealso cref="TestResult"/> /// <seealso cref="TestSuite"/> public abstract class TestCase: Assertion, ITest { #region Instance Variables /// <summary>the name of the test case.</summary> private readonly string fName; #endregion #region Constructors /// <summary>Constructs a test case with no name.</summary> public TestCase() : this(String.Empty){} /// <summary>Constructs a test case with the given name.</summary> public TestCase(string testName) { this.fName = testName; } #endregion #region Properties /// <value>Counts the number of test cases executed by /// Run(TestResult result).</value> public int CountTestCases { get { return 1; } } /// <value>The name of the test case.</value> public string Name { get { return this.fName; } } #endregion #region Utility Methods /// <summary>Creates a default <see cref="TestResult"/> object.</summary> protected TestResult CreateResult() { return new TestResul... [truncated message content] |