From 66862d2385a3bddfa457b1469f2435639d7296ae Mon Sep 17 00:00:00 2001 From: Dai Michael Date: Sun, 9 Sep 2018 18:27:52 +0100 Subject: [PATCH 001/174] New branch, new code. --- .../framework/Attributes/TimeoutAttribute.cs | 15 ++++- .../tests/Attributes/TimeoutTests.cs | 56 ++++++++++++++++++- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs index aa3b065f35..20ec71f682 100644 --- a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2008 Charlie Poole, Rob Prouse +// Copyright (c) 2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -21,7 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if THREAD_ABORT using System; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Commands; @@ -52,12 +51,22 @@ public TimeoutAttribute(int timeout) #region IApplyToContext Members +#if PLATFORM_DETECTION + void IApplyToContext.ApplyToContext(TestExecutionContext context) { context.TestCaseTimeout = _timeout; } +#else + + void IApplyToContext.ApplyToContext(TestExecutionContext context) + { + + } + +#endif #endregion } } -#endif + diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index c7dba83181..4bd4f6591c 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if PLATFORM_DETECTION +#if PLATFORM_DETECTION && THREAD_ABORT using System; using System.Linq; using System.Threading; @@ -169,4 +169,58 @@ public void TimeoutWithMessagePumpShouldAbort() } } } +#else + +using System; +using System.Linq; +using System.Threading; +using NUnit.Framework; +using NUnit.Framework.Interfaces; +using NUnit.Framework.Internal; +using NUnit.TestData; +using NUnit.TestUtilities; + +namespace NUnit.Framework.Attributes +{ + [TestFixture] + public class TimeoutTests + { + [Timeout(50)] + public void TestTimesOutWhichThrowsTimeoutException() + { + while (true) { } + } + + [Test, Timeout(80)] + public void TestTimesOutDoesNotStopCompletion() + { + Thread.Sleep(20); + Assert.True(true); + } + + [Test] + public void TestTimesOut() + { + ITestResult testResult = null; + try + { + var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimesOutWhichThrowsTimeoutException)); + var workItem = TestBuilder.CreateWorkItem(testCase); + testResult = TestBuilder.ExecuteWorkItem(workItem); + } + catch (TimeoutException) + { + Assert.AreEqual(TestStatus.Inconclusive, testResult?.ResultState.Status); + Assert.AreEqual(FailureSite.Test, testResult?.ResultState.Site); + Assert.AreEqual("Invalid", testResult?.ResultState.Label); + } + catch (Exception e) + { + Assert.Fail($"{nameof(TimeoutException)} is expected but exception type {e.GetType().Name} thrown."); + } + } + } +} + + #endif From 7679b67c9cd55023c2d761b7a4d36bc04583c299 Mon Sep 17 00:00:00 2001 From: Dai Michael Date: Wed, 12 Sep 2018 20:08:22 +0100 Subject: [PATCH 002/174] Updated test with #if --- src/NUnitFramework/tests/Attributes/TimeoutTests.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 4bd4f6591c..9a6d0d2598 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2012 Charlie Poole, Rob Prouse +// Copyright (c) 2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if PLATFORM_DETECTION && THREAD_ABORT +#if PLATFORM_DETECTION using System; using System.Linq; using System.Threading; @@ -169,15 +169,15 @@ public void TimeoutWithMessagePumpShouldAbort() } } } -#else +#endif + +#if !THREAD_ABORT using System; -using System.Linq; using System.Threading; using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; -using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes @@ -222,5 +222,4 @@ public void TestTimesOut() } } - #endif From 6e91f95d0900963e80c684be445fdf21a0483551 Mon Sep 17 00:00:00 2001 From: DaiMichael Date: Sun, 16 Sep 2018 13:01:46 +0100 Subject: [PATCH 003/174] Updated for Tests and code for Timeout in .net core. --- .../framework/Attributes/TimeoutAttribute.cs | 10 ---- .../Internal/Commands/TimeoutCommand.cs | 52 +++++++++++++++++-- .../tests/Attributes/TimeoutTests.cs | 28 +++++----- .../tests/nunit.framework.tests.csproj | 6 +-- 4 files changed, 66 insertions(+), 30 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs index 20ec71f682..1cd910a165 100644 --- a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs @@ -51,20 +51,10 @@ public TimeoutAttribute(int timeout) #region IApplyToContext Members -#if PLATFORM_DETECTION - void IApplyToContext.ApplyToContext(TestExecutionContext context) { context.TestCaseTimeout = _timeout; } -#else - - void IApplyToContext.ApplyToContext(TestExecutionContext context) - { - - } - -#endif #endregion } diff --git a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs index c1e72902af..bf8f7caa6f 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2017 Charlie Poole, Rob Prouse +// Copyright (c) 2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -21,10 +21,13 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if THREAD_ABORT using System; using System.Collections.Generic; + using System.Threading; +#if !NET20 && !NET35 +using System.Threading.Tasks; +#endif namespace NUnit.Framework.Internal.Commands { @@ -38,6 +41,7 @@ namespace NUnit.Framework.Internal.Commands /// public class TimeoutCommand : BeforeAndAfterTestCommand { + private readonly int _timeout; Timer _commandTimer; private bool _commandTimedOut = false; @@ -51,6 +55,9 @@ public TimeoutCommand(TestCommand innerCommand, int timeout) { Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", nameof(innerCommand)); Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", nameof(timeout)); + _timeout = timeout; + +#if THREAD_ABORT BeforeTest = (context) => { @@ -81,7 +88,46 @@ public TimeoutCommand(TestCommand innerCommand, int timeout) string.Format("Test exceeded Timeout value of {0}ms", timeout)); } }; + +#endif + } + + /// + /// Runs the test, saving a TestResult in the supplied TestExecutionContext. + /// + /// The context in which the test should run. + /// A TestResult + public override TestResult Execute(TestExecutionContext context) + { + +#if THREAD_ABORT + + return base.Execute(context); + +#endif + +#if !THREAD_ABORT && !NET20 && !NET35 + + try + { + if (!Task.Run(() => context.CurrentResult = base.Execute(context)).Wait(_timeout)) + { + context.CurrentResult.SetResult(new ResultState( + TestStatus.Failed, + $"Test exceeded Timeout value {_timeout}.", + FailureSite.Test)); + } + } + catch (Exception exception) + { + context.CurrentResult.SetResult(new ResultState( + TestStatus.Failed, + exception.ToString(), + FailureSite.Test)); + } + + return context.CurrentResult; +#endif } } } -#endif diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 4bd4f6591c..9388e1a437 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -20,8 +20,7 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** - -#if PLATFORM_DETECTION && THREAD_ABORT +#if PLATFORM_DETECTION using System; using System.Linq; using System.Threading; @@ -169,20 +168,19 @@ public void TimeoutWithMessagePumpShouldAbort() } } } -#else +#endif + +#if !THREAD_ABORT using System; -using System.Linq; +using System.Collections.Generic; using System.Threading; -using NUnit.Framework; using NUnit.Framework.Interfaces; -using NUnit.Framework.Internal; -using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { - [TestFixture] + [TestFixture, NonParallelizable] public class TimeoutTests { [Timeout(50)] @@ -201,26 +199,28 @@ public void TestTimesOutDoesNotStopCompletion() [Test] public void TestTimesOut() { - ITestResult testResult = null; try { var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimesOutWhichThrowsTimeoutException)); var workItem = TestBuilder.CreateWorkItem(testCase); - testResult = TestBuilder.ExecuteWorkItem(workItem); + var testResult = TestBuilder.ExecuteWorkItem(workItem); + + Assert.AreEqual(TestStatus.Failed, testResult?.ResultState.Status); + Assert.AreEqual(FailureSite.Test, testResult?.ResultState.Site); + StringAssert.Contains("Test exceeded Timeout value 50.", testResult?.ResultState.Label); } catch (TimeoutException) { - Assert.AreEqual(TestStatus.Inconclusive, testResult?.ResultState.Status); - Assert.AreEqual(FailureSite.Test, testResult?.ResultState.Site); - Assert.AreEqual("Invalid", testResult?.ResultState.Label); + Assert.Fail(); + return; } catch (Exception e) { Assert.Fail($"{nameof(TimeoutException)} is expected but exception type {e.GetType().Name} thrown."); } + Assert.Fail($"Failed as test should be marked invalid."); } } } - #endif diff --git a/src/NUnitFramework/tests/nunit.framework.tests.csproj b/src/NUnitFramework/tests/nunit.framework.tests.csproj index 800de12833..9ce0d4af8a 100644 --- a/src/NUnitFramework/tests/nunit.framework.tests.csproj +++ b/src/NUnitFramework/tests/nunit.framework.tests.csproj @@ -1,7 +1,7 @@ - + - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + netcoreapp1.1 NUnit.Framework Full @@ -18,7 +18,7 @@ - + From 7e5030dae83825beff62a9c5761d592ae24ab83b Mon Sep 17 00:00:00 2001 From: Dai Michael Date: Wed, 19 Sep 2018 20:32:13 +0100 Subject: [PATCH 004/174] Fixes #1638 - Allows Timeout to be used on .NetStandard 1.4 and 2.0. --- .../framework/Attributes/TimeoutAttribute.cs | 51 +++++++++- .../Internal/Commands/TimeoutCommand.cs | 95 ++++++++++++------- .../tests/Attributes/TimeoutTests.cs | 50 +++++----- 3 files changed, 137 insertions(+), 59 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs index 1cd910a165..766d64928c 100644 --- a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs @@ -20,6 +20,7 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +#if THREAD_ABORT using System; using NUnit.Framework.Internal; @@ -49,14 +50,60 @@ public TimeoutAttribute(int timeout) _timeout = timeout; } - #region IApplyToContext Members +#region IApplyToContext Members void IApplyToContext.ApplyToContext(TestExecutionContext context) { context.TestCaseTimeout = _timeout; } - #endregion +#endregion } } +#endif + +#if !THREAD_ABORT && !NET20 && !NET35 + +using System; +using System.Threading.Tasks; +using NUnit.Framework.Internal; +using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework +{ + /// + /// Used on a method, marks the test with a timeout value in milliseconds. + /// The test will be run in a separate thread and is cancelled if the timeout + /// is exceeded. Used on a class or assembly, sets the default timeout + /// for all contained test methods. + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false)] + public class TimeoutAttribute : PropertyAttribute, IWrapTestMethod + { + private readonly int _timeout; + + /// + /// Construct a TimeoutAttribute given a time in milliseconds + /// + /// The timeout value in milliseconds + public TimeoutAttribute(int timeout) : base(timeout) + { + _timeout = timeout; + } + + /// + /// Wrap a command and return the result. + /// + /// The command to be wrapped + /// The wrapped command + public TestCommand Wrap(TestCommand command) + { + return new TimeoutCommand(command, _timeout); + } + } +} + +#endif + diff --git a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs index bf8f7caa6f..3d0bec183c 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs @@ -20,20 +20,12 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** - -using System; -using System.Collections.Generic; - +#if THREAD_ABORT using System.Threading; -#if !NET20 && !NET35 -using System.Threading.Tasks; -#endif +using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Commands { - using Execution; - using Interfaces; - /// /// TimeoutCommand creates a timer in order to cancel /// a test if it exceeds a specified time and adjusts @@ -41,23 +33,18 @@ namespace NUnit.Framework.Internal.Commands /// public class TimeoutCommand : BeforeAndAfterTestCommand { - private readonly int _timeout; Timer _commandTimer; - private bool _commandTimedOut = false; + private bool _commandTimedOut; /// /// Initializes a new instance of the class. /// /// The inner command /// Timeout value - public TimeoutCommand(TestCommand innerCommand, int timeout) - : base(innerCommand) + public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand) { Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", nameof(innerCommand)); Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", nameof(timeout)); - _timeout = timeout; - -#if THREAD_ABORT BeforeTest = (context) => { @@ -84,12 +71,45 @@ public TimeoutCommand(TestCommand innerCommand, int timeout) // If the timer cancelled the current thread, change the result if (_commandTimedOut) { - context.CurrentResult.SetResult(ResultState.Failure, - string.Format("Test exceeded Timeout value of {0}ms", timeout)); + context.CurrentResult.SetResult(ResultState.Failure, $"Test exceeded Timeout value of {timeout}ms"); } }; - + } + } +} #endif + +#if !THREAD_ABORT && !NET20 && !NET35 + +using System; +using System.Linq; +using System.Threading.Tasks; +using NUnit.Framework.Interfaces; + +namespace NUnit.Framework.Internal.Commands +{ + /// + /// TimeoutCommand uses Task.Wait() for .NetCore, + /// if a test exceeds a specified time and adjusts + /// the test result if it did time out. + /// + public class TimeoutCommand : TestCommand + { + private readonly TestCommand _innerCommand; + private readonly int _timeout; + + /// + /// Initializes a new instance of the class. + /// + /// The inner command + /// Timeout value + public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand.Test) + { + Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", nameof(innerCommand)); + Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", nameof(timeout)); + + _innerCommand = innerCommand; + _timeout = timeout; } /// @@ -99,35 +119,42 @@ public TimeoutCommand(TestCommand innerCommand, int timeout) /// A TestResult public override TestResult Execute(TestExecutionContext context) { - -#if THREAD_ABORT - - return base.Execute(context); - -#endif - -#if !THREAD_ABORT && !NET20 && !NET35 - try { - if (!Task.Run(() => context.CurrentResult = base.Execute(context)).Wait(_timeout)) + if (!Task.Run(() => context.CurrentResult = _innerCommand.Execute(context)).Wait(_timeout)) { context.CurrentResult.SetResult(new ResultState( TestStatus.Failed, - $"Test exceeded Timeout value {_timeout}.", + $"Test exceeded Timeout value {_timeout}ms.", FailureSite.Test)); } } + catch (AggregateException ae) + { + var message = string.Empty; + + ae.Handle(x => + { + message += x.InnerException != null ? x.InnerException.Message : x.Message; + return true; + }); + + context.CurrentResult.SetResult(new ResultState( + TestStatus.Failed, + message, + FailureSite.Test)); + } catch (Exception exception) { context.CurrentResult.SetResult(new ResultState( - TestStatus.Failed, - exception.ToString(), + TestStatus.Failed, + exception.InnerException != null ? exception.InnerException.Message : exception.Message, FailureSite.Test)); } return context.CurrentResult; -#endif } } } + +#endif diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 366113510b..ba6d3a738e 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -174,7 +174,6 @@ public void TimeoutWithMessagePumpShouldAbort() #if !THREAD_ABORT using System; -using System.Collections.Generic; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.TestUtilities; @@ -185,41 +184,46 @@ namespace NUnit.Framework.Attributes public class TimeoutTests { [Timeout(50)] - public void TestTimesOutWhichThrowsTimeoutException() + public void TestTimeoutAndReportsTimeoutFailure() { while (true) { } } - [Test, Timeout(80)] - public void TestTimesOutDoesNotStopCompletion() + [Test, Timeout(100)] + public void TestTimesoutDoesNotStopCompletion() { Thread.Sleep(20); Assert.True(true); } + [Timeout(50)] + public void TestTimeoutWhichThrowsTestException() + { + throw new ArgumentException($"{nameof(ArgumentException)} was thrown."); + } + [Test] public void TestTimesOut() { - try - { - var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimesOutWhichThrowsTimeoutException)); - var workItem = TestBuilder.CreateWorkItem(testCase); - var testResult = TestBuilder.ExecuteWorkItem(workItem); + var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutAndReportsTimeoutFailure)); + var workItem = TestBuilder.CreateWorkItem(testCase, this); + var testResult = TestBuilder.ExecuteWorkItem(workItem); - Assert.AreEqual(TestStatus.Failed, testResult?.ResultState.Status); - Assert.AreEqual(FailureSite.Test, testResult?.ResultState.Site); - StringAssert.Contains("Test exceeded Timeout value 50.", testResult?.ResultState.Label); - } - catch (TimeoutException) - { - Assert.Fail(); - return; - } - catch (Exception e) - { - Assert.Fail($"{nameof(TimeoutException)} is expected but exception type {e.GetType().Name} thrown."); - } - Assert.Fail($"Failed as test should be marked invalid."); + Assert.That(testResult?.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(testResult?.ResultState.Site, Is.EqualTo(FailureSite.Test)); + Assert.That(testResult?.ResultState.Label, Is.EqualTo("Test exceeded Timeout value 50ms.")); + } + + [Test] + public void TestTimeoutWithExceptionThrown() + { + var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutWhichThrowsTestException)); + var workItem = TestBuilder.CreateWorkItem(testCase, this); + var testResult = TestBuilder.ExecuteWorkItem(workItem); + + Assert.That(testResult?.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(testResult?.ResultState.Site, Is.EqualTo(FailureSite.Test)); + Assert.That(testResult?.ResultState.Label, Is.EqualTo($"{nameof(ArgumentException)} was thrown.")); } } } From de82cff6b435fc0704a02ec22429238cd4598eb9 Mon Sep 17 00:00:00 2001 From: Dai Michael Date: Wed, 19 Sep 2018 20:43:19 +0100 Subject: [PATCH 005/174] Fix name of test. --- src/NUnitFramework/tests/Attributes/TimeoutTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index ba6d3a738e..de42d938d2 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -190,7 +190,7 @@ public void TestTimeoutAndReportsTimeoutFailure() } [Test, Timeout(100)] - public void TestTimesoutDoesNotStopCompletion() + public void TestTimeoutDoesNotStopCompletion() { Thread.Sleep(20); Assert.True(true); From 2c9bc1660f669917de63a9d8b2aaa29ba74e5836 Mon Sep 17 00:00:00 2001 From: DaiMichael Date: Thu, 20 Sep 2018 19:56:50 +0100 Subject: [PATCH 006/174] Fix debug change in csproj file --- src/NUnitFramework/tests/nunit.framework.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/nunit.framework.tests.csproj b/src/NUnitFramework/tests/nunit.framework.tests.csproj index 9ce0d4af8a..ccda099ae1 100644 --- a/src/NUnitFramework/tests/nunit.framework.tests.csproj +++ b/src/NUnitFramework/tests/nunit.framework.tests.csproj @@ -1,7 +1,7 @@ - netcoreapp1.1 + net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 NUnit.Framework Full From 3e9acb9702e5705d279dd8f103aa41d0fd3c50a2 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 7 May 2018 21:07:08 -0400 Subject: [PATCH 007/174] Made IDE naming configuration more helpful --- .editorconfig | 43 ++++++++++++++++++++++++++++++++++++++----- NUnit.sln.DotSettings | 14 +++++++++++++- 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/.editorconfig b/.editorconfig index 314583f2d1..d98918308f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -59,19 +59,52 @@ dotnet_style_predefined_type_for_member_access = true:suggestion dotnet_naming_style.pascal_case.capitalization = pascal_case +# Required dotnet_naming_symbols.namespaces_types_and_non_field_members.applicable_kinds = namespace, class, struct, enum, interface, delegate, type_parameter, method, property, event dotnet_naming_rule.namespaces_types_and_non_field_members.severity = suggestion dotnet_naming_rule.namespaces_types_and_non_field_members.symbols = namespaces_types_and_non_field_members dotnet_naming_rule.namespaces_types_and_non_field_members.style = pascal_case -dotnet_naming_symbols.public_fields.applicable_kinds = field -dotnet_naming_symbols.public_fields.applicable_accessibilities = public -dotnet_naming_rule.public_fields.severity = suggestion -dotnet_naming_rule.public_fields.symbols = public_fields -dotnet_naming_rule.public_fields.style = pascal_case +# Required +dotnet_naming_symbols.visible_fields.applicable_kinds = field +dotnet_naming_symbols.visible_fields.applicable_accessibilities = public, protected, protected_internal +dotnet_naming_rule.visible_fields.severity = suggestion +dotnet_naming_rule.visible_fields.symbols = visible_fields +dotnet_naming_rule.visible_fields.style = pascal_case + +# Defaults without diagnostics +dotnet_naming_symbols.internal_fields.applicable_kinds = field +dotnet_naming_symbols.internal_fields.applicable_accessibilities = internal +dotnet_naming_rule.internal_fields.severity = none +dotnet_naming_rule.internal_fields.symbols = internal_fields +dotnet_naming_rule.internal_fields.style = pascal_case + +# Defaults without diagnostics +dotnet_naming_symbols.static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.static_readonly_fields.required_modifiers = static, readonly +dotnet_naming_rule.static_readonly_fields.severity = none +dotnet_naming_rule.static_readonly_fields.symbols = static_readonly_fields +dotnet_naming_rule.static_readonly_fields.style = pascal_case + +# Defaults without diagnostics +dotnet_naming_symbols.constant_fields.applicable_kinds = field +dotnet_naming_symbols.constant_fields.required_modifiers = const +dotnet_naming_rule.constant_fields.severity = none +dotnet_naming_rule.constant_fields.symbols = constant_fields +dotnet_naming_rule.constant_fields.style = pascal_case + +dotnet_naming_style.underscore_camel_case.capitalization = camel_case +dotnet_naming_style.underscore_camel_case.required_prefix = _ + +# Required +dotnet_naming_symbols.remaining_fields.applicable_kinds = field +dotnet_naming_rule.remaining_fields.severity = suggestion +dotnet_naming_rule.remaining_fields.symbols = remaining_fields +dotnet_naming_rule.remaining_fields.style = underscore_camel_case dotnet_naming_style.camel_case.capitalization = camel_case +# Required dotnet_naming_symbols.parameters_and_locals.applicable_kinds = parameter, local dotnet_naming_rule.parameters_and_locals.severity = suggestion dotnet_naming_rule.parameters_and_locals.symbols = parameters_and_locals diff --git a/NUnit.sln.DotSettings b/NUnit.sln.DotSettings index 3e5f493d31..8b15d8a754 100644 --- a/NUnit.sln.DotSettings +++ b/NUnit.sln.DotSettings @@ -36,8 +36,20 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************** UI + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy> <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private, Internal" Description="Non-visible static readonly and constant fields"><ElementKinds><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> + <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Protected, ProtectedInternal, Public" Description="Visible fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Internal" Description="Internal fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> True True True @@ -173,4 +185,4 @@ namespace $NAMESPACE$ $END$ } } -} \ No newline at end of file +} From 7d3893624ee627a07e8411d1d6cd53c4e6a7dd44 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 7 May 2018 22:40:53 -0400 Subject: [PATCH 008/174] Allow IDE to show errors for important names --- .editorconfig | 8 ++++---- NUnit.sln.DotSettings | 28 ++++++++++++++++++++++------ 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/.editorconfig b/.editorconfig index d98918308f..dcbbaec354 100644 --- a/.editorconfig +++ b/.editorconfig @@ -61,14 +61,14 @@ dotnet_naming_style.pascal_case.capitalization = pascal_case # Required dotnet_naming_symbols.namespaces_types_and_non_field_members.applicable_kinds = namespace, class, struct, enum, interface, delegate, type_parameter, method, property, event -dotnet_naming_rule.namespaces_types_and_non_field_members.severity = suggestion +dotnet_naming_rule.namespaces_types_and_non_field_members.severity = error dotnet_naming_rule.namespaces_types_and_non_field_members.symbols = namespaces_types_and_non_field_members dotnet_naming_rule.namespaces_types_and_non_field_members.style = pascal_case # Required dotnet_naming_symbols.visible_fields.applicable_kinds = field dotnet_naming_symbols.visible_fields.applicable_accessibilities = public, protected, protected_internal -dotnet_naming_rule.visible_fields.severity = suggestion +dotnet_naming_rule.visible_fields.severity = error dotnet_naming_rule.visible_fields.symbols = visible_fields dotnet_naming_rule.visible_fields.style = pascal_case @@ -96,7 +96,7 @@ dotnet_naming_rule.constant_fields.style = pascal_case dotnet_naming_style.underscore_camel_case.capitalization = camel_case dotnet_naming_style.underscore_camel_case.required_prefix = _ -# Required +# Required for newly added fields dotnet_naming_symbols.remaining_fields.applicable_kinds = field dotnet_naming_rule.remaining_fields.severity = suggestion dotnet_naming_rule.remaining_fields.symbols = remaining_fields @@ -106,7 +106,7 @@ dotnet_naming_style.camel_case.capitalization = camel_case # Required dotnet_naming_symbols.parameters_and_locals.applicable_kinds = parameter, local -dotnet_naming_rule.parameters_and_locals.severity = suggestion +dotnet_naming_rule.parameters_and_locals.severity = error dotnet_naming_rule.parameters_and_locals.symbols = parameters_and_locals dotnet_naming_rule.parameters_and_locals.style = camel_case diff --git a/NUnit.sln.DotSettings b/NUnit.sln.DotSettings index 8b15d8a754..d8f7a5b5cf 100644 --- a/NUnit.sln.DotSettings +++ b/NUnit.sln.DotSettings @@ -1,5 +1,6 @@  True + ERROR SUGGESTION True True @@ -35,7 +36,19 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************** + CDATA + CE + ID + ME + MTA + NT + OS + OSX + SSCLI + STA UI + XP + <Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> @@ -43,13 +56,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> - <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy> - <Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="False" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="False" Prefix="_" Suffix="" Style="aaBb" /> + <Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /> + <Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> - <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> - <Policy><Descriptor Staticness="Static" AccessRightKinds="Private, Internal" Description="Non-visible static readonly and constant fields"><ElementKinds><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> - <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Protected, ProtectedInternal, Public" Description="Visible fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /></Policy> - <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Internal" Description="Internal fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="_" Suffix="" Style="aaBb" /></Policy></Policy> + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb"><ExtraRule Prefix="" Suffix="" Style="AA_BB" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private, Internal" Description="Non-visible static readonly and constant fields"><ElementKinds><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Protected, ProtectedInternal, Public" Description="Visible fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="AA_BB" /></Policy></Policy> + <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Internal" Description="Internal fields"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="False" Prefix="" Suffix="" Style="AaBb" /></Policy> True True True From 96f228be551d1ef3d279bcbdf1f100c4cae211cc Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 7 May 2018 22:42:23 -0400 Subject: [PATCH 009/174] Fix or annotate important naming rule departures --- .../Api/DefaultTestAssemblyBuilder.cs | 2 +- .../framework/Attributes/CategoryAttribute.cs | 4 ++ .../framework/Attributes/RandomAttribute.cs | 48 +++++++++---------- .../framework/Attributes/ValuesAttribute.cs | 4 ++ .../ConcurrentQueue.cs | 3 ++ .../CollectionDebuggerView.cs | 5 +- .../framework/Compatibility/System/Lazy.cs | 5 +- .../Constraints/ConstraintExpression.cs | 4 ++ .../Constraints/NUnitEqualityComparer.cs | 6 +-- .../Operators/ConstraintOperator.cs | 10 +++- .../framework/Constraints/StringConstraint.cs | 12 +++++ .../framework/Constraints/TypeConstraint.cs | 10 +++- .../framework/Interfaces/TNode.cs | 2 + .../Commands/DelegatingTestCommand.cs | 6 ++- .../framework/Internal/OSPlatform.cs | 4 ++ .../framework/Internal/PropertyNames.cs | 2 +- .../framework/Internal/TestListener.cs | 2 + .../framework/Internal/TestNameGenerator.cs | 6 +-- .../framework/Internal/ThreadUtility.cs | 4 ++ .../Internal/TypeNameDifferenceResolver.cs | 20 ++++---- src/NUnitFramework/framework/TestContext.cs | 6 +-- .../nunitlite.tests/TextUITests.cs | 4 +- .../nunitlite/ColorConsoleWriter.cs | 4 +- src/NUnitFramework/nunitlite/Options.cs | 18 +++---- src/NUnitFramework/nunitlite/TextRunner.cs | 4 +- src/NUnitFramework/nunitlite/TextUI.cs | 10 ++-- src/NUnitFramework/nunitlite/Tokenizer.cs | 2 +- 27 files changed, 137 insertions(+), 70 deletions(-) diff --git a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs index 02fc1d6fe8..bbd830fb3b 100644 --- a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs +++ b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs @@ -265,7 +265,7 @@ private TestSuite BuildTestAssembly(Assembly assembly, string suiteName, IList /// The name of the category /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected string categoryName; +#pragma warning restore IDE1006 /// /// Construct attribute for a given category based on diff --git a/src/NUnitFramework/framework/Attributes/RandomAttribute.cs b/src/NUnitFramework/framework/Attributes/RandomAttribute.cs index 496cc16920..fac016b9ff 100644 --- a/src/NUnitFramework/framework/Attributes/RandomAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/RandomAttribute.cs @@ -237,7 +237,7 @@ abstract class RandomDataSource : RandomDataSource private readonly List previousValues = new List(); - protected Randomizer _randomizer; + protected Randomizer Randomizer; protected RandomDataSource(int count) { @@ -261,7 +261,7 @@ public override IEnumerable GetData(Type fixtureType, ParameterInfo parameter) { //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter"); - _randomizer = Randomizer.GetRandomizer(parameter); + Randomizer = Randomizer.GetRandomizer(parameter); Guard.OperationValid(!(Distinct && _inRange && !CanBeDistinct(_min, _max, _count)), $"The range of values is [{_min}, {_max}[ and the random value count is {_count} so the values cannot be distinct."); @@ -350,12 +350,12 @@ class IntDataSource : RandomDataSource protected override int GetNext() { - return _randomizer.Next(); + return Randomizer.Next(); } protected override int GetNext(int min, int max) { - return _randomizer.Next(min, max); + return Randomizer.Next(min, max); } protected override bool CanBeDistinct(int min, int max, int count) @@ -376,12 +376,12 @@ class UIntDataSource : RandomDataSource protected override uint GetNext() { - return _randomizer.NextUInt(); + return Randomizer.NextUInt(); } protected override uint GetNext(uint min, uint max) { - return _randomizer.NextUInt(min, max); + return Randomizer.NextUInt(min, max); } protected override bool CanBeDistinct(uint min, uint max, int count) @@ -402,12 +402,12 @@ class LongDataSource : RandomDataSource protected override long GetNext() { - return _randomizer.NextLong(); + return Randomizer.NextLong(); } protected override long GetNext(long min, long max) { - return _randomizer.NextLong(min, max); + return Randomizer.NextLong(min, max); } protected override bool CanBeDistinct(long min, long max, int count) @@ -428,12 +428,12 @@ class ULongDataSource : RandomDataSource protected override ulong GetNext() { - return _randomizer.NextULong(); + return Randomizer.NextULong(); } protected override ulong GetNext(ulong min, ulong max) { - return _randomizer.NextULong(min, max); + return Randomizer.NextULong(min, max); } protected override bool CanBeDistinct(ulong min, ulong max, int count) @@ -454,12 +454,12 @@ class ShortDataSource : RandomDataSource protected override short GetNext() { - return _randomizer.NextShort(); + return Randomizer.NextShort(); } protected override short GetNext(short min, short max) { - return _randomizer.NextShort(min, max); + return Randomizer.NextShort(min, max); } protected override bool CanBeDistinct(short min, short max, int count) @@ -480,12 +480,12 @@ class UShortDataSource : RandomDataSource protected override ushort GetNext() { - return _randomizer.NextUShort(); + return Randomizer.NextUShort(); } protected override ushort GetNext(ushort min, ushort max) { - return _randomizer.NextUShort(min, max); + return Randomizer.NextUShort(min, max); } protected override bool CanBeDistinct(ushort min, ushort max, int count) @@ -506,12 +506,12 @@ class DoubleDataSource : RandomDataSource protected override double GetNext() { - return _randomizer.NextDouble(); + return Randomizer.NextDouble(); } protected override double GetNext(double min, double max) { - return _randomizer.NextDouble(min, max); + return Randomizer.NextDouble(min, max); } protected override bool CanBeDistinct(double min, double max, int count) @@ -532,12 +532,12 @@ class FloatDataSource : RandomDataSource protected override float GetNext() { - return _randomizer.NextFloat(); + return Randomizer.NextFloat(); } protected override float GetNext(float min, float max) { - return _randomizer.NextFloat(min, max); + return Randomizer.NextFloat(min, max); } protected override bool CanBeDistinct(float min, float max, int count) @@ -558,12 +558,12 @@ class ByteDataSource : RandomDataSource protected override byte GetNext() { - return _randomizer.NextByte(); + return Randomizer.NextByte(); } protected override byte GetNext(byte min, byte max) { - return _randomizer.NextByte(min, max); + return Randomizer.NextByte(min, max); } protected override bool CanBeDistinct(byte min, byte max, int count) @@ -584,12 +584,12 @@ class SByteDataSource : RandomDataSource protected override sbyte GetNext() { - return _randomizer.NextSByte(); + return Randomizer.NextSByte(); } protected override sbyte GetNext(sbyte min, sbyte max) { - return _randomizer.NextSByte(min, max); + return Randomizer.NextSByte(min, max); } protected override bool CanBeDistinct(sbyte min, sbyte max, int count) @@ -661,12 +661,12 @@ class DecimalDataSource : RandomDataSource protected override decimal GetNext() { - return _randomizer.NextDecimal(); + return Randomizer.NextDecimal(); } protected override decimal GetNext(decimal min, decimal max) { - return _randomizer.NextDecimal(min, max); + return Randomizer.NextDecimal(min, max); } protected override bool CanBeDistinct(decimal min, decimal max, int count) diff --git a/src/NUnitFramework/framework/Attributes/ValuesAttribute.cs b/src/NUnitFramework/framework/Attributes/ValuesAttribute.cs index 6a015fff14..5917b1ae0a 100644 --- a/src/NUnitFramework/framework/Attributes/ValuesAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/ValuesAttribute.cs @@ -45,7 +45,11 @@ public class ValuesAttribute : NUnitAttribute, IParameterDataSource /// elements may have their type changed in GetData /// if necessary /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected object[] data; +#pragma warning restore IDE1006 /// /// Constructs for use with an Enum parameter. Will pass every enum diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs index d6e3382288..88445e252d 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs @@ -1,3 +1,6 @@ +// ReSharper disable InconsistentNaming +// Disregarding naming convention in polyfill code + #if NET20 || NET35 #pragma warning disable 0420 diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs index 4b84d5c7db..72547c3150 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs @@ -1,3 +1,6 @@ +// ReSharper disable InconsistentNaming +// Disregarding naming convention in polyfill code + // // CollectionDebuggerView.cs // @@ -73,4 +76,4 @@ public CollectionDebuggerView (ICollection> col) } } } -#endif \ No newline at end of file +#endif diff --git a/src/NUnitFramework/framework/Compatibility/System/Lazy.cs b/src/NUnitFramework/framework/Compatibility/System/Lazy.cs index 14df7cff60..bf1714f457 100644 --- a/src/NUnitFramework/framework/Compatibility/System/Lazy.cs +++ b/src/NUnitFramework/framework/Compatibility/System/Lazy.cs @@ -1,3 +1,6 @@ +// ReSharper disable InconsistentNaming +// Disregarding naming convention in polyfill code + // // Lazy.cs // @@ -229,4 +232,4 @@ public override string ToString () } } } -#endif \ No newline at end of file +#endif diff --git a/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs b/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs index 61cfa2237c..81215843e0 100644 --- a/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs +++ b/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs @@ -45,7 +45,11 @@ public class ConstraintExpression /// /// The ConstraintBuilder holding the elements recognized so far /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected readonly ConstraintBuilder builder; +#pragma warning restore IDE1006 #endregion diff --git a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs index 531658ec36..7c4a3f837d 100644 --- a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs +++ b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs @@ -67,10 +67,10 @@ public sealed class NUnitEqualityComparer /// public NUnitEqualityComparer() { - EnumerablesComparer _enumerablesComparer = new EnumerablesComparer(this); + var enumerablesComparer = new EnumerablesComparer(this); _comparers = new List { - new ArraysComparer(this, _enumerablesComparer), + new ArraysComparer(this, enumerablesComparer), new DictionariesComparer(this), new DictionaryEntriesComparer(this), new KeyValuePairsComparer(this), @@ -84,7 +84,7 @@ public NUnitEqualityComparer() new EquatablesComparer(this), new TupleComparer(this), new ValueTupleComparer(this), - _enumerablesComparer + enumerablesComparer }; } diff --git a/src/NUnitFramework/framework/Constraints/Operators/ConstraintOperator.cs b/src/NUnitFramework/framework/Constraints/Operators/ConstraintOperator.cs index fd88fcaf62..e11a00dee8 100644 --- a/src/NUnitFramework/framework/Constraints/Operators/ConstraintOperator.cs +++ b/src/NUnitFramework/framework/Constraints/Operators/ConstraintOperator.cs @@ -41,13 +41,21 @@ public abstract class ConstraintOperator /// The precedence value used when the operator /// is about to be pushed to the stack. /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected int left_precedence; +#pragma warning restore IDE1006 /// /// The precedence value used when the operator /// is on the top of the stack. /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected int right_precedence; +#pragma warning restore IDE1006 /// /// The syntax element preceding this operator @@ -93,4 +101,4 @@ public virtual int RightPrecedence /// public abstract void Reduce(ConstraintBuilder.ConstraintStack stack); } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/StringConstraint.cs b/src/NUnitFramework/framework/Constraints/StringConstraint.cs index 539eaf1ec2..36d45c1812 100644 --- a/src/NUnitFramework/framework/Constraints/StringConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/StringConstraint.cs @@ -35,17 +35,29 @@ public abstract class StringConstraint : Constraint /// /// The expected value /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected string expected; +#pragma warning restore IDE1006 /// /// Indicates whether tests should be case-insensitive /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected bool caseInsensitive; +#pragma warning restore IDE1006 /// /// Description of this constraint /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected string descriptionText; +#pragma warning restore IDE1006 /// /// The Description of what this constraint tests, for diff --git a/src/NUnitFramework/framework/Constraints/TypeConstraint.cs b/src/NUnitFramework/framework/Constraints/TypeConstraint.cs index f7ffa23a2a..5e3debe8d5 100644 --- a/src/NUnitFramework/framework/Constraints/TypeConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/TypeConstraint.cs @@ -34,12 +34,20 @@ public abstract class TypeConstraint : Constraint /// /// The expected Type used by the constraint /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected Type expectedType; +#pragma warning restore IDE1006 /// /// The type of the actual argument to which the constraint was applied /// +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected Type actualType; +#pragma warning restore IDE1006 /// /// Construct a TypeConstraint for a given Type @@ -75,4 +83,4 @@ public override ConstraintResult ApplyTo(TActual actual) /// True if the constraint succeeds, otherwise false. protected abstract bool Matches(object actual); } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index ea69a2f914..c5bb09d159 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -37,6 +37,8 @@ namespace NUnit.Framework.Interfaces /// System.Xml.Linq.XElement, providing a minimal set of methods /// for operating on the XML in a platform-independent manner. /// + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat public class TNode { #region Constructors diff --git a/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs b/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs index a57e0c383b..b6d39de7a2 100644 --- a/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2010 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,7 +31,11 @@ namespace NUnit.Framework.Internal.Commands public abstract class DelegatingTestCommand : TestCommand { /// TODO: Documentation needed for field +#pragma warning disable IDE1006 + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat protected TestCommand innerCommand; +#pragma warning restore IDE1006 /// /// TODO: Documentation needed for constructor diff --git a/src/NUnitFramework/framework/Internal/OSPlatform.cs b/src/NUnitFramework/framework/Internal/OSPlatform.cs index e94efeb298..d670b08be6 100644 --- a/src/NUnitFramework/framework/Internal/OSPlatform.cs +++ b/src/NUnitFramework/framework/Internal/OSPlatform.cs @@ -184,6 +184,7 @@ public enum ProductType [StructLayout(LayoutKind.Sequential)] struct OSVERSIONINFOEX { +#pragma warning disable IDE1006 // P/invoke doesn’t need to follow naming convention public uint dwOSVersionInfoSize; public readonly uint dwMajorVersion; public readonly uint dwMinorVersion; @@ -194,6 +195,7 @@ struct OSVERSIONINFOEX public readonly Int16 wServicePackMajor; public readonly Int16 wServicePackMinor; public readonly Int16 wSuiteMask; +#pragma warning restore IDE1006 public readonly Byte ProductType; public readonly Byte Reserved; } @@ -350,7 +352,9 @@ public bool IsMacOSX } [DllImport("libc")] +#pragma warning disable IDE1006 // P/invoke doesn’t need to follow naming convention static extern int uname(IntPtr buf); +#pragma warning restore IDE1006 static bool CheckIfIsMacOSX(PlatformID platform) { diff --git a/src/NUnitFramework/framework/Internal/PropertyNames.cs b/src/NUnitFramework/framework/Internal/PropertyNames.cs index d6629e887e..415df42a86 100644 --- a/src/NUnitFramework/framework/Internal/PropertyNames.cs +++ b/src/NUnitFramework/framework/Internal/PropertyNames.cs @@ -46,7 +46,7 @@ public class PropertyNames /// /// The process ID of the executing assembly /// - public const string ProcessID = "_PID"; + public const string ProcessId = "_PID"; /// /// The stack trace from any data provider that threw diff --git a/src/NUnitFramework/framework/Internal/TestListener.cs b/src/NUnitFramework/framework/Internal/TestListener.cs index 7314da8b24..551e1374dd 100644 --- a/src/NUnitFramework/framework/Internal/TestListener.cs +++ b/src/NUnitFramework/framework/Internal/TestListener.cs @@ -64,6 +64,8 @@ public class TestListener : ITestListener /// /// Get a listener that does nothing /// + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat public static ITestListener NULL { get { return new TestListener();} diff --git a/src/NUnitFramework/framework/Internal/TestNameGenerator.cs b/src/NUnitFramework/framework/Internal/TestNameGenerator.cs index 25041c1b31..29a9f2ab38 100644 --- a/src/NUnitFramework/framework/Internal/TestNameGenerator.cs +++ b/src/NUnitFramework/framework/Internal/TestNameGenerator.cs @@ -230,9 +230,9 @@ protected static string GetDisplayString(object arg, int stringMax) var builder = new StringBuilder(); builder.Append("["); - const int MaxNumItemsToEnumerate = 5; + const int maxNumItemsToEnumerate = 5; - var numItemsToEnumerate = Math.Min(argArray.Length, MaxNumItemsToEnumerate); + var numItemsToEnumerate = Math.Min(argArray.Length, maxNumItemsToEnumerate); for (int i = 0; i < numItemsToEnumerate; i++) { if (i > 0) @@ -253,7 +253,7 @@ protected static string GetDisplayString(object arg, int stringMax) } } - if (argArray.Length > MaxNumItemsToEnumerate) + if (argArray.Length > maxNumItemsToEnumerate) builder.Append(", ..."); builder.Append("]"); diff --git a/src/NUnitFramework/framework/Internal/ThreadUtility.cs b/src/NUnitFramework/framework/Internal/ThreadUtility.cs index de4a8d304e..20dadd1cd5 100644 --- a/src/NUnitFramework/framework/Internal/ThreadUtility.cs +++ b/src/NUnitFramework/framework/Internal/ThreadUtility.cs @@ -211,6 +211,8 @@ private static void PostThreadCloseMessage(int nativeId) { if (!PostThreadMessage(nativeId, WM.CLOSE, IntPtr.Zero, IntPtr.Zero)) { + // ReSharper disable once InconsistentNaming + // P/invoke doesn’t need to follow naming convention const int ERROR_INVALID_THREAD_ID = 0x5A4; var errorCode = Marshal.GetLastWin32Error(); if (errorCode != ERROR_INVALID_THREAD_ID) @@ -227,6 +229,8 @@ private static void PostThreadCloseMessage(int nativeId) private enum WM : uint { + // ReSharper disable once InconsistentNaming + // P/invoke doesn’t need to follow naming convention CLOSE = 0x0010 } #endif diff --git a/src/NUnitFramework/framework/Internal/TypeNameDifferenceResolver.cs b/src/NUnitFramework/framework/Internal/TypeNameDifferenceResolver.cs index dc31f5461e..ad56266f34 100644 --- a/src/NUnitFramework/framework/Internal/TypeNameDifferenceResolver.cs +++ b/src/NUnitFramework/framework/Internal/TypeNameDifferenceResolver.cs @@ -117,21 +117,21 @@ private void GetShortenedGenericParams(Type expectedFullType, Type actualFullTyp /// /// Obtain a shortened name of the given . /// - public string FullyShortenTypeName(Type GenericType) + public string FullyShortenTypeName(Type genericType) { - if (IsTypeGeneric(GenericType)) + if (IsTypeGeneric(genericType)) { - string genericType = GenericType.GetGenericTypeDefinition().Name; + string genericTypeDefinition = genericType.GetGenericTypeDefinition().Name; - List genericParams = new List(GenericType.GetGenericArguments()); + List genericParams = new List(genericType.GetGenericArguments()); List shortenedGenericParams = new List(); genericParams.ForEach(x => shortenedGenericParams.Add(FullyShortenTypeName(x))); - return ReconstructGenericTypeName(genericType, shortenedGenericParams); + return ReconstructGenericTypeName(genericTypeDefinition, shortenedGenericParams); } else { - return GenericType.Name; + return genericType.Name; } } @@ -207,11 +207,11 @@ public string GetGenericTypeName(Type type) /// Reconstruct a generic type name using the provided generic type name, and a /// of the template parameters. /// - /// The name of the generic type, including the number of template parameters expected. - /// A of names of the template parameters of the provided generic type. - public string ReconstructGenericTypeName(string GenericTypeName, List TemplateParamNames) + /// The name of the generic type, including the number of template parameters expected. + /// A of names of the template parameters of the provided generic type. + public string ReconstructGenericTypeName(string genericTypeName, List templateParamNames) { - return GenericTypeName + "[" + string.Join(",", TemplateParamNames.ToArray()) + "]"; + return genericTypeName + "[" + string.Join(",", templateParamNames.ToArray()) + "]"; } /// diff --git a/src/NUnitFramework/framework/TestContext.cs b/src/NUnitFramework/framework/TestContext.cs index 57e95e59d6..4094203d91 100644 --- a/src/NUnitFramework/framework/TestContext.cs +++ b/src/NUnitFramework/framework/TestContext.cs @@ -338,11 +338,11 @@ public static void AddTestAttachment(string filePath, string description = null) /// is the only criterion for selection of the formatter, since /// it can be used without getting involved with a compound function. /// - /// The type supported by this formatter + /// The type supported by this formatter /// The ValueFormatter delegate - public static void AddFormatter(ValueFormatter formatter) + public static void AddFormatter(ValueFormatter formatter) { - AddFormatter(next => val => (val is TSUPPORTED) ? formatter(val) : next(val)); + AddFormatter(next => val => (val is TSupported) ? formatter(val) : next(val)); } #endregion diff --git a/src/NUnitFramework/nunitlite.tests/TextUITests.cs b/src/NUnitFramework/nunitlite.tests/TextUITests.cs index 752fee3c9e..a3d8b0a0c0 100644 --- a/src/NUnitFramework/nunitlite.tests/TextUITests.cs +++ b/src/NUnitFramework/nunitlite.tests/TextUITests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2015-2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -249,7 +249,7 @@ public void SuiteFinished(string labelsOption, TestStatus resultStatus, string r } #pragma warning disable 414 - static TestCaseData[] ImmediateOutputData = new[] { + static readonly TestCaseData[] ImmediateOutputData = new[] { new TestCaseData("Off", new [] { new TestOutput("OUTPUT\n", "", null, "SomeMethod") }, "OUTPUT\n"), diff --git a/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs b/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs index 06762cd60a..89020a5a08 100644 --- a/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs +++ b/src/NUnitFramework/nunitlite/ColorConsoleWriter.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -29,6 +29,8 @@ namespace NUnit.Common { public class ColorConsoleWriter : ExtendedTextWrapper { + // ReSharper disable once InconsistentNaming + // Disregarding naming convention for back-compat public bool _colorEnabled; /// diff --git a/src/NUnitFramework/nunitlite/Options.cs b/src/NUnitFramework/nunitlite/Options.cs index 2221738456..364ecd226e 100644 --- a/src/NUnitFramework/nunitlite/Options.cs +++ b/src/NUnitFramework/nunitlite/Options.cs @@ -515,7 +515,7 @@ public override void GetObjectData (SerializationInfo info, StreamingContext con public class OptionSet : KeyedCollection { - string localizer(string msg) + string Localizer(string msg) { return msg; } @@ -742,7 +742,7 @@ private static bool Unprocessed (ICollection extra, Option def, OptionCo return false; } - private readonly Regex ValueOption = new Regex ( + private readonly static Regex ValueOption = new Regex( @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) @@ -814,7 +814,7 @@ private void ParseValue (string option, OptionContext c) c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { - throw new OptionException (localizer (string.Format ( + throw new OptionException (Localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); @@ -849,7 +849,7 @@ private bool ParseBundledValue (string f, string n, OptionContext c) if (!Contains (rn)) { if (i == 0) return false; - throw new OptionException (string.Format (localizer ( + throw new OptionException (string.Format (Localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; @@ -898,7 +898,7 @@ public void WriteOptionDescriptions (TextWriter o) bool indent = false; string prefix = new string (' ', OptionWidth+2); - foreach (string line in GetLines (localizer (GetDescription (p.Description)))) { + foreach (string line in GetLines (Localizer (GetDescription (p.Description)))) { if (indent) o.Write (prefix); o.WriteLine (line); @@ -934,17 +934,17 @@ bool WriteOptionPrototype (TextWriter o, Option p, ref int written) if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("[")); + Write (o, ref written, Localizer ("[")); } - Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); + Write (o, ref written, Localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { - Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); + Write (o, ref written, Localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("]")); + Write (o, ref written, Localizer ("]")); } } return true; diff --git a/src/NUnitFramework/nunitlite/TextRunner.cs b/src/NUnitFramework/nunitlite/TextRunner.cs index 8322042148..697ec3ecdb 100644 --- a/src/NUnitFramework/nunitlite/TextRunner.cs +++ b/src/NUnitFramework/nunitlite/TextRunner.cs @@ -428,7 +428,7 @@ private void InitializeInternalTrace() private string GetLogFileName() { - const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.{2}"; + const string logFileFormat = "InternalTrace.{0}.{1}.{2}"; // Some mobiles don't have an Open With menu item, // so we use .txt, which is opened easily. @@ -445,7 +445,7 @@ private string GetLogFileName() var id = Process.GetCurrentProcess().Id; #endif - return string.Format(LOG_FILE_FORMAT, id, baseName, ext); + return string.Format(logFileFormat, id, baseName, ext); } #endregion diff --git a/src/NUnitFramework/nunitlite/TextUI.cs b/src/NUnitFramework/nunitlite/TextUI.cs index bd2a261a68..c4451950f8 100644 --- a/src/NUnitFramework/nunitlite/TextUI.cs +++ b/src/NUnitFramework/nunitlite/TextUI.cs @@ -511,27 +511,27 @@ private void DisplayTestResult(ITestResult result) string fullName = result.FullName; string message = result.Message; string stackTrace = result.StackTrace; - string reportID = (++_reportIndex).ToString(); + string reportId = (++_reportIndex).ToString(); int numAsserts = result.AssertionResults.Count; if (numAsserts > 0) { int assertionCounter = 0; - string assertID = reportID; + string assertId = reportId; foreach (var assertion in result.AssertionResults) { if (numAsserts > 1) - assertID = string.Format("{0}-{1}", reportID, ++assertionCounter); + assertId = string.Format("{0}-{1}", reportId, ++assertionCounter); ColorStyle style = GetColorStyle(resultState); string status = assertion.Status.ToString(); - DisplayTestResult(style, assertID, status, fullName, assertion.Message, assertion.StackTrace); + DisplayTestResult(style, assertId, status, fullName, assertion.Message, assertion.StackTrace); } } else { ColorStyle style = GetColorStyle(resultState); string status = GetResultStatus(resultState); - DisplayTestResult(style, reportID, status, fullName, message, stackTrace); + DisplayTestResult(style, reportId, status, fullName, message, stackTrace); } } diff --git a/src/NUnitFramework/nunitlite/Tokenizer.cs b/src/NUnitFramework/nunitlite/Tokenizer.cs index f6c9c053e3..56feb30ff8 100644 --- a/src/NUnitFramework/nunitlite/Tokenizer.cs +++ b/src/NUnitFramework/nunitlite/Tokenizer.cs @@ -109,7 +109,7 @@ public class Tokenizer private const char EOF_CHAR = '\0'; private const string WORD_BREAK_CHARS = "=!()&|"; - private readonly string[] DOUBLE_CHAR_SYMBOLS = new string[] { "==", "=~", "!=", "!~", "&&", "||" }; + private static readonly string[] DOUBLE_CHAR_SYMBOLS = new string[] { "==", "=~", "!=", "!~", "&&", "||" }; private Token _lookahead; From b0d7ba3a290962de620447349c8a6eb8b571fda9 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 7 May 2018 23:33:06 -0400 Subject: [PATCH 010/174] Fix or annotate important naming rule departures in tests --- .../testdata/AttributeInheritanceData.cs | 2 +- .../testdata/OneTimeSetUpTearDownData.cs | 164 +++++++++--------- .../testdata/RepeatedTestFixture.cs | 34 ++-- .../testdata/RepeatingTestsFixtureBase.cs | 6 +- src/NUnitFramework/testdata/RetryFixture.cs | 44 ++--- src/NUnitFramework/testdata/SetUpData.cs | 72 ++++---- .../TestCaseSourceAttributeFixture.cs | 12 +- .../testdata/TestContextData.cs | 26 +-- src/NUnitFramework/testdata/TheoryFixture.cs | 6 +- .../tests/Assertions/AssertEqualsTests.cs | 16 +- .../Attributes/OneTimeSetUpTearDownTests.cs | 154 ++++++++-------- .../tests/Attributes/TheoryTests.cs | 10 +- .../Compatibility/AttributeHelperTests.cs | 4 +- .../tests/Constraints/AndConstraintTests.cs | 6 +- .../tests/Constraints/AnyOfConstraintTests.cs | 6 +- .../AssignableFromConstraintTests.cs | 6 +- .../AssignableToConstraintTests.cs | 6 +- .../AttributeExistsConstraintTests.cs | 6 +- .../tests/Constraints/BasicConstraintTests.cs | 24 +-- .../Constraints/BinarySerializableTest.cs | 8 +- .../CollectionSubsetConstraintTests.cs | 6 +- .../CollectionSupersetConstraintTests.cs | 6 +- .../ComparisonConstraintTestBase.cs | 14 +- .../tests/Constraints/ConstraintTestBase.cs | 18 +- .../Constraints/DelayedConstraintTests.cs | 10 +- .../tests/Constraints/EmptyConstraintTest.cs | 22 +-- .../Constraints/EndsWithConstraintTests.cs | 14 +- .../tests/Constraints/EqualConstraintTests.cs | 28 +-- .../Constraints/ExactTypeConstraintTests.cs | 8 +- .../Constraints/GreaterThanConstraintTests.cs | 8 +- .../GreaterThanOrEqualConstraintTests.cs | 8 +- .../InstanceOfTypeConstraintTests.cs | 10 +- .../Constraints/LessThanConstraintTests.cs | 8 +- .../LessThanOrEqualConstraintTests.cs | 8 +- .../tests/Constraints/NotConstraintTests.cs | 8 +- .../tests/Constraints/OrConstraintTests.cs | 8 +- .../tests/Constraints/PathConstraintTests.cs | 36 ++-- .../Constraints/PredicateConstraintTests.cs | 6 +- .../tests/Constraints/PropertyTests.cs | 20 +-- .../tests/Constraints/RangeConstraintTests.cs | 8 +- .../tests/Constraints/SameAsTest.cs | 8 +- .../Constraints/StartsWithConstraintTests.cs | 14 +- .../tests/Constraints/StringConstraintTest.cs | 2 +- .../Constraints/SubstringConstraintTests.cs | 18 +- .../Constraints/ThrowsConstraintTests.cs | 24 +-- .../ThrowsExceptionConstraintTests.cs | 8 +- .../Constraints/UniqueItemsConstraintTests.cs | 6 +- .../tests/Constraints/XmlSerializableTest.cs | 8 +- .../Internal/EventListenerTextWriterTests.cs | 4 + .../Internal/NUnitTestCaseBuilderTests.cs | 4 + .../tests/Internal/RuntimeFrameworkTests.cs | 56 +++--- .../tests/Internal/SetUpFixtureTests.cs | 20 +-- .../tests/Internal/SetUpTearDownTests.cs | 68 ++++---- src/NUnitFramework/tests/Syntax/AfterTests.cs | 106 +++++------ src/NUnitFramework/tests/Syntax/AnyOfTests.cs | 12 +- .../tests/Syntax/CollectionTests.cs | 74 ++++---- .../tests/Syntax/ComparisonTests.cs | 38 ++-- .../tests/Syntax/EqualityTests.cs | 20 +-- .../tests/Syntax/OperatorOverrides.cs | 20 +-- .../tests/Syntax/OperatorTests.cs | 134 +++++++------- .../tests/Syntax/PathConstraintTests.cs | 62 +++---- .../tests/Syntax/PropertyTests.cs | 46 ++--- .../tests/Syntax/SerializableConstraints.cs | 12 +- .../tests/Syntax/SimpleConstraints.cs | 44 ++--- .../tests/Syntax/StringConstraints.cs | 56 +++--- src/NUnitFramework/tests/Syntax/SyntaxTest.cs | 16 +- .../tests/Syntax/TypeConstraints.cs | 68 ++++---- src/NUnitFramework/tests/TestContextTests.cs | 14 +- 68 files changed, 916 insertions(+), 912 deletions(-) diff --git a/src/NUnitFramework/testdata/AttributeInheritanceData.cs b/src/NUnitFramework/testdata/AttributeInheritanceData.cs index bfa29c0c2c..769be81888 100644 --- a/src/NUnitFramework/testdata/AttributeInheritanceData.cs +++ b/src/NUnitFramework/testdata/AttributeInheritanceData.cs @@ -53,7 +53,7 @@ class SpecAttribute : TestAttribute public class When_collecting_test_fixtures { [Spec] - public void should_include_classes_with_an_attribute_derived_from_TestFixtureAttribute() + public void Should_include_classes_with_an_attribute_derived_from_TestFixtureAttribute() { } } diff --git a/src/NUnitFramework/testdata/OneTimeSetUpTearDownData.cs b/src/NUnitFramework/testdata/OneTimeSetUpTearDownData.cs index 6db6513799..6c03ef2a99 100644 --- a/src/NUnitFramework/testdata/OneTimeSetUpTearDownData.cs +++ b/src/NUnitFramework/testdata/OneTimeSetUpTearDownData.cs @@ -30,22 +30,22 @@ namespace NUnit.TestData.OneTimeSetUpTearDownData [TestFixture] public class SetUpAndTearDownFixture { - public int setUpCount = 0; - public int tearDownCount = 0; - public bool throwInBaseSetUp = false; + public int SetUpCount = 0; + public int TearDownCount = 0; + public bool ThrowInBaseSetUp = false; [OneTimeSetUp] public virtual void Init() { - setUpCount++; - if (throwInBaseSetUp) + SetUpCount++; + if (ThrowInBaseSetUp) throw new Exception("Error in base OneTimeSetUp"); } [OneTimeTearDown] public virtual void Destroy() { - tearDownCount++; + TearDownCount++; } [Test] @@ -58,19 +58,19 @@ public virtual void Destroy() [TestFixture] public class SetUpAndTearDownFixtureWithTestCases { - public int setUpCount = 0; - public int tearDownCount = 0; + public int SetUpCount = 0; + public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { - tearDownCount++; + TearDownCount++; } [TestCase(1)] @@ -86,19 +86,19 @@ public void Success(int i) [TestFixture] public class SetUpAndTearDownFixtureWithTheories { - public int setUpCount = 0; - public int tearDownCount = 0; + public int SetUpCount = 0; + public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { - tearDownCount++; + TearDownCount++; } public struct Data @@ -107,7 +107,7 @@ public struct Data } [DatapointSource] - public IEnumerable fetchAllRows() + public IEnumerable FetchAllRows() { yield return new Data { Id = 1 }; yield return new Data { Id = 2 }; @@ -125,19 +125,19 @@ public void TheoryTest(Data entry) [TestFixture, Explicit] public class ExplicitSetUpAndTearDownFixture { - public int setUpCount = 0; - public int tearDownCount = 0; + public int SetUpCount = 0; + public int TearDownCount = 0; [OneTimeSetUp] public virtual void Init() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public virtual void Destroy() { - tearDownCount++; + TearDownCount++; } [Test] @@ -160,19 +160,19 @@ public class InheritSetUpAndTearDown : SetUpAndTearDownFixture [TestFixture] public class OverrideSetUpAndTearDown : SetUpAndTearDownFixture { - public int derivedSetUpCount; - public int derivedTearDownCount; + public int DerivedSetUpCount; + public int DerivedTearDownCount; [OneTimeSetUp] public override void Init() { - derivedSetUpCount++; + DerivedSetUpCount++; } [OneTimeTearDown] public override void Destroy() { - derivedTearDownCount++; + DerivedTearDownCount++; } [Test] @@ -185,24 +185,24 @@ public override void Destroy() [TestFixture] public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture { - public int derivedSetUpCount; - public int derivedTearDownCount; + public int DerivedSetUpCount; + public int DerivedTearDownCount; - public bool baseSetUpCalledFirst; - public bool baseTearDownCalledLast; + public bool BaseSetUpCalledFirst; + public bool BaseTearDownCalledLast; [OneTimeSetUp] public void Init2() { - derivedSetUpCount++; - baseSetUpCalledFirst = this.setUpCount > 0; + DerivedSetUpCount++; + BaseSetUpCalledFirst = this.SetUpCount > 0; } [OneTimeTearDown] public void Destroy2() { - derivedTearDownCount++; - baseTearDownCalledLast = this.tearDownCount == 0; + DerivedTearDownCount++; + BaseTearDownCalledLast = this.TearDownCount == 0; } [Test] @@ -215,19 +215,19 @@ public void Destroy2() [TestFixture] public class StaticSetUpAndTearDownFixture { - public static int setUpCount = 0; - public static int tearDownCount = 0; + public static int SetUpCount = 0; + public static int TearDownCount = 0; [OneTimeSetUp] public static void Init() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public static void Destroy() { - tearDownCount++; + TearDownCount++; } [Test] @@ -237,25 +237,25 @@ public static void Destroy() [TestFixture] public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture { - public static int derivedSetUpCount; - public static int derivedTearDownCount; + public static int DerivedSetUpCount; + public static int DerivedTearDownCount; - public static bool baseSetUpCalledFirst; - public static bool baseTearDownCalledLast; + public static bool BaseSetUpCalledFirst; + public static bool BaseTearDownCalledLast; [OneTimeSetUp] public static void Init2() { - derivedSetUpCount++; - baseSetUpCalledFirst = setUpCount > 0; + DerivedSetUpCount++; + BaseSetUpCalledFirst = SetUpCount > 0; } [OneTimeTearDown] public static void Destroy2() { - derivedTearDownCount++; - baseTearDownCalledLast = tearDownCount == 0; + DerivedTearDownCount++; + BaseTearDownCalledLast = TearDownCount == 0; } [Test] @@ -265,19 +265,19 @@ public static void Destroy2() [TestFixture] public static class StaticClassSetUpAndTearDownFixture { - public static int setUpCount = 0; - public static int tearDownCount = 0; + public static int SetUpCount = 0; + public static int TearDownCount = 0; [OneTimeSetUp] public static void Init() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public static void Destroy() { - tearDownCount++; + TearDownCount++; } [Test] @@ -298,42 +298,42 @@ public class FixtureWithParallelizableOnOneTimeSetUp [TestFixture] public class MisbehavingFixture { - public bool blowUpInSetUp = false; - public bool blowUpInTest = false; - public bool blowUpInTearDown = false; + public bool BlowUpInSetUp = false; + public bool BlowUpInTest = false; + public bool BlowUpInTearDown = false; - public int setUpCount = 0; - public int tearDownCount = 0; + public int SetUpCount = 0; + public int TearDownCount = 0; public void Reinitialize() { - setUpCount = 0; - tearDownCount = 0; + SetUpCount = 0; + TearDownCount = 0; - blowUpInSetUp = false; - blowUpInTearDown = false; + BlowUpInSetUp = false; + BlowUpInTearDown = false; } [OneTimeSetUp] - public void BlowUpInSetUp() + public void SetUp() { - setUpCount++; - if (blowUpInSetUp) + SetUpCount++; + if (BlowUpInSetUp) throw new Exception("This was thrown from fixture setup"); } [OneTimeTearDown] - public void BlowUpInTearDown() + public void TearDown() { - tearDownCount++; - if ( blowUpInTearDown ) + TearDownCount++; + if (BlowUpInTearDown) throw new Exception("This was thrown from fixture teardown"); } [Test] - public void BlowUpInTest() + public void Test() { - if (blowUpInTest) + if (BlowUpInTest) throw new Exception("This was thrown from a test"); } } @@ -347,7 +347,7 @@ public ExceptionInConstructor() } [Test] - public void nothingToTest() + public void NothingToTest() { } } @@ -362,7 +362,7 @@ public void SetUpCallsIgnore() } [Test] - public void nothingToTest() + public void NothingToTest() { } } @@ -370,19 +370,19 @@ public void nothingToTest() [TestFixture] public class SetUpAndTearDownWithTestInName { - public int setUpCount = 0; - public int tearDownCount = 0; + public int SetUpCount = 0; + public int TearDownCount = 0; [OneTimeSetUp] public virtual void OneTimeSetUp() { - setUpCount++; + SetUpCount++; } [OneTimeTearDown] public virtual void OneTimeTearDown() { - tearDownCount++; + TearDownCount++; } [Test] @@ -395,19 +395,19 @@ public virtual void OneTimeTearDown() [TestFixture, Ignore( "Do Not Run This" )] public class IgnoredFixture { - public bool setupCalled = false; - public bool teardownCalled = false; + public bool SetupCalled = false; + public bool TeardownCalled = false; [OneTimeSetUp] public virtual void ShouldNotRun() { - setupCalled = true; + SetupCalled = true; } [OneTimeTearDown] public virtual void NeitherShouldThis() { - teardownCalled = true; + TeardownCalled = true; } [Test] @@ -420,26 +420,26 @@ public virtual void NeitherShouldThis() [TestFixture] public class FixtureWithNoTests { - public bool setupCalled = false; - public bool teardownCalled = false; + public bool SetupCalled = false; + public bool TeardownCalled = false; [OneTimeSetUp] public virtual void Init() { - setupCalled = true; + SetupCalled = true; } [OneTimeTearDown] public virtual void Destroy() { - teardownCalled = true; + TeardownCalled = true; } } [TestFixture] public class DisposableFixture : IDisposable { - public int disposeCalled = 0; + public int DisposeCalled = 0; public List Actions = new List(); [OneTimeSetUp] @@ -460,14 +460,14 @@ public void OneTimeTearDown() public void Dispose() { Actions.Add("Dispose"); - disposeCalled++; + DisposeCalled++; } } [TestFixture] public class DisposableFixtureWithTestCases : IDisposable { - public int disposeCalled = 0; + public int DisposeCalled = 0; [TestCase(1)] [TestCase(2)] @@ -477,7 +477,7 @@ public class DisposableFixtureWithTestCases : IDisposable public void Dispose() { - disposeCalled++; + DisposeCalled++; } } } diff --git a/src/NUnitFramework/testdata/RepeatedTestFixture.cs b/src/NUnitFramework/testdata/RepeatedTestFixture.cs index cb1ec7b019..bb48aee261 100644 --- a/src/NUnitFramework/testdata/RepeatedTestFixture.cs +++ b/src/NUnitFramework/testdata/RepeatedTestFixture.cs @@ -38,7 +38,7 @@ public class RepeatSuccessFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void RepeatSuccess() { - count++; + Count++; Assert.IsTrue (true); } } @@ -48,7 +48,7 @@ public class RepeatFailOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void RepeatFailOnFirst() { - count++; + Count++; Assert.IsFalse (true); } } @@ -58,9 +58,9 @@ public class RepeatFailOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void RepeatFailOnThird() { - count++; + Count++; - if (count == 2) + if (Count == 2) Assert.IsTrue(false); } } @@ -70,9 +70,9 @@ public class RepeatFailOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void RepeatFailOnThird() { - count++; + Count++; - if (count == 3) + if (Count == 3) Assert.IsTrue(false); } } @@ -91,7 +91,7 @@ public class RepeatIgnoredOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; Assert.Ignore("Ignoring"); } } @@ -101,9 +101,9 @@ public class RepeatIgnoredOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; - if (count == 2) + if (Count == 2) Assert.Ignore("Ignoring"); } } @@ -113,9 +113,9 @@ public class RepeatIgnoredOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; - if (count == 3) + if (Count == 3) Assert.Ignore("Ignoring"); } } @@ -125,7 +125,7 @@ public class RepeatErrorOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; throw new Exception("Deliberate Exception"); } } @@ -135,9 +135,9 @@ public class RepeatErrorOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; - if (count == 2) + if (Count == 2) throw new Exception("Deliberate Exception"); } } @@ -147,9 +147,9 @@ public class RepeatErrorOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Repeat(3)] public void Test() { - count++; + Count++; - if (count == 3) + if (Count == 3) throw new Exception("Deliberate Exception"); } } @@ -159,7 +159,7 @@ public class RepeatedTestWithCategory : RepeatingTestsFixtureBase [Test, Repeat(3), Category("SAMPLE")] public void TestWithCategory() { - count++; + Count++; Assert.IsTrue(true); } } diff --git a/src/NUnitFramework/testdata/RepeatingTestsFixtureBase.cs b/src/NUnitFramework/testdata/RepeatingTestsFixtureBase.cs index 1458ab1524..376165b636 100644 --- a/src/NUnitFramework/testdata/RepeatingTestsFixtureBase.cs +++ b/src/NUnitFramework/testdata/RepeatingTestsFixtureBase.cs @@ -36,7 +36,6 @@ public class RepeatingTestsFixtureBase private int setupCount; private int teardownCount; private readonly List tearDownResults = new List(); - protected int count; [OneTimeSetUp] public void FixtureSetUp() @@ -84,9 +83,6 @@ public List TearDownResults { get { return tearDownResults; } } - public int Count - { - get { return count; } - } + public int Count { get; protected set; } } } diff --git a/src/NUnitFramework/testdata/RetryFixture.cs b/src/NUnitFramework/testdata/RetryFixture.cs index f662bb1267..0f34ec1bee 100644 --- a/src/NUnitFramework/testdata/RetryFixture.cs +++ b/src/NUnitFramework/testdata/RetryFixture.cs @@ -32,7 +32,7 @@ public class RetrySucceedsOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void SucceedsEveryTime() { - count++; + Count++; Assert.IsTrue(true); } } @@ -42,7 +42,7 @@ public class RetryFailsEveryTimeFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void FailsEveryTime() { - count++; + Count++; Assert.IsFalse(true); } } @@ -52,9 +52,9 @@ public class RetrySucceedsOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void SucceedsOnSecondTry() { - count++; + Count++; - if (count < 2) + if (Count < 2) Assert.IsTrue(false); } } @@ -64,9 +64,9 @@ public class RetrySucceedsOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void SucceedsOnThirdTry() { - count++; + Count++; - if (count < 3) + if (Count < 3) Assert.IsTrue(false); } } @@ -85,7 +85,7 @@ public class RetryIgnoredOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; Assert.Ignore("Ignoring"); } } @@ -95,9 +95,9 @@ public class RetryIgnoredOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; - if (count < 2) + if (Count < 2) Assert.Fail("Failed"); Assert.Ignore("Ignoring"); @@ -109,9 +109,9 @@ public class RetryIgnoredOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; - if (count < 3) + if (Count < 3) Assert.Fail("Failed"); Assert.Ignore("Ignoring"); @@ -123,7 +123,7 @@ public class RetryErrorOnFirstTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; throw new Exception("Deliberate Exception"); } } @@ -133,9 +133,9 @@ public class RetryErrorOnSecondTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; - if (count < 2) + if (Count < 2) Assert.Fail("Failed"); throw new Exception("Deliberate Exception"); @@ -147,9 +147,9 @@ public class RetryErrorOnThirdTryFixture : RepeatingTestsFixtureBase [Test, Retry(3)] public void Test() { - count++; + Count++; - if (count < 3) + if (Count < 3) Assert.Fail("Failed"); throw new Exception("Deliberate Exception"); @@ -161,7 +161,7 @@ public class RetryTestWithCategoryFixture : RepeatingTestsFixtureBase [Test, Retry(3), Category("SAMPLE")] public void TestWithCategory() { - count++; + Count++; Assert.IsTrue(true); } } @@ -172,7 +172,7 @@ public class RetryTestCaseFixture : RepeatingTestsFixtureBase [TestCase(0)] public void FailsEveryTime(int unused) { - count++; + Count++; Assert.IsTrue(false); } } @@ -210,17 +210,17 @@ public class RetryTestVerifyAttempt : RepeatingTestsFixtureBase [Test, Retry(3)] public void NeverPasses() { - count = TestContext.CurrentContext.CurrentRepeatCount; + Count = TestContext.CurrentContext.CurrentRepeatCount; Assert.Fail("forcing a failure so we retry maximum times"); } [Test, Retry(3)] public void PassesOnLastRetry() { - Assert.That(count, Is.EqualTo(TestContext.CurrentContext.CurrentRepeatCount), "expected CurrentRepeatCount to be incremented only after first attempt"); - if (count < 2) // second Repeat is 3rd Retry (i.e. end of attempts) + Assert.That(Count, Is.EqualTo(TestContext.CurrentContext.CurrentRepeatCount), "expected CurrentRepeatCount to be incremented only after first attempt"); + if (Count < 2) // second Repeat is 3rd Retry (i.e. end of attempts) { - count++; + Count++; Assert.Fail("forced failure so we will use maximum number of Retries for PassesOnLastRetry"); } } diff --git a/src/NUnitFramework/testdata/SetUpData.cs b/src/NUnitFramework/testdata/SetUpData.cs index fbbda2f7ff..976101ec5d 100644 --- a/src/NUnitFramework/testdata/SetUpData.cs +++ b/src/NUnitFramework/testdata/SetUpData.cs @@ -29,22 +29,22 @@ namespace NUnit.TestData.SetUpData [TestFixture] public class SetUpAndTearDownFixture { - public bool wasSetUpCalled; - public bool wasTearDownCalled; - public bool throwInBaseSetUp; + public bool WasSetUpCalled; + public bool WasTearDownCalled; + public bool ThrowInBaseSetUp; [SetUp] public virtual void Init() { - wasSetUpCalled = true; - if (throwInBaseSetUp) + WasSetUpCalled = true; + if (ThrowInBaseSetUp) throw (new Exception("Exception in base setup")); } [TearDown] public virtual void Destroy() { - wasTearDownCalled = true; + WasTearDownCalled = true; } [Test] @@ -55,19 +55,19 @@ public virtual void Destroy() [TestFixture] public class SetUpAndTearDownCounterFixture { - public int setUpCounter; - public int tearDownCounter; + public int SetUpCounter; + public int TearDownCounter; [SetUp] public virtual void Init() { - setUpCounter++; + SetUpCounter++; } [TearDown] public virtual void Destroy() { - tearDownCounter++; + TearDownCounter++; } [Test] @@ -90,19 +90,19 @@ public class InheritSetUpAndTearDown : SetUpAndTearDownFixture [TestFixture] public class DefineInheritSetUpAndTearDown : SetUpAndTearDownFixture { - public bool derivedSetUpCalled; - public bool derivedTearDownCalled; + public bool DerivedSetUpCalled; + public bool DerivedTearDownCalled; [SetUp] public override void Init() { - derivedSetUpCalled = true; + DerivedSetUpCalled = true; } [TearDown] public override void Destroy() { - derivedTearDownCalled = true; + DerivedTearDownCalled = true; } [Test] @@ -111,37 +111,37 @@ public override void Destroy() public class MultipleSetUpTearDownFixture { - public bool wasSetUp1Called; - public bool wasSetUp2Called; - public bool wasSetUp3Called; - public bool wasTearDown1Called; - public bool wasTearDown2Called; + public bool WasSetUp1Called; + public bool WasSetUp2Called; + public bool WasSetUp3Called; + public bool WasTearDown1Called; + public bool WasTearDown2Called; [SetUp] public virtual void Init1() { - wasSetUp1Called = true; + WasSetUp1Called = true; } [SetUp] public virtual void Init2() { - wasSetUp2Called = true; + WasSetUp2Called = true; } [SetUp] public virtual void Init3() { - wasSetUp3Called = true; + WasSetUp3Called = true; } [TearDown] public virtual void TearDown1() { - wasTearDown1Called = true; + WasTearDown1Called = true; } [TearDown] public virtual void TearDown2() { - wasTearDown2Called = true; + WasTearDown2Called = true; } [Test] @@ -151,42 +151,42 @@ public virtual void TearDown2() [TestFixture] public class DerivedClassWithSeparateSetUp : SetUpAndTearDownFixture { - public bool wasDerivedSetUpCalled; - public bool wasDerivedTearDownCalled; - public bool wasBaseSetUpCalledFirst; - public bool wasBaseTearDownCalledLast; + public bool WasDerivedSetUpCalled; + public bool WasDerivedTearDownCalled; + public bool WasBaseSetUpCalledFirst; + public bool WasBaseTearDownCalledLast; [SetUp] public void DerivedInit() { - wasDerivedSetUpCalled = true; - wasBaseSetUpCalledFirst = wasSetUpCalled; + WasDerivedSetUpCalled = true; + WasBaseSetUpCalledFirst = WasSetUpCalled; } [TearDown] public void DerivedTearDown() { - wasDerivedTearDownCalled = true; - wasBaseTearDownCalledLast = !wasTearDownCalled; + WasDerivedTearDownCalled = true; + WasBaseTearDownCalledLast = !WasTearDownCalled; } } [TestFixture] public class SetupAndTearDownExceptionFixture { - public Exception setupException; - public Exception tearDownException; + public Exception SetupException; + public Exception TearDownException; [SetUp] public void SetUp() { - if (setupException != null) throw setupException; + if (SetupException != null) throw SetupException; } [TearDown] public void TearDown() { - if (tearDownException!=null) throw tearDownException; + if (TearDownException!=null) throw TearDownException; } [Test] diff --git a/src/NUnitFramework/testdata/TestCaseSourceAttributeFixture.cs b/src/NUnitFramework/testdata/TestCaseSourceAttributeFixture.cs index 69d0c65e20..6587c47acd 100644 --- a/src/NUnitFramework/testdata/TestCaseSourceAttributeFixture.cs +++ b/src/NUnitFramework/testdata/TestCaseSourceAttributeFixture.cs @@ -49,12 +49,12 @@ public void MethodCallsIgnore(int x, int y, int z) #region Test With Ignored TestCaseData - [TestCaseSource(nameof(ignored_source))] + [TestCaseSource(nameof(IgnoredSource))] public void MethodWithIgnoredTestCases(int num) { } - private static IEnumerable ignored_source + private static IEnumerable IgnoredSource { get { @@ -69,12 +69,12 @@ private static IEnumerable ignored_source #region Test With Explicit TestCaseData - [TestCaseSource(nameof(explicit_source))] + [TestCaseSource(nameof(ExplicitSource))] public void MethodWithExplicitTestCases(int num) { } - private static IEnumerable explicit_source + private static IEnumerable ExplicitSource { get { @@ -139,7 +139,7 @@ public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam(int { } - [TestCaseSource(nameof(exception_source))] + [TestCaseSource(nameof(ExceptionSource))] public void MethodWithSourceThrowingException(string lhs, string rhs) { } @@ -154,7 +154,7 @@ public void MethodWithArrayArguments(object o) { } - static IEnumerable exception_source + static IEnumerable ExceptionSource { get { diff --git a/src/NUnitFramework/testdata/TestContextData.cs b/src/NUnitFramework/testdata/TestContextData.cs index 2e7a613a01..600b17e2f1 100644 --- a/src/NUnitFramework/testdata/TestContextData.cs +++ b/src/NUnitFramework/testdata/TestContextData.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -30,39 +30,39 @@ namespace NUnit.TestData.TestContextData [TestFixture] public class TestStateRecordingFixture { - public string stateList; + public string StateList; - public bool testFailure; - public bool testInconclusive; - public bool setUpFailure; - public bool setUpIgnore; + public bool TestFailure; + public bool TestInconclusive; + public bool SetUpFailure; + public bool SetUpIgnore; [SetUp] public void SetUp() { - stateList = TestContext.CurrentContext.Result.Outcome + "=>"; + StateList = TestContext.CurrentContext.Result.Outcome + "=>"; - if (setUpFailure) + if (SetUpFailure) Assert.Fail("Failure in SetUp"); - if (setUpIgnore) + if (SetUpIgnore) Assert.Ignore("Ignored in SetUp"); } [Test] public void TheTest() { - stateList += TestContext.CurrentContext.Result.Outcome; + StateList += TestContext.CurrentContext.Result.Outcome; - if (testFailure) + if (TestFailure) Assert.Fail("Deliberate failure"); - if (testInconclusive) + if (TestInconclusive) Assert.Inconclusive("Inconclusive test"); } [TearDown] public void TearDown() { - stateList += "=>" + TestContext.CurrentContext.Result.Outcome; + StateList += "=>" + TestContext.CurrentContext.Result.Outcome; } } diff --git a/src/NUnitFramework/testdata/TheoryFixture.cs b/src/NUnitFramework/testdata/TheoryFixture.cs index e37f29aa49..572a0a9a28 100644 --- a/src/NUnitFramework/testdata/TheoryFixture.cs +++ b/src/NUnitFramework/testdata/TheoryFixture.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -35,7 +35,7 @@ public class TheoryFixture static int i1 = 1; #pragma warning restore 414 [Datapoint] - public int i100 = 100; + public int I100 = 100; [Theory] public void TheoryWithNoArguments() @@ -105,4 +105,4 @@ public void TestWithNullableEnumAsArgument(System.AttributeTargets? targets) Assert.Pass(); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs b/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs index 4cddfae250..c7f56d47e2 100644 --- a/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2004 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -373,19 +373,19 @@ public void EqualsSameTypes() [Test] public void EnumsEqual() { - MyEnum actual = MyEnum.a; - Assert.AreEqual( MyEnum.a, actual ); + MyEnum actual = MyEnum.A; + Assert.AreEqual(MyEnum.A, actual); } [Test] public void EnumsNotEqual() { - MyEnum actual = MyEnum.a; + MyEnum actual = MyEnum.A; var expectedMessage = - " Expected: c" + Environment.NewLine + - " But was: a" + Environment.NewLine; + " Expected: " + nameof(MyEnum.C) + Environment.NewLine + + " But was: " + nameof(MyEnum.A) + Environment.NewLine; - var ex = Assert.Throws(() => Assert.AreEqual( MyEnum.c, actual )); + var ex = Assert.Throws(() => Assert.AreEqual(MyEnum.C, actual)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } @@ -445,7 +445,7 @@ public void DirectoryInfoNotEqual() private enum MyEnum { - a, b, c + A, B, C } [Test] diff --git a/src/NUnitFramework/tests/Attributes/OneTimeSetUpTearDownTests.cs b/src/NUnitFramework/tests/Attributes/OneTimeSetUpTearDownTests.cs index 18fd0a7bbd..a6053422ec 100644 --- a/src/NUnitFramework/tests/Attributes/OneTimeSetUpTearDownTests.cs +++ b/src/NUnitFramework/tests/Attributes/OneTimeSetUpTearDownTests.cs @@ -42,8 +42,8 @@ public void MakeSureSetUpAndTearDownAreCalled() SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount, "SetUp"); - Assert.AreEqual(1, fixture.tearDownCount, "TearDown"); + Assert.AreEqual(1, fixture.SetUpCount, "SetUp"); + Assert.AreEqual(1, fixture.TearDownCount, "TearDown"); } [Test] @@ -52,8 +52,8 @@ public void MakeSureSetUpAndTearDownAreCalledOnFixtureWithTestCases() var fixture = new SetUpAndTearDownFixtureWithTestCases(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount, "SetUp"); - Assert.AreEqual(1, fixture.tearDownCount, "TearDown"); + Assert.AreEqual(1, fixture.SetUpCount, "SetUp"); + Assert.AreEqual(1, fixture.TearDownCount, "TearDown"); } [Test] @@ -62,8 +62,8 @@ public void MakeSureSetUpAndTearDownAreCalledOnFixtureWithTheories() var fixture = new SetUpAndTearDownFixtureWithTheories(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount, "SetUp"); - Assert.AreEqual(1, fixture.tearDownCount, "TearDown"); + Assert.AreEqual(1, fixture.SetUpCount, "SetUp"); + Assert.AreEqual(1, fixture.TearDownCount, "TearDown"); } [Test] @@ -72,8 +72,8 @@ public void MakeSureSetUpAndTearDownAreNotCalledOnExplicitFixture() ExplicitSetUpAndTearDownFixture fixture = new ExplicitSetUpAndTearDownFixture(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(0, fixture.setUpCount, "SetUp"); - Assert.AreEqual(0, fixture.tearDownCount, "TearDown"); + Assert.AreEqual(0, fixture.SetUpCount, "SetUp"); + Assert.AreEqual(0, fixture.TearDownCount, "TearDown"); } [Test] @@ -82,31 +82,31 @@ public void CheckInheritedSetUpAndTearDownAreCalled() InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); + Assert.AreEqual(1, fixture.SetUpCount); + Assert.AreEqual(1, fixture.TearDownCount); } [Test] public static void StaticSetUpAndTearDownAreCalled() { - StaticSetUpAndTearDownFixture.setUpCount = 0; - StaticSetUpAndTearDownFixture.tearDownCount = 0; + StaticSetUpAndTearDownFixture.SetUpCount = 0; + StaticSetUpAndTearDownFixture.TearDownCount = 0; TestBuilder.RunTestFixture(typeof(StaticSetUpAndTearDownFixture)); - Assert.AreEqual(1, StaticSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, StaticSetUpAndTearDownFixture.tearDownCount); + Assert.AreEqual(1, StaticSetUpAndTearDownFixture.SetUpCount); + Assert.AreEqual(1, StaticSetUpAndTearDownFixture.TearDownCount); } [Test] public static void StaticClassSetUpAndTearDownAreCalled() { - StaticClassSetUpAndTearDownFixture.setUpCount = 0; - StaticClassSetUpAndTearDownFixture.tearDownCount = 0; + StaticClassSetUpAndTearDownFixture.SetUpCount = 0; + StaticClassSetUpAndTearDownFixture.TearDownCount = 0; TestBuilder.RunTestFixture(typeof(StaticClassSetUpAndTearDownFixture)); - Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.tearDownCount); + Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.SetUpCount); + Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.TearDownCount); } [Test] @@ -115,10 +115,10 @@ public void OverriddenSetUpAndTearDownAreNotCalled() OverrideSetUpAndTearDown fixture = new OverrideSetUpAndTearDown(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(0, fixture.setUpCount); - Assert.AreEqual(0, fixture.tearDownCount); - Assert.AreEqual(1, fixture.derivedSetUpCount); - Assert.AreEqual(1, fixture.derivedTearDownCount); + Assert.AreEqual(0, fixture.SetUpCount); + Assert.AreEqual(0, fixture.TearDownCount); + Assert.AreEqual(1, fixture.DerivedSetUpCount); + Assert.AreEqual(1, fixture.DerivedTearDownCount); } [Test] @@ -127,55 +127,55 @@ public void BaseSetUpCalledFirstAndTearDownCalledLast() DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); - Assert.AreEqual(1, fixture.derivedSetUpCount); - Assert.AreEqual(1, fixture.derivedTearDownCount); - Assert.That(fixture.baseSetUpCalledFirst, "Base SetUp called first"); - Assert.That(fixture.baseTearDownCalledLast, "Base TearDown called last"); + Assert.AreEqual(1, fixture.SetUpCount); + Assert.AreEqual(1, fixture.TearDownCount); + Assert.AreEqual(1, fixture.DerivedSetUpCount); + Assert.AreEqual(1, fixture.DerivedTearDownCount); + Assert.That(fixture.BaseSetUpCalledFirst, "Base SetUp called first"); + Assert.That(fixture.BaseTearDownCalledLast, "Base TearDown called last"); } [Test] public void FailedBaseSetUpCausesDerivedSetUpAndTeardownToBeSkipped() { DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture(); - fixture.throwInBaseSetUp = true; + fixture.ThrowInBaseSetUp = true; TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); - Assert.AreEqual(0, fixture.derivedSetUpCount); - Assert.AreEqual(0, fixture.derivedTearDownCount); + Assert.AreEqual(1, fixture.SetUpCount); + Assert.AreEqual(1, fixture.TearDownCount); + Assert.AreEqual(0, fixture.DerivedSetUpCount); + Assert.AreEqual(0, fixture.DerivedTearDownCount); } [Test] public void StaticBaseSetUpCalledFirstAndTearDownCalledLast() { - StaticSetUpAndTearDownFixture.setUpCount = 0; - StaticSetUpAndTearDownFixture.tearDownCount = 0; - DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount = 0; - DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount = 0; + StaticSetUpAndTearDownFixture.SetUpCount = 0; + StaticSetUpAndTearDownFixture.TearDownCount = 0; + DerivedStaticSetUpAndTearDownFixture.DerivedSetUpCount = 0; + DerivedStaticSetUpAndTearDownFixture.DerivedTearDownCount = 0; DerivedStaticSetUpAndTearDownFixture fixture = new DerivedStaticSetUpAndTearDownFixture(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.setUpCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.tearDownCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount); - Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount); - Assert.That(DerivedStaticSetUpAndTearDownFixture.baseSetUpCalledFirst, "Base SetUp called first"); - Assert.That(DerivedStaticSetUpAndTearDownFixture.baseTearDownCalledLast, "Base TearDown called last"); + Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.SetUpCount); + Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.TearDownCount); + Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.DerivedSetUpCount); + Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.DerivedTearDownCount); + Assert.That(DerivedStaticSetUpAndTearDownFixture.BaseSetUpCalledFirst, "Base SetUp called first"); + Assert.That(DerivedStaticSetUpAndTearDownFixture.BaseTearDownCalledLast, "Base TearDown called last"); } [Test] public void HandleErrorInFixtureSetup() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInSetUp = true; + fixture.BlowUpInSetUp = true; ITestResult result = TestBuilder.RunTestFixture(fixture); - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" ); + Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" ); + Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" ); Assert.AreEqual(ResultState.SetUpError, result.ResultState); Assert.AreEqual("System.Exception : This was thrown from fixture setup", result.Message, "TestSuite Message"); @@ -189,7 +189,7 @@ public void HandleErrorInFixtureSetup() public void RerunFixtureAfterSetUpFixed() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInSetUp = true; + fixture.BlowUpInSetUp = true; ITestResult result = TestBuilder.RunTestFixture(fixture); Assert.AreEqual(ResultState.SetUpError, result.ResultState); @@ -198,8 +198,8 @@ public void RerunFixtureAfterSetUpFixed() fixture.Reinitialize(); result = TestBuilder.RunTestFixture(fixture); - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" ); + Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" ); + Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" ); Assert.AreEqual(ResultState.Success, result.ResultState); } @@ -223,13 +223,13 @@ public void HandleIgnoreInFixtureSetup() public void HandleErrorInFixtureTearDown() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInTearDown = true; + fixture.BlowUpInTearDown = true; ITestResult result = TestBuilder.RunTestFixture(fixture); Assert.AreEqual(1, result.Children.Count()); Assert.AreEqual(ResultState.TearDownError, result.ResultState); - Assert.AreEqual(1, fixture.setUpCount, "setUpCount"); - Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount"); + Assert.AreEqual(1, fixture.SetUpCount, "setUpCount"); + Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount"); Assert.AreEqual("TearDown : System.Exception : This was thrown from fixture teardown", result.Message); Assert.That(result.StackTrace, Does.Contain("--TearDown")); @@ -239,14 +239,14 @@ public void HandleErrorInFixtureTearDown() public void HandleErrorInFixtureTearDownAfterErrorInTest() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInTest = true; - fixture.blowUpInTearDown = true; + fixture.BlowUpInTest = true; + fixture.BlowUpInTearDown = true; ITestResult result = TestBuilder.RunTestFixture(fixture); Assert.AreEqual(1, result.Children.Count()); Assert.AreEqual(ResultState.TearDownError, result.ResultState); - Assert.AreEqual(1, fixture.setUpCount, "setUpCount"); - Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount"); + Assert.AreEqual(1, fixture.SetUpCount, "setUpCount"); + Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount"); Assert.AreEqual(TestResult.CHILD_ERRORS_MESSAGE + Environment.NewLine + "TearDown : System.Exception : This was thrown from fixture teardown", result.Message); Assert.That(result.ResultState.Site, Is.EqualTo(FailureSite.TearDown)); @@ -257,14 +257,14 @@ public void HandleErrorInFixtureTearDownAfterErrorInTest() public void HandleErrorInFixtureTearDownAfterErrorInFixtureSetUp() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInSetUp = true; - fixture.blowUpInTearDown = true; + fixture.BlowUpInSetUp = true; + fixture.BlowUpInTearDown = true; ITestResult result = TestBuilder.RunTestFixture(fixture); Assert.AreEqual(1, result.Children.Count()); Assert.AreEqual(ResultState.TearDownError, result.ResultState); - Assert.AreEqual(1, fixture.setUpCount, "setUpCount"); - Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount"); + Assert.AreEqual(1, fixture.SetUpCount, "setUpCount"); + Assert.AreEqual(1, fixture.TearDownCount, "tearDownCount"); Assert.AreEqual("System.Exception : This was thrown from fixture setup" + Environment.NewLine + "TearDown : System.Exception : This was thrown from fixture teardown", result.Message); @@ -288,15 +288,15 @@ public void HandleExceptionInFixtureConstructor() public void RerunFixtureAfterTearDownFixed() { MisbehavingFixture fixture = new MisbehavingFixture(); - fixture.blowUpInTearDown = true; + fixture.BlowUpInTearDown = true; ITestResult result = TestBuilder.RunTestFixture(fixture); Assert.AreEqual(1, result.Children.Count()); fixture.Reinitialize(); result = TestBuilder.RunTestFixture(fixture); - Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" ); - Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" ); + Assert.AreEqual( 1, fixture.SetUpCount, "setUpCount" ); + Assert.AreEqual( 1, fixture.TearDownCount, "tearDownCount" ); } [Test] @@ -305,8 +305,8 @@ public void HandleSetUpAndTearDownWithTestInName() SetUpAndTearDownWithTestInName fixture = new SetUpAndTearDownWithTestInName(); TestBuilder.RunTestFixture(fixture); - Assert.AreEqual(1, fixture.setUpCount); - Assert.AreEqual(1, fixture.tearDownCount); + Assert.AreEqual(1, fixture.SetUpCount); + Assert.AreEqual(1, fixture.TearDownCount); } //[Test] @@ -319,8 +319,8 @@ public void HandleSetUpAndTearDownWithTestInName() // suite.Run(TestListener.NULL, new NameFilter(test.TestName)); - // Assert.AreEqual(1, fixture.setUpCount); - // Assert.AreEqual(1, fixture.tearDownCount); + // Assert.AreEqual(1, fixture.SetUpCount); + // Assert.AreEqual(1, fixture.TearDownCount); //} [Test] @@ -333,16 +333,16 @@ public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown() suite.Add( fixtureSuite ); TestBuilder.RunTest(fixtureSuite, fixture); - Assert.IsFalse( fixture.setupCalled, "OneTimeSetUp called running fixture"); - Assert.IsFalse( fixture.teardownCalled, "OneTimeSetUp called running fixture"); + Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running fixture"); + Assert.IsFalse( fixture.TeardownCalled, "OneTimeSetUp called running fixture"); TestBuilder.RunTest(suite, fixture); - Assert.IsFalse( fixture.setupCalled, "OneTimeSetUp called running enclosing suite"); - Assert.IsFalse( fixture.teardownCalled, "OneTimeTearDown called running enclosing suite"); + Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running enclosing suite"); + Assert.IsFalse( fixture.TeardownCalled, "OneTimeTearDown called running enclosing suite"); TestBuilder.RunTest(testMethod, fixture); - Assert.IsFalse( fixture.setupCalled, "OneTimeSetUp called running a test case"); - Assert.IsFalse( fixture.teardownCalled, "OneTimeTearDown called running a test case"); + Assert.IsFalse( fixture.SetupCalled, "OneTimeSetUp called running a test case"); + Assert.IsFalse( fixture.TeardownCalled, "OneTimeTearDown called running a test case"); } [Test] @@ -352,8 +352,8 @@ public void FixtureWithNoTestsShouldNotCallFixtureSetUpOrTearDown() TestBuilder.RunTestFixture(fixture); - Assert.That( fixture.setupCalled, Is.False, "OneTimeSetUp should not be called for a fixture with no tests" ); - Assert.That( fixture.teardownCalled, Is.False, "OneTimeTearDown should not be called for a fixture with no tests" ); + Assert.That( fixture.SetupCalled, Is.False, "OneTimeSetUp should not be called for a fixture with no tests" ); + Assert.That( fixture.TeardownCalled, Is.False, "OneTimeTearDown should not be called for a fixture with no tests" ); } [Test] @@ -361,7 +361,7 @@ public void DisposeCalledOnceWhenFixtureImplementsIDisposable() { var fixture = new DisposableFixture(); TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.disposeCalled, Is.EqualTo(1)); + Assert.That(fixture.DisposeCalled, Is.EqualTo(1)); Assert.That(fixture.Actions, Is.EqualTo(new object[] { "OneTimeSetUp", "OneTimeTearDown", "Dispose" })); } @@ -370,7 +370,7 @@ public void DisposeCalledOnceWhenFixtureImplementsIDisposableAndHasTestCases() { var fixture = new DisposableFixtureWithTestCases(); TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.disposeCalled, Is.EqualTo(1)); + Assert.That(fixture.DisposeCalled, Is.EqualTo(1)); } } diff --git a/src/NUnitFramework/tests/Attributes/TheoryTests.cs b/src/NUnitFramework/tests/Attributes/TheoryTests.cs index a0ff56f421..c06722f5df 100644 --- a/src/NUnitFramework/tests/Attributes/TheoryTests.cs +++ b/src/NUnitFramework/tests/Attributes/TheoryTests.cs @@ -170,19 +170,19 @@ public void TheoryFailsIfAllTestsAreInconclusive() public class SqrtTests { [Datapoint] - public double zero = 0; + public double Zero = 0; [Datapoint] - public double positive = 1; + public double Positive = 1; [Datapoint] - public double negative = -1; + public double Negative = -1; [Datapoint] - public double max = double.MaxValue; + public double Max = double.MaxValue; [Datapoint] - public double infinity = double.PositiveInfinity; + public double Infinity = double.PositiveInfinity; [Theory] public void SqrtTimesItselfGivesOriginal(double num) diff --git a/src/NUnitFramework/tests/Compatibility/AttributeHelperTests.cs b/src/NUnitFramework/tests/Compatibility/AttributeHelperTests.cs index cb9b931360..c342308fb1 100644 --- a/src/NUnitFramework/tests/Compatibility/AttributeHelperTests.cs +++ b/src/NUnitFramework/tests/Compatibility/AttributeHelperTests.cs @@ -97,7 +97,7 @@ public void CanGetAttributesOnFields() { var type = typeof(A); Assert.That(type, Is.Not.Null); - var field = type.GetTypeInfo().GetField("field"); + var field = type.GetTypeInfo().GetField(nameof(A.Field)); Assert.That(field, Is.Not.Null); var attr = AttributeHelper.GetCustomAttributes(field, typeof(DatapointAttribute), true); Assert.That(attr, Is.Not.Null); @@ -135,7 +135,7 @@ public int Add([Random(1)]int x, [Random(1)]int y) public int MyProperty { get; set; } [Datapoint] - public int field = 1; + public int Field = 1; } class B : A diff --git a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs index f7810ea99b..335841e953 100644 --- a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs @@ -29,9 +29,9 @@ public class AndConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new AndConstraint(new GreaterThanConstraint(40), new LessThanConstraint(50)); - expectedDescription = "greater than 40 and less than 50"; - stringRepresentation = " >"; + TheConstraint = new AndConstraint(new GreaterThanConstraint(40), new LessThanConstraint(50)); + ExpectedDescription = "greater than 40 and less than 50"; + StringRepresentation = " >"; } static object[] SuccessData = new object[] { 42 }; diff --git a/src/NUnitFramework/tests/Constraints/AnyOfConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AnyOfConstraintTests.cs index fc6559bec9..dcd50e3d3f 100644 --- a/src/NUnitFramework/tests/Constraints/AnyOfConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AnyOfConstraintTests.cs @@ -31,9 +31,9 @@ public class AnyOfConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new AnyOfConstraint(new object[] { 1, 2, 3 }); - expectedDescription = "any of < 1, 2, 3 >"; - stringRepresentation = ""; + TheConstraint = new AnyOfConstraint(new object[] { 1, 2, 3 }); + ExpectedDescription = "any of < 1, 2, 3 >"; + StringRepresentation = ""; } private static object[] SuccessData = new object[] { 1, 2, 3 }; diff --git a/src/NUnitFramework/tests/Constraints/AssignableFromConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AssignableFromConstraintTests.cs index b1535cb23c..8e8ee2f5fc 100644 --- a/src/NUnitFramework/tests/Constraints/AssignableFromConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AssignableFromConstraintTests.cs @@ -29,9 +29,9 @@ public class AssignableFromConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new AssignableFromConstraint(typeof(D1)); - expectedDescription = string.Format("assignable from <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); + TheConstraint = new AssignableFromConstraint(typeof(D1)); + ExpectedDescription = string.Format("assignable from <{0}>", typeof(D1)); + StringRepresentation = string.Format("", typeof(D1)); } static object[] SuccessData = new object[] { new D1(), new B() }; diff --git a/src/NUnitFramework/tests/Constraints/AssignableToConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AssignableToConstraintTests.cs index df5ef28363..1d42736a39 100644 --- a/src/NUnitFramework/tests/Constraints/AssignableToConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AssignableToConstraintTests.cs @@ -29,9 +29,9 @@ public class AssignableToConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new AssignableToConstraint(typeof(D1)); - expectedDescription = string.Format("assignable to <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); + TheConstraint = new AssignableToConstraint(typeof(D1)); + ExpectedDescription = string.Format("assignable to <{0}>", typeof(D1)); + StringRepresentation = string.Format("", typeof(D1)); } static object[] SuccessData = new object[] { new D1(), new D2() }; diff --git a/src/NUnitFramework/tests/Constraints/AttributeExistsConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AttributeExistsConstraintTests.cs index f04eb60891..79631504fb 100644 --- a/src/NUnitFramework/tests/Constraints/AttributeExistsConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AttributeExistsConstraintTests.cs @@ -31,9 +31,9 @@ public class AttributeExistsConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new AttributeExistsConstraint(typeof(TestFixtureAttribute)); - expectedDescription = "type with attribute "; - stringRepresentation = ""; + TheConstraint = new AttributeExistsConstraint(typeof(TestFixtureAttribute)); + ExpectedDescription = "type with attribute "; + StringRepresentation = ""; } static object[] SuccessData = new object[] { typeof(AttributeExistsConstraintTests) }; diff --git a/src/NUnitFramework/tests/Constraints/BasicConstraintTests.cs b/src/NUnitFramework/tests/Constraints/BasicConstraintTests.cs index 09253bed0a..ac545e911b 100644 --- a/src/NUnitFramework/tests/Constraints/BasicConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/BasicConstraintTests.cs @@ -34,9 +34,9 @@ public class NullConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new NullConstraint(); - expectedDescription = "null"; - stringRepresentation = ""; + TheConstraint = new NullConstraint(); + ExpectedDescription = "null"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { null }; @@ -50,9 +50,9 @@ public class TrueConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new TrueConstraint(); - expectedDescription = "True"; - stringRepresentation = ""; + TheConstraint = new TrueConstraint(); + ExpectedDescription = "True"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { true, 2+2==4 }; @@ -68,9 +68,9 @@ public class FalseConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new FalseConstraint(); - expectedDescription = "False"; - stringRepresentation = ""; + TheConstraint = new FalseConstraint(); + ExpectedDescription = "False"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { false, 2 + 2 == 5 }; @@ -88,9 +88,9 @@ public class NaNConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new NaNConstraint(); - expectedDescription = "NaN"; - stringRepresentation = ""; + TheConstraint = new NaNConstraint(); + ExpectedDescription = "NaN"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { double.NaN, float.NaN }; diff --git a/src/NUnitFramework/tests/Constraints/BinarySerializableTest.cs b/src/NUnitFramework/tests/Constraints/BinarySerializableTest.cs index fe9c46f866..4423624ab2 100644 --- a/src/NUnitFramework/tests/Constraints/BinarySerializableTest.cs +++ b/src/NUnitFramework/tests/Constraints/BinarySerializableTest.cs @@ -33,9 +33,9 @@ public class BinarySerializableTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new BinarySerializableConstraint(); - expectedDescription = "binary serializable"; - stringRepresentation = ""; + TheConstraint = new BinarySerializableConstraint(); + ExpectedDescription = "binary serializable"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 1, "a", new List(), new InternalWithSerializableAttributeClass() }; @@ -46,7 +46,7 @@ public void SetUp() public void NullArgumentThrowsException() { object o = null; - Assert.Throws(() => theConstraint.ApplyTo(o)); + Assert.Throws(() => TheConstraint.ApplyTo(o)); } } } diff --git a/src/NUnitFramework/tests/Constraints/CollectionSubsetConstraintTests.cs b/src/NUnitFramework/tests/Constraints/CollectionSubsetConstraintTests.cs index eaa9b3d1d6..c65283ba6c 100644 --- a/src/NUnitFramework/tests/Constraints/CollectionSubsetConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/CollectionSubsetConstraintTests.cs @@ -34,9 +34,9 @@ public class CollectionSubsetConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new CollectionSubsetConstraint(new int[] { 1, 2, 3, 4, 5 }); - stringRepresentation = ""; - expectedDescription = "subset of < 1, 2, 3, 4, 5 >"; + TheConstraint = new CollectionSubsetConstraint(new int[] { 1, 2, 3, 4, 5 }); + StringRepresentation = ""; + ExpectedDescription = "subset of < 1, 2, 3, 4, 5 >"; } static object[] SuccessData = new object[] { new int[] { 1, 3, 5 }, new int[] { 1, 2, 3, 4, 5 } }; diff --git a/src/NUnitFramework/tests/Constraints/CollectionSupersetConstraintTests.cs b/src/NUnitFramework/tests/Constraints/CollectionSupersetConstraintTests.cs index 8734a80367..0ebc06db40 100644 --- a/src/NUnitFramework/tests/Constraints/CollectionSupersetConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/CollectionSupersetConstraintTests.cs @@ -34,9 +34,9 @@ public class CollectionSupersetConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new CollectionSupersetConstraint(new int[] { 1, 2, 3, 4, 5 }); - stringRepresentation = ""; - expectedDescription = "superset of < 1, 2, 3, 4, 5 >"; + TheConstraint = new CollectionSupersetConstraint(new int[] { 1, 2, 3, 4, 5 }); + StringRepresentation = ""; + ExpectedDescription = "superset of < 1, 2, 3, 4, 5 >"; } static object[] SuccessData = new object[] diff --git a/src/NUnitFramework/tests/Constraints/ComparisonConstraintTestBase.cs b/src/NUnitFramework/tests/Constraints/ComparisonConstraintTestBase.cs index 4276fcf204..04b3e5c4a5 100644 --- a/src/NUnitFramework/tests/Constraints/ComparisonConstraintTestBase.cs +++ b/src/NUnitFramework/tests/Constraints/ComparisonConstraintTestBase.cs @@ -32,20 +32,20 @@ namespace NUnit.Framework.Constraints public abstract class ComparisonConstraintTestBase : ConstraintTestBase { - protected ComparisonConstraint comparisonConstraint; + protected ComparisonConstraint ComparisonConstraint; [TestCase(null)] [TestCase("xxx")] public void InvalidDataThrowsArgumentException(object data) { - Assert.Throws(() => theConstraint.ApplyTo(data)); + Assert.Throws(() => TheConstraint.ApplyTo(data)); } [Test] public void UsesProvidedIComparer() { var comparer = new ObjectComparer(); - comparisonConstraint.Using(comparer).ApplyTo(0); + ComparisonConstraint.Using(comparer).ApplyTo(0); Assert.That(comparer.WasCalled, "Comparer was not called"); } @@ -53,7 +53,7 @@ public void UsesProvidedIComparer() public void UsesProvidedGenericComparer() { var comparer = new GenericComparer(); - comparisonConstraint.Using(comparer).ApplyTo(0); + ComparisonConstraint.Using(comparer).ApplyTo(0); Assert.That(comparer.WasCalled, "Comparer was not called"); } @@ -61,7 +61,7 @@ public void UsesProvidedGenericComparer() public void UsesProvidedGenericComparison() { var comparer = new GenericComparison(); - comparisonConstraint.Using(comparer.Delegate).ApplyTo(0); + ComparisonConstraint.Using(comparer.Delegate).ApplyTo(0); Assert.That(comparer.WasCalled, "Comparer was not called"); } @@ -69,7 +69,7 @@ public void UsesProvidedGenericComparison() public void UsesProvidedLambda() { Comparison comparer = (x, y) => x.CompareTo(y); - comparisonConstraint.Using(comparer).ApplyTo(0); + ComparisonConstraint.Using(comparer).ApplyTo(0); } } @@ -112,4 +112,4 @@ public int CompareTo(ClassWithIComparableOfT other) } #endregion -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/ConstraintTestBase.cs b/src/NUnitFramework/tests/Constraints/ConstraintTestBase.cs index 0a10ad7de9..bbcddc6167 100644 --- a/src/NUnitFramework/tests/Constraints/ConstraintTestBase.cs +++ b/src/NUnitFramework/tests/Constraints/ConstraintTestBase.cs @@ -28,20 +28,20 @@ namespace NUnit.Framework.Constraints { public abstract class ConstraintTestBaseNoData { - protected Constraint theConstraint; - protected string expectedDescription = ""; - protected string stringRepresentation = ""; + protected Constraint TheConstraint; + protected string ExpectedDescription = ""; + protected string StringRepresentation = ""; [Test] public void ProvidesProperDescription() { - Assert.That(theConstraint.Description, Is.EqualTo(expectedDescription)); + Assert.That(TheConstraint.Description, Is.EqualTo(ExpectedDescription)); } [Test] public void ProvidesProperStringRepresentation() { - Assert.That(theConstraint.ToString(), Is.EqualTo(stringRepresentation)); + Assert.That(TheConstraint.ToString(), Is.EqualTo(StringRepresentation)); } } @@ -50,7 +50,7 @@ public abstract class ConstraintTestBase : ConstraintTestBaseNoData [Test, TestCaseSource("SuccessData")] public void SucceedsWithGoodValues(object value) { - var constraintResult = theConstraint.ApplyTo(value); + var constraintResult = TheConstraint.ApplyTo(value); if (!constraintResult.IsSuccess) { MessageWriter writer = new TextMessageWriter(); @@ -64,14 +64,14 @@ public void FailsWithBadValues(object badValue, string message) { string NL = Environment.NewLine; - var constraintResult = theConstraint.ApplyTo(badValue); + var constraintResult = TheConstraint.ApplyTo(badValue); Assert.IsFalse(constraintResult.IsSuccess); TextMessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo(writer); Assert.That( writer.ToString(), Is.EqualTo( - TextMessageWriter.Pfx_Expected + expectedDescription + NL + + TextMessageWriter.Pfx_Expected + ExpectedDescription + NL + TextMessageWriter.Pfx_Actual + message + NL )); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/DelayedConstraintTests.cs b/src/NUnitFramework/tests/Constraints/DelayedConstraintTests.cs index e9ecd67633..c16d854bbc 100644 --- a/src/NUnitFramework/tests/Constraints/DelayedConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/DelayedConstraintTests.cs @@ -51,9 +51,9 @@ public class DelayedConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new DelayedConstraint(new EqualConstraint(true), 500); - expectedDescription = "True after 500 milliseconds delay"; - stringRepresentation = ">"; + TheConstraint = new DelayedConstraint(new EqualConstraint(true), 500); + ExpectedDescription = "True after 500 milliseconds delay"; + StringRepresentation = ">"; boolValue = false; list = new List(); @@ -91,13 +91,13 @@ static DelayedConstraintTests() public void SucceedsWithGoodDelegates(ActualValueDelegate del) { SetValuesAfterDelay(DELAY); - Assert.That(theConstraint.ApplyTo(del).IsSuccess); + Assert.That(TheConstraint.ApplyTo(del).IsSuccess); } [Test, TestCaseSource(nameof(FailureDelegates))] public void FailsWithBadDelegates(ActualValueDelegate del) { - Assert.IsFalse(theConstraint.ApplyTo(del).IsSuccess); + Assert.IsFalse(TheConstraint.ApplyTo(del).IsSuccess); } [Test] diff --git a/src/NUnitFramework/tests/Constraints/EmptyConstraintTest.cs b/src/NUnitFramework/tests/Constraints/EmptyConstraintTest.cs index 2bd6ad6088..730eff6b04 100644 --- a/src/NUnitFramework/tests/Constraints/EmptyConstraintTest.cs +++ b/src/NUnitFramework/tests/Constraints/EmptyConstraintTest.cs @@ -35,9 +35,9 @@ public class EmptyConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new EmptyConstraint(); - expectedDescription = ""; - stringRepresentation = ""; + TheConstraint = new EmptyConstraint(); + ExpectedDescription = ""; + StringRepresentation = ""; } static object[] SuccessData = new object[] @@ -60,23 +60,23 @@ public void SetUp() [TestCase(5)] public void InvalidDataThrowsArgumentException(object data) { - Assert.Throws(() => theConstraint.ApplyTo(data)); + Assert.Throws(() => TheConstraint.ApplyTo(data)); } [Test] public void NullStringGivesFailureResult() { string actual = null; - var result = theConstraint.ApplyTo(actual); + var result = TheConstraint.ApplyTo(actual); Assert.That(result.Status, Is.EqualTo(ConstraintStatus.Failure)); } [Test] public void NullArgumentExceptionMessageContainsTypeName() { - int? testInput = null; - Assert.That(() => theConstraint.ApplyTo(testInput), - Throws.ArgumentException.With.Message.Contains("System.Int32")); + int? testInput = null; + Assert.That(() => TheConstraint.ApplyTo(testInput), + Throws.ArgumentException.With.Message.Contains("System.Int32")); } } @@ -86,9 +86,9 @@ public class EmptyStringConstraintTest : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new EmptyStringConstraint(); - expectedDescription = ""; - stringRepresentation = ""; + TheConstraint = new EmptyStringConstraint(); + ExpectedDescription = ""; + StringRepresentation = ""; } static object[] SuccessData = new object[] diff --git a/src/NUnitFramework/tests/Constraints/EndsWithConstraintTests.cs b/src/NUnitFramework/tests/Constraints/EndsWithConstraintTests.cs index 52c29a6205..2bf2382696 100644 --- a/src/NUnitFramework/tests/Constraints/EndsWithConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/EndsWithConstraintTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -32,9 +32,9 @@ public class EndsWithConstraintTests : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new EndsWithConstraint("hello"); - expectedDescription = "String ending with \"hello\""; - stringRepresentation = ""; + TheConstraint = new EndsWithConstraint("hello"); + ExpectedDescription = "String ending with \"hello\""; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "hello", "I said hello" }; @@ -53,9 +53,9 @@ public class EndsWithConstraintTestsIgnoringCase : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new EndsWithConstraint("hello").IgnoreCase; - expectedDescription = "String ending with \"hello\", ignoring case"; - stringRepresentation = ""; + TheConstraint = new EndsWithConstraint("hello").IgnoreCase; + ExpectedDescription = "String ending with \"hello\", ignoring case"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "HELLO", "I said Hello" }; diff --git a/src/NUnitFramework/tests/Constraints/EqualConstraintTests.cs b/src/NUnitFramework/tests/Constraints/EqualConstraintTests.cs index ca92ee905d..5ca801e70a 100644 --- a/src/NUnitFramework/tests/Constraints/EqualConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/EqualConstraintTests.cs @@ -36,9 +36,9 @@ public class EqualConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new EqualConstraint(4); - expectedDescription = "4"; - stringRepresentation = ""; + TheConstraint = new EqualConstraint(4); + ExpectedDescription = "4"; + StringRepresentation = ""; } static object[] SuccessData = new object[] {4, 4.0f, 4.0d, 4.0000m}; @@ -184,7 +184,7 @@ public class DateTimeOffsetShouldBeSame { [Datapoints] - public static readonly DateTimeOffset[] sameDateTimeOffsets = + public static readonly DateTimeOffset[] SameDateTimeOffsets = { new DateTimeOffset(new DateTime(2014, 1, 30, 12, 34, 56), new TimeSpan(6, 15, 0)), new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 0, 0)), @@ -664,8 +664,8 @@ private static IEnumerable DifferentTypeSameValueTestData get { var ptr = new System.IntPtr(0); - var ExampleTestA = new ExampleTest.classA(0); - var ExampleTestB = new ExampleTest.classB(0); + var ExampleTestA = new ExampleTest.ClassA(0); + var ExampleTestB = new ExampleTest.ClassB(0); var clipTestA = new ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere(); var clipTestB = new ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere(); yield return new object[] { 0, ptr }; @@ -801,13 +801,13 @@ public override string ToString() } namespace ExampleTest { - class baseTest { + class BaseTest { readonly int _value; - public baseTest() + public BaseTest() { _value = 0; } - public baseTest(int value) { + public BaseTest(int value) { _value = value; } public override bool Equals(object obj) @@ -816,7 +816,7 @@ public override bool Equals(object obj) { return false; } - return _value.Equals(((baseTest)obj)._value); + return _value.Equals(((BaseTest)obj)._value); } public override string ToString() @@ -830,14 +830,14 @@ public override int GetHashCode() } } - class classA : baseTest { - public classA(int x) : base(x) { } + class ClassA : BaseTest { + public ClassA(int x) : base(x) { } } - class classB : baseTest + class ClassB : BaseTest { - public classB(int x) : base(x) { } + public ClassB(int x) : base(x) { } } } #endregion diff --git a/src/NUnitFramework/tests/Constraints/ExactTypeConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ExactTypeConstraintTests.cs index 00ca21afe7..9262dbfd6c 100644 --- a/src/NUnitFramework/tests/Constraints/ExactTypeConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/ExactTypeConstraintTests.cs @@ -29,9 +29,9 @@ public class ExactTypeConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new ExactTypeConstraint(typeof(D1)); - expectedDescription = string.Format("<{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); + TheConstraint = new ExactTypeConstraint(typeof(D1)); + ExpectedDescription = string.Format("<{0}>", typeof(D1)); + StringRepresentation = string.Format("", typeof(D1)); } static object[] SuccessData = new object[] { new D1() }; @@ -47,4 +47,4 @@ class D1 : B { } class D2 : D1 { } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/GreaterThanConstraintTests.cs b/src/NUnitFramework/tests/Constraints/GreaterThanConstraintTests.cs index 4b165a12f2..aa90750f53 100644 --- a/src/NUnitFramework/tests/Constraints/GreaterThanConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/GreaterThanConstraintTests.cs @@ -33,9 +33,9 @@ public class GreaterThanConstraintTests : ComparisonConstraintTestBase [SetUp] public void SetUp() { - theConstraint = comparisonConstraint = new GreaterThanConstraint(5); - expectedDescription = "greater than 5"; - stringRepresentation = ""; + TheConstraint = ComparisonConstraint = new GreaterThanConstraint(5); + ExpectedDescription = "greater than 5"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 6, 5.001 }; @@ -114,4 +114,4 @@ public void PercentTolerance_Failure(object actual, object expected, object tole Assert.That(ex.Message, Contains.Substring("Expected: greater than " + MsgUtils.FormatValue(expected) + " within " + MsgUtils.FormatValue(tolerance) + " percent")); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/GreaterThanOrEqualConstraintTests.cs b/src/NUnitFramework/tests/Constraints/GreaterThanOrEqualConstraintTests.cs index da4e60ff3a..cc689bc8b1 100644 --- a/src/NUnitFramework/tests/Constraints/GreaterThanOrEqualConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/GreaterThanOrEqualConstraintTests.cs @@ -33,9 +33,9 @@ public class GreaterThanOrEqualConstraintTests : ComparisonConstraintTestBase [SetUp] public void SetUp() { - theConstraint = comparisonConstraint = new GreaterThanOrEqualConstraint(5); - expectedDescription = "greater than or equal to 5"; - stringRepresentation = ""; + TheConstraint = ComparisonConstraint = new GreaterThanOrEqualConstraint(5); + ExpectedDescription = "greater than or equal to 5"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 6, 5 }; @@ -114,4 +114,4 @@ public void PercentTolerance_Failure(object actual, object expected, object tole Assert.That(ex.Message, Contains.Substring("Expected: greater than or equal to " + MsgUtils.FormatValue(expected) + " within " + MsgUtils.FormatValue(tolerance) + " percent" )); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/InstanceOfTypeConstraintTests.cs b/src/NUnitFramework/tests/Constraints/InstanceOfTypeConstraintTests.cs index bb4d762c49..bd1a380b14 100644 --- a/src/NUnitFramework/tests/Constraints/InstanceOfTypeConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/InstanceOfTypeConstraintTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -29,9 +29,9 @@ public class InstanceOfTypeConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new InstanceOfTypeConstraint(typeof(D1)); - expectedDescription = string.Format("instance of <{0}>", typeof(D1)); - stringRepresentation = string.Format("", typeof(D1)); + TheConstraint = new InstanceOfTypeConstraint(typeof(D1)); + ExpectedDescription = string.Format("instance of <{0}>", typeof(D1)); + StringRepresentation = string.Format("", typeof(D1)); } static object[] SuccessData = new object[] { new D1(), new D2() }; @@ -46,4 +46,4 @@ class D1 : B { } class D2 : D1 { } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/LessThanConstraintTests.cs b/src/NUnitFramework/tests/Constraints/LessThanConstraintTests.cs index afd9a6478d..bbd2a73ea4 100644 --- a/src/NUnitFramework/tests/Constraints/LessThanConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/LessThanConstraintTests.cs @@ -33,9 +33,9 @@ public class LessThanConstraintTests : ComparisonConstraintTestBase [SetUp] public void SetUp() { - theConstraint = comparisonConstraint = new LessThanConstraint(5); - expectedDescription = "less than 5"; - stringRepresentation = ""; + TheConstraint = ComparisonConstraint = new LessThanConstraint(5); + ExpectedDescription = "less than 5"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 4, 4.999 }; @@ -114,4 +114,4 @@ public void PercentTolerance_Failure(object actual, object expected, object tole Assert.That(ex.Message, Contains.Substring("Expected: less than " + MsgUtils.FormatValue(expected) + " within " + MsgUtils.FormatValue(tolerance) + " percent")); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/LessThanOrEqualConstraintTests.cs b/src/NUnitFramework/tests/Constraints/LessThanOrEqualConstraintTests.cs index 84783e3857..932bd6e65c 100644 --- a/src/NUnitFramework/tests/Constraints/LessThanOrEqualConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/LessThanOrEqualConstraintTests.cs @@ -33,9 +33,9 @@ public class LessThanOrEqualConstraintTests : ComparisonConstraintTestBase [SetUp] public void SetUp() { - theConstraint = comparisonConstraint = new LessThanOrEqualConstraint(5); - expectedDescription = "less than or equal to 5"; - stringRepresentation = ""; + TheConstraint = ComparisonConstraint = new LessThanOrEqualConstraint(5); + ExpectedDescription = "less than or equal to 5"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 4, 5 }; @@ -114,4 +114,4 @@ public void PercentTolerance_Failure(object actual, object expected, object tole Assert.That(ex.Message, Contains.Substring("Expected: less than or equal to " + MsgUtils.FormatValue(expected) + " within " + MsgUtils.FormatValue(tolerance) + " percent")); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/NotConstraintTests.cs b/src/NUnitFramework/tests/Constraints/NotConstraintTests.cs index 69ef37b2ff..21685fe21b 100644 --- a/src/NUnitFramework/tests/Constraints/NotConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/NotConstraintTests.cs @@ -31,9 +31,9 @@ public class NotConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new NotConstraint( new EqualConstraint(null) ); - expectedDescription = "not equal to null"; - stringRepresentation = ">"; + TheConstraint = new NotConstraint( new EqualConstraint(null) ); + ExpectedDescription = "not equal to null"; + StringRepresentation = ">"; } static object[] SuccessData = new object[] { 42, "Hello" }; @@ -67,4 +67,4 @@ public void CanUseNotOperator() Assert.That(42, !new EqualConstraint(99)); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/OrConstraintTests.cs b/src/NUnitFramework/tests/Constraints/OrConstraintTests.cs index 06295fdd59..37f2e9754b 100644 --- a/src/NUnitFramework/tests/Constraints/OrConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/OrConstraintTests.cs @@ -29,9 +29,9 @@ public class OrConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new OrConstraint(new EqualConstraint(42), new EqualConstraint(99)); - expectedDescription = "42 or 99"; - stringRepresentation = " >"; + TheConstraint = new OrConstraint(new EqualConstraint(42), new EqualConstraint(99)); + ExpectedDescription = "42 or 99"; + StringRepresentation = " >"; } static object[] SuccessData = new object[] { 99, 42 }; @@ -44,4 +44,4 @@ public void CanCombineTestsWithOrOperator() Assert.That(99, new EqualConstraint(42) | new EqualConstraint(99) ); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/PathConstraintTests.cs b/src/NUnitFramework/tests/Constraints/PathConstraintTests.cs index 7bba1a0dd6..52826cac6a 100644 --- a/src/NUnitFramework/tests/Constraints/PathConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/PathConstraintTests.cs @@ -34,9 +34,9 @@ public class SamePathTest_Windows : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SamePathConstraint( @"C:\folder1\file.tmp" ).IgnoreCase; - expectedDescription = @"Path matching ""C:\folder1\file.tmp"""; - stringRepresentation = ""; + TheConstraint = new SamePathConstraint( @"C:\folder1\file.tmp" ).IgnoreCase; + ExpectedDescription = @"Path matching ""C:\folder1\file.tmp"""; + StringRepresentation = ""; } static object[] SuccessData = new object[] @@ -67,9 +67,9 @@ public class SamePathTest_Linux : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SamePathConstraint(@"/folder1/folder2").RespectCase; - expectedDescription = @"Path matching ""/folder1/folder2"""; - stringRepresentation = @""; + TheConstraint = new SamePathConstraint(@"/folder1/folder2").RespectCase; + ExpectedDescription = @"Path matching ""/folder1/folder2"""; + StringRepresentation = @""; } static object[] SuccessData = new object[] @@ -108,9 +108,9 @@ public class SubPathTest_Windows : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new SubPathConstraint(@"C:\folder1\folder2").IgnoreCase; - expectedDescription = @"Subpath of ""C:\folder1\folder2"""; - stringRepresentation = @""; + TheConstraint = new SubPathConstraint(@"C:\folder1\folder2").IgnoreCase; + ExpectedDescription = @"Subpath of ""C:\folder1\folder2"""; + StringRepresentation = @""; } static object[] SuccessData = new object[] @@ -146,9 +146,9 @@ public class SubPathTest_Linux : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new SubPathConstraint(@"/folder1/folder2").RespectCase; - expectedDescription = @"Subpath of ""/folder1/folder2"""; - stringRepresentation = @""; + TheConstraint = new SubPathConstraint(@"/folder1/folder2").RespectCase; + ExpectedDescription = @"Subpath of ""/folder1/folder2"""; + StringRepresentation = @""; } static object[] SuccessData = new object[] @@ -185,9 +185,9 @@ public class SamePathOrUnderTest_Windows : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SamePathOrUnderConstraint( @"C:\folder1\folder2" ).IgnoreCase; - expectedDescription = @"Path under or matching ""C:\folder1\folder2"""; - stringRepresentation = @""; + TheConstraint = new SamePathOrUnderConstraint( @"C:\folder1\folder2" ).IgnoreCase; + ExpectedDescription = @"Path under or matching ""C:\folder1\folder2"""; + StringRepresentation = @""; } static object[] SuccessData = new object[] @@ -217,9 +217,9 @@ public class SamePathOrUnderTest_Linux : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SamePathOrUnderConstraint( @"/folder1/folder2" ).RespectCase; - expectedDescription = @"Path under or matching ""/folder1/folder2"""; - stringRepresentation = @""; + TheConstraint = new SamePathOrUnderConstraint( @"/folder1/folder2" ).RespectCase; + ExpectedDescription = @"Path under or matching ""/folder1/folder2"""; + StringRepresentation = @""; } static object[] SuccessData = new object[] diff --git a/src/NUnitFramework/tests/Constraints/PredicateConstraintTests.cs b/src/NUnitFramework/tests/Constraints/PredicateConstraintTests.cs index 72db4cb5c1..de0eb707a4 100644 --- a/src/NUnitFramework/tests/Constraints/PredicateConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/PredicateConstraintTests.cs @@ -34,9 +34,9 @@ public class PredicateConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new PredicateConstraint((x) => x < 5); - expectedDescription = @"value matching lambda expression"; - stringRepresentation = ""; + TheConstraint = new PredicateConstraint((x) => x < 5); + ExpectedDescription = @"value matching lambda expression"; + StringRepresentation = ""; } static object[] SuccessData = new object[] diff --git a/src/NUnitFramework/tests/Constraints/PropertyTests.cs b/src/NUnitFramework/tests/Constraints/PropertyTests.cs index a79b7a1020..06898672c9 100644 --- a/src/NUnitFramework/tests/Constraints/PropertyTests.cs +++ b/src/NUnitFramework/tests/Constraints/PropertyTests.cs @@ -72,9 +72,9 @@ public class PropertyExistsTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new PropertyExistsConstraint("Length"); - expectedDescription = "property Length"; - stringRepresentation = ""; + TheConstraint = new PropertyExistsConstraint("Length"); + ExpectedDescription = "property Length"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { new int[0], "hello", typeof(Array) }; @@ -87,7 +87,7 @@ public void SetUp() public void NullDataThrowsArgumentNullException() { object value = null; - Assert.Throws(() => theConstraint.ApplyTo(value)); + Assert.Throws(() => TheConstraint.ApplyTo(value)); } } @@ -96,9 +96,9 @@ public class PropertyTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new PropertyConstraint("Length", new EqualConstraint(5)); - expectedDescription = "property Length equal to 5"; - stringRepresentation = ">"; + TheConstraint = new PropertyConstraint("Length", new EqualConstraint(5)); + ExpectedDescription = "property Length equal to 5"; + StringRepresentation = ">"; } static object[] SuccessData = new object[] { new int[5], "hello" }; @@ -111,19 +111,19 @@ public void SetUp() public void NullDataThrowsArgumentNullException() { object value = null; - Assert.Throws(() => theConstraint.ApplyTo(value)); + Assert.Throws(() => TheConstraint.ApplyTo(value)); } [Test] public void InvalidDataThrowsArgumentException() { - Assert.Throws(() => theConstraint.ApplyTo(42)); + Assert.Throws(() => TheConstraint.ApplyTo(42)); } [Test] public void InvalidPropertyExceptionMessageContainsTypeName() { - Assert.That(() => theConstraint.ApplyTo(42), + Assert.That(() => TheConstraint.ApplyTo(42), Throws.ArgumentException.With.Message.Contains("System.Int32")); } diff --git a/src/NUnitFramework/tests/Constraints/RangeConstraintTests.cs b/src/NUnitFramework/tests/Constraints/RangeConstraintTests.cs index d3607f23f0..bd93be83cd 100644 --- a/src/NUnitFramework/tests/Constraints/RangeConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/RangeConstraintTests.cs @@ -35,9 +35,9 @@ public class RangeConstraintTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = rangeConstraint = new RangeConstraint(5, 42); - expectedDescription = "in range (5,42)"; - stringRepresentation = ""; + TheConstraint = rangeConstraint = new RangeConstraint(5, 42); + ExpectedDescription = "in range (5,42)"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 5, 23, 42 }; @@ -48,7 +48,7 @@ public void SetUp() [TestCase("xxx")] public void InvalidDataThrowsArgumentException(object data) { - Assert.Throws(() => theConstraint.ApplyTo(data)); + Assert.Throws(() => TheConstraint.ApplyTo(data)); } [Test] diff --git a/src/NUnitFramework/tests/Constraints/SameAsTest.cs b/src/NUnitFramework/tests/Constraints/SameAsTest.cs index 51b83b1bb5..153417f78d 100644 --- a/src/NUnitFramework/tests/Constraints/SameAsTest.cs +++ b/src/NUnitFramework/tests/Constraints/SameAsTest.cs @@ -32,9 +32,9 @@ public class SameAsTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new SameAsConstraint(obj1); - expectedDescription = "same as "; - stringRepresentation = ""; + TheConstraint = new SameAsConstraint(obj1); + ExpectedDescription = "same as "; + StringRepresentation = ""; } static object[] SuccessData = new object[] { obj1 }; @@ -44,4 +44,4 @@ public void SetUp() new TestCaseData( 3, "3" ), new TestCaseData( "Hello", "\"Hello\"" ) }; } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/StartsWithConstraintTests.cs b/src/NUnitFramework/tests/Constraints/StartsWithConstraintTests.cs index 3d284d9f3b..372f22f833 100644 --- a/src/NUnitFramework/tests/Constraints/StartsWithConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/StartsWithConstraintTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -32,9 +32,9 @@ public class StartsWithConstraintTests : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new StartsWithConstraint("hello"); - expectedDescription = "String starting with \"hello\""; - stringRepresentation = ""; + TheConstraint = new StartsWithConstraint("hello"); + ExpectedDescription = "String starting with \"hello\""; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "hello", "hello there" }; @@ -54,9 +54,9 @@ public class StartsWithConstraintTestsIgnoringCase : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new StartsWithConstraint("hello").IgnoreCase; - expectedDescription = "String starting with \"hello\", ignoring case"; - stringRepresentation = ""; + TheConstraint = new StartsWithConstraint("hello").IgnoreCase; + ExpectedDescription = "String starting with \"hello\", ignoring case"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "Hello", "HELLO there" }; diff --git a/src/NUnitFramework/tests/Constraints/StringConstraintTest.cs b/src/NUnitFramework/tests/Constraints/StringConstraintTest.cs index f05f350f39..1344409a42 100644 --- a/src/NUnitFramework/tests/Constraints/StringConstraintTest.cs +++ b/src/NUnitFramework/tests/Constraints/StringConstraintTest.cs @@ -31,7 +31,7 @@ public abstract class StringConstraintTests : ConstraintTestBase [Test] public void NonStringDataThrowsArgumentException() { - Assert.Throws(() => theConstraint.ApplyTo(123)); + Assert.Throws(() => TheConstraint.ApplyTo(123)); } } } diff --git a/src/NUnitFramework/tests/Constraints/SubstringConstraintTests.cs b/src/NUnitFramework/tests/Constraints/SubstringConstraintTests.cs index 24656a5d33..5f77448a48 100644 --- a/src/NUnitFramework/tests/Constraints/SubstringConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/SubstringConstraintTests.cs @@ -32,9 +32,9 @@ public class SubstringConstraintTests : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SubstringConstraint("hello"); - expectedDescription = "String containing \"hello\""; - stringRepresentation = ""; + TheConstraint = new SubstringConstraint("hello"); + ExpectedDescription = "String containing \"hello\""; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "hello", "hello there", "I said hello", "say hello to fred" }; @@ -87,7 +87,7 @@ public void SpecifyComparisonType(string actual, string expected, StringComparis [Test] public void UseDifferentComparisonTypes_ThrowsException() { - var subStringConstraint = theConstraint as SubstringConstraint; + var subStringConstraint = TheConstraint as SubstringConstraint; // Invoke Using method before IgnoreCase Assert.That(() => subStringConstraint.Using(StringComparison.CurrentCulture).IgnoreCase, Throws.TypeOf()); @@ -120,13 +120,13 @@ public void UseDifferentComparisonTypes_ThrowsException() [Test] public void UseSameComparisonTypes_DoesNotThrowException() { - var subStringConstraint = theConstraint as SubstringConstraint; + var subStringConstraint = TheConstraint as SubstringConstraint; Assert.DoesNotThrow(() => { var newConstraint = subStringConstraint.Using(StringComparison.CurrentCultureIgnoreCase).IgnoreCase; }); - var stringConstraint = theConstraint as StringConstraint; + var stringConstraint = TheConstraint as StringConstraint; Assert.DoesNotThrow(() => { var newConstraint = stringConstraint.IgnoreCase as SubstringConstraint; @@ -141,9 +141,9 @@ public class SubstringConstraintTestsIgnoringCase : StringConstraintTests [SetUp] public void SetUp() { - theConstraint = new SubstringConstraint("hello").IgnoreCase; - expectedDescription = "String containing \"hello\", ignoring case"; - stringRepresentation = ""; + TheConstraint = new SubstringConstraint("hello").IgnoreCase; + ExpectedDescription = "String containing \"hello\", ignoring case"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { "Hello", "HellO there", "I said HELLO", "say hello to fred" }; diff --git a/src/NUnitFramework/tests/Constraints/ThrowsConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ThrowsConstraintTests.cs index 5a192343c1..18a08e9f92 100644 --- a/src/NUnitFramework/tests/Constraints/ThrowsConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/ThrowsConstraintTests.cs @@ -33,10 +33,10 @@ public class ThrowsConstraintTest_ExactType : ThrowsConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new ThrowsConstraint( + TheConstraint = new ThrowsConstraint( new ExceptionTypeConstraint(typeof(ArgumentException))); - expectedDescription = ""; - stringRepresentation = ">"; + ExpectedDescription = ""; + StringRepresentation = ">"; } static readonly object[] SuccessData = @@ -58,10 +58,10 @@ public class ThrowsConstraintTest_InstanceOfType : ThrowsConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new ThrowsConstraint( + TheConstraint = new ThrowsConstraint( new InstanceOfTypeConstraint(typeof(TestDelegates.BaseException))); - expectedDescription = "instance of "; - stringRepresentation = ">"; + ExpectedDescription = "instance of "; + StringRepresentation = ">"; } static object[] SuccessData = new object[] @@ -83,12 +83,12 @@ public class ThrowsConstraintTest_WithConstraint : ThrowsConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new ThrowsConstraint( + TheConstraint = new ThrowsConstraint( new AndConstraint( new ExceptionTypeConstraint(typeof(ArgumentException)), new PropertyConstraint("ParamName", new EqualConstraint("myParam")))); - expectedDescription = @" and property ParamName equal to ""myParam"""; - stringRepresentation = @" >>>"; + ExpectedDescription = @" and property ParamName equal to ""myParam"""; + StringRepresentation = @" >>>"; } static readonly object[] SuccessData = @@ -109,7 +109,7 @@ public abstract class ThrowsConstraintTestBase : ConstraintTestBaseNoData [Test, TestCaseSource("SuccessData")] public void SucceedsWithGoodValues(object value) { - var constraintResult = theConstraint.ApplyTo(value); + var constraintResult = TheConstraint.ApplyTo(value); if (!constraintResult.IsSuccess) { MessageWriter writer = new TextMessageWriter(); @@ -123,13 +123,13 @@ public void FailsWithBadValues(object badValue, string message) { string NL = Environment.NewLine; - var constraintResult = theConstraint.ApplyTo(badValue); + var constraintResult = TheConstraint.ApplyTo(badValue); Assert.IsFalse(constraintResult.IsSuccess); TextMessageWriter writer = new TextMessageWriter(); constraintResult.WriteMessageTo(writer); Assert.That(writer.ToString(), Does.StartWith( - TextMessageWriter.Pfx_Expected + expectedDescription + NL + + TextMessageWriter.Pfx_Expected + ExpectedDescription + NL + TextMessageWriter.Pfx_Actual + message)); } } diff --git a/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs index 9e44dfdc15..687863845e 100644 --- a/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs @@ -37,15 +37,15 @@ public class ThrowsExceptionConstraintTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new ThrowsExceptionConstraint(); - expectedDescription = "an exception to be thrown"; - stringRepresentation = ""; + TheConstraint = new ThrowsExceptionConstraint(); + ExpectedDescription = "an exception to be thrown"; + StringRepresentation = ""; } [Test] public void SucceedsWithNonVoidReturningFunction() { - var constraintResult = theConstraint.ApplyTo(TestDelegates.ThrowsInsteadOfReturns); + var constraintResult = TheConstraint.ApplyTo(TestDelegates.ThrowsInsteadOfReturns); if (!constraintResult.IsSuccess) { MessageWriter writer = new TextMessageWriter(); diff --git a/src/NUnitFramework/tests/Constraints/UniqueItemsConstraintTests.cs b/src/NUnitFramework/tests/Constraints/UniqueItemsConstraintTests.cs index 602977a0a7..82c0ef8ee9 100644 --- a/src/NUnitFramework/tests/Constraints/UniqueItemsConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/UniqueItemsConstraintTests.cs @@ -35,9 +35,9 @@ public class UniqueItemsTests : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new UniqueItemsConstraint(); - stringRepresentation = ""; - expectedDescription = "all items unique"; + TheConstraint = new UniqueItemsConstraint(); + StringRepresentation = ""; + ExpectedDescription = "all items unique"; } static object[] SuccessData = new object[] { new int[] { 1, 3, 17, -2, 34 }, new object[0] }; diff --git a/src/NUnitFramework/tests/Constraints/XmlSerializableTest.cs b/src/NUnitFramework/tests/Constraints/XmlSerializableTest.cs index e80d3b31e4..daa413600f 100644 --- a/src/NUnitFramework/tests/Constraints/XmlSerializableTest.cs +++ b/src/NUnitFramework/tests/Constraints/XmlSerializableTest.cs @@ -34,9 +34,9 @@ public class XmlSerializableTest : ConstraintTestBase [SetUp] public void SetUp() { - theConstraint = new XmlSerializableConstraint(); - expectedDescription = "XML serializable"; - stringRepresentation = ""; + TheConstraint = new XmlSerializableConstraint(); + ExpectedDescription = "XML serializable"; + StringRepresentation = ""; } static object[] SuccessData = new object[] { 1, "a", new List() }; @@ -51,7 +51,7 @@ public void SetUp() public void NullArgumentThrowsException() { object o = null; - Assert.Throws(() => theConstraint.ApplyTo(o)); + Assert.Throws(() => TheConstraint.ApplyTo(o)); } } diff --git a/src/NUnitFramework/tests/Internal/EventListenerTextWriterTests.cs b/src/NUnitFramework/tests/Internal/EventListenerTextWriterTests.cs index 920386b4e0..37b0dd6a47 100644 --- a/src/NUnitFramework/tests/Internal/EventListenerTextWriterTests.cs +++ b/src/NUnitFramework/tests/Internal/EventListenerTextWriterTests.cs @@ -35,8 +35,12 @@ public class EventListenerTextWriterTests private static readonly string STREAM_NAME = "EventListenerTextWriterTestsStream"; private static readonly string NL = Environment.NewLine; +#pragma warning disable IDE1006 // Naming Styles TestListenerIntercepter ListenerResult; +#pragma warning restore IDE1006 // Naming Styles +#pragma warning disable IDE1006 // Naming Styles TextWriter ListenerWriter; +#pragma warning restore IDE1006 // Naming Styles [SetUp] public void SetUp() diff --git a/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs b/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs index c082bf3266..1044b5087d 100644 --- a/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs +++ b/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs @@ -32,7 +32,9 @@ namespace NUnit.Framework.Internal public class NUnitTestCaseBuilderTests { #if ASYNC +#pragma warning disable IDE1006 // Naming Styles private readonly Type fixtureType = typeof(AsyncDummyFixture); +#pragma warning restore IDE1006 // Naming Styles [TestCase(nameof(AsyncDummyFixture.AsyncVoid), RunState.NotRunnable)] [TestCase(nameof(AsyncDummyFixture.AsyncTask), RunState.Runnable)] @@ -63,7 +65,9 @@ public void AsyncTestCases(string methodName, RunState expectedState) } #endif +#pragma warning disable IDE1006 // Naming Styles private readonly Type optionalTestParametersFixtureType = typeof(OptionalTestParametersFixture); +#pragma warning restore IDE1006 // Naming Styles [TestCase(nameof(OptionalTestParametersFixture.MethodWithOptionalParams0), RunState.NotRunnable)] [TestCase(nameof(OptionalTestParametersFixture.MethodWithOptionalParams1), RunState.Runnable)] diff --git a/src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs b/src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs index 238719242a..e014a4ac62 100644 --- a/src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs +++ b/src/NUnitFramework/tests/Internal/RuntimeFrameworkTests.cs @@ -109,40 +109,40 @@ public void SpecifyingNetCoreWithoutVersioningSucceeds() [TestCaseSource(nameof(frameworkData))] public void CanCreateUsingFrameworkVersion(FrameworkData data) { - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); - Assert.AreEqual(data.runtime, framework.Runtime, "#1"); - Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); - Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); + RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.FrameworkVersion); + Assert.AreEqual(data.Runtime, framework.Runtime, "#1"); + Assert.AreEqual(data.FrameworkVersion, framework.FrameworkVersion, "#2"); + Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#3"); } [TestCaseSource(nameof(frameworkData))] public void CanCreateUsingClrVersion(FrameworkData data) { - Assume.That(data.frameworkVersion.Major != 3, "#0"); + Assume.That(data.FrameworkVersion.Major != 3, "#0"); //.NET Framework 4.0+ and .NET Core 2.0+ all have the same CLR version - Assume.That(data.frameworkVersion.Major != 4 && data.frameworkVersion.Minor != 5, "#0"); - Assume.That(data.runtime != RuntimeType.NetCore, "#0"); + Assume.That(data.FrameworkVersion.Major != 4 && data.FrameworkVersion.Minor != 5, "#0"); + Assume.That(data.Runtime != RuntimeType.NetCore, "#0"); - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion); - Assert.AreEqual(data.runtime, framework.Runtime, "#1"); - Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); - Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); + RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.ClrVersion); + Assert.AreEqual(data.Runtime, framework.Runtime, "#1"); + Assert.AreEqual(data.FrameworkVersion, framework.FrameworkVersion, "#2"); + Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#3"); } [TestCaseSource(nameof(frameworkData))] public void CanParseRuntimeFramework(FrameworkData data) { - RuntimeFramework framework = RuntimeFramework.Parse(data.representation); - Assert.AreEqual(data.runtime, framework.Runtime, "#1"); - Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#2"); + RuntimeFramework framework = RuntimeFramework.Parse(data.Representation); + Assert.AreEqual(data.Runtime, framework.Runtime, "#1"); + Assert.AreEqual(data.ClrVersion, framework.ClrVersion, "#2"); } [TestCaseSource(nameof(frameworkData))] public void CanDisplayFrameworkAsString(FrameworkData data) { - RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); - Assert.AreEqual(data.representation, framework.ToString(), "#1"); - Assert.AreEqual(data.displayName, framework.DisplayName, "#2"); + RuntimeFramework framework = new RuntimeFramework(data.Runtime, data.FrameworkVersion); + Assert.AreEqual(data.Representation, framework.ToString(), "#1"); + Assert.AreEqual(data.DisplayName, framework.DisplayName, "#2"); } [TestCaseSource(nameof(matchData))] @@ -308,25 +308,25 @@ public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2) public struct FrameworkData { - public RuntimeType runtime; - public Version frameworkVersion; - public Version clrVersion; - public string representation; - public string displayName; + public RuntimeType Runtime; + public Version FrameworkVersion; + public Version ClrVersion; + public string Representation; + public string DisplayName; public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion, string representation, string displayName) { - this.runtime = runtime; - this.frameworkVersion = frameworkVersion; - this.clrVersion = clrVersion; - this.representation = representation; - this.displayName = displayName; + Runtime = runtime; + FrameworkVersion = frameworkVersion; + ClrVersion = clrVersion; + Representation = representation; + DisplayName = displayName; } public override string ToString() { - return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion); + return string.Format("<{0},{1},{2}>", this.Runtime, this.FrameworkVersion, this.ClrVersion); } } diff --git a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs index 29032bba4d..e1eccdd484 100644 --- a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs +++ b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs @@ -33,12 +33,12 @@ public void SetUp() } #endregion SetUp - private ITestResult runTests(string nameSpace) + private ITestResult RunTests(string nameSpace) { - return runTests(nameSpace, TestFilter.Empty); + return RunTests(nameSpace, TestFilter.Empty); } - private ITestResult runTests(string nameSpace, TestFilter filter) + private ITestResult RunTests(string nameSpace, TestFilter filter) { IDictionary options = new Dictionary(); if (nameSpace != null) @@ -143,7 +143,7 @@ public void InvalidAssemblySetUpFixtureIsLoadedCorrectly() [NUnit.Framework.Test] public void NamespaceSetUpFixtureWrapsExecutionOfSingleTest() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace1").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace1").ResultState.Status, Is.EqualTo(TestStatus.Passed)); TestUtilities.SimpleEventRecorder.Verify("NS1.OneTimeSetup", "NS1.Fixture.SetUp", "NS1.Test.SetUp", @@ -158,7 +158,7 @@ public void NamespaceSetUpFixtureWrapsExecutionOfSingleTest() [Test] public void NamespaceSetUpMethodsMayBeStatic() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace5").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace5").ResultState.Status, Is.EqualTo(TestStatus.Passed)); TestUtilities.SimpleEventRecorder.Verify("NS5.OneTimeSetUp", "NS5.Fixture.SetUp", "NS5.Test.SetUp", @@ -173,7 +173,7 @@ public void NamespaceSetUpMethodsMayBeStatic() [NUnit.Framework.Test] public void NamespaceSetUpFixtureWrapsExecutionOfTwoTests() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace2").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace2").ResultState.Status, Is.EqualTo(TestStatus.Passed)); // There are two fixtures but we can't be sure of the order of execution so they use the same events TestUtilities.SimpleEventRecorder.Verify("NS2.OneTimeSetUp", @@ -195,7 +195,7 @@ public void NamespaceSetUpFixtureWrapsExecutionOfTwoTests() [NUnit.Framework.Test] public void NamespaceSetUpFixtureWrapsNestedNamespaceSetUpFixture() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace3").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace3").ResultState.Status, Is.EqualTo(TestStatus.Passed)); TestUtilities.SimpleEventRecorder.Verify("NS3.OneTimeSetUp", "NS3.Fixture.SetUp", "NS3.Test.SetUp", @@ -217,7 +217,7 @@ public void NamespaceSetUpFixtureWrapsNestedNamespaceSetUpFixture() [NUnit.Framework.Test] public void WithTwoSetUpFixturesBothAreUsed() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace4").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace4").ResultState.Status, Is.EqualTo(TestStatus.Passed)); TestUtilities.SimpleEventRecorder.ExpectEvents("NS4.OneTimeSetUp1", "NS4.OneTimeSetUp2") .AndThen("NS4.Fixture.SetUp") .AndThen("NS4.Test.SetUp") @@ -234,7 +234,7 @@ public void WithTwoSetUpFixturesBothAreUsed() [Test] public void InvalidSetUpFixtureTest() { - Assert.That(runTests("NUnit.TestData.SetupFixture.Namespace6").ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(RunTests("NUnit.TestData.SetupFixture.Namespace6").ResultState.Status, Is.EqualTo(TestStatus.Failed)); TestUtilities.SimpleEventRecorder.Verify(new string[0]); } @@ -244,7 +244,7 @@ public void InvalidSetUpFixtureTest() [NUnit.Framework.Test] public void AssemblySetupFixtureWrapsExecutionOfTest() { - ITestResult result = runTests(null, new Filters.FullNameFilter("SomeFixture")); + ITestResult result = RunTests(null, new Filters.FullNameFilter("SomeFixture")); Assert.AreEqual(1, result.PassCount); Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Passed)); TestUtilities.SimpleEventRecorder.Verify("Assembly.OneTimeSetUp", diff --git a/src/NUnitFramework/tests/Internal/SetUpTearDownTests.cs b/src/NUnitFramework/tests/Internal/SetUpTearDownTests.cs index 0c935e2ad4..58773604ca 100644 --- a/src/NUnitFramework/tests/Internal/SetUpTearDownTests.cs +++ b/src/NUnitFramework/tests/Internal/SetUpTearDownTests.cs @@ -38,8 +38,8 @@ public void SetUpAndTearDownCounter() SetUpAndTearDownCounterFixture fixture = new SetUpAndTearDownCounterFixture(); TestBuilder.RunTestFixture( fixture ); - Assert.AreEqual(3, fixture.setUpCounter); - Assert.AreEqual(3, fixture.tearDownCounter); + Assert.AreEqual(3, fixture.SetUpCounter); + Assert.AreEqual(3, fixture.TearDownCounter); } @@ -49,8 +49,8 @@ public void MakeSureSetUpAndTearDownAreCalled() SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture(); TestBuilder.RunTestFixture( fixture ); - Assert.IsTrue(fixture.wasSetUpCalled); - Assert.IsTrue(fixture.wasTearDownCalled); + Assert.IsTrue(fixture.WasSetUpCalled); + Assert.IsTrue(fixture.WasTearDownCalled); } [Test] @@ -59,8 +59,8 @@ public void CheckInheritedSetUpAndTearDownAreCalled() InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown(); TestBuilder.RunTestFixture( fixture ); - Assert.IsTrue(fixture.wasSetUpCalled); - Assert.IsTrue(fixture.wasTearDownCalled); + Assert.IsTrue(fixture.WasSetUpCalled); + Assert.IsTrue(fixture.WasTearDownCalled); } [Test] @@ -69,10 +69,10 @@ public void CheckOverriddenSetUpAndTearDownAreNotCalled() DefineInheritSetUpAndTearDown fixture = new DefineInheritSetUpAndTearDown(); TestBuilder.RunTestFixture( fixture ); - Assert.IsFalse(fixture.wasSetUpCalled); - Assert.IsFalse(fixture.wasTearDownCalled); - Assert.IsTrue(fixture.derivedSetUpCalled); - Assert.IsTrue(fixture.derivedTearDownCalled); + Assert.IsFalse(fixture.WasSetUpCalled); + Assert.IsFalse(fixture.WasTearDownCalled); + Assert.IsTrue(fixture.DerivedSetUpCalled); + Assert.IsTrue(fixture.DerivedTearDownCalled); } [Test] @@ -81,11 +81,11 @@ public void MultipleSetUpAndTearDownMethodsAreCalled() MultipleSetUpTearDownFixture fixture = new MultipleSetUpTearDownFixture(); TestBuilder.RunTestFixture(fixture); - Assert.IsTrue(fixture.wasSetUp1Called, "SetUp1"); - Assert.IsTrue(fixture.wasSetUp2Called, "SetUp2"); - Assert.IsTrue(fixture.wasSetUp3Called, "SetUp3"); - Assert.IsTrue(fixture.wasTearDown1Called, "TearDown1"); - Assert.IsTrue(fixture.wasTearDown2Called, "TearDown2"); + Assert.IsTrue(fixture.WasSetUp1Called, "SetUp1"); + Assert.IsTrue(fixture.WasSetUp2Called, "SetUp2"); + Assert.IsTrue(fixture.WasSetUp3Called, "SetUp3"); + Assert.IsTrue(fixture.WasTearDown1Called, "TearDown1"); + Assert.IsTrue(fixture.WasTearDown2Called, "TearDown2"); } [Test] @@ -94,25 +94,25 @@ public void BaseSetUpIsCalledFirstTearDownLast() DerivedClassWithSeparateSetUp fixture = new DerivedClassWithSeparateSetUp(); TestBuilder.RunTestFixture(fixture); - Assert.IsTrue(fixture.wasSetUpCalled, "Base SetUp Called"); - Assert.IsTrue(fixture.wasTearDownCalled, "Base TearDown Called"); - Assert.IsTrue(fixture.wasDerivedSetUpCalled, "Derived SetUp Called"); - Assert.IsTrue(fixture.wasDerivedTearDownCalled, "Derived TearDown Called"); - Assert.IsTrue(fixture.wasBaseSetUpCalledFirst, "SetUp Order"); - Assert.IsTrue(fixture.wasBaseTearDownCalledLast, "TearDown Order"); + Assert.IsTrue(fixture.WasSetUpCalled, "Base SetUp Called"); + Assert.IsTrue(fixture.WasTearDownCalled, "Base TearDown Called"); + Assert.IsTrue(fixture.WasDerivedSetUpCalled, "Derived SetUp Called"); + Assert.IsTrue(fixture.WasDerivedTearDownCalled, "Derived TearDown Called"); + Assert.IsTrue(fixture.WasBaseSetUpCalledFirst, "SetUp Order"); + Assert.IsTrue(fixture.WasBaseTearDownCalledLast, "TearDown Order"); } [Test] public void FailureInBaseSetUpCausesDerivedSetUpAndTearDownToBeSkipped() { DerivedClassWithSeparateSetUp fixture = new DerivedClassWithSeparateSetUp(); - fixture.throwInBaseSetUp = true; + fixture.ThrowInBaseSetUp = true; TestBuilder.RunTestFixture(fixture); - Assert.IsTrue(fixture.wasSetUpCalled, "Base SetUp Called"); - Assert.IsTrue(fixture.wasTearDownCalled, "Base TearDown Called"); - Assert.IsFalse(fixture.wasDerivedSetUpCalled, "Derived SetUp Called"); - Assert.IsFalse(fixture.wasDerivedTearDownCalled, "Derived TearDown Called"); + Assert.IsTrue(fixture.WasSetUpCalled, "Base SetUp Called"); + Assert.IsTrue(fixture.WasTearDownCalled, "Base TearDown Called"); + Assert.IsFalse(fixture.WasDerivedSetUpCalled, "Derived SetUp Called"); + Assert.IsFalse(fixture.WasDerivedTearDownCalled, "Derived TearDown Called"); } [Test] @@ -120,7 +120,7 @@ public void HandleExceptionInSetUp() { Exception e = new Exception("Test message for exception thrown from setup"); SetupAndTearDownExceptionFixture fixture = new SetupAndTearDownExceptionFixture(); - fixture.setupException = e; + fixture.SetupException = e; ITestResult suiteResult = TestBuilder.RunTestFixture(fixture); Assert.IsTrue(suiteResult.HasChildren, "Fixture test should have child result."); TestResult result = (TestResult)suiteResult.Children.ToArray()[0]; @@ -135,7 +135,7 @@ public void HandleExceptionInTearDown() { Exception e = new Exception("Test message for exception thrown from tear down"); SetupAndTearDownExceptionFixture fixture = new SetupAndTearDownExceptionFixture(); - fixture.tearDownException = e; + fixture.TearDownException = e; ITestResult suiteResult = TestBuilder.RunTestFixture(fixture); Assert.That(suiteResult.HasChildren, "Fixture test should have child result."); ITestResult result = suiteResult.Children.ToArray()[0]; @@ -152,8 +152,8 @@ public void HandleExceptionInBothSetUpAndTearDown() Exception e1 = new Exception("Test message for exception thrown from setup"); Exception e2 = new Exception("Test message for exception thrown from tear down"); SetupAndTearDownExceptionFixture fixture = new SetupAndTearDownExceptionFixture(); - fixture.setupException = e1; - fixture.tearDownException = e2; + fixture.SetupException = e1; + fixture.TearDownException = e2; ITestResult suiteResult = TestBuilder.RunTestFixture(fixture); Assert.That(suiteResult.HasChildren, "Fixture test should have child result."); ITestResult result = suiteResult.Children.ToArray()[0]; @@ -167,10 +167,10 @@ public void HandleExceptionInBothSetUpAndTearDown() public class SetupCallBase { - protected int setupCount = 0; + protected int SetupCount = 0; public virtual void Init() { - setupCount++; + SetupCount++; } public virtual void AssertCount() { @@ -184,13 +184,13 @@ public class SetupCallDerived : SetupCallBase [SetUp] public override void Init() { - setupCount++; + SetupCount++; base.Init(); } [Test] public override void AssertCount() { - Assert.AreEqual(2, setupCount); + Assert.AreEqual(2, SetupCount); } } } diff --git a/src/NUnitFramework/tests/Syntax/AfterTests.cs b/src/NUnitFramework/tests/Syntax/AfterTests.cs index e5f51becce..e6d157ff66 100644 --- a/src/NUnitFramework/tests/Syntax/AfterTests.cs +++ b/src/NUnitFramework/tests/Syntax/AfterTests.cs @@ -36,9 +36,9 @@ public class AfterTest_SimpleConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.EqualTo(10).After(1000); - builderSyntax = Builder().EqualTo(10).After(1000); + ParseTree = ">"; + StaticSyntax = Is.EqualTo(10).After(1000); + BuilderSyntax = Builder().EqualTo(10).After(1000); } } @@ -47,9 +47,9 @@ public class AfterMinutesTest_SimpleConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.EqualTo(10).After(1).Minutes; - builderSyntax = Builder().EqualTo(10).After(1).Minutes; + ParseTree = ">"; + StaticSyntax = Is.EqualTo(10).After(1).Minutes; + BuilderSyntax = Builder().EqualTo(10).After(1).Minutes; } } @@ -58,9 +58,9 @@ public class AfterSecondsTest_SimpleConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.EqualTo(10).After(20).Seconds; - builderSyntax = Builder().EqualTo(10).After(20).Seconds; + ParseTree = ">"; + StaticSyntax = Is.EqualTo(10).After(20).Seconds; + BuilderSyntax = Builder().EqualTo(10).After(20).Seconds; } } @@ -69,9 +69,9 @@ public class AfterMillisecondsTest_SimpleConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.EqualTo(10).After(500).MilliSeconds; - builderSyntax = Builder().EqualTo(10).After(500).MilliSeconds; + ParseTree = ">"; + StaticSyntax = Is.EqualTo(10).After(500).MilliSeconds; + BuilderSyntax = Builder().EqualTo(10).After(500).MilliSeconds; } } @@ -81,9 +81,9 @@ public class AfterTest_PropertyTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">>"; - staticSyntax = Has.Property("X").EqualTo(10).After(1000); - builderSyntax = Builder().Property("X").EqualTo(10).After(1000); + ParseTree = ">>"; + StaticSyntax = Has.Property("X").EqualTo(10).After(1000); + BuilderSyntax = Builder().Property("X").EqualTo(10).After(1000); } } @@ -92,33 +92,33 @@ public class AfterTest_AndOperator : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >>"; - staticSyntax = Is.GreaterThan(0).And.LessThan(10).After(1000); - builderSyntax = Builder().GreaterThan(0).And.LessThan(10).After(1000); + ParseTree = " >>"; + StaticSyntax = Is.GreaterThan(0).And.LessThan(10).After(1000); + BuilderSyntax = Builder().GreaterThan(0).And.LessThan(10).After(1000); } } public abstract class AfterSyntaxTests { - protected bool flag; - protected int num; - protected object ob1, ob2, ob3; - protected List list; - protected string greeting; + protected bool Flag; + protected int Num; + protected object Ob1, Ob2, Ob3; + protected List List; + protected string Greeting; [SetUp] public void InitializeValues() { - this.flag = false; - this.num = 0; - this.ob1 = new object(); - this.ob2 = new object(); - this.ob3 = new object(); - this.list = new List(); - this.list.Add(1); - this.list.Add(2); - this.list.Add(3); - this.greeting = "hello"; + this.Flag = false; + this.Num = 0; + this.Ob1 = new object(); + this.Ob2 = new object(); + this.Ob3 = new object(); + this.List = new List(); + this.List.Add(1); + this.List.Add(2); + this.List.Add(3); + this.Greeting = "hello"; new Thread(ModifyValuesAfterDelay).Start(); } @@ -127,12 +127,12 @@ private void ModifyValuesAfterDelay() { Thread.Sleep(100); - this.flag = true; - this.num = 1; - this.ob1 = ob2; - this.ob3 = null; - this.list.Add(4); - this.greeting += "world"; + this.Flag = true; + this.Num = 1; + this.Ob1 = Ob2; + this.Ob3 = null; + this.List.Add(4); + this.Greeting += "world"; } } @@ -141,43 +141,43 @@ public class AfterSyntaxUsingAnonymousDelegates : AfterSyntaxTests [Test] public void TrueTest() { - Assert.That(delegate { return flag; }, Is.True.After(5000, 200)); + Assert.That(delegate { return Flag; }, Is.True.After(5000, 200)); } [Test] public void EqualToTest() { - Assert.That(delegate { return num; }, Is.EqualTo(1).After(5000, 200)); + Assert.That(delegate { return Num; }, Is.EqualTo(1).After(5000, 200)); } [Test] public void SameAsTest() { - Assert.That(delegate { return ob1; }, Is.SameAs(ob2).After(5000, 200)); + Assert.That(delegate { return Ob1; }, Is.SameAs(Ob2).After(5000, 200)); } [Test] public void GreaterTest() { - Assert.That(delegate { return num; }, Is.GreaterThan(0).After(5000,200)); + Assert.That(delegate { return Num; }, Is.GreaterThan(0).After(5000,200)); } [Test] public void HasMemberTest() { - Assert.That(delegate { return list; }, Has.Member(4).After(5000, 200)); + Assert.That(delegate { return List; }, Has.Member(4).After(5000, 200)); } [Test] public void NullTest() { - Assert.That(delegate { return ob3; }, Is.Null.After(5000, 200)); + Assert.That(delegate { return Ob3; }, Is.Null.After(5000, 200)); } [Test] public void TextTest() { - Assert.That(delegate { return greeting; }, Does.EndWith("world").After(5000, 200)); + Assert.That(delegate { return Greeting; }, Does.EndWith("world").After(5000, 200)); } } @@ -186,43 +186,43 @@ public class AfterSyntaxUsingLambda : AfterSyntaxTests [Test] public void TrueTest() { - Assert.That(() => flag, Is.True.After(5000, 200)); + Assert.That(() => Flag, Is.True.After(5000, 200)); } [Test] public void EqualToTest() { - Assert.That(() => num, Is.EqualTo(1).After(5000, 200)); + Assert.That(() => Num, Is.EqualTo(1).After(5000, 200)); } [Test] public void SameAsTest() { - Assert.That(() => ob1, Is.SameAs(ob2).After(5000, 200)); + Assert.That(() => Ob1, Is.SameAs(Ob2).After(5000, 200)); } [Test] public void GreaterTest() { - Assert.That(() => num, Is.GreaterThan(0).After(5000, 200)); + Assert.That(() => Num, Is.GreaterThan(0).After(5000, 200)); } [Test] public void HasMemberTest() { - Assert.That(() => list, Has.Member(4).After(5000, 200)); + Assert.That(() => List, Has.Member(4).After(5000, 200)); } [Test] public void NullTest() { - Assert.That(() => ob3, Is.Null.After(5000, 200)); + Assert.That(() => Ob3, Is.Null.After(5000, 200)); } [Test] public void TextTest() { - Assert.That(() => greeting, Does.EndWith("world").After(5000, 200)); + Assert.That(() => Greeting, Does.EndWith("world").After(5000, 200)); } } } diff --git a/src/NUnitFramework/tests/Syntax/AnyOfTests.cs b/src/NUnitFramework/tests/Syntax/AnyOfTests.cs index b8126ac036..4ef055b29e 100644 --- a/src/NUnitFramework/tests/Syntax/AnyOfTests.cs +++ b/src/NUnitFramework/tests/Syntax/AnyOfTests.cs @@ -28,9 +28,9 @@ public class AnyOfTests : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AnyOf(1, 2, 3); - builderSyntax = Builder().AnyOf(1, 2, 3); + ParseTree = ""; + StaticSyntax = Is.AnyOf(1, 2, 3); + BuilderSyntax = Builder().AnyOf(1, 2, 3); } [Test] @@ -51,9 +51,9 @@ public class AnyOf_NullValue_Tests : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AnyOf(null); - builderSyntax = Builder().AnyOf(null); + ParseTree = ""; + StaticSyntax = Is.AnyOf(null); + BuilderSyntax = Builder().AnyOf(null); } } } diff --git a/src/NUnitFramework/tests/Syntax/CollectionTests.cs b/src/NUnitFramework/tests/Syntax/CollectionTests.cs index ae77bb7ac9..0ee35f8c29 100644 --- a/src/NUnitFramework/tests/Syntax/CollectionTests.cs +++ b/src/NUnitFramework/tests/Syntax/CollectionTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -32,9 +32,9 @@ public class UniqueTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Unique; - builderSyntax = Builder().Unique; + ParseTree = ""; + StaticSyntax = Is.Unique; + BuilderSyntax = Builder().Unique; } } @@ -43,9 +43,9 @@ public class CollectionOrderedTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered; - builderSyntax = Builder().Ordered; + ParseTree = ""; + StaticSyntax = Is.Ordered; + BuilderSyntax = Builder().Ordered; } } @@ -54,9 +54,9 @@ public class CollectionOrderedTest_Descending : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered.Descending; - builderSyntax = Builder().Ordered.Descending; + ParseTree = ""; + StaticSyntax = Is.Ordered.Descending; + BuilderSyntax = Builder().Ordered.Descending; } } @@ -66,9 +66,9 @@ public class CollectionOrderedTest_Comparer : SyntaxTest public void SetUp() { IComparer comparer = ObjectComparer.Default; - parseTree = ""; - staticSyntax = Is.Ordered.Using(comparer); - builderSyntax = Builder().Ordered.Using(comparer); + ParseTree = ""; + StaticSyntax = Is.Ordered.Using(comparer); + BuilderSyntax = Builder().Ordered.Using(comparer); } } @@ -78,9 +78,9 @@ public class CollectionOrderedTest_Comparer_Descending : SyntaxTest public void SetUp() { IComparer comparer = ObjectComparer.Default; - parseTree = ""; - staticSyntax = Is.Ordered.Using(comparer).Descending; - builderSyntax = Builder().Ordered.Using(comparer).Descending; + ParseTree = ""; + StaticSyntax = Is.Ordered.Using(comparer).Descending; + BuilderSyntax = Builder().Ordered.Using(comparer).Descending; } } @@ -89,9 +89,9 @@ public class CollectionOrderedByTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName"); - builderSyntax = Builder().Ordered.By("SomePropertyName"); + ParseTree = ""; + StaticSyntax = Is.Ordered.By("SomePropertyName"); + BuilderSyntax = Builder().Ordered.By("SomePropertyName"); } } @@ -100,9 +100,9 @@ public class CollectionOrderedByTest_Descending : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Descending; - builderSyntax = Builder().Ordered.By("SomePropertyName").Descending; + ParseTree = ""; + StaticSyntax = Is.Ordered.By("SomePropertyName").Descending; + BuilderSyntax = Builder().Ordered.By("SomePropertyName").Descending; } } @@ -111,9 +111,9 @@ public class CollectionOrderedByTest_Comparer : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Using(ObjectComparer.Default); - builderSyntax = Builder().Ordered.By("SomePropertyName").Using(ObjectComparer.Default); + ParseTree = ""; + StaticSyntax = Is.Ordered.By("SomePropertyName").Using(ObjectComparer.Default); + BuilderSyntax = Builder().Ordered.By("SomePropertyName").Using(ObjectComparer.Default); } } @@ -122,9 +122,9 @@ public class CollectionOrderedByTest_Comparer_Descending : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Ordered.By("SomePropertyName").Using(ObjectComparer.Default).Descending; - builderSyntax = Builder().Ordered.By("SomePropertyName").Using(ObjectComparer.Default).Descending; + ParseTree = ""; + StaticSyntax = Is.Ordered.By("SomePropertyName").Using(ObjectComparer.Default).Descending; + BuilderSyntax = Builder().Ordered.By("SomePropertyName").Using(ObjectComparer.Default).Descending; } } @@ -133,9 +133,9 @@ public class CollectionContainsTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Member(42); - builderSyntax = Builder().Contains(42); + ParseTree = ">"; + StaticSyntax = Has.Member(42); + BuilderSyntax = Builder().Contains(42); } } @@ -145,9 +145,9 @@ public class CollectionSubsetTest : SyntaxTest public void SetUp() { int[] ints = new int[] { 1, 2, 3 }; - parseTree = ""; - staticSyntax = Is.SubsetOf(ints); - builderSyntax = Builder().SubsetOf(ints); + ParseTree = ""; + StaticSyntax = Is.SubsetOf(ints); + BuilderSyntax = Builder().SubsetOf(ints); } } @@ -157,9 +157,9 @@ public class CollectionEquivalentTest : SyntaxTest public void SetUp() { int[] ints = new int[] { 1, 2, 3 }; - parseTree = ""; - staticSyntax = Is.EquivalentTo(ints); - builderSyntax = Builder().EquivalentTo(ints); + ParseTree = ""; + StaticSyntax = Is.EquivalentTo(ints); + BuilderSyntax = Builder().EquivalentTo(ints); } } } diff --git a/src/NUnitFramework/tests/Syntax/ComparisonTests.cs b/src/NUnitFramework/tests/Syntax/ComparisonTests.cs index 3e7052b1b6..cf61e7cc21 100644 --- a/src/NUnitFramework/tests/Syntax/ComparisonTests.cs +++ b/src/NUnitFramework/tests/Syntax/ComparisonTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -30,9 +30,9 @@ public class GreaterThanTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.GreaterThan(7); - builderSyntax = Builder().GreaterThan(7); + ParseTree = ""; + StaticSyntax = Is.GreaterThan(7); + BuilderSyntax = Builder().GreaterThan(7); } } @@ -41,9 +41,9 @@ public class GreaterThanOrEqualTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.GreaterThanOrEqualTo(7); - builderSyntax = Builder().GreaterThanOrEqualTo(7); + ParseTree = ""; + StaticSyntax = Is.GreaterThanOrEqualTo(7); + BuilderSyntax = Builder().GreaterThanOrEqualTo(7); } } @@ -52,9 +52,9 @@ public class AtLeastTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AtLeast(7); - builderSyntax = Builder().AtLeast(7); + ParseTree = ""; + StaticSyntax = Is.AtLeast(7); + BuilderSyntax = Builder().AtLeast(7); } } @@ -63,9 +63,9 @@ public class LessThanTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.LessThan(7); - builderSyntax = Builder().LessThan(7); + ParseTree = ""; + StaticSyntax = Is.LessThan(7); + BuilderSyntax = Builder().LessThan(7); } } @@ -74,9 +74,9 @@ public class LessThanOrEqualTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.LessThanOrEqualTo(7); - builderSyntax = Builder().LessThanOrEqualTo(7); + ParseTree = ""; + StaticSyntax = Is.LessThanOrEqualTo(7); + BuilderSyntax = Builder().LessThanOrEqualTo(7); } } @@ -85,9 +85,9 @@ public class AtMostTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AtMost(7); - builderSyntax = Builder().AtMost(7); + ParseTree = ""; + StaticSyntax = Is.AtMost(7); + BuilderSyntax = Builder().AtMost(7); } } } diff --git a/src/NUnitFramework/tests/Syntax/EqualityTests.cs b/src/NUnitFramework/tests/Syntax/EqualityTests.cs index 9eff2ba0ec..87eef2a79e 100644 --- a/src/NUnitFramework/tests/Syntax/EqualityTests.cs +++ b/src/NUnitFramework/tests/Syntax/EqualityTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,9 +31,9 @@ public class EqualToTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.EqualTo(999); - builderSyntax = Builder().EqualTo(999); + ParseTree = ""; + StaticSyntax = Is.EqualTo(999); + BuilderSyntax = Builder().EqualTo(999); } } @@ -42,9 +42,9 @@ public class EqualToTest_IgnoreCase : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Is.EqualTo("X").IgnoreCase; - builderSyntax = Builder().EqualTo("X").IgnoreCase; + ParseTree = @""; + StaticSyntax = Is.EqualTo("X").IgnoreCase; + BuilderSyntax = Builder().EqualTo("X").IgnoreCase; } } @@ -53,9 +53,9 @@ public class EqualToTest_WithinTolerance : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.EqualTo(0.7).Within(.005); - builderSyntax = Builder().EqualTo(0.7).Within(.005); + ParseTree = ""; + StaticSyntax = Is.EqualTo(0.7).Within(.005); + BuilderSyntax = Builder().EqualTo(0.7).Within(.005); } } diff --git a/src/NUnitFramework/tests/Syntax/OperatorOverrides.cs b/src/NUnitFramework/tests/Syntax/OperatorOverrides.cs index 3f06b6e05b..40199169b9 100644 --- a/src/NUnitFramework/tests/Syntax/OperatorOverrides.cs +++ b/src/NUnitFramework/tests/Syntax/OperatorOverrides.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,9 +31,9 @@ public class NotOperatorOverride : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = !Is.Null; - builderSyntax = !Builder().Null; + ParseTree = ">"; + StaticSyntax = !Is.Null; + BuilderSyntax = !Builder().Null; } } @@ -42,9 +42,9 @@ public class AndOperatorOverride : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >"; - staticSyntax = Is.GreaterThan(5) & Is.LessThan(10); - builderSyntax = Builder().GreaterThan(5) & Builder().LessThan(10); + ParseTree = " >"; + StaticSyntax = Is.GreaterThan(5) & Is.LessThan(10); + BuilderSyntax = Builder().GreaterThan(5) & Builder().LessThan(10); } } @@ -53,9 +53,9 @@ public class OrOperatorOverride : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >"; - staticSyntax = Is.LessThan(5) | Is.GreaterThan(10); - builderSyntax = Builder().LessThan(5) | Is.GreaterThan(10); + ParseTree = " >"; + StaticSyntax = Is.LessThan(5) | Is.GreaterThan(10); + BuilderSyntax = Builder().LessThan(5) | Is.GreaterThan(10); } } diff --git a/src/NUnitFramework/tests/Syntax/OperatorTests.cs b/src/NUnitFramework/tests/Syntax/OperatorTests.cs index d30f858395..581b3c1e04 100644 --- a/src/NUnitFramework/tests/Syntax/OperatorTests.cs +++ b/src/NUnitFramework/tests/Syntax/OperatorTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,9 +31,9 @@ public class NotTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.Not.Null; - builderSyntax = Builder().Not.Null; + ParseTree = ">"; + StaticSyntax = Is.Not.Null; + BuilderSyntax = Builder().Not.Null; } } @@ -42,9 +42,9 @@ public class NotTest_Cascaded : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">>>"; - staticSyntax = Is.Not.Not.Not.Null; - builderSyntax = Builder().Not.Not.Not.Null; + ParseTree = ">>>"; + StaticSyntax = Is.Not.Not.Not.Null; + BuilderSyntax = Builder().Not.Not.Not.Null; } } #endregion @@ -55,9 +55,9 @@ public class AllTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Is.All.GreaterThan(0); - builderSyntax = Builder().All.GreaterThan(0); + ParseTree = ">"; + StaticSyntax = Is.All.GreaterThan(0); + BuilderSyntax = Builder().All.GreaterThan(0); } } #endregion @@ -68,9 +68,9 @@ public class SomeTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Some.EqualTo(3); - builderSyntax = Builder().Some.EqualTo(3); + ParseTree = ">"; + StaticSyntax = Has.Some.EqualTo(3); + BuilderSyntax = Builder().Some.EqualTo(3); } } @@ -79,9 +79,9 @@ public class SomeTest_BeforeBinaryOperators : SyntaxTest [SetUp] public void SetUp() { - parseTree = " > >>"; - staticSyntax = Has.Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); - builderSyntax = Builder().Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); + ParseTree = " > >>"; + StaticSyntax = Has.Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); + BuilderSyntax = Builder().Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999); } } @@ -90,9 +90,9 @@ public class SomeTest_NestedSome : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">>"; - staticSyntax = Has.Some.With.Some.LessThan(100); - builderSyntax = Builder().Some.With.Some.LessThan(100); + ParseTree = ">>"; + StaticSyntax = Has.Some.With.Some.LessThan(100); + BuilderSyntax = Builder().Some.With.Some.LessThan(100); } } @@ -102,9 +102,9 @@ public class SomeTest_UseOfAndSome : SyntaxTest [SetUp] public void SetUp() { - parseTree = "> >>"; - staticSyntax = Has.Some.GreaterThan(0).And.Some.LessThan(100); - builderSyntax = Builder().Some.GreaterThan(0).And.Some.LessThan(100); + ParseTree = "> >>"; + StaticSyntax = Has.Some.GreaterThan(0).And.Some.LessThan(100); + BuilderSyntax = Builder().Some.GreaterThan(0).And.Some.LessThan(100); } } #endregion @@ -115,9 +115,9 @@ public class NoneTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.None.LessThan(0); - builderSyntax = Builder().None.LessThan(0); + ParseTree = ">"; + StaticSyntax = Has.None.LessThan(0); + BuilderSyntax = Builder().None.LessThan(0); } } #endregion @@ -128,9 +128,9 @@ public class Exactly_WithoutConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Has.Exactly(3).Items; - builderSyntax = Builder().Exactly(3).Items; + ParseTree = ""; + StaticSyntax = Has.Exactly(3).Items; + BuilderSyntax = Builder().Exactly(3).Items; } } @@ -139,9 +139,9 @@ public class Exactly_WithConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Exactly(3).Items.LessThan(0); - builderSyntax = Builder().Exactly(3).Items.LessThan(0); + ParseTree = ">"; + StaticSyntax = Has.Exactly(3).Items.LessThan(0); + BuilderSyntax = Builder().Exactly(3).Items.LessThan(0); } } @@ -150,9 +150,9 @@ public class Exactly_WithConstraint_BeforeBinaryOperators : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >>>"; - staticSyntax = Has.Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); - builderSyntax = Builder().Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); + ParseTree = " >>>"; + StaticSyntax = Has.Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); + BuilderSyntax = Builder().Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); } } @@ -161,9 +161,9 @@ public class Exactly_WithConstraint_BeforeAndAfterBinaryOperators : SyntaxTest [SetUp] public void SetUp() { - parseTree = "> >>"; - staticSyntax = Has.Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10); - builderSyntax = Builder().Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10); + ParseTree = "> >>"; + StaticSyntax = Has.Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10); + BuilderSyntax = Builder().Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10); } } #endregion @@ -175,9 +175,9 @@ public class One_WithoutConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Has.One.Items; - builderSyntax = Builder().One.Items; + ParseTree = ""; + StaticSyntax = Has.One.Items; + BuilderSyntax = Builder().One.Items; } } @@ -186,9 +186,9 @@ public class One_WithConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.One.Items.LessThan(0); - builderSyntax = Builder().One.Items.LessThan(0); + ParseTree = ">"; + StaticSyntax = Has.One.Items.LessThan(0); + BuilderSyntax = Builder().One.Items.LessThan(0); } } @@ -197,9 +197,9 @@ public class One_WithConstraint_BeforeBinaryOperators : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >>>"; - staticSyntax = Has.One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); - builderSyntax = Builder().One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); + ParseTree = " >>>"; + StaticSyntax = Has.One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); + BuilderSyntax = Builder().One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20); } } @@ -208,9 +208,9 @@ public class One_WithConstraint_BeforeAndAfterBinaryOperators : SyntaxTest [SetUp] public void SetUp() { - parseTree = "> >>"; - staticSyntax = Has.One.Items.LessThan(0).And.One.Items.GreaterThan(10); - builderSyntax = Builder().One.Items.LessThan(0).And.One.Items.GreaterThan(10); + ParseTree = "> >>"; + StaticSyntax = Has.One.Items.LessThan(0).And.One.Items.GreaterThan(10); + BuilderSyntax = Builder().One.Items.LessThan(0).And.One.Items.GreaterThan(10); } } @@ -222,9 +222,9 @@ public class AndTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >"; - staticSyntax = Is.GreaterThan(5).And.LessThan(10); - builderSyntax = Builder().GreaterThan(5).And.LessThan(10); + ParseTree = " >"; + StaticSyntax = Is.GreaterThan(5).And.LessThan(10); + BuilderSyntax = Builder().GreaterThan(5).And.LessThan(10); } } @@ -233,9 +233,9 @@ public class AndTest_ThreeAndsWithNot : SyntaxTest [SetUp] public void SetUp() { - parseTree = "> > >>>"; - staticSyntax = Is.Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); - builderSyntax = Builder().Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); + ParseTree = "> > >>>"; + StaticSyntax = Is.Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); + BuilderSyntax = Builder().Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10); } } #endregion @@ -246,9 +246,9 @@ public class OrTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >"; - staticSyntax = Is.LessThan(5).Or.GreaterThan(10); - builderSyntax = Builder().LessThan(5).Or.GreaterThan(10); + ParseTree = " >"; + StaticSyntax = Is.LessThan(5).Or.GreaterThan(10); + BuilderSyntax = Builder().LessThan(5).Or.GreaterThan(10); } } @@ -257,9 +257,9 @@ public class OrTest_ThreeOrs : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >>"; - staticSyntax = Is.LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); - builderSyntax = Builder().LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); + ParseTree = " >>"; + StaticSyntax = Is.LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); + BuilderSyntax = Builder().LessThan(5).Or.GreaterThan(10).Or.EqualTo(7); } } #endregion @@ -270,9 +270,9 @@ public class AndIsEvaluatedBeforeFollowingOr : SyntaxTest [SetUp] public void SetUp() { - parseTree = " > >"; - staticSyntax = Is.LessThan(100).And.GreaterThan(0).Or.EqualTo(999); - builderSyntax = Builder().LessThan(100).And.GreaterThan(0).Or.EqualTo(999); + ParseTree = " > >"; + StaticSyntax = Is.LessThan(100).And.GreaterThan(0).Or.EqualTo(999); + BuilderSyntax = Builder().LessThan(100).And.GreaterThan(0).Or.EqualTo(999); } } @@ -281,9 +281,9 @@ public class AndIsEvaluatedBeforePrecedingOr : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >>"; - staticSyntax = Is.EqualTo(999).Or.GreaterThan(0).And.LessThan(100); - builderSyntax = Builder().EqualTo(999).Or.GreaterThan(0).And.LessThan(100); + ParseTree = " >>"; + StaticSyntax = Is.EqualTo(999).Or.GreaterThan(0).And.LessThan(100); + BuilderSyntax = Builder().EqualTo(999).Or.GreaterThan(0).And.LessThan(100); } } #endregion diff --git a/src/NUnitFramework/tests/Syntax/PathConstraintTests.cs b/src/NUnitFramework/tests/Syntax/PathConstraintTests.cs index 6fe1ec4f48..44287d177b 100644 --- a/src/NUnitFramework/tests/Syntax/PathConstraintTests.cs +++ b/src/NUnitFramework/tests/Syntax/PathConstraintTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -35,9 +35,9 @@ public void SetUp() string defaultCaseSensitivity = Path.DirectorySeparatorChar == '\\' ? "ignorecase" : "respectcase"; - parseTree = string.Format(@"", path, defaultCaseSensitivity); - staticSyntax = Is.SamePath(path); - builderSyntax = Builder().SamePath(path); + ParseTree = string.Format(@"", path, defaultCaseSensitivity); + StaticSyntax = Is.SamePath(path); + BuilderSyntax = Builder().SamePath(path); } } @@ -48,9 +48,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePath(path).IgnoreCase; - builderSyntax = Builder().SamePath(path).IgnoreCase; + ParseTree = string.Format(@"", path); + StaticSyntax = Is.SamePath(path).IgnoreCase; + BuilderSyntax = Builder().SamePath(path).IgnoreCase; } } @@ -61,9 +61,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePath(path).IgnoreCase; - builderSyntax = Builder().Not.SamePath(path).IgnoreCase; + ParseTree = string.Format(@">", path); + StaticSyntax = Is.Not.SamePath(path).IgnoreCase; + BuilderSyntax = Builder().Not.SamePath(path).IgnoreCase; } } @@ -74,9 +74,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePath(path).RespectCase; - builderSyntax = Builder().SamePath(path).RespectCase; + ParseTree = string.Format(@"", path); + StaticSyntax = Is.SamePath(path).RespectCase; + BuilderSyntax = Builder().SamePath(path).RespectCase; } } @@ -87,9 +87,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePath(path).RespectCase; - builderSyntax = Builder().Not.SamePath(path).RespectCase; + ParseTree = string.Format(@">", path); + StaticSyntax = Is.Not.SamePath(path).RespectCase; + BuilderSyntax = Builder().Not.SamePath(path).RespectCase; } } @@ -102,9 +102,9 @@ public void SetUp() string defaultCaseSensitivity = Path.DirectorySeparatorChar == '\\' ? "ignorecase" : "respectcase"; - parseTree = string.Format(@"", path, defaultCaseSensitivity); - staticSyntax = Is.SamePathOrUnder(path); - builderSyntax = Builder().SamePathOrUnder(path); + ParseTree = string.Format(@"", path, defaultCaseSensitivity); + StaticSyntax = Is.SamePathOrUnder(path); + BuilderSyntax = Builder().SamePathOrUnder(path); } } @@ -115,9 +115,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePathOrUnder(path).IgnoreCase; - builderSyntax = Builder().SamePathOrUnder(path).IgnoreCase; + ParseTree = string.Format(@"", path); + StaticSyntax = Is.SamePathOrUnder(path).IgnoreCase; + BuilderSyntax = Builder().SamePathOrUnder(path).IgnoreCase; } } @@ -128,9 +128,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePathOrUnder(path).IgnoreCase; - builderSyntax = Builder().Not.SamePathOrUnder(path).IgnoreCase; + ParseTree = string.Format(@">", path); + StaticSyntax = Is.Not.SamePathOrUnder(path).IgnoreCase; + BuilderSyntax = Builder().Not.SamePathOrUnder(path).IgnoreCase; } } @@ -141,9 +141,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@"", path); - staticSyntax = Is.SamePathOrUnder(path).RespectCase; - builderSyntax = Builder().SamePathOrUnder(path).RespectCase; + ParseTree = string.Format(@"", path); + StaticSyntax = Is.SamePathOrUnder(path).RespectCase; + BuilderSyntax = Builder().SamePathOrUnder(path).RespectCase; } } @@ -154,9 +154,9 @@ public void SetUp() { string path = "/path/to/match"; - parseTree = string.Format(@">", path); - staticSyntax = Is.Not.SamePathOrUnder(path).RespectCase; - builderSyntax = Builder().Not.SamePathOrUnder(path).RespectCase; + ParseTree = string.Format(@">", path); + StaticSyntax = Is.Not.SamePathOrUnder(path).RespectCase; + BuilderSyntax = Builder().Not.SamePathOrUnder(path).RespectCase; } } } diff --git a/src/NUnitFramework/tests/Syntax/PropertyTests.cs b/src/NUnitFramework/tests/Syntax/PropertyTests.cs index e51d571807..f211940274 100644 --- a/src/NUnitFramework/tests/Syntax/PropertyTests.cs +++ b/src/NUnitFramework/tests/Syntax/PropertyTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,9 +31,9 @@ public class PropertyExistsTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Has.Property("X"); - builderSyntax = Builder().Property("X"); + ParseTree = ""; + StaticSyntax = Has.Property("X"); + BuilderSyntax = Builder().Property("X"); } } @@ -42,9 +42,9 @@ public class PropertyExistsTest_AndFollows : SyntaxTest [SetUp] public void SetUp() { - parseTree = " >"; - staticSyntax = Has.Property("X").And.EqualTo(7); - builderSyntax = Builder().Property("X").And.EqualTo(7); + ParseTree = " >"; + StaticSyntax = Has.Property("X").And.EqualTo(7); + BuilderSyntax = Builder().Property("X").And.EqualTo(7); } } @@ -53,9 +53,9 @@ public class PropertyTest_ConstraintFollows : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Property("X").GreaterThan(5); - builderSyntax = Builder().Property("X").GreaterThan(5); + ParseTree = ">"; + StaticSyntax = Has.Property("X").GreaterThan(5); + BuilderSyntax = Builder().Property("X").GreaterThan(5); } } @@ -64,9 +64,9 @@ public class PropertyTest_NotFollows : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">>"; - staticSyntax = Has.Property("X").Not.GreaterThan(5); - builderSyntax = Builder().Property("X").Not.GreaterThan(5); + ParseTree = ">>"; + StaticSyntax = Has.Property("X").Not.GreaterThan(5); + BuilderSyntax = Builder().Property("X").Not.GreaterThan(5); } } @@ -75,9 +75,9 @@ public class LengthTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Length.GreaterThan(5); - builderSyntax = Builder().Length.GreaterThan(5); + ParseTree = ">"; + StaticSyntax = Has.Length.GreaterThan(5); + BuilderSyntax = Builder().Length.GreaterThan(5); } } @@ -86,9 +86,9 @@ public class CountTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ">"; - staticSyntax = Has.Count.EqualTo(5); - builderSyntax = Builder().Count.EqualTo(5); + ParseTree = ">"; + StaticSyntax = Has.Count.EqualTo(5); + BuilderSyntax = Builder().Count.EqualTo(5); } } @@ -97,9 +97,9 @@ public class MessageTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @">"; - staticSyntax = Has.Message.StartsWith("Expected"); - builderSyntax = Builder().Message.StartsWith("Expected"); + ParseTree = @">"; + StaticSyntax = Has.Message.StartsWith("Expected"); + BuilderSyntax = Builder().Message.StartsWith("Expected"); } } @@ -121,4 +121,4 @@ public void SeparateConstraintTest() Assert.That(ints, Has.Length.EqualTo(3)); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Syntax/SerializableConstraints.cs b/src/NUnitFramework/tests/Syntax/SerializableConstraints.cs index 2fce168b1b..b47ccc3bc8 100644 --- a/src/NUnitFramework/tests/Syntax/SerializableConstraints.cs +++ b/src/NUnitFramework/tests/Syntax/SerializableConstraints.cs @@ -30,9 +30,9 @@ public class BinarySerializableTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.BinarySerializable; - builderSyntax = Builder().BinarySerializable; + ParseTree = ""; + StaticSyntax = Is.BinarySerializable; + BuilderSyntax = Builder().BinarySerializable; } } @@ -42,9 +42,9 @@ public class XmlSerializableTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.XmlSerializable; - builderSyntax = Builder().XmlSerializable; + ParseTree = ""; + StaticSyntax = Is.XmlSerializable; + BuilderSyntax = Builder().XmlSerializable; } } } diff --git a/src/NUnitFramework/tests/Syntax/SimpleConstraints.cs b/src/NUnitFramework/tests/Syntax/SimpleConstraints.cs index 073d182256..32158710f9 100644 --- a/src/NUnitFramework/tests/Syntax/SimpleConstraints.cs +++ b/src/NUnitFramework/tests/Syntax/SimpleConstraints.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -30,9 +30,9 @@ public class NullTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Null; - builderSyntax = Builder().Null; + ParseTree = ""; + StaticSyntax = Is.Null; + BuilderSyntax = Builder().Null; } } @@ -41,9 +41,9 @@ public class TrueTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.True; - builderSyntax = Builder().True; + ParseTree = ""; + StaticSyntax = Is.True; + BuilderSyntax = Builder().True; } } @@ -52,9 +52,9 @@ public class FalseTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.False; - builderSyntax = Builder().False; + ParseTree = ""; + StaticSyntax = Is.False; + BuilderSyntax = Builder().False; } } @@ -63,9 +63,9 @@ public class PositiveTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Positive; - builderSyntax = Builder().Positive; + ParseTree = ""; + StaticSyntax = Is.Positive; + BuilderSyntax = Builder().Positive; } } @@ -74,9 +74,9 @@ public class NegativeTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Negative; - builderSyntax = Builder().Negative; + ParseTree = ""; + StaticSyntax = Is.Negative; + BuilderSyntax = Builder().Negative; } } @@ -85,9 +85,9 @@ public class ZeroTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.Zero; - builderSyntax = Builder().Zero; + ParseTree = ""; + StaticSyntax = Is.Zero; + BuilderSyntax = Builder().Zero; } } @@ -96,9 +96,9 @@ public class NaNTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.NaN; - builderSyntax = Builder().NaN; + ParseTree = ""; + StaticSyntax = Is.NaN; + BuilderSyntax = Builder().NaN; } } } diff --git a/src/NUnitFramework/tests/Syntax/StringConstraints.cs b/src/NUnitFramework/tests/Syntax/StringConstraints.cs index 6f0251092f..69b5caa9d4 100644 --- a/src/NUnitFramework/tests/Syntax/StringConstraints.cs +++ b/src/NUnitFramework/tests/Syntax/StringConstraints.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -30,9 +30,9 @@ public class ContainsTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.Contain("X"); - builderSyntax = Builder().Contains("X"); + ParseTree = @""; + StaticSyntax = Does.Contain("X"); + BuilderSyntax = Builder().Contains("X"); } } @@ -41,9 +41,9 @@ public class ContainsTest_IgnoreCase : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.Contain("X").IgnoreCase; - builderSyntax = Builder().Contains("X").IgnoreCase; + ParseTree = @""; + StaticSyntax = Does.Contain("X").IgnoreCase; + BuilderSyntax = Builder().Contains("X").IgnoreCase; } } @@ -52,9 +52,9 @@ public class StartsWithTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.StartWith("X"); - builderSyntax = Builder().StartsWith("X"); + ParseTree = @""; + StaticSyntax = Does.StartWith("X"); + BuilderSyntax = Builder().StartsWith("X"); } } @@ -63,9 +63,9 @@ public class TextStartsWithTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.StartWith("X"); - builderSyntax = Builder().StartsWith("X"); + ParseTree = @""; + StaticSyntax = Does.StartWith("X"); + BuilderSyntax = Builder().StartsWith("X"); } } @@ -74,9 +74,9 @@ public class StartsWithTest_IgnoreCase : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.StartWith("X").IgnoreCase; - builderSyntax = Builder().StartsWith("X").IgnoreCase; + ParseTree = @""; + StaticSyntax = Does.StartWith("X").IgnoreCase; + BuilderSyntax = Builder().StartsWith("X").IgnoreCase; } } @@ -85,9 +85,9 @@ public class EndsWithTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.EndWith("X"); - builderSyntax = Builder().EndsWith("X"); + ParseTree = @""; + StaticSyntax = Does.EndWith("X"); + BuilderSyntax = Builder().EndsWith("X"); } } @@ -96,9 +96,9 @@ public class EndsWithTest_IgnoreCase : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.EndWith("X").IgnoreCase; - builderSyntax = Builder().EndsWith("X").IgnoreCase; + ParseTree = @""; + StaticSyntax = Does.EndWith("X").IgnoreCase; + BuilderSyntax = Builder().EndsWith("X").IgnoreCase; } } @@ -107,9 +107,9 @@ public class RegexTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.Match("X"); - builderSyntax = Builder().Matches("X"); + ParseTree = @""; + StaticSyntax = Does.Match("X"); + BuilderSyntax = Builder().Matches("X"); } } @@ -118,9 +118,9 @@ public class RegexTest_IgnoreCase : SyntaxTest [SetUp] public void SetUp() { - parseTree = @""; - staticSyntax = Does.Match("X").IgnoreCase; - builderSyntax = Builder().Matches("X").IgnoreCase; + ParseTree = @""; + StaticSyntax = Does.Match("X").IgnoreCase; + BuilderSyntax = Builder().Matches("X").IgnoreCase; } } } diff --git a/src/NUnitFramework/tests/Syntax/SyntaxTest.cs b/src/NUnitFramework/tests/Syntax/SyntaxTest.cs index 3e8bf85c6d..f1e9fd5e1a 100644 --- a/src/NUnitFramework/tests/Syntax/SyntaxTest.cs +++ b/src/NUnitFramework/tests/Syntax/SyntaxTest.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -28,9 +28,9 @@ namespace NUnit.Framework.Syntax { public abstract class SyntaxTest { - protected string parseTree; - protected IResolveConstraint staticSyntax; - protected IResolveConstraint builderSyntax; + protected string ParseTree; + protected IResolveConstraint StaticSyntax; + protected IResolveConstraint BuilderSyntax; protected ConstraintExpression Builder() { @@ -41,16 +41,16 @@ protected ConstraintExpression Builder() public void SupportedByStaticSyntax() { Assert.That( - staticSyntax.Resolve().ToString(), - Is.EqualTo(parseTree).NoClip); + StaticSyntax.Resolve().ToString(), + Is.EqualTo(ParseTree).NoClip); } [Test] public void SupportedByConstraintBuilder() { Assert.That( - builderSyntax.Resolve().ToString(), - Is.EqualTo(parseTree).NoClip); + BuilderSyntax.Resolve().ToString(), + Is.EqualTo(ParseTree).NoClip); } } } diff --git a/src/NUnitFramework/tests/Syntax/TypeConstraints.cs b/src/NUnitFramework/tests/Syntax/TypeConstraints.cs index 1af4927161..63ccefe315 100644 --- a/src/NUnitFramework/tests/Syntax/TypeConstraints.cs +++ b/src/NUnitFramework/tests/Syntax/TypeConstraints.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -31,9 +31,9 @@ public class ExactTypeTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.TypeOf(typeof(string)); - builderSyntax = Builder().TypeOf(typeof(string)); + ParseTree = ""; + StaticSyntax = Is.TypeOf(typeof(string)); + BuilderSyntax = Builder().TypeOf(typeof(string)); } } @@ -43,9 +43,9 @@ public class InstanceOfTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.InstanceOf(typeof(string)); - builderSyntax = Builder().InstanceOf(typeof(string)); + ParseTree = ""; + StaticSyntax = Is.InstanceOf(typeof(string)); + BuilderSyntax = Builder().InstanceOf(typeof(string)); } } @@ -55,9 +55,9 @@ public class AssignableFromTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AssignableFrom(typeof(string)); - builderSyntax = Builder().AssignableFrom(typeof(string)); + ParseTree = ""; + StaticSyntax = Is.AssignableFrom(typeof(string)); + BuilderSyntax = Builder().AssignableFrom(typeof(string)); } } @@ -67,9 +67,9 @@ public class AssignableToTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AssignableTo(typeof(string)); - builderSyntax = Builder().AssignableTo(typeof(string)); + ParseTree = ""; + StaticSyntax = Is.AssignableTo(typeof(string)); + BuilderSyntax = Builder().AssignableTo(typeof(string)); } } @@ -79,9 +79,9 @@ public class AttributeTest : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Has.Attribute(typeof(TestFixtureAttribute)); - builderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)); + ParseTree = ""; + StaticSyntax = Has.Attribute(typeof(TestFixtureAttribute)); + BuilderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)); } } @@ -91,9 +91,9 @@ public class AttributeTestWithFollowingConstraint : SyntaxTest [SetUp] public void SetUp() { - parseTree = @">>>"; - staticSyntax = Has.Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; - builderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; + ParseTree = @">>>"; + StaticSyntax = Has.Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; + BuilderSyntax = Builder().Attribute(typeof(TestFixtureAttribute)).Property("Description").Not.Null; } } @@ -103,9 +103,9 @@ public class ExactTypeTest_Generic : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.TypeOf(); - builderSyntax = Builder().TypeOf(); + ParseTree = ""; + StaticSyntax = Is.TypeOf(); + BuilderSyntax = Builder().TypeOf(); } } @@ -115,9 +115,9 @@ public class InstanceOfTest_Generic : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.InstanceOf(); - builderSyntax = Builder().InstanceOf(); + ParseTree = ""; + StaticSyntax = Is.InstanceOf(); + BuilderSyntax = Builder().InstanceOf(); } } @@ -127,9 +127,9 @@ public class AssignableFromTest_Generic : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AssignableFrom(); - builderSyntax = Builder().AssignableFrom(); + ParseTree = ""; + StaticSyntax = Is.AssignableFrom(); + BuilderSyntax = Builder().AssignableFrom(); } } @@ -139,9 +139,9 @@ public class AssignableToTest_Generic : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Is.AssignableTo(); - builderSyntax = Builder().AssignableTo(); + ParseTree = ""; + StaticSyntax = Is.AssignableTo(); + BuilderSyntax = Builder().AssignableTo(); } } @@ -151,9 +151,9 @@ public class AttributeTest_Generic : SyntaxTest [SetUp] public void SetUp() { - parseTree = ""; - staticSyntax = Has.Attribute(); - builderSyntax = Builder().Attribute(); + ParseTree = ""; + StaticSyntax = Has.Attribute(); + BuilderSyntax = Builder().Attribute(); } } } diff --git a/src/NUnitFramework/tests/TestContextTests.cs b/src/NUnitFramework/tests/TestContextTests.cs index 7e790caa70..b4ce6d2386 100644 --- a/src/NUnitFramework/tests/TestContextTests.cs +++ b/src/NUnitFramework/tests/TestContextTests.cs @@ -282,34 +282,34 @@ public void TestCanAccessTestState_PassingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); + Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>Inconclusive=>Passed")); } [Test] public void TestCanAccessTestState_FailureInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.setUpFailure = true; + fixture.SetUpFailure = true; TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Failed")); + Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>=>Failed")); } [Test] public void TestCanAccessTestState_FailingTest() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.testFailure = true; + fixture.TestFailure = true; TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); + Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>Inconclusive=>Failed")); } [Test] public void TestCanAccessTestState_IgnoredInSetUp() { TestStateRecordingFixture fixture = new TestStateRecordingFixture(); - fixture.setUpIgnore = true; + fixture.SetUpIgnore = true; TestBuilder.RunTestFixture(fixture); - Assert.That(fixture.stateList, Is.EqualTo("Inconclusive=>=>Skipped:Ignored")); + Assert.That(fixture.StateList, Is.EqualTo("Inconclusive=>=>Skipped:Ignored")); } [Test] From 24d6d04b61e53527e748c1b2feced72e389655ba Mon Sep 17 00:00:00 2001 From: DaiMichael Date: Sat, 29 Sep 2018 13:08:45 +0100 Subject: [PATCH 011/174] PR improvements for inter-framework code (#if) --- .../framework/Attributes/TimeoutAttribute.cs | 50 ++---------- .../Internal/Commands/TimeoutCommand.cs | 81 +++++-------------- .../tests/Attributes/ThreadingTests.cs | 7 +- .../tests/Attributes/TimeoutTests.cs | 26 ++---- 4 files changed, 40 insertions(+), 124 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs index 766d64928c..11a7f2771a 100644 --- a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2018 Charlie Poole, Rob Prouse +// Copyright (c) 2008-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -20,7 +20,6 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if THREAD_ABORT using System; using NUnit.Framework.Internal; @@ -36,7 +35,7 @@ namespace NUnit.Framework /// for all contained test methods. /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)] - public class TimeoutAttribute : PropertyAttribute, IApplyToContext + public class TimeoutAttribute : PropertyAttribute, IApplyToContext, IWrapTestMethod { private readonly int _timeout; @@ -50,48 +49,14 @@ public TimeoutAttribute(int timeout) _timeout = timeout; } -#region IApplyToContext Members + #region IApplyToContext void IApplyToContext.ApplyToContext(TestExecutionContext context) { context.TestCaseTimeout = _timeout; } -#endregion - } -} - -#endif - -#if !THREAD_ABORT && !NET20 && !NET35 - -using System; -using System.Threading.Tasks; -using NUnit.Framework.Internal; -using NUnit.Framework.Internal.Commands; -using NUnit.Framework.Interfaces; - -namespace NUnit.Framework -{ - /// - /// Used on a method, marks the test with a timeout value in milliseconds. - /// The test will be run in a separate thread and is cancelled if the timeout - /// is exceeded. Used on a class or assembly, sets the default timeout - /// for all contained test methods. - /// - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, Inherited = false)] - public class TimeoutAttribute : PropertyAttribute, IWrapTestMethod - { - private readonly int _timeout; - - /// - /// Construct a TimeoutAttribute given a time in milliseconds - /// - /// The timeout value in milliseconds - public TimeoutAttribute(int timeout) : base(timeout) - { - _timeout = timeout; - } + #endregion /// /// Wrap a command and return the result. @@ -100,10 +65,11 @@ public TimeoutAttribute(int timeout) : base(timeout) /// The wrapped command public TestCommand Wrap(TestCommand command) { +#if !THREAD_ABORT && !(NET20 || NET35) return new TimeoutCommand(command, _timeout); +#else + return command; +#endif } } } - -#endif - diff --git a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs index 3d0bec183c..6d9e002e0f 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2018 Charlie Poole, Rob Prouse +// Copyright (c) 2017-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -20,8 +20,12 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if THREAD_ABORT + +using System; using System.Threading; +#if !THREAD_ABORT +using System.Threading.Tasks; +#endif using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Commands @@ -33,8 +37,11 @@ namespace NUnit.Framework.Internal.Commands /// public class TimeoutCommand : BeforeAndAfterTestCommand { + private readonly int _timeout; +#if THREAD_ABORT Timer _commandTimer; private bool _commandTimedOut; +#endif /// /// Initializes a new instance of the class. @@ -43,9 +50,11 @@ public class TimeoutCommand : BeforeAndAfterTestCommand /// Timeout value public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand) { + _timeout = timeout; Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", nameof(innerCommand)); Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", nameof(timeout)); +#if THREAD_ABORT BeforeTest = (context) => { var testThread = Thread.CurrentThread; @@ -74,44 +83,13 @@ public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand context.CurrentResult.SetResult(ResultState.Failure, $"Test exceeded Timeout value of {timeout}ms"); } }; - } - } -} +#else + BeforeTest = _ => { }; + AfterTest = _ => { }; #endif - -#if !THREAD_ABORT && !NET20 && !NET35 - -using System; -using System.Linq; -using System.Threading.Tasks; -using NUnit.Framework.Interfaces; - -namespace NUnit.Framework.Internal.Commands -{ - /// - /// TimeoutCommand uses Task.Wait() for .NetCore, - /// if a test exceeds a specified time and adjusts - /// the test result if it did time out. - /// - public class TimeoutCommand : TestCommand - { - private readonly TestCommand _innerCommand; - private readonly int _timeout; - - /// - /// Initializes a new instance of the class. - /// - /// The inner command - /// Timeout value - public TimeoutCommand(TestCommand innerCommand, int timeout) : base(innerCommand.Test) - { - Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", nameof(innerCommand)); - Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", nameof(timeout)); - - _innerCommand = innerCommand; - _timeout = timeout; } +#if !THREAD_ABORT /// /// Runs the test, saving a TestResult in the supplied TestExecutionContext. /// @@ -121,7 +99,11 @@ public override TestResult Execute(TestExecutionContext context) { try { - if (!Task.Run(() => context.CurrentResult = _innerCommand.Execute(context)).Wait(_timeout)) + if (!Task.Run(() => + { + context.CurrentResult = innerCommand.Execute(context); + + }).Wait(_timeout)) { context.CurrentResult.SetResult(new ResultState( TestStatus.Failed, @@ -129,32 +111,13 @@ public override TestResult Execute(TestExecutionContext context) FailureSite.Test)); } } - catch (AggregateException ae) - { - var message = string.Empty; - - ae.Handle(x => - { - message += x.InnerException != null ? x.InnerException.Message : x.Message; - return true; - }); - - context.CurrentResult.SetResult(new ResultState( - TestStatus.Failed, - message, - FailureSite.Test)); - } catch (Exception exception) { - context.CurrentResult.SetResult(new ResultState( - TestStatus.Failed, - exception.InnerException != null ? exception.InnerException.Message : exception.Message, - FailureSite.Test)); + context.CurrentResult.RecordException(exception); } return context.CurrentResult; } +#endif } } - -#endif diff --git a/src/NUnitFramework/tests/Attributes/ThreadingTests.cs b/src/NUnitFramework/tests/Attributes/ThreadingTests.cs index b3546622e6..d80311b4ee 100644 --- a/src/NUnitFramework/tests/Attributes/ThreadingTests.cs +++ b/src/NUnitFramework/tests/Attributes/ThreadingTests.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2009 Charlie Poole, Rob Prouse +// Copyright (c) 2009-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -21,13 +21,14 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if !NETCOREAPP1_1 + using System.Threading; namespace NUnit.Framework.Attributes { public class ThreadingTests { +#if !NETCOREAPP1_1 protected Thread ParentThread { get; private set; } protected Thread SetupThread { get; private set; } protected ApartmentState ParentThreadApartment { get; private set; } @@ -65,6 +66,6 @@ protected static ApartmentState GetApartmentState(Thread thread) { return thread.GetApartmentState(); } +#endif } } -#endif diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index de42d938d2..8a6630dea2 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2018 Charlie Poole, Rob Prouse +// Copyright (c) 2012-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -21,7 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if PLATFORM_DETECTION using System; using System.Linq; using System.Threading; @@ -36,6 +35,7 @@ namespace NUnit.Framework.Attributes [NonParallelizable] public class TimeoutTests : ThreadingTests { +#if PLATFORM_DETECTION [Test, Timeout(500)] public void TestWithTimeoutRunsOnSameThread() { @@ -167,22 +167,9 @@ public void TimeoutWithMessagePumpShouldAbort() Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure)); Assert.That(result.Message, Is.EqualTo("Test exceeded Timeout value of 500ms")); } - } -} #endif -#if !THREAD_ABORT - -using System; -using System.Threading; -using NUnit.Framework.Interfaces; -using NUnit.TestUtilities; - -namespace NUnit.Framework.Attributes -{ - [TestFixture, NonParallelizable] - public class TimeoutTests - { +#if !THREAD_ABORT && !(NET20 || NET35) [Timeout(50)] public void TestTimeoutAndReportsTimeoutFailure() { @@ -196,7 +183,7 @@ public void TestTimeoutDoesNotStopCompletion() Assert.True(true); } - [Timeout(50)] + [Timeout(100)] public void TestTimeoutWhichThrowsTestException() { throw new ArgumentException($"{nameof(ArgumentException)} was thrown."); @@ -223,9 +210,8 @@ public void TestTimeoutWithExceptionThrown() Assert.That(testResult?.ResultState.Status, Is.EqualTo(TestStatus.Failed)); Assert.That(testResult?.ResultState.Site, Is.EqualTo(FailureSite.Test)); - Assert.That(testResult?.ResultState.Label, Is.EqualTo($"{nameof(ArgumentException)} was thrown.")); + Assert.That(testResult?.ResultState.Label, Is.EqualTo("Test exceeded Timeout value 50ms.")); } +#endif } } - -#endif From 4e8d545d7bb04b3655da4199dd95fbbaad2c5710 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sat, 29 Sep 2018 23:19:55 -0400 Subject: [PATCH 012/174] #3035 Apartment state can't be used for .NET Standard 2.0 tests Enables apartment state for .NET Standard 2.0 builds. All tests pass under Windows, Unix may have some failing tests, but I think I've added platform includes in all the places they might. --- src/NUnitFramework/Directory.Build.props | 4 ++-- .../tests/Attributes/ApartmentAttributeTests.cs | 3 +++ .../tests/Attributes/RequiresThreadAttributeTests.cs | 6 ++++++ src/NUnitFramework/tests/SynchronizationContextTests.cs | 3 +++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/Directory.Build.props b/src/NUnitFramework/Directory.Build.props index b986a3a789..08ae768c33 100644 --- a/src/NUnitFramework/Directory.Build.props +++ b/src/NUnitFramework/Directory.Build.props @@ -28,10 +28,10 @@ $(DefineConstants);THREAD_ABORT;APARTMENT_STATE + and '$(TargetFramework)' != 'netcoreapp2.0'">$(DefineConstants);THREAD_ABORT $(DefineConstants);PLATFORM_DETECTION + and '$(TargetFramework)' != 'netcoreapp1.1'">$(DefineConstants);PLATFORM_DETECTION;APARTMENT_STATE diff --git a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs index e0d1fb5243..8107e00e4d 100644 --- a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs @@ -27,6 +27,9 @@ namespace NUnit.Framework.Attributes { +#if PLATFORM_DETECTION + [Platform(Include = "Win")] +#endif [TestFixture] public class ApartmentAttributeTests : ThreadingTests { diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index b55bef287e..f117493189 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -43,6 +43,9 @@ public void TestWithRequiresThreadRunsSetUpAndTestOnSameThread() } #if APARTMENT_STATE +#if PLATFORM_DETECTION + [Platform(Include = "Win")] +#endif [Test, RequiresThread( ApartmentState.STA )] public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() { @@ -50,6 +53,9 @@ public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() Assert.That( Thread.CurrentThread, Is.Not.EqualTo( ParentThread ) ); } +#if PLATFORM_DETECTION + [Platform(Include = "Win")] +#endif [Test, RequiresThread( ApartmentState.MTA )] public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() { diff --git a/src/NUnitFramework/tests/SynchronizationContextTests.cs b/src/NUnitFramework/tests/SynchronizationContextTests.cs index 40e8d4faa4..57352f641e 100644 --- a/src/NUnitFramework/tests/SynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/SynchronizationContextTests.cs @@ -73,6 +73,9 @@ public static void SynchronizationContextIsRestoredBetweenTestCaseSources() public static IEnumerable ApiAdapters => AsyncExecutionApiAdapter.All; #if APARTMENT_STATE +#if PLATFORM_DETECTION + [Platform(Include = "Win")] +#endif [Apartment(ApartmentState.STA)] [TestCaseSource(nameof(ApiAdapters))] public static void ContinuationStaysOnStaThread(AsyncExecutionApiAdapter apiAdapter) From 4d5c5df78914e91bea9f33af40793b5b7b1bb76f Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sun, 30 Sep 2018 15:14:16 -0400 Subject: [PATCH 013/174] Adds Microsoft.DotNet.Analyzers.Compatibility per jnm2's comments. In all places that we are setting the apartment state, check which OS we're running on and mark the unit tests as failing rather than throwing the PNSE. --- .../Execution/SimpleWorkItemDispatcher.cs | 9 ++++++ .../Internal/Execution/TestWorker.cs | 29 ++++++++++++++++--- .../framework/Internal/Execution/WorkItem.cs | 10 +++++++ .../framework/nunit.framework.csproj | 6 +++- .../Attributes/SingleThreadedFixtureTests.cs | 3 ++ 5 files changed, 52 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs index 72c7535df8..70c2387077 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -60,7 +60,16 @@ public void Start(WorkItem topLevelWorkItem) #if APARTMENT_STATE if (topLevelWorkItem.TargetApartment == ApartmentState.STA) + { +#if NETSTANDARD2_0 + if (!OSPlatform.CurrentPlatform.IsWindows) + { + topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on non-windows platforms."); + return; + } +#endif _runnerThread.SetApartmentState(ApartmentState.STA); + } #endif _runnerThread.Start(); diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index 11d77f3cdf..bcbc54bef1 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -24,6 +24,7 @@ #if PARALLEL using System; using System.Threading; +using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { @@ -41,6 +42,8 @@ public class TestWorker private bool _running; + private bool _queueNotSupportedDueToApartmentState; + #region Events /// @@ -131,9 +134,18 @@ private void TestWorkerThreadProc() // worrying about competing workers. Busy(this, _currentWorkItem); - // Because we execute the current item AFTER the queue state - // is saved, its children end up in the new queue set. - _currentWorkItem.Execute(); + if (_queueNotSupportedDueToApartmentState) + { + string msg = "Apartment state cannot be set on non-windows platforms."; + log.Error(msg); + _currentWorkItem.Result.SetResult(ResultState.NotRunnable, msg); + } + else + { + // Because we execute the current item AFTER the queue state + // is saved, its children end up in the new queue set. + _currentWorkItem.Execute(); + } // This call may result in the queues being restored. There // is a potential race condition here. We should not restore @@ -157,7 +169,16 @@ public void Start() _workerThread = new Thread(new ThreadStart(TestWorkerThreadProc)); _workerThread.Name = Name; #if APARTMENT_STATE - _workerThread.SetApartmentState(WorkQueue.TargetApartment); +#if NETSTANDARD2_0 + if (OSPlatform.CurrentPlatform.IsWindows) + { + _workerThread.SetApartmentState(WorkQueue.TargetApartment); + } + else + { + _queueNotSupportedDueToApartmentState = true; + } +#endif #endif log.Info("{0} starting on thread [{1}]", Name, _workerThread.ManagedThreadId); _workerThread.Start(); diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index a00b987b7d..4bb6b6681d 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -248,6 +248,16 @@ public virtual void Execute() Test.RequiresThread ? "RequiresThread" : "different Apartment"); #if APARTMENT_STATE +#if NETSTANDARD2_0 + if (!OSPlatform.CurrentPlatform.IsWindows) + { + string msg = "Apartment state cannot be set on non-windows platforms."; + log.Error(msg); + Result.SetResult(ResultState.NotRunnable, msg); + WorkItemComplete(); + return; + } +#endif RunOnSeparateThread(targetApartment); #else RunOnSeparateThread(); diff --git a/src/NUnitFramework/framework/nunit.framework.csproj b/src/NUnitFramework/framework/nunit.framework.csproj index 3ba2ffe322..f4ab2dd1b5 100644 --- a/src/NUnitFramework/framework/nunit.framework.csproj +++ b/src/NUnitFramework/framework/nunit.framework.csproj @@ -1,4 +1,4 @@ - + net20;net35;net40;net45;netstandard1.4;netstandard2.0 @@ -28,6 +28,10 @@ + + + + diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index 58e9e9e421..846a53bac6 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -79,6 +79,9 @@ private void CheckTestIsInvalid(string reason) } #if APARTMENT_STATE +#if PLATFORM_DETECTION + [Platform(Include = "Windows")] +#endif [SingleThreaded, Apartment(ApartmentState.STA)] public class SingleThreadedFixtureRunInSTA : ThreadingTests { From 301a2b2dba7e29c65c10032e527d70f4e7468de3 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sun, 30 Sep 2018 15:23:19 -0400 Subject: [PATCH 014/174] Comment out the analyzer as it causes the build to fail due to warnings as errors being enabled. --- src/NUnitFramework/framework/nunit.framework.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/nunit.framework.csproj b/src/NUnitFramework/framework/nunit.framework.csproj index f4ab2dd1b5..306e2de2d5 100644 --- a/src/NUnitFramework/framework/nunit.framework.csproj +++ b/src/NUnitFramework/framework/nunit.framework.csproj @@ -30,7 +30,7 @@ - + From 5a51d3b04edace17d1825d3be2e826d695eab3e8 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sun, 30 Sep 2018 19:00:31 -0400 Subject: [PATCH 015/174] Fix a warning. --- .../framework/Internal/Execution/TestWorker.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index bcbc54bef1..632131e8d4 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -42,7 +42,9 @@ public class TestWorker private bool _running; +#if NETSTANDARD2_0 private bool _queueNotSupportedDueToApartmentState; +#endif #region Events @@ -63,9 +65,9 @@ public class TestWorker /// public event TestWorkerEventHandler Idle; - #endregion +#endregion - #region Constructor +#region Constructor /// /// Construct a new TestWorker. @@ -80,9 +82,9 @@ public TestWorker(WorkItemQueue queue, string name) Name = name; } - #endregion +#endregion - #region Properties +#region Properties /// /// The WorkItemQueue from which this worker pulls WorkItems @@ -102,7 +104,7 @@ public bool IsAlive get { return _workerThread.IsAlive; } } - #endregion +#endregion /// /// Our ThreadProc, which pulls and runs tests in a loop @@ -134,6 +136,7 @@ private void TestWorkerThreadProc() // worrying about competing workers. Busy(this, _currentWorkItem); +#if NETSTANDARD2_0 if (_queueNotSupportedDueToApartmentState) { string msg = "Apartment state cannot be set on non-windows platforms."; @@ -142,10 +145,13 @@ private void TestWorkerThreadProc() } else { +#endif // Because we execute the current item AFTER the queue state // is saved, its children end up in the new queue set. _currentWorkItem.Execute(); +#if NETSTANDARD2_0 } +#endif // This call may result in the queues being restored. There // is a potential race condition here. We should not restore From 2f2fc18f6725e11dda7c1380a94fa428eb049a46 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Mon, 1 Oct 2018 18:51:36 -0400 Subject: [PATCH 016/174] Fix another test failure. --- .../tests/Attributes/SingleThreadedFixtureTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index 846a53bac6..bde1e04b49 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -80,7 +80,7 @@ private void CheckTestIsInvalid(string reason) #if APARTMENT_STATE #if PLATFORM_DETECTION - [Platform(Include = "Windows")] + [Platform(Include = "Win")] #endif [SingleThreaded, Apartment(ApartmentState.STA)] public class SingleThreadedFixtureRunInSTA : ThreadingTests From e59b1fe48372a68794e6c81704ede1ca342acc67 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Mon, 1 Oct 2018 21:38:56 -0400 Subject: [PATCH 017/174] Fix some indentation I accidentally committed and fix the remaining failing unit tests. --- .../framework/Internal/Execution/TestWorker.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index 632131e8d4..789ac407a6 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -65,9 +65,9 @@ public class TestWorker /// public event TestWorkerEventHandler Idle; -#endregion + #endregion -#region Constructor + #region Constructor /// /// Construct a new TestWorker. @@ -82,9 +82,9 @@ public TestWorker(WorkItemQueue queue, string name) Name = name; } -#endregion + #endregion -#region Properties + #region Properties /// /// The WorkItemQueue from which this worker pulls WorkItems @@ -104,7 +104,7 @@ public bool IsAlive get { return _workerThread.IsAlive; } } -#endregion + #endregion /// /// Our ThreadProc, which pulls and runs tests in a loop @@ -178,7 +178,9 @@ public void Start() #if NETSTANDARD2_0 if (OSPlatform.CurrentPlatform.IsWindows) { +#endif _workerThread.SetApartmentState(WorkQueue.TargetApartment); +#if NETSTANDARD2_0 } else { From af719be8e9a15c8e6f4e98d4c94afa99b4961af8 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Tue, 2 Oct 2018 23:29:06 -0400 Subject: [PATCH 018/174] Make wording changes per jnm2. Hopefully address the never ending unit tests on Unix/Mac by implementing scenario 2 (for now). --- .../Execution/SimpleWorkItemDispatcher.cs | 7 +++++-- .../framework/Internal/Execution/WorkItem.cs | 18 ++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs index 70c2387077..c47521a42f 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -25,6 +25,9 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +#if NETSTANDARD2_0 +using System.Runtime.InteropServices; +#endif namespace NUnit.Framework.Internal.Execution { @@ -62,9 +65,9 @@ public void Start(WorkItem topLevelWorkItem) if (topLevelWorkItem.TargetApartment == ApartmentState.STA) { #if NETSTANDARD2_0 - if (!OSPlatform.CurrentPlatform.IsWindows) + if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { - topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on non-windows platforms."); + topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on platforms other than Windows."); return; } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 4bb6b6681d..538f8717eb 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -29,6 +29,9 @@ using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; +#if NETSTANDARD2_0 +using System.Runtime.InteropServices; +#endif namespace NUnit.Framework.Internal.Execution { @@ -249,13 +252,16 @@ public virtual void Execute() #if APARTMENT_STATE #if NETSTANDARD2_0 - if (!OSPlatform.CurrentPlatform.IsWindows) + if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { - string msg = "Apartment state cannot be set on non-windows platforms."; - log.Error(msg); - Result.SetResult(ResultState.NotRunnable, msg); - WorkItemComplete(); - return; + if(targetApartment != ApartmentState.Unknown) + { + string msg = "Apartment state cannot be set on platforms other than Windows."; + log.Error(msg); + Result.SetResult(ResultState.NotRunnable, msg); + WorkItemComplete(); + return; + } } #endif RunOnSeparateThread(targetApartment); From a7250fc1732475df7f337abda182ea1e94d9b8ce Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Wed, 3 Oct 2018 00:12:21 -0400 Subject: [PATCH 019/174] Fix a third spot that wasn't running code that it should have been (plus changes to make it use RuntimeInformation). --- .../framework/Internal/Execution/TestWorker.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index 789ac407a6..ef4b484f8c 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -25,6 +25,9 @@ using System; using System.Threading; using NUnit.Framework.Interfaces; +#if NETSTANDARD2_0 +using System.Runtime.InteropServices; +#endif namespace NUnit.Framework.Internal.Execution { @@ -176,15 +179,18 @@ public void Start() _workerThread.Name = Name; #if APARTMENT_STATE #if NETSTANDARD2_0 - if (OSPlatform.CurrentPlatform.IsWindows) + if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { -#endif - _workerThread.SetApartmentState(WorkQueue.TargetApartment); -#if NETSTANDARD2_0 + if (WorkQueue.TargetApartment != ApartmentState.STA) + { + _queueNotSupportedDueToApartmentState = true; + } } else { - _queueNotSupportedDueToApartmentState = true; +#endif + _workerThread.SetApartmentState(WorkQueue.TargetApartment); +#if NETSTANDARD2_0 } #endif #endif From f7a66e2f296da1c2b4c06707f70ba802c39d420d Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Wed, 3 Oct 2018 16:04:21 +0300 Subject: [PATCH 020/174] Fix ContainsConstraint ignoring IgnoreCase for collection --- .../Constraints/ContainsConstraint.cs | 22 +++++--- .../Constraints/ContainsConstraintTests.cs | 50 +++++++++++++++++++ 2 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs diff --git a/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs b/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs index c6cefa9c57..b55799b448 100644 --- a/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs @@ -34,9 +34,9 @@ namespace NUnit.Framework.Constraints /// public class ContainsConstraint : Constraint { - readonly object _expected; - Constraint _realConstraint; - bool _ignoreCase; + private readonly object _expected; + private Constraint _realConstraint; + private bool _ignoreCase; /// /// Initializes a new instance of the class. @@ -53,9 +53,12 @@ public ContainsConstraint(object expected) /// public override string Description { - get { return _realConstraint != null ? - _realConstraint.Description : - "containing " + MsgUtils.FormatValue(_expected); } + get + { + return _realConstraint != null ? + _realConstraint.Description : + "containing " + MsgUtils.FormatValue(_expected); + } } /// @@ -81,7 +84,12 @@ public override ConstraintResult ApplyTo(TActual actual) _realConstraint = constraint; } else - _realConstraint = new SomeItemsConstraint(new EqualConstraint(_expected)); + { + var itemConstraint = new EqualConstraint(_expected); + if (_ignoreCase) + itemConstraint = itemConstraint.IgnoreCase; + _realConstraint = new SomeItemsConstraint(itemConstraint); + } return _realConstraint.ApplyTo(actual); } diff --git a/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs new file mode 100644 index 0000000000..abd8685878 --- /dev/null +++ b/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs @@ -0,0 +1,50 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +namespace NUnit.Framework.Constraints +{ + public class ContainsConstraintTests + { + [Test] + public void HonorsIgnoreCaseForStringCollection() + { + var actualItems = new[] { "ABC", "def" }; + var constraint = new ContainsConstraint("abc").IgnoreCase; + + var result = constraint.ApplyTo(actualItems); + + Assert.That(result.IsSuccess); + } + + [Test] + public void HonorsIgnoreCaseForString() + { + var actualString = "ABCdef"; + var constraint = new ContainsConstraint("abc").IgnoreCase; + + var result = constraint.ApplyTo(actualString); + + Assert.That(result.IsSuccess); + } + } +} From 2c7995923dc924aeba73e0bbd06cca8011aa990d Mon Sep 17 00:00:00 2001 From: DaiMichael Date: Wed, 3 Oct 2018 19:06:57 +0100 Subject: [PATCH 021/174] Simplified conditional branches. Used nUnit helpers. --- .../framework/Attributes/TimeoutAttribute.cs | 16 +--------------- .../Internal/Commands/TimeoutCommand.cs | 8 ++------ .../Internal/Execution/SimpleWorkItem.cs | 4 +--- .../tests/Attributes/TimeoutTests.cs | 12 +++++------- 4 files changed, 9 insertions(+), 31 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs index 11a7f2771a..0be66f6405 100644 --- a/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TimeoutAttribute.cs @@ -35,7 +35,7 @@ namespace NUnit.Framework /// for all contained test methods. /// [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited=false)] - public class TimeoutAttribute : PropertyAttribute, IApplyToContext, IWrapTestMethod + public class TimeoutAttribute : PropertyAttribute, IApplyToContext { private readonly int _timeout; @@ -57,19 +57,5 @@ void IApplyToContext.ApplyToContext(TestExecutionContext context) } #endregion - - /// - /// Wrap a command and return the result. - /// - /// The command to be wrapped - /// The wrapped command - public TestCommand Wrap(TestCommand command) - { -#if !THREAD_ABORT && !(NET20 || NET35) - return new TimeoutCommand(command, _timeout); -#else - return command; -#endif - } } } diff --git a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs index 6d9e002e0f..6f614d530e 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs @@ -99,11 +99,7 @@ public override TestResult Execute(TestExecutionContext context) { try { - if (!Task.Run(() => - { - context.CurrentResult = innerCommand.Execute(context); - - }).Wait(_timeout)) + if (!Task.Run(() => context.CurrentResult = innerCommand.Execute(context)).Wait(_timeout)) { context.CurrentResult.SetResult(new ResultState( TestStatus.Failed, @@ -113,7 +109,7 @@ public override TestResult Execute(TestExecutionContext context) } catch (Exception exception) { - context.CurrentResult.RecordException(exception); + context.CurrentResult.RecordException(exception, FailureSite.Test); } return context.CurrentResult; diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs index c723d57118..fc17975ca3 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItem.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2012-2017 Charlie Poole, Rob Prouse +// Copyright (c) 2012-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -141,7 +141,6 @@ private TestCommand MakeTestCommand() command = new ApplyChangesToContextCommand(command, attr); // If a timeout is specified, create a TimeoutCommand -#if THREAD_ABORT // Timeout set at a higher level int timeout = Context.TestCaseTimeout; @@ -151,7 +150,6 @@ private TestCommand MakeTestCommand() if (timeout > 0) command = new TimeoutCommand(command, timeout); -#endif return command; } diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 8a6630dea2..e6c7c05573 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -192,9 +192,8 @@ public void TestTimeoutWhichThrowsTestException() [Test] public void TestTimesOut() { - var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutAndReportsTimeoutFailure)); - var workItem = TestBuilder.CreateWorkItem(testCase, this); - var testResult = TestBuilder.ExecuteWorkItem(workItem); + var testMethod = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutAndReportsTimeoutFailure)); + var testResult = TestBuilder.RunTest(testMethod, this); Assert.That(testResult?.ResultState.Status, Is.EqualTo(TestStatus.Failed)); Assert.That(testResult?.ResultState.Site, Is.EqualTo(FailureSite.Test)); @@ -204,13 +203,12 @@ public void TestTimesOut() [Test] public void TestTimeoutWithExceptionThrown() { - var testCase = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutWhichThrowsTestException)); - var workItem = TestBuilder.CreateWorkItem(testCase, this); - var testResult = TestBuilder.ExecuteWorkItem(workItem); + var testMethod = TestBuilder.MakeTestCase(GetType(), nameof(TestTimeoutWhichThrowsTestException)); + var testResult = TestBuilder.RunTest(testMethod, this); Assert.That(testResult?.ResultState.Status, Is.EqualTo(TestStatus.Failed)); Assert.That(testResult?.ResultState.Site, Is.EqualTo(FailureSite.Test)); - Assert.That(testResult?.ResultState.Label, Is.EqualTo("Test exceeded Timeout value 50ms.")); + Assert.That(testResult?.ResultState.Label, Is.EqualTo("Error")); } #endif } From 5ce8dee719e0a7018f6bdc36a2a5b7a46452c0cd Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Thu, 4 Oct 2018 09:37:35 +0300 Subject: [PATCH 022/174] fix for extra allocating ComparisonConstraint constructors no longer allocates description string on creation --- .../Constraints/ComparisonConstraint.cs | 21 ++++++++++++++++++- .../Constraints/GreaterThanConstraint.cs | 11 +++++++--- .../GreaterThanOrEqualConstraint.cs | 13 +++++++++--- .../Constraints/LessThanConstraint.cs | 11 +++++++--- .../Constraints/LessThanOrEqualConstraint.cs | 11 +++++++--- 5 files changed, 54 insertions(+), 13 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs index 9eb732fb75..4297cdb02f 100644 --- a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs @@ -77,6 +77,25 @@ public override ConstraintResult ApplyTo(TActual actual) return new ConstraintResult(this, actual, PerformComparison(_comparer, actual, _expected, _tolerance)); } + /// + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. + /// + public override string Description + { + get + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(DisplayMessageBase); + sb.Append(MsgUtils.FormatValue(_expected)); + return sb.ToString(); + } + } + + /// + /// Protected field overriden by derived class to provide basis for Description construction + /// + protected abstract string DisplayMessageBase { get; } + /// /// Protected function overridden by derived class to actually perform the comparison /// @@ -150,4 +169,4 @@ public ComparisonConstraint Percent #endregion } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs index a0a0471fe7..5ab66fd80a 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs @@ -34,9 +34,14 @@ public class GreaterThanConstraint : ComparisonConstraint /// Initializes a new instance of the class. /// /// The expected value. - public GreaterThanConstraint(object expected) : base(expected) + public GreaterThanConstraint(object expected) : base(expected) {} + + /// + /// Description basis + /// + protected override string DisplayMessageBase { - Description = "greater than " + MsgUtils.FormatValue(expected); + get { return "greater than "; } } /// @@ -47,4 +52,4 @@ protected override bool PerformComparison(ComparisonAdapter comparer, object act return comparer.Compare(actual, tolerance.ApplyToValue(expected).LowerBound) > 0; } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs index 10d4af55d8..a8c35522ae 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs @@ -21,6 +21,8 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +using System; + namespace NUnit.Framework.Constraints { /// @@ -32,9 +34,14 @@ public class GreaterThanOrEqualConstraint : ComparisonConstraint /// Initializes a new instance of the class. /// /// The expected value. - public GreaterThanOrEqualConstraint(object expected) : base(expected) + public GreaterThanOrEqualConstraint(object expected) : base(expected) {} + + /// + /// Description basis + /// + protected override string DisplayMessageBase { - Description = "greater than or equal to " + MsgUtils.FormatValue(expected); + get { return "greater than or equal to "; } } /// @@ -45,4 +52,4 @@ protected override bool PerformComparison(ComparisonAdapter comparer, object act return comparer.Compare(actual, tolerance.ApplyToValue(expected).LowerBound) >= 0; } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs index b8820abb76..ac58e9a39d 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs @@ -32,9 +32,14 @@ public class LessThanConstraint : ComparisonConstraint /// Initializes a new instance of the class. /// /// The expected value. - public LessThanConstraint(object expected) : base(expected) + public LessThanConstraint(object expected) : base(expected) {} + + /// + /// Description basis + /// + protected override string DisplayMessageBase { - Description = "less than " + MsgUtils.FormatValue(expected); + get { return "less than "; } } /// @@ -45,4 +50,4 @@ protected override bool PerformComparison(ComparisonAdapter comparer, object act return comparer.Compare(actual, tolerance.ApplyToValue(expected).UpperBound) < 0; } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs index 9f26555e26..a3b67f43a8 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs @@ -32,9 +32,14 @@ public class LessThanOrEqualConstraint : ComparisonConstraint /// Initializes a new instance of the class. /// /// The expected value. - public LessThanOrEqualConstraint(object expected) : base(expected) + public LessThanOrEqualConstraint(object expected) : base(expected) {} + + /// + /// Description basis + /// + protected override string DisplayMessageBase { - Description = "less than or equal to " + MsgUtils.FormatValue(expected); + get { return "less than or equal to "; } } /// @@ -45,4 +50,4 @@ protected override bool PerformComparison(ComparisonAdapter comparer, object act return comparer.Compare(actual, tolerance.ApplyToValue(expected).UpperBound) <= 0; } } -} \ No newline at end of file +} From 99ca32b6eef99fdb6e3504b5bddea8c006585ea5 Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Fri, 5 Oct 2018 00:14:59 +0300 Subject: [PATCH 023/174] Updates after review --- .../Constraints/ContainsConstraint.cs | 14 ++++- .../Constraints/ContainsConstraintTests.cs | 61 +++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs b/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs index b55799b448..3c294110b5 100644 --- a/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ContainsConstraint.cs @@ -55,9 +55,17 @@ public override string Description { get { - return _realConstraint != null ? - _realConstraint.Description : - "containing " + MsgUtils.FormatValue(_expected); + if (_realConstraint != null) + { + return _realConstraint.Description; + } + + var description = "containing " + MsgUtils.FormatValue(_expected); + + if (_ignoreCase) + description += ", ignoring case"; + + return description; } } diff --git a/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs index abd8685878..34592c4485 100644 --- a/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/ContainsConstraintTests.cs @@ -21,10 +21,15 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +using System; +using NUnit.Framework.Internal; + namespace NUnit.Framework.Constraints { public class ContainsConstraintTests { + private readonly string NL = Environment.NewLine; + [Test] public void HonorsIgnoreCaseForStringCollection() { @@ -46,5 +51,61 @@ public void HonorsIgnoreCaseForString() Assert.That(result.IsSuccess); } + + [Test] + public void ContainsSubstringErrorMessage() + { + var actualString = "abc"; + var expected = "bcd"; + + var expectedMessage = + TextMessageWriter.Pfx_Expected + "String containing \"bcd\"" + NL + + TextMessageWriter.Pfx_Actual + "\"abc\"" + NL; + + var ex = Assert.Throws(() => Assert.That(actualString, Does.Contain(expected))); + Assert.That(ex.Message, Is.EqualTo(expectedMessage)); + } + + [Test] + public void ContainsSubstringIgnoreCaseErrorMessage() + { + var actualString = "abc"; + var expected = "bcd"; + + var expectedMessage = + TextMessageWriter.Pfx_Expected + "String containing \"bcd\", ignoring case" + NL + + TextMessageWriter.Pfx_Actual + "\"abc\"" + NL; + + var ex = Assert.Throws(() => Assert.That(actualString, Does.Contain(expected).IgnoreCase)); + Assert.That(ex.Message, Is.EqualTo(expectedMessage)); + } + + [Test] + public void ContainsItemErrorMessage() + { + var actualItems = new[] { "a", "b" }; + var expected = "c"; + + var expectedMessage = + TextMessageWriter.Pfx_Expected + "some item equal to \"c\"" + NL + + TextMessageWriter.Pfx_Actual + "< \"a\", \"b\" >" + NL; + + var ex = Assert.Throws(() => Assert.That(actualItems, Does.Contain(expected))); + Assert.That(ex.Message, Is.EqualTo(expectedMessage)); + } + + [Test] + public void ContainsItemIgnoreCaseErrorMessage() + { + var actualItems = new[] { "a", "b" }; + var expected = "c"; + + var expectedMessage = + TextMessageWriter.Pfx_Expected + "some item equal to \"c\", ignoring case" + NL + + TextMessageWriter.Pfx_Actual + "< \"a\", \"b\" >" + NL; + + var ex = Assert.Throws(() => Assert.That(actualItems, Does.Contain(expected).IgnoreCase)); + Assert.That(ex.Message, Is.EqualTo(expectedMessage)); + } } } From 54e17163a58d09983589cadbb209c0af5f732d10 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Thu, 4 Oct 2018 22:36:18 -0400 Subject: [PATCH 024/174] Address pull request comments from jnm2. --- .../framework/Internal/Execution/TestWorker.cs | 8 ++++---- .../framework/Internal/Execution/WorkItem.cs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index ef4b484f8c..754a2373e0 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -142,7 +142,7 @@ private void TestWorkerThreadProc() #if NETSTANDARD2_0 if (_queueNotSupportedDueToApartmentState) { - string msg = "Apartment state cannot be set on non-windows platforms."; + string msg = "Apartment state cannot be set on platforms other than Windows."; log.Error(msg); _currentWorkItem.Result.SetResult(ResultState.NotRunnable, msg); } @@ -179,9 +179,9 @@ public void Start() _workerThread.Name = Name; #if APARTMENT_STATE #if NETSTANDARD2_0 - if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + if (WorkQueue.TargetApartment != ApartmentState.STA) { - if (WorkQueue.TargetApartment != ApartmentState.STA) + if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { _queueNotSupportedDueToApartmentState = true; } @@ -189,7 +189,7 @@ public void Start() else { #endif - _workerThread.SetApartmentState(WorkQueue.TargetApartment); + _workerThread.SetApartmentState(WorkQueue.TargetApartment); #if NETSTANDARD2_0 } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 538f8717eb..e8a8c6ad89 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -252,9 +252,9 @@ public virtual void Execute() #if APARTMENT_STATE #if NETSTANDARD2_0 - if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + if(targetApartment != ApartmentState.STA) { - if(targetApartment != ApartmentState.Unknown) + if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { string msg = "Apartment state cannot be set on platforms other than Windows."; log.Error(msg); From 994df4001fa8ee381a86fb177d69258596e75e63 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Thu, 4 Oct 2018 22:40:30 -0400 Subject: [PATCH 025/174] Remove analyzer per jmn2 as that will need to be a separate issue. --- src/NUnitFramework/framework/nunit.framework.csproj | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/NUnitFramework/framework/nunit.framework.csproj b/src/NUnitFramework/framework/nunit.framework.csproj index 306e2de2d5..2fd8c2868e 100644 --- a/src/NUnitFramework/framework/nunit.framework.csproj +++ b/src/NUnitFramework/framework/nunit.framework.csproj @@ -28,10 +28,6 @@ - - - - From a5e1f96c067f5b7249dad26ba62b5e274e29e35e Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Thu, 4 Oct 2018 23:16:54 -0400 Subject: [PATCH 026/174] Block STA apartment states - not unknown or MTA states. --- src/NUnitFramework/framework/Internal/Execution/TestWorker.cs | 2 +- src/NUnitFramework/framework/Internal/Execution/WorkItem.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index 754a2373e0..d1818c38d4 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -179,7 +179,7 @@ public void Start() _workerThread.Name = Name; #if APARTMENT_STATE #if NETSTANDARD2_0 - if (WorkQueue.TargetApartment != ApartmentState.STA) + if (WorkQueue.TargetApartment == ApartmentState.STA) { if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index e8a8c6ad89..15139521dc 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -252,7 +252,7 @@ public virtual void Execute() #if APARTMENT_STATE #if NETSTANDARD2_0 - if(targetApartment != ApartmentState.STA) + if(targetApartment == ApartmentState.STA) { if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { From 9be981cf7518f044cec61f40788731c8915a604c Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Fri, 5 Oct 2018 20:22:22 -0400 Subject: [PATCH 027/174] Disable the STA tests on platforms other than Windows as they won't be able to run with netcoreapp2.0. --- .../Internal/Execution/TestWorker.cs | 4 ++++ .../Attributes/ApartmentAttributeTests.cs | 24 +++++++++++++++++++ .../RequiresThreadAttributeTests.cs | 4 ++-- .../Attributes/SingleThreadedFixtureTests.cs | 2 +- .../tests/SynchronizationContextTests.cs | 5 +++- 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index d1818c38d4..d44a964303 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -185,6 +185,10 @@ public void Start() { _queueNotSupportedDueToApartmentState = true; } + else + { + _workerThread.SetApartmentState(WorkQueue.TargetApartment); + } } else { diff --git a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs index 8107e00e4d..dde81345f2 100644 --- a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs @@ -39,6 +39,9 @@ public void ApartmentStateUnknownThrowsException() Assert.That(() => new ApartmentAttribute(ApartmentState.Unknown), Throws.ArgumentException); } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [Test, Apartment(ApartmentState.STA)] public void TestWithRequiresSTARunsInSTA() { @@ -50,6 +53,9 @@ public void TestWithRequiresSTARunsInSTA() [Test] #if THREAD_ABORT [Timeout(10000)] +#endif +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] #endif [Apartment(ApartmentState.STA)] public void TestWithTimeoutAndSTARunsInSTA() @@ -60,6 +66,9 @@ public void TestWithTimeoutAndSTARunsInSTA() [TestFixture] #if THREAD_ABORT [Timeout(10000)] +#endif +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] #endif [Apartment(ApartmentState.STA)] public class FixtureWithTimeoutRequiresSTA @@ -71,6 +80,9 @@ public void RequiresSTACanBeSetOnTestFixtureWithTimeout() } } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [TestFixture, Apartment(ApartmentState.STA)] public class FixtureRequiresSTA { @@ -128,6 +140,9 @@ public void RequiresMTAAttributeIsInheritable() } } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] @@ -147,6 +162,9 @@ public void TestCasesShouldInheritApartmentFromFixture(int n) } } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] @@ -168,6 +186,9 @@ public void TestCasesShouldRespectTheirApartment(int n) } } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] @@ -187,6 +208,9 @@ public void TestCasesShouldInheritApartmentFromFixture(int n) } } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index f117493189..3d1c8c6542 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -43,7 +43,7 @@ public void TestWithRequiresThreadRunsSetUpAndTestOnSameThread() } #if APARTMENT_STATE -#if PLATFORM_DETECTION +#if PLATFORM_DETECTION && NETCOREAPP2_0 [Platform(Include = "Win")] #endif [Test, RequiresThread( ApartmentState.STA )] @@ -53,7 +53,7 @@ public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() Assert.That( Thread.CurrentThread, Is.Not.EqualTo( ParentThread ) ); } -#if PLATFORM_DETECTION +#if PLATFORM_DETECTION && NETCOREAPP2_0 [Platform(Include = "Win")] #endif [Test, RequiresThread( ApartmentState.MTA )] diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index bde1e04b49..89fdb1c50e 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -79,7 +79,7 @@ private void CheckTestIsInvalid(string reason) } #if APARTMENT_STATE -#if PLATFORM_DETECTION +#if PLATFORM_DETECTION && NETCOREAPP2_0 [Platform(Include = "Win")] #endif [SingleThreaded, Apartment(ApartmentState.STA)] diff --git a/src/NUnitFramework/tests/SynchronizationContextTests.cs b/src/NUnitFramework/tests/SynchronizationContextTests.cs index 57352f641e..dfb0ad6327 100644 --- a/src/NUnitFramework/tests/SynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/SynchronizationContextTests.cs @@ -73,7 +73,7 @@ public static void SynchronizationContextIsRestoredBetweenTestCaseSources() public static IEnumerable ApiAdapters => AsyncExecutionApiAdapter.All; #if APARTMENT_STATE -#if PLATFORM_DETECTION +#if PLATFORM_DETECTION && NETCOREAPP2_0 [Platform(Include = "Win")] #endif [Apartment(ApartmentState.STA)] @@ -89,6 +89,9 @@ public static void ContinuationStaysOnStaThread(AsyncExecutionApiAdapter apiAdap }); } +#if PLATFORM_DETECTION && NETCOREAPP2_0 + [Platform(Include = "Win")] +#endif [Apartment(ApartmentState.STA)] [TestCaseSource(nameof(ApiAdapters))] public static void AsyncDelegatesAreExecutedOnStaThread(AsyncExecutionApiAdapter apiAdapter) From 780e588da5d85f0c839efdb14afb1afd4a4d3e30 Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sat, 6 Oct 2018 06:21:52 +0300 Subject: [PATCH 028/174] tolerance info added --- .../framework/Constraints/ComparisonConstraint.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs index 4297cdb02f..e1fbe91f8a 100644 --- a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs @@ -87,6 +87,18 @@ public override string Description { System.Text.StringBuilder sb = new System.Text.StringBuilder(DisplayMessageBase); sb.Append(MsgUtils.FormatValue(_expected)); + + if (_tolerance != null && !_tolerance.IsUnsetOrDefault) + { + sb.Append(" within "); + sb.Append(MsgUtils.FormatValue(_tolerance.Amount)); + + if (_tolerance.Mode == ToleranceMode.Percent) + { + sb.Append(" percent"); + } + } + return sb.ToString(); } } @@ -147,7 +159,6 @@ public ComparisonConstraint Within(object amount) throw new InvalidOperationException("Within modifier may appear only once in a constraint expression"); _tolerance = new Tolerance(amount); - Description += " within " + MsgUtils.FormatValue(amount); return this; } @@ -162,7 +173,6 @@ public ComparisonConstraint Percent get { _tolerance = _tolerance.Percent; - Description += " percent"; return this; } } From 90a19501c7689673f1666f4437e3d1edf01d58a6 Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sat, 6 Oct 2018 21:54:18 +0300 Subject: [PATCH 029/174] public interface fix Restored public interface of ComparisonConstraint to its previous state. Moved description building logic to a separate method --- .../Constraints/ComparisonConstraint.cs | 64 ++++++++++--------- .../Constraints/GreaterThanConstraint.cs | 9 ++- .../GreaterThanOrEqualConstraint.cs | 9 ++- .../Constraints/LessThanConstraint.cs | 7 +- .../Constraints/LessThanOrEqualConstraint.cs | 7 +- 5 files changed, 49 insertions(+), 47 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs index e1fbe91f8a..fadc7ffec2 100644 --- a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs @@ -77,37 +77,6 @@ public override ConstraintResult ApplyTo(TActual actual) return new ConstraintResult(this, actual, PerformComparison(_comparer, actual, _expected, _tolerance)); } - /// - /// The Description of what this constraint tests, for - /// use in messages and in the ConstraintResult. - /// - public override string Description - { - get - { - System.Text.StringBuilder sb = new System.Text.StringBuilder(DisplayMessageBase); - sb.Append(MsgUtils.FormatValue(_expected)); - - if (_tolerance != null && !_tolerance.IsUnsetOrDefault) - { - sb.Append(" within "); - sb.Append(MsgUtils.FormatValue(_tolerance.Amount)); - - if (_tolerance.Mode == ToleranceMode.Percent) - { - sb.Append(" percent"); - } - } - - return sb.ToString(); - } - } - - /// - /// Protected field overriden by derived class to provide basis for Description construction - /// - protected abstract string DisplayMessageBase { get; } - /// /// Protected function overridden by derived class to actually perform the comparison /// @@ -178,5 +147,38 @@ public ComparisonConstraint Percent } #endregion + + #region Protected Methods + + /// + /// Provides standard description of what the constraint tests + /// based on comparison text. + /// + /// Describes, what constraint tests, throws + /// if null + /// Is thrown when null passed to a method + protected string DefaultDescription(string comparisonText) + { + if (comparisonText == null) + throw new ArgumentNullException(nameof(comparisonText), "Comparison text can not be null"); + + System.Text.StringBuilder sb = new System.Text.StringBuilder(comparisonText); + sb.Append(MsgUtils.FormatValue(_expected)); + + if (_tolerance != null && !_tolerance.IsUnsetOrDefault) + { + sb.Append(" within "); + sb.Append(MsgUtils.FormatValue(_tolerance.Amount)); + + if (_tolerance.Mode == ToleranceMode.Percent) + { + sb.Append(" percent"); + } + } + + return sb.ToString(); + } + + #endregion } } diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs index 5ab66fd80a..e1492c0418 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs @@ -21,8 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -using System; - namespace NUnit.Framework.Constraints { /// @@ -37,11 +35,12 @@ public class GreaterThanConstraint : ComparisonConstraint public GreaterThanConstraint(object expected) : base(expected) {} /// - /// Description basis + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. /// - protected override string DisplayMessageBase + public override string Description { - get { return "greater than "; } + get { return DefaultDescription("greater than "); } } /// diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs index a8c35522ae..25d5b81260 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs @@ -21,8 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -using System; - namespace NUnit.Framework.Constraints { /// @@ -37,11 +35,12 @@ public class GreaterThanOrEqualConstraint : ComparisonConstraint public GreaterThanOrEqualConstraint(object expected) : base(expected) {} /// - /// Description basis + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. /// - protected override string DisplayMessageBase + public override string Description { - get { return "greater than or equal to "; } + get { return DefaultDescription("greater than or equal to "); } } /// diff --git a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs index ac58e9a39d..2e480ed1fd 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs @@ -35,11 +35,12 @@ public class LessThanConstraint : ComparisonConstraint public LessThanConstraint(object expected) : base(expected) {} /// - /// Description basis + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. /// - protected override string DisplayMessageBase + public override string Description { - get { return "less than "; } + get { return DefaultDescription("less than "); } } /// diff --git a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs index a3b67f43a8..6a95e602d6 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs @@ -35,11 +35,12 @@ public class LessThanOrEqualConstraint : ComparisonConstraint public LessThanOrEqualConstraint(object expected) : base(expected) {} /// - /// Description basis + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. /// - protected override string DisplayMessageBase + public override string Description { - get { return "less than or equal to "; } + get { return DefaultDescription("less than or equal to "); } } /// From 9ed4bd10d2fdae03cf7693bc009e52902183d9c7 Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sat, 6 Oct 2018 22:30:06 +0300 Subject: [PATCH 030/174] storage variable added Added variable to store description value in order to avoid extra calculations on consecutive test runs --- .../framework/Constraints/GreaterThanConstraint.cs | 13 ++++++++++++- .../Constraints/GreaterThanOrEqualConstraint.cs | 13 ++++++++++++- .../framework/Constraints/LessThanConstraint.cs | 13 ++++++++++++- .../Constraints/LessThanOrEqualConstraint.cs | 13 ++++++++++++- 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs index e1492c0418..e484fad720 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs @@ -28,6 +28,12 @@ namespace NUnit.Framework.Constraints /// public class GreaterThanConstraint : ComparisonConstraint { + /// + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. + /// + private string _description; + /// /// Initializes a new instance of the class. /// @@ -40,7 +46,12 @@ public class GreaterThanConstraint : ComparisonConstraint /// public override string Description { - get { return DefaultDescription("greater than "); } + get + { + if (System.String.IsNullOrEmpty(_description)) + _description = DefaultDescription("greater than "); + return _description; + } } /// diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs index 25d5b81260..b187071549 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs @@ -28,6 +28,12 @@ namespace NUnit.Framework.Constraints /// public class GreaterThanOrEqualConstraint : ComparisonConstraint { + /// + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. + /// + private string _description; + /// /// Initializes a new instance of the class. /// @@ -40,7 +46,12 @@ public class GreaterThanOrEqualConstraint : ComparisonConstraint /// public override string Description { - get { return DefaultDescription("greater than or equal to "); } + get + { + if (System.String.IsNullOrEmpty(_description)) + _description = DefaultDescription("greater than or equal to "); + return _description; + } } /// diff --git a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs index 2e480ed1fd..6a80248e7a 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs @@ -28,6 +28,12 @@ namespace NUnit.Framework.Constraints /// public class LessThanConstraint : ComparisonConstraint { + /// + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. + /// + private string _description; + /// /// Initializes a new instance of the class. /// @@ -40,7 +46,12 @@ public class LessThanConstraint : ComparisonConstraint /// public override string Description { - get { return DefaultDescription("less than "); } + get + { + if (System.String.IsNullOrEmpty(_description)) + _description = DefaultDescription("less than "); + return _description; + } } /// diff --git a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs index 6a95e602d6..2850dd73f8 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs @@ -28,6 +28,12 @@ namespace NUnit.Framework.Constraints /// public class LessThanOrEqualConstraint : ComparisonConstraint { + /// + /// The Description of what this constraint tests, for + /// use in messages and in the ConstraintResult. + /// + private string _description; + /// /// Initializes a new instance of the class. /// @@ -40,7 +46,12 @@ public class LessThanOrEqualConstraint : ComparisonConstraint /// public override string Description { - get { return DefaultDescription("less than or equal to "); } + get + { + if (System.String.IsNullOrEmpty(_description)) + _description = DefaultDescription("less than or equal to "); + return _description; + } } /// From d4b1e3bea7e984a4319b786feac06bb868fc1def Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Sat, 6 Oct 2018 21:12:11 -0400 Subject: [PATCH 031/174] Update version to 3.12 for ongoing development --- build.cake | 2 +- src/NUnitFramework/FrameworkVersion.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build.cake b/build.cake index db672bb015..9b50c8e331 100644 --- a/build.cake +++ b/build.cake @@ -18,7 +18,7 @@ var ErrorDetail = new List(); // SET PACKAGE VERSION ////////////////////////////////////////////////////////////////////// -var version = "3.11.0"; +var version = "3.12.0"; var modifier = ""; var dbgSuffix = configuration == "Debug" ? "-dbg" : ""; diff --git a/src/NUnitFramework/FrameworkVersion.cs b/src/NUnitFramework/FrameworkVersion.cs index 5962546d2e..da66111a20 100644 --- a/src/NUnitFramework/FrameworkVersion.cs +++ b/src/NUnitFramework/FrameworkVersion.cs @@ -26,5 +26,5 @@ // // Current version for the NUnit Framework // -[assembly: AssemblyVersion("3.11.0.0")] -[assembly: AssemblyFileVersion("3.11.0.0")] +[assembly: AssemblyVersion("3.12.0.0")] +[assembly: AssemblyFileVersion("3.12.0.0")] From 2efe715b350d64073921e222f72fbd2f3d6c94cd Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Sat, 6 Oct 2018 21:30:11 -0400 Subject: [PATCH 032/174] Update CHANGES.md --- CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index d21193d83c..b3b2c6dbe7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,4 @@ -### NUnit 3.11 - October 11, 2018 +### NUnit 3.11 - October 6, 2018 * More informative assertion messages * PlatformAttribute is available on and now detects .NET Core From 3b94c6363cff561bf86b1abee13372c0bce429e3 Mon Sep 17 00:00:00 2001 From: Sunitha Patel Date: Sun, 7 Oct 2018 00:40:21 -0400 Subject: [PATCH 033/174] Support multiple TestOf attributes on test fixture or test method. --- .../framework/Attributes/TestOfAttribute.cs | 2 +- src/NUnitFramework/testdata/TestOfFixture.cs | 8 ++++++++ .../tests/Attributes/TestOfTests.cs | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Attributes/TestOfAttribute.cs b/src/NUnitFramework/framework/Attributes/TestOfAttribute.cs index c0d48030b2..d4469c2321 100644 --- a/src/NUnitFramework/framework/Attributes/TestOfAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestOfAttribute.cs @@ -35,7 +35,7 @@ namespace NUnit.Framework /// /// Indicates the method or class the assembly, test fixture or test method is testing. /// - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public class TestOfAttribute : PropertyAttribute { /// diff --git a/src/NUnitFramework/testdata/TestOfFixture.cs b/src/NUnitFramework/testdata/TestOfFixture.cs index ac9ffd0659..872ace82a2 100644 --- a/src/NUnitFramework/testdata/TestOfFixture.cs +++ b/src/NUnitFramework/testdata/TestOfFixture.cs @@ -25,12 +25,15 @@ #region Using Directives using NUnit.Framework; +using NUnit.Framework.Internal; #endregion namespace NUnit.TestData { [TestFixture(TestOf = typeof(TestOfAttribute))] + [TestOf(typeof(TestOfAttribute))] + [TestOf(typeof(TestFixtureAttribute))] public class TestOfFixture { [Test(TestOf = typeof(TestOfAttribute))] @@ -55,5 +58,10 @@ public void SeparateTestOfStringMethod() [TestCase(5, TestOf = typeof(TestCaseAttribute))] public void TestCaseWithTestOf(int x) { } + + [Test] + [TestOf(typeof(TestOfAttribute))][TestOf(typeof(TestAttribute))] + public void TestOfMultipleAttributesMethod() + { } } } \ No newline at end of file diff --git a/src/NUnitFramework/tests/Attributes/TestOfTests.cs b/src/NUnitFramework/tests/Attributes/TestOfTests.cs index ee89ea3d94..f5e9e85529 100644 --- a/src/NUnitFramework/tests/Attributes/TestOfTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestOfTests.cs @@ -95,5 +95,23 @@ public void TestOfOnTestCase() var testCase = (Test)parameterizedMethodSuite.Tests[0]; Assert.AreEqual("NUnit.Framework.TestCaseAttribute", testCase.Properties.Get(PropertyNames.TestOf)); } + + [Test] + public void TestOfAttributeMultipleTimes() + { + Test testCase = TestBuilder.MakeTestCase(FixtureType, "TestOfMultipleAttributesMethod"); + Assert.That(testCase.Properties[PropertyNames.TestOf], Is.EquivalentTo( + new[] { "NUnit.Framework.TestOfAttribute", "NUnit.Framework.TestAttribute" })); + } + + [Test] + public void TestFixtureMultipleTestOfAttributes() + { + var suite = new TestSuite("suite"); + suite.Add(TestBuilder.MakeFixture(typeof(TestOfFixture))); + var mockFixtureSuite = (TestSuite)suite.Tests[0]; + Assert.That(mockFixtureSuite.Properties[PropertyNames.TestOf], Is.EquivalentTo( + new[] { "NUnit.Framework.TestOfAttribute", "NUnit.Framework.TestOfAttribute", "NUnit.Framework.TestFixtureAttribute" })); + } } } From f432952a5886a2a4e0738417acd79a25e922667b Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 7 Oct 2018 10:21:05 -0400 Subject: [PATCH 034/174] Fixed hang with STA tests on platforms other than Windows --- .../Execution/SimpleWorkItemDispatcher.cs | 4 +- .../Internal/Execution/TestWorker.cs | 43 ++++--------------- .../framework/Internal/Execution/WorkItem.cs | 16 ++++--- 3 files changed, 19 insertions(+), 44 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs index c47521a42f..57138f1fec 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -62,7 +62,7 @@ public void Start(WorkItem topLevelWorkItem) _runnerThread = new Thread(RunnerThreadProc); #if APARTMENT_STATE - if (topLevelWorkItem.TargetApartment == ApartmentState.STA) + if (topLevelWorkItem.TargetApartment != ApartmentState.Unknown) { #if NETSTANDARD2_0 if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) @@ -71,7 +71,7 @@ public void Start(WorkItem topLevelWorkItem) return; } #endif - _runnerThread.SetApartmentState(ApartmentState.STA); + _runnerThread.SetApartmentState(topLevelWorkItem.TargetApartment); } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index d44a964303..91d060a41a 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -45,10 +45,6 @@ public class TestWorker private bool _running; -#if NETSTANDARD2_0 - private bool _queueNotSupportedDueToApartmentState; -#endif - #region Events /// @@ -131,30 +127,17 @@ private void TestWorkerThreadProc() _currentWorkItem.TestWorker = this; // During this Busy call, the queue state may be saved. - // This gives us a new set of queues, which are initially + // This gives us a new set of queues, which are initially // empty. The intention is that only children of the current // executing item should make use of the new set of queues. - // TODO: If we had a separate NonParallelTestWorker, it + // TODO: If we had a separate NonParallelTestWorker, it // could simply create the isolated queue without any // worrying about competing workers. Busy(this, _currentWorkItem); -#if NETSTANDARD2_0 - if (_queueNotSupportedDueToApartmentState) - { - string msg = "Apartment state cannot be set on platforms other than Windows."; - log.Error(msg); - _currentWorkItem.Result.SetResult(ResultState.NotRunnable, msg); - } - else - { -#endif - // Because we execute the current item AFTER the queue state - // is saved, its children end up in the new queue set. - _currentWorkItem.Execute(); -#if NETSTANDARD2_0 - } -#endif + // Because we execute the current item AFTER the queue state + // is saved, its children end up in the new queue set. + _currentWorkItem.Execute(); // This call may result in the queues being restored. There // is a potential race condition here. We should not restore @@ -179,21 +162,11 @@ public void Start() _workerThread.Name = Name; #if APARTMENT_STATE #if NETSTANDARD2_0 - if (WorkQueue.TargetApartment == ApartmentState.STA) - { - if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) - { - _queueNotSupportedDueToApartmentState = true; - } - else - { - _workerThread.SetApartmentState(WorkQueue.TargetApartment); - } - } - else + if (WorkQueue.TargetApartment != ApartmentState.Unknown + && RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { #endif - _workerThread.SetApartmentState(WorkQueue.TargetApartment); + _workerThread.SetApartmentState(WorkQueue.TargetApartment); #if NETSTANDARD2_0 } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 15139521dc..67f5c7fb8d 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -228,8 +228,9 @@ public virtual void Execute() #if APARTMENT_STATE CurrentApartment = Thread.CurrentThread.GetApartmentState(); var targetApartment = TargetApartment == ApartmentState.Unknown ? CurrentApartment : TargetApartment; + var needsNewThreadToSetApartmentState = targetApartment != CurrentApartment; - if (Test.RequiresThread || targetApartment != CurrentApartment) + if (Test.RequiresThread || needsNewThreadToSetApartmentState) #else if (Test.RequiresThread) #endif @@ -247,12 +248,8 @@ public virtual void Execute() return; } - log.Debug("Running on separate thread because {0} is specified.", - Test.RequiresThread ? "RequiresThread" : "different Apartment"); - -#if APARTMENT_STATE -#if NETSTANDARD2_0 - if(targetApartment == ApartmentState.STA) +#if APARTMENT_STATE && NETSTANDARD2_0 + if (needsNewThreadToSetApartmentState) { if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { @@ -264,6 +261,11 @@ public virtual void Execute() } } #endif + + log.Debug("Running on separate thread because {0} is specified.", + Test.RequiresThread ? "RequiresThread" : "different Apartment"); + +#if APARTMENT_STATE RunOnSeparateThread(targetApartment); #else RunOnSeparateThread(); From 0518d5e9caf2b1067779179d8cf19420fc71f406 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 7 Oct 2018 11:06:57 -0400 Subject: [PATCH 035/174] MTA is not considered the same apartment as unspecified except on Windows or Mono --- .../tests/Attributes/SingleThreadedFixtureTests.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index 89fdb1c50e..dba70a2e7e 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -61,6 +61,9 @@ public void TestWithDifferentApartmentIsInvalid() CheckTestIsInvalid("may not specify a different apartment"); } +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] +#endif [Test, Apartment(ApartmentState.MTA)] public void TestWithSameApartmentIsValid() { From b05195b8463285824d271cc9d8cfea0b9c1556a0 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 7 Oct 2018 11:36:22 -0400 Subject: [PATCH 036/174] Skip STA parallel execution tests unless on Windows or Mono --- .../Execution/ParallelExecutionTests.cs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs b/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs index d1dcefaa6e..803a93d608 100644 --- a/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs +++ b/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs @@ -423,14 +423,19 @@ static IEnumerable GetParallelSuites() .SetName("Issue-2464"); #if APARTMENT_STATE - yield return new TestFixtureData( - Suite("fake-assembly.dll").Parallelizable() - .Containing(Fixture(typeof(STAFixture)).Parallelizable()), - Expecting( - That("fake-assembly.dll").StartsOn("ParallelWorker"), - That("STAFixture").RunsOn("ParallelSTAWorker"), - That("STAFixture_Test").RunsOn("ParallelSTAWorker"))) - .SetName("Issue-2467"); +#if NETSTANDARD2_0 + if (new PlatformHelper().IsPlatformSupported(new PlatformAttribute { Include = "Win, Mono" })) +#endif + { + yield return new TestFixtureData( + Suite("fake-assembly.dll").Parallelizable() + .Containing(Fixture(typeof(STAFixture)).Parallelizable()), + Expecting( + That("fake-assembly.dll").StartsOn("ParallelWorker"), + That("STAFixture").RunsOn("ParallelSTAWorker"), + That("STAFixture_Test").RunsOn("ParallelSTAWorker"))) + .SetName("Issue-2467"); + } #endif } @@ -466,7 +471,7 @@ public void TestOutput(TestOutput output) public void SendMessage(TestMessage message) { - + } #endregion From 7599fbd83edd1875ab178f6401b1249ca101fd97 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sun, 7 Oct 2018 12:26:18 -0400 Subject: [PATCH 037/174] Fix comments and change ifdefs to only include NETCOREAPP2_0 instead of also requiring PLATFORM_DETECTION. --- .../Execution/SimpleWorkItemDispatcher.cs | 2 +- .../framework/Internal/Execution/WorkItem.cs | 2 +- .../Attributes/ApartmentAttributeTests.cs | 34 +++++++++---------- .../RequiresThreadAttributeTests.cs | 8 ++--- .../Attributes/SingleThreadedFixtureTests.cs | 2 +- .../tests/SynchronizationContextTests.cs | 8 ++--- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs index 57138f1fec..cf9d1e0037 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -67,7 +67,7 @@ public void Start(WorkItem topLevelWorkItem) #if NETSTANDARD2_0 if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { - topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on platforms other than Windows."); + topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on this platform."); return; } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 67f5c7fb8d..8c2ed6c9ac 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -253,7 +253,7 @@ public virtual void Execute() { if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { - string msg = "Apartment state cannot be set on platforms other than Windows."; + string msg = "Apartment state cannot be set on this platform."; log.Error(msg); Result.SetResult(ResultState.NotRunnable, msg); WorkItemComplete(); diff --git a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs index dde81345f2..75572062d6 100644 --- a/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ApartmentAttributeTests.cs @@ -28,7 +28,7 @@ namespace NUnit.Framework.Attributes { #if PLATFORM_DETECTION - [Platform(Include = "Win")] + [Platform(Include = "Win, Mono")] #endif [TestFixture] public class ApartmentAttributeTests : ThreadingTests @@ -39,8 +39,8 @@ public void ApartmentStateUnknownThrowsException() Assert.That(() => new ApartmentAttribute(ApartmentState.Unknown), Throws.ArgumentException); } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Test, Apartment(ApartmentState.STA)] public void TestWithRequiresSTARunsInSTA() @@ -54,8 +54,8 @@ public void TestWithRequiresSTARunsInSTA() #if THREAD_ABORT [Timeout(10000)] #endif -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] public void TestWithTimeoutAndSTARunsInSTA() @@ -67,8 +67,8 @@ public void TestWithTimeoutAndSTARunsInSTA() #if THREAD_ABORT [Timeout(10000)] #endif -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] public class FixtureWithTimeoutRequiresSTA @@ -80,8 +80,8 @@ public void RequiresSTACanBeSetOnTestFixtureWithTimeout() } } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [TestFixture, Apartment(ApartmentState.STA)] public class FixtureRequiresSTA @@ -140,8 +140,8 @@ public void RequiresMTAAttributeIsInheritable() } } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] @@ -162,8 +162,8 @@ public void TestCasesShouldInheritApartmentFromFixture(int n) } } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] @@ -186,8 +186,8 @@ public void TestCasesShouldRespectTheirApartment(int n) } } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] @@ -208,8 +208,8 @@ public void TestCasesShouldInheritApartmentFromFixture(int n) } } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index 3d1c8c6542..3827955230 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -43,8 +43,8 @@ public void TestWithRequiresThreadRunsSetUpAndTestOnSameThread() } #if APARTMENT_STATE -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Test, RequiresThread( ApartmentState.STA )] public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() @@ -53,8 +53,8 @@ public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() Assert.That( Thread.CurrentThread, Is.Not.EqualTo( ParentThread ) ); } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Test, RequiresThread( ApartmentState.MTA )] public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index dba70a2e7e..c508496c60 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -82,7 +82,7 @@ private void CheckTestIsInvalid(string reason) } #if APARTMENT_STATE -#if PLATFORM_DETECTION && NETCOREAPP2_0 +#if NETCOREAPP2_0 [Platform(Include = "Win")] #endif [SingleThreaded, Apartment(ApartmentState.STA)] diff --git a/src/NUnitFramework/tests/SynchronizationContextTests.cs b/src/NUnitFramework/tests/SynchronizationContextTests.cs index dfb0ad6327..62809e5b47 100644 --- a/src/NUnitFramework/tests/SynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/SynchronizationContextTests.cs @@ -73,8 +73,8 @@ public static void SynchronizationContextIsRestoredBetweenTestCaseSources() public static IEnumerable ApiAdapters => AsyncExecutionApiAdapter.All; #if APARTMENT_STATE -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] [TestCaseSource(nameof(ApiAdapters))] @@ -89,8 +89,8 @@ public static void ContinuationStaysOnStaThread(AsyncExecutionApiAdapter apiAdap }); } -#if PLATFORM_DETECTION && NETCOREAPP2_0 - [Platform(Include = "Win")] +#if NETCOREAPP2_0 + [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] [TestCaseSource(nameof(ApiAdapters))] From dde2bb4c7e507ff5792a28d091e98cfef38530ae Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 7 Oct 2018 12:33:03 -0400 Subject: [PATCH 038/174] Used NETSTANDARD instead of NETCORE --- .../tests/Internal/Execution/ParallelExecutionTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs b/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs index 803a93d608..b9eefd2471 100644 --- a/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs +++ b/src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs @@ -423,7 +423,7 @@ static IEnumerable GetParallelSuites() .SetName("Issue-2464"); #if APARTMENT_STATE -#if NETSTANDARD2_0 +#if NETCOREAPP2_0 if (new PlatformHelper().IsPlatformSupported(new PlatformAttribute { Include = "Win, Mono" })) #endif { From 5b2d211222fd3d86701087bf22df2317350dfc34 Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sun, 7 Oct 2018 19:51:09 +0300 Subject: [PATCH 039/174] review fixes Removed extra documentation. Added System.Text namespace to ComparisonConstraint. Simplified Description getter --- .../framework/Constraints/ComparisonConstraint.cs | 3 ++- .../framework/Constraints/GreaterThanConstraint.cs | 7 ++----- .../Constraints/GreaterThanOrEqualConstraint.cs | 7 ++----- .../framework/Constraints/LessThanConstraint.cs | 7 ++----- .../framework/Constraints/LessThanOrEqualConstraint.cs | 9 +++------ 5 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs index fadc7ffec2..cfcabb0a9e 100644 --- a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs @@ -22,6 +22,7 @@ // *********************************************************************** using System; +using System.Text; using System.Collections; using System.Collections.Generic; @@ -162,7 +163,7 @@ protected string DefaultDescription(string comparisonText) if (comparisonText == null) throw new ArgumentNullException(nameof(comparisonText), "Comparison text can not be null"); - System.Text.StringBuilder sb = new System.Text.StringBuilder(comparisonText); + StringBuilder sb = new StringBuilder(comparisonText); sb.Append(MsgUtils.FormatValue(_expected)); if (_tolerance != null && !_tolerance.IsUnsetOrDefault) diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs index e484fad720..298dd4f4e5 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanConstraint.cs @@ -28,10 +28,6 @@ namespace NUnit.Framework.Constraints /// public class GreaterThanConstraint : ComparisonConstraint { - /// - /// The Description of what this constraint tests, for - /// use in messages and in the ConstraintResult. - /// private string _description; /// @@ -48,8 +44,9 @@ public override string Description { get { - if (System.String.IsNullOrEmpty(_description)) + if (_description == null) _description = DefaultDescription("greater than "); + return _description; } } diff --git a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs index b187071549..6ce7f6bb55 100644 --- a/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/GreaterThanOrEqualConstraint.cs @@ -28,10 +28,6 @@ namespace NUnit.Framework.Constraints /// public class GreaterThanOrEqualConstraint : ComparisonConstraint { - /// - /// The Description of what this constraint tests, for - /// use in messages and in the ConstraintResult. - /// private string _description; /// @@ -48,8 +44,9 @@ public override string Description { get { - if (System.String.IsNullOrEmpty(_description)) + if (_description == null) _description = DefaultDescription("greater than or equal to "); + return _description; } } diff --git a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs index 6a80248e7a..3dd09588fc 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanConstraint.cs @@ -28,10 +28,6 @@ namespace NUnit.Framework.Constraints /// public class LessThanConstraint : ComparisonConstraint { - /// - /// The Description of what this constraint tests, for - /// use in messages and in the ConstraintResult. - /// private string _description; /// @@ -48,8 +44,9 @@ public override string Description { get { - if (System.String.IsNullOrEmpty(_description)) + if (_description == null) _description = DefaultDescription("less than "); + return _description; } } diff --git a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs index 2850dd73f8..ec36f3a092 100644 --- a/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/LessThanOrEqualConstraint.cs @@ -28,12 +28,8 @@ namespace NUnit.Framework.Constraints /// public class LessThanOrEqualConstraint : ComparisonConstraint { - /// - /// The Description of what this constraint tests, for - /// use in messages and in the ConstraintResult. - /// private string _description; - + /// /// Initializes a new instance of the class. /// @@ -48,8 +44,9 @@ public override string Description { get { - if (System.String.IsNullOrEmpty(_description)) + if (_description == null) _description = DefaultDescription("less than or equal to "); + return _description; } } From 6a0aa6d18cb0db99d9a1652af7d7bafbfa6c7737 Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sun, 7 Oct 2018 21:04:07 +0300 Subject: [PATCH 040/174] documentation improvement --- .../framework/Constraints/ComparisonConstraint.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs index cfcabb0a9e..3d21f13d93 100644 --- a/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ComparisonConstraint.cs @@ -155,7 +155,7 @@ public ComparisonConstraint Percent /// Provides standard description of what the constraint tests /// based on comparison text. /// - /// Describes, what constraint tests, throws + /// Describes the comparison being tested, throws /// if null /// Is thrown when null passed to a method protected string DefaultDescription(string comparisonText) From fe7f6010cbb688d5ce679f683ef2a2710f9af976 Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Sun, 7 Oct 2018 14:32:07 -0400 Subject: [PATCH 041/174] Changes based on code review --- CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index b3b2c6dbe7..ba8e5f41bd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,7 +1,7 @@ ### NUnit 3.11 - October 6, 2018 * More informative assertion messages - * PlatformAttribute is available on and now detects .NET Core + * PlatformAttribute is available on .NET Standard and now detects .NET Core * ValuesAttribute now works with nullable types * Async tests detecting and running Windows Forms or WPF message pumps rather than deadlocking * Support for UWP 10.0 is back via .NET Standard 1.4 From a35a887c4f29e2a7ccaae389f3bc44d6e7889d0c Mon Sep 17 00:00:00 2001 From: Danil Kabanov Date: Sun, 7 Oct 2018 23:26:44 +0300 Subject: [PATCH 042/174] .idea added to .gitignore --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 89d6996252..dac5e01856 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -## Ignore Visual Studio temporary files, build results, and +## Ignore Visual Studio and Rider temporary files, build results, and ## files generated by popular Visual Studio add-ons. # User-specific files @@ -109,6 +109,9 @@ csx # Windows Store app package directory AppPackages/ +# Rider specific folder +\.idea/ + # Others sql/ *.Cache From d80d7ea03d6e1dc74d33f6bd6517763374e88729 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Mon, 8 Oct 2018 13:34:05 +0200 Subject: [PATCH 043/174] Update BUILDING.md Add example on how to supply arguments on Linux (inspired by https://github.com/nunit/nunit/issues/2975#issuecomment-426982193) --- BUILDING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/BUILDING.md b/BUILDING.md index 5eb0493393..12fa826003 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -35,6 +35,8 @@ Key arguments to build.cmd / build: * -ShowDescription Shows all of the build tasks and their descriptions * -Experimental, -e Use the experimental build of Roslyn +Note that the above format for supplying arguments only work on Windows. On Linux one has to use double dashes to specify the argument, like `build.sh --target=Test` or `build.sh --target Test` to run the `Test` task. + The build.cake script contains a large number of interdependent tasks. The most important top-level tasks to use are listed here: ``` From 72cd2ff96c704b0ae4b2c24d280b283df64c5af4 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Mon, 8 Oct 2018 13:42:53 +0200 Subject: [PATCH 044/174] Update BUILDING.md --- BUILDING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILDING.md b/BUILDING.md index 12fa826003..20d3d8c795 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -35,7 +35,7 @@ Key arguments to build.cmd / build: * -ShowDescription Shows all of the build tasks and their descriptions * -Experimental, -e Use the experimental build of Roslyn -Note that the above format for supplying arguments only work on Windows. On Linux one has to use double dashes to specify the argument, like `build.sh --target=Test` or `build.sh --target Test` to run the `Test` task. +Note that the above format for supplying arguments only work on Windows. On Linux one has to use double dashes to specify the argument, like `./build.sh --target=Test` or `./build.sh --target Test` to run the `Test` task. The build.cake script contains a large number of interdependent tasks. The most important top-level tasks to use are listed here: From a5579f03e57a4e46d9703ee8697dca4024eb12e4 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Mon, 8 Oct 2018 21:10:17 -0400 Subject: [PATCH 045/174] Changes checking for whether thread apartments are supported to using PNSE. Move the failing unit tests into a separate class, as we can't test those as they will fail. Adds a unit test that verifies that Unix+NetCore will fail when apartment state is set. --- .../Execution/SimpleWorkItemDispatcher.cs | 14 +++-- .../Internal/Execution/TestWorker.cs | 13 ++--- .../framework/Internal/Execution/WorkItem.cs | 30 +++++------ .../RequiresThreadAttributeTests.cs | 53 +++++++++++++++---- .../Attributes/SingleThreadedFixtureTests.cs | 12 +++-- 5 files changed, 72 insertions(+), 50 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs index cf9d1e0037..4347da01ad 100644 --- a/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/SimpleWorkItemDispatcher.cs @@ -22,12 +22,10 @@ // *********************************************************************** #if PARALLEL +using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; -#if NETSTANDARD2_0 -using System.Runtime.InteropServices; -#endif namespace NUnit.Framework.Internal.Execution { @@ -64,14 +62,14 @@ public void Start(WorkItem topLevelWorkItem) #if APARTMENT_STATE if (topLevelWorkItem.TargetApartment != ApartmentState.Unknown) { -#if NETSTANDARD2_0 - if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + try + { + _runnerThread.SetApartmentState(topLevelWorkItem.TargetApartment); + } + catch (PlatformNotSupportedException) { topLevelWorkItem.MarkNotRunnable("Apartment state cannot be set on this platform."); - return; } -#endif - _runnerThread.SetApartmentState(topLevelWorkItem.TargetApartment); } #endif diff --git a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs index 91d060a41a..a7c23b8fd6 100644 --- a/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs +++ b/src/NUnitFramework/framework/Internal/Execution/TestWorker.cs @@ -25,9 +25,6 @@ using System; using System.Threading; using NUnit.Framework.Interfaces; -#if NETSTANDARD2_0 -using System.Runtime.InteropServices; -#endif namespace NUnit.Framework.Internal.Execution { @@ -161,15 +158,13 @@ public void Start() _workerThread = new Thread(new ThreadStart(TestWorkerThreadProc)); _workerThread.Name = Name; #if APARTMENT_STATE -#if NETSTANDARD2_0 - if (WorkQueue.TargetApartment != ApartmentState.Unknown - && RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + try { -#endif _workerThread.SetApartmentState(WorkQueue.TargetApartment); -#if NETSTANDARD2_0 } -#endif + catch (PlatformNotSupportedException) + { + } #endif log.Info("{0} starting on thread [{1}]", Name, _workerThread.ManagedThreadId); _workerThread.Start(); diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 8c2ed6c9ac..47e08518d4 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -29,9 +29,6 @@ using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; -#if NETSTANDARD2_0 -using System.Runtime.InteropServices; -#endif namespace NUnit.Framework.Internal.Execution { @@ -248,20 +245,6 @@ public virtual void Execute() return; } -#if APARTMENT_STATE && NETSTANDARD2_0 - if (needsNewThreadToSetApartmentState) - { - if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) - { - string msg = "Apartment state cannot be set on this platform."; - log.Error(msg); - Result.SetResult(ResultState.NotRunnable, msg); - WorkItemComplete(); - return; - } - } -#endif - log.Debug("Running on separate thread because {0} is specified.", Test.RequiresThread ? "RequiresThread" : "different Apartment"); @@ -498,7 +481,18 @@ private void RunOnSeparateThread() RunOnCurrentThread(); }); #if APARTMENT_STATE - thread.SetApartmentState(apartment); + try + { + thread.SetApartmentState(apartment); + } + catch (PlatformNotSupportedException) + { + string msg = "Apartment state cannot be set on this platform."; + log.Error(msg); + Result.SetResult(ResultState.NotRunnable, msg); + WorkItemComplete(); + return; + } #endif thread.Start(); thread.Join(); diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index 3827955230..8c12c8e5c1 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -24,6 +24,8 @@ #if !NETCOREAPP1_1 using System; using System.Threading; +using NUnit.Framework.Interfaces; +using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { @@ -46,22 +48,51 @@ public void TestWithRequiresThreadRunsSetUpAndTestOnSameThread() #if NETCOREAPP2_0 [Platform(Include = "Win, Mono")] #endif - [Test, RequiresThread( ApartmentState.STA )] - public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() + [TestFixture] + public class ApartmentStateRequiredTests : ThreadingTests { - Assert.That( GetApartmentState( Thread.CurrentThread ), Is.EqualTo( ApartmentState.STA ) ); - Assert.That( Thread.CurrentThread, Is.Not.EqualTo( ParentThread ) ); - } + [Test, RequiresThread(ApartmentState.STA)] + public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() + { + Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); + Assert.That(Thread.CurrentThread, Is.Not.EqualTo(ParentThread)); + } + [Test, RequiresThread(ApartmentState.MTA)] + public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() + { + Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.MTA)); + Assert.That(Thread.CurrentThread, Is.Not.EqualTo(ParentThread)); + } + } #if NETCOREAPP2_0 - [Platform(Include = "Win, Mono")] -#endif - [Test, RequiresThread( ApartmentState.MTA )] - public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() + [Platform(Include = "Unix")] + [TestFixture] + public class ApartmentStateRequiredToFailOnUnixNetCoreTests : ThreadingTests { - Assert.That( GetApartmentState( Thread.CurrentThread ), Is.EqualTo( ApartmentState.MTA ) ); - Assert.That( Thread.CurrentThread, Is.Not.EqualTo( ParentThread ) ); + [Test] + public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() + { + var test = TestBuilder.MakeTestFromMethod(typeof(ApartmentStateRequiredTests), nameof(ApartmentStateRequiredTests.TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA)); + var work = TestBuilder.CreateWorkItem(test); + var result = TestBuilder.ExecuteWorkItem(work); + + Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable)); + Assert.That(result.Message, Is.EqualTo("Apartment state cannot be set on this platform.")); + } + + [Test] + public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() + { + var test = TestBuilder.MakeTestFromMethod(typeof(ApartmentStateRequiredTests), nameof(ApartmentStateRequiredTests.TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA)); + var work = TestBuilder.CreateWorkItem(test); + var result = TestBuilder.ExecuteWorkItem(work); + + Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable)); + Assert.That(result.Message, Is.EqualTo("Apartment state cannot be set on this platform.")); + } } +#endif #endif [TestFixture, RequiresThread] diff --git a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs index c508496c60..1dcf88ec56 100644 --- a/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs +++ b/src/NUnitFramework/tests/Attributes/SingleThreadedFixtureTests.cs @@ -64,11 +64,15 @@ public void TestWithDifferentApartmentIsInvalid() #if NETCOREAPP2_0 [Platform(Include = "Win, Mono")] #endif - [Test, Apartment(ApartmentState.MTA)] - public void TestWithSameApartmentIsValid() + [SingleThreaded] + public class SingleThreadedFixtureWithApartmentStateTests : ThreadingTests { - Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); - Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); + [Test, Apartment(ApartmentState.MTA)] + public void TestWithSameApartmentIsValid() + { + Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); + Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); + } } #endif From 51e74da313111183a4ba56017e58a94fc61c2713 Mon Sep 17 00:00:00 2001 From: Matti Petrelius Date: Tue, 9 Oct 2018 22:04:02 +0300 Subject: [PATCH 046/174] Add guard to not allow ApartmentState.Unknown for RequiresThreadAttribute Fix RequiresThreadAttribute unknown throws errr unit test Add guard to not allow ApartmentState.Unknown for RequiresThreadAttribute --- .../framework/Attributes/RequiresThreadAttribute.cs | 2 ++ .../tests/Attributes/RequiresThreadAttributeTests.cs | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/src/NUnitFramework/framework/Attributes/RequiresThreadAttribute.cs b/src/NUnitFramework/framework/Attributes/RequiresThreadAttribute.cs index 2f747591fa..4d7b12c27d 100644 --- a/src/NUnitFramework/framework/Attributes/RequiresThreadAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/RequiresThreadAttribute.cs @@ -48,6 +48,8 @@ public RequiresThreadAttribute() public RequiresThreadAttribute(ApartmentState apartment) : base(true) { + Guard.ArgumentValid(apartment != ApartmentState.Unknown, "must be STA or MTA", nameof(apartment)); + this.Properties.Add(PropertyNames.ApartmentState, apartment); } #endif diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index b55bef287e..703f8b7c44 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -43,6 +43,11 @@ public void TestWithRequiresThreadRunsSetUpAndTestOnSameThread() } #if APARTMENT_STATE + [Test] + public void ApartmentStateUnknownThrowsException() { + Assert.That(() => new RequiresThreadAttribute(ApartmentState.Unknown), Throws.ArgumentException); + } + [Test, RequiresThread( ApartmentState.STA )] public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() { From fb5648bf7bc44817c9810644d6bc7ca6d87de41c Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sat, 13 Oct 2018 17:06:32 -0400 Subject: [PATCH 047/174] Remove a base class that isn't needed. --- .../tests/Attributes/RequiresThreadAttributeTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index 8c12c8e5c1..fdf292972b 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -68,7 +68,7 @@ public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() #if NETCOREAPP2_0 [Platform(Include = "Unix")] [TestFixture] - public class ApartmentStateRequiredToFailOnUnixNetCoreTests : ThreadingTests + public class ApartmentStateRequiredToFailOnUnixNetCoreTests { [Test] public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() From 5c550ac87546088b31dfdaaccc149e1b54f5622e Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sat, 13 Oct 2018 20:25:44 -0400 Subject: [PATCH 048/174] Fix the unix netcoreapp2.0 tests. They were being marked as failed due to the apartment state attribute marking the test as failed instead of skipped. --- src/NUnitFramework/framework/Internal/Execution/WorkItem.cs | 2 +- .../tests/Attributes/RequiresThreadAttributeTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index 47e08518d4..3c821c1ced 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -489,7 +489,7 @@ private void RunOnSeparateThread() { string msg = "Apartment state cannot be set on this platform."; log.Error(msg); - Result.SetResult(ResultState.NotRunnable, msg); + Result.SetResult(ResultState.Skipped, msg); WorkItemComplete(); return; } diff --git a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs index fdf292972b..e08f254b7d 100644 --- a/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RequiresThreadAttributeTests.cs @@ -77,7 +77,7 @@ public void TestWithRequiresThreadWithSTAArgRunsOnSeparateThreadInSTA() var work = TestBuilder.CreateWorkItem(test); var result = TestBuilder.ExecuteWorkItem(work); - Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable)); + Assert.That(result.ResultState, Is.EqualTo(ResultState.Skipped)); Assert.That(result.Message, Is.EqualTo("Apartment state cannot be set on this platform.")); } @@ -88,7 +88,7 @@ public void TestWithRequiresThreadWithMTAArgRunsOnSeparateThreadInMTA() var work = TestBuilder.CreateWorkItem(test); var result = TestBuilder.ExecuteWorkItem(work); - Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable)); + Assert.That(result.ResultState, Is.EqualTo(ResultState.Skipped)); Assert.That(result.Message, Is.EqualTo("Apartment state cannot be set on this platform.")); } } From 33c36df34d1c187b837497e093e0435c9bbeba92 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sat, 13 Oct 2018 21:55:26 -0400 Subject: [PATCH 049/174] Improve performance of discovery/execution #2488 Changes the regex that stripped out invalid XML characters to an equivalent method that will not allocate more strings unless there is an invalid character in the string. This was a performance issue for me when attempting to run a single test in a project with 20,000 tests with the VS test runner as this method took nearly 8s before (now down to < 1s with my changes). --- .../framework/Interfaces/TNode.cs | 58 +++++++++++++++++-- .../tests/Internal/TestXmlTests.cs | 8 +++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index ea69a2f914..28ee7401a4 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -22,6 +22,7 @@ // *********************************************************************** using System; +using System.Text; using System.Text.RegularExpressions; using System.Xml; @@ -318,17 +319,64 @@ private static NodeList ApplySelection(NodeList nodeList, string xpath) : resultNodes; } - private static readonly Regex InvalidXmlCharactersRegex = new Regex("[^\u0009\u000a\u000d\u0020-\ufffd]|([\ud800-\udbff](?![\udc00-\udfff]))|((? CharToUnicodeSequence(match.Value[0])); - } + StringBuilder builder = null; + for (int i = 0; i < str.Length; i++) + { + char c = str[i]; + if(c > 0x20 && c < 0x7F) + { + // ASCII characters - break quickly for these + if (builder != null) + builder.Append(c); + } + else if (!(0x0 <= c && c <= 0x8) && + c != 0xB && + c != 0xC && + !(0xE <= c && c <= 0x1F) && + !(0x7F <= c && c <= 0x84) && + !(0x86 <= c && c <= 0x9F) && + !(0xD800 <= c && c <= 0xDFFF) && + c != 0xFFFE && + c != 0xFFFF) + { + if (builder != null) + builder.Append(c); + } + else if (char.IsHighSurrogate(c) && + i + 1 != str.Length && + char.IsLowSurrogate(str[i + 1])) + { + if (builder != null) + { + builder.Append(c); + builder.Append(str[i + 1]); + } + i++; + } + else + { + if (builder == null) + { + builder = new StringBuilder(); + for (int index = 0; index < i; index++) + builder.Append(str[index]); + } + builder.Append(CharToUnicodeSequence(c)); + } + } + if (builder != null) + return builder.ToString(); + else + return str; + } + private static string CharToUnicodeSequence(char symbol) { return string.Format("\\u{0}", ((int)symbol).ToString("x4")); @@ -400,7 +448,7 @@ public bool Pass(TNode node) } } - #endregion +#endregion } /// diff --git a/src/NUnitFramework/tests/Internal/TestXmlTests.cs b/src/NUnitFramework/tests/Internal/TestXmlTests.cs index dead2b9f7f..b290a94507 100644 --- a/src/NUnitFramework/tests/Internal/TestXmlTests.cs +++ b/src/NUnitFramework/tests/Internal/TestXmlTests.cs @@ -113,6 +113,14 @@ public void TestNameWithInvalidCharacter() Assert.That(testMethod.ToXml(false).OuterXml, Contains.Substring("name=\"\\u0001HappyFace\"")); } + [Test] + public void TestNameWithInvalidCharacter_NonFirstPosition() + { + testMethod.Name = "Happy\u0001Face"; + // This throws if the name is not properly escaped + Assert.That(testMethod.ToXml(false).OuterXml, Contains.Substring("name=\"Happy\\u0001Face\"")); + } + #region Helper Methods For Checking XML private void CheckXmlForTest(Test test, bool recursive) From a4936e4eac23cb48665b8ec5caf2172aa51d7024 Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Sat, 13 Oct 2018 22:46:29 -0400 Subject: [PATCH 050/174] Timeout failures on MacOS #3014 Converts the timeout tests from using sleeping to test the behavior via test to a test that checks how the test would have executed without running it to verify that the behavior will work. --- ...peatableTestsWithTimeoutAttributesTests.cs | 78 ++++++++++++++++--- 1 file changed, 68 insertions(+), 10 deletions(-) diff --git a/src/NUnitFramework/tests/Attributes/RepeatableTestsWithTimeoutAttributesTests.cs b/src/NUnitFramework/tests/Attributes/RepeatableTestsWithTimeoutAttributesTests.cs index 4837dbaf42..71a88bdc63 100644 --- a/src/NUnitFramework/tests/Attributes/RepeatableTestsWithTimeoutAttributesTests.cs +++ b/src/NUnitFramework/tests/Attributes/RepeatableTestsWithTimeoutAttributesTests.cs @@ -22,9 +22,11 @@ // *********************************************************************** using System; +using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Commands; +using NUnit.Framework.Internal.Execution; using NUnit.TestUtilities; #if THREAD_ABORT @@ -35,8 +37,6 @@ namespace NUnit.Framework.Attributes public class RepeatableTestsWithTimeoutAttributesTests { private int retryOnlyCount; - private int retryTimeoutCount; - private int repeatTimeoutCount; [Test] [Retry(3)] @@ -46,24 +46,82 @@ public void ShouldPassAfter3Retries() Assert.True(retryOnlyCount >= 2); } + public class HelperMethodForTimeoutsClass + { + [Test] + [Retry(3), Timeout(85)] + public void ShouldPassAfter3RetriesAndTimeoutIsResetEachTime() + { + } + + [Test] + [Repeat(3), Timeout(85)] + public void ShouldPassAfter2RepeatsAndTimeoutIsResetEachTime() + { + } + } + [Test] - [Retry(3), Timeout(85)] public void ShouldPassAfter3RetriesAndTimeoutIsResetEachTime() { - retryTimeoutCount++; + // Rather than testing with sleeps, this tests that the execution will occur in the correct + // order by checking which commands are run when. As the retry command comes first, the + // timeout will be reset each time it runs + var test = TestBuilder.MakeTestFromMethod(typeof(HelperMethodForTimeoutsClass), nameof(HelperMethodForTimeoutsClass.ShouldPassAfter3RetriesAndTimeoutIsResetEachTime)); + SimpleWorkItem work = TestBuilder.CreateWorkItem(test) as SimpleWorkItem; + var method = typeof(SimpleWorkItem).GetMethod("MakeTestCommand", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); + TestCommand command = (TestCommand)method.Invoke(work, null); + + Assert.That(command, Is.TypeOf(typeof(RetryAttribute.RetryCommand))); + RetryAttribute.RetryCommand retryCommand = (RetryAttribute.RetryCommand)command; + + command = GetInnerCommand(retryCommand); + + Assert.That(command, Is.TypeOf(typeof(TimeoutCommand))); + TimeoutCommand timeoutCommand = (TimeoutCommand)command; + + command = GetInnerCommand(timeoutCommand); + + Assert.That(command, Is.TypeOf(typeof(ApplyChangesToContextCommand))); + ApplyChangesToContextCommand applyChangesToContextCommand = (ApplyChangesToContextCommand)command; + + command = GetInnerCommand(applyChangesToContextCommand); - System.Threading.Thread.Sleep(30); - Assert.True(retryTimeoutCount >= 2); + Assert.That(command, Is.TypeOf(typeof(TestMethodCommand))); } [Test] - [Repeat(3), Timeout(85)] public void ShouldPassAfter2RepeatsAndTimeoutIsResetEachTime() { - repeatTimeoutCount++; + // Rather than testing with sleeps, this tests that the execution will occur in the correct + // order by checking which commands are run when. As the repeat command comes first, the + // timeout will be reset each time it runs + var test = TestBuilder.MakeTestFromMethod(typeof(HelperMethodForTimeoutsClass), nameof(HelperMethodForTimeoutsClass.ShouldPassAfter2RepeatsAndTimeoutIsResetEachTime)); + SimpleWorkItem work = TestBuilder.CreateWorkItem(test) as SimpleWorkItem; + var method = typeof(SimpleWorkItem).GetMethod("MakeTestCommand", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); + TestCommand command = (TestCommand)method.Invoke(work, null); - System.Threading.Thread.Sleep(30); - Assert.True(repeatTimeoutCount >= 1); + Assert.That(command, Is.TypeOf(typeof(RepeatAttribute.RepeatedTestCommand))); + RepeatAttribute.RepeatedTestCommand repeatedCommand = (RepeatAttribute.RepeatedTestCommand)command; + + command = GetInnerCommand(repeatedCommand); + + Assert.That(command, Is.TypeOf(typeof(TimeoutCommand))); + TimeoutCommand timeoutCommand = (TimeoutCommand)command; + + command = GetInnerCommand(timeoutCommand); + + Assert.That(command, Is.TypeOf(typeof(ApplyChangesToContextCommand))); + ApplyChangesToContextCommand applyChangesToContextCommand = (ApplyChangesToContextCommand)command; + + command = GetInnerCommand(applyChangesToContextCommand); + + Assert.That(command, Is.TypeOf(typeof(TestMethodCommand))); + } + + private TestCommand GetInnerCommand(DelegatingTestCommand command) + { + return (TestCommand)command.GetType().GetField("innerCommand", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(command); } [Test] From 30c4fe5d5212e45cda0559b0cace17352a6e680c Mon Sep 17 00:00:00 2001 From: Matthew Beardmore Date: Tue, 16 Oct 2018 22:31:13 -0400 Subject: [PATCH 051/174] Add comments to the EscapeInvalidXmlCharacters method. --- src/NUnitFramework/framework/Interfaces/TNode.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index 28ee7401a4..94f71870bf 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -323,8 +323,6 @@ private static string EscapeInvalidXmlCharacters(string str) { if (str == null) return null; - // Based on the XML spec http://www.w3.org/TR/xml/#charsets - StringBuilder builder = null; for (int i = 0; i < str.Length; i++) { @@ -335,6 +333,9 @@ private static string EscapeInvalidXmlCharacters(string str) if (builder != null) builder.Append(c); } + // From the XML specification: http://www.w3.org/TR/xml/#charsets + // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + // Any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. else if (!(0x0 <= c && c <= 0x8) && c != 0xB && c != 0xC && @@ -348,6 +349,8 @@ private static string EscapeInvalidXmlCharacters(string str) if (builder != null) builder.Append(c); } + // Also check if the char is actually a high/low surogate pair of two characters + // If it is, then it is a valid XML character (from above based on the surrogate blocks) else if (char.IsHighSurrogate(c) && i + 1 != str.Length && char.IsLowSurrogate(str[i + 1])) @@ -361,6 +364,10 @@ private static string EscapeInvalidXmlCharacters(string str) } else { + // We keep the builder null so that we don't allocate a string + // when doing this conversion until we encounter a unicode character + // Then, we allocate the rest of the string and escape the invalid + // character if (builder == null) { builder = new StringBuilder(); From 4fa0dfacc66b680ab7c688695a2ebda5b5917d4a Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Tue, 16 Oct 2018 22:31:34 -0400 Subject: [PATCH 052/174] Update src/NUnitFramework/framework/Interfaces/TNode.cs --- src/NUnitFramework/framework/Interfaces/TNode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index 94f71870bf..0903352f21 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -455,7 +455,7 @@ public bool Pass(TNode node) } } -#endregion + #endregion } /// From fb55f56d05ce7d1811348c050bcbaaf568c00ad4 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Wed, 17 Oct 2018 12:44:08 +0200 Subject: [PATCH 053/174] Minor nitpick --- src/NUnitFramework/framework/Interfaces/TNode.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index 0903352f21..0c7e558be1 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -349,8 +349,8 @@ private static string EscapeInvalidXmlCharacters(string str) if (builder != null) builder.Append(c); } - // Also check if the char is actually a high/low surogate pair of two characters - // If it is, then it is a valid XML character (from above based on the surrogate blocks) + // Also check if the char is actually a high/low surogate pair of two characters. + // If it is, then it is a valid XML character (from above based on the surrogate blocks). else if (char.IsHighSurrogate(c) && i + 1 != str.Length && char.IsLowSurrogate(str[i + 1])) @@ -365,9 +365,9 @@ private static string EscapeInvalidXmlCharacters(string str) else { // We keep the builder null so that we don't allocate a string - // when doing this conversion until we encounter a unicode character + // when doing this conversion until we encounter a unicode character. // Then, we allocate the rest of the string and escape the invalid - // character + // character. if (builder == null) { builder = new StringBuilder(); @@ -383,7 +383,7 @@ private static string EscapeInvalidXmlCharacters(string str) else return str; } - + private static string CharToUnicodeSequence(char symbol) { return string.Format("\\u{0}", ((int)symbol).ToString("x4")); From 5b75e5741baece7d382f9e10fa8a9bff2c54acab Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Tue, 23 Oct 2018 23:43:27 +0200 Subject: [PATCH 054/174] Compare element within ValueTuples with NUnitEqualityComparer ValueTuples implement IEquatable and we tried to compare using EquatablesComparer before ValueTupleComparer, so ValueTuples was compared using the standard semantics and not using NUnitEqualityComparer, so e.g. Dictionaries was compared using reference equality and not using DictionariesComparer. Note that the test for Tuples passed before this change as Tuples does not implement IEquatable. Fixes #3073 --- .../Constraints/NUnitEqualityComparer.cs | 2 +- .../tests/Assertions/CollectionAssertTest.cs | 16 ++++++++++++++++ .../tests/Constraints/TupleEqualityTests.cs | 9 +++++++++ .../tests/Constraints/ValueTupleEqualityTests.cs | 11 ++++++++++- 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs index 7c4a3f837d..04c8c92fe7 100644 --- a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs +++ b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs @@ -81,9 +81,9 @@ public NUnitEqualityComparer() new NumericsComparer(), new DateTimeOffsetsComparer(this), new TimeSpanToleranceComparer(), - new EquatablesComparer(this), new TupleComparer(this), new ValueTupleComparer(this), + new EquatablesComparer(this), enumerablesComparer }; } diff --git a/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs b/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs index b246cbfe17..9205a015dd 100644 --- a/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs +++ b/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs @@ -778,6 +778,22 @@ public void ValueTupleAreEqualFail() var ex = Assert.Throws(() => CollectionAssert.AreEqual(set1, set2, new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } + + [Test] + public void ElementsWithinTuplesAreComparedUsingNUnitEqualityComparer() + { + var a = new Dictionary>>() + { + { "key", ValueTuple.Create("name", new Dictionary())} + }; + + var b = new Dictionary>>() + { + { "key", ValueTuple.Create("name", new Dictionary())} + }; + + CollectionAssert.AreEquivalent(a, b); + } #endregion #endif } diff --git a/src/NUnitFramework/tests/Constraints/TupleEqualityTests.cs b/src/NUnitFramework/tests/Constraints/TupleEqualityTests.cs index 0cbce8eb12..51f4bcddd2 100644 --- a/src/NUnitFramework/tests/Constraints/TupleEqualityTests.cs +++ b/src/NUnitFramework/tests/Constraints/TupleEqualityTests.cs @@ -23,6 +23,7 @@ #if !NET20 && !NET35 using System; +using System.Collections.Generic; namespace NUnit.Framework.Constraints { @@ -88,6 +89,14 @@ public void FailsWhenContentOfTuplesAreDifferentWith8Elements() var tuple2 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 9); Assert.That(tuple1, Is.Not.EqualTo(tuple2)); } + + [Test] + public void TupleElementsAreComparedUsingNUnitEqualityComparer() + { + var a = Tuple.Create(new Dictionary()); + var b = Tuple.Create(new Dictionary()); + Assert.That(a, Is.EqualTo(b)); + } } } #endif diff --git a/src/NUnitFramework/tests/Constraints/ValueTupleEqualityTests.cs b/src/NUnitFramework/tests/Constraints/ValueTupleEqualityTests.cs index c81a9290e9..2ecbf13026 100644 --- a/src/NUnitFramework/tests/Constraints/ValueTupleEqualityTests.cs +++ b/src/NUnitFramework/tests/Constraints/ValueTupleEqualityTests.cs @@ -23,6 +23,7 @@ #if !NET20 && !NET35 using System; +using System.Collections.Generic; namespace NUnit.Framework.Constraints { @@ -88,6 +89,14 @@ public void FailsWhenContentOfTuplesAreDifferentWith8Elements() var tuple2 = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 9); Assert.That(tuple1, Is.Not.EqualTo(tuple2)); } + + [Test] + public void ValueTupleElementsAreComparedUsingNUnitEqualityComparer() + { + var a = ValueTuple.Create(new Dictionary()); + var b = ValueTuple.Create(new Dictionary()); + Assert.That(a, Is.EqualTo(b)); + } } } -#endif \ No newline at end of file +#endif From 4a448801c46b2d613b885ffb5295e827d8a76245 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 29 Oct 2018 22:07:19 -0400 Subject: [PATCH 055/174] Byte ranges fail when they end on a boundary --- .../tests/Attributes/RangeAttributeTests.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs index 4b9f15763c..503328da8f 100644 --- a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs @@ -349,6 +349,14 @@ public static void OpposingStepBackwardRangeDisallowed_Double() #region MaxValue + [Test] + public static void MaxValueRange_Byte() + { + Assert.That( + GetData(new RangeAttribute(byte.MaxValue - 2, byte.MaxValue), typeof(byte)), + Is.EqualTo(new[] { byte.MaxValue - 2, byte.MaxValue - 1, byte.MaxValue })); + } + [Test] public static void MaxValueRange_Int32() { @@ -439,6 +447,14 @@ public static void MaxValueRangeLosingPrecision_Decimal() #region MinValue + [Test] + public static void MinValueRange_Byte() + { + Assert.That( + GetData(new RangeAttribute(byte.MinValue + 2, byte.MinValue), typeof(byte)), + Is.EqualTo(new[] { byte.MinValue + 2, byte.MinValue + 1, byte.MinValue })); + } + [Test] public static void MinValueRange_Int32() { From a0b1bc2222f21159cad6cdd12ce90e3a2666d294 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 29 Oct 2018 22:31:45 -0400 Subject: [PATCH 056/174] Byte ranges no longer fail when they end on a boundary --- .../framework/Internal/ValueGenerator.ByteValueGenerator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ValueGenerator.ByteValueGenerator.cs b/src/NUnitFramework/framework/Internal/ValueGenerator.ByteValueGenerator.cs index 4478500ef9..a777a9c884 100644 --- a/src/NUnitFramework/framework/Internal/ValueGenerator.ByteValueGenerator.cs +++ b/src/NUnitFramework/framework/Internal/ValueGenerator.ByteValueGenerator.cs @@ -31,7 +31,7 @@ public override bool TryCreateStep(object value, out ValueGenerator.Step step) { if (value is byte) { - step = new ComparableStep((byte)value, (prev, stepValue) => unchecked((byte)(prev + stepValue))); + step = new ComparableStep((byte)value, (prev, stepValue) => checked((byte)(prev + stepValue))); return true; } @@ -40,7 +40,7 @@ public override bool TryCreateStep(object value, out ValueGenerator.Step step) // -1 can be converted natively to Int16, SByte and Decimal, so we can fall back on the automatic conversion for them. if (value is int) { - step = new ComparableStep((int)value, (prev, stepValue) => unchecked((byte)(prev + stepValue))); + step = new ComparableStep((int)value, (prev, stepValue) => checked((byte)(prev + stepValue))); return true; } From a14f17006ee10383fb71dd4b28dc46ee0ee24210 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 29 Oct 2018 23:15:05 -0400 Subject: [PATCH 057/174] Test remaining valid integer ranges ending on boundaries --- .../tests/Attributes/RangeAttributeTests.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs index 503328da8f..2f0485bdbb 100644 --- a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs @@ -357,6 +357,22 @@ public static void MaxValueRange_Byte() Is.EqualTo(new[] { byte.MaxValue - 2, byte.MaxValue - 1, byte.MaxValue })); } + [Test] + public static void MaxValueRange_SByte() + { + Assert.That( + GetData(new RangeAttribute(sbyte.MaxValue - 2, sbyte.MaxValue), typeof(sbyte)), + Is.EqualTo(new[] { sbyte.MaxValue - 2, sbyte.MaxValue - 1, sbyte.MaxValue })); + } + + [Test] + public static void MaxValueRange_Int16() + { + Assert.That( + GetData(new RangeAttribute(short.MaxValue - 2, short.MaxValue), typeof(short)), + Is.EqualTo(new[] { short.MaxValue - 2, short.MaxValue - 1, short.MaxValue })); + } + [Test] public static void MaxValueRange_Int32() { @@ -455,6 +471,22 @@ public static void MinValueRange_Byte() Is.EqualTo(new[] { byte.MinValue + 2, byte.MinValue + 1, byte.MinValue })); } + [Test] + public static void MinValueRange_SByte() + { + Assert.That( + GetData(new RangeAttribute(sbyte.MinValue + 2, sbyte.MinValue), typeof(sbyte)), + Is.EqualTo(new[] { sbyte.MinValue + 2, sbyte.MinValue + 1, sbyte.MinValue })); + } + + [Test] + public static void MinValueRange_Int16() + { + Assert.That( + GetData(new RangeAttribute(short.MinValue + 2, short.MinValue), typeof(short)), + Is.EqualTo(new[] { short.MinValue + 2, short.MinValue + 1, short.MinValue })); + } + [Test] public static void MinValueRange_Int32() { From 061f4355df785f52be4eb56c823ea839bccd8f82 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 4 Nov 2018 08:48:23 -0500 Subject: [PATCH 058/174] Removed NET20 compile output --- BUILDING.md | 4 +- build.cake | 17 ------ nuget/framework/nunit.nuspec | 7 +-- nuget/nunitlite/nunitlite.nuspec | 7 --- src/CommonAssemblyInfo.cs | 4 -- src/NUnitFramework/Directory.Build.props | 3 +- src/NUnitFramework/SchemaTestUtils.cs | 6 +-- .../framework/Api/FrameworkController.cs | 3 -- .../framework/Api/NUnitTestAssemblyRunner.cs | 6 +-- src/NUnitFramework/framework/Assert.That.cs | 11 +--- src/NUnitFramework/framework/Assume.cs | 10 +--- .../Attributes/TestFixtureAttribute.cs | 3 +- .../Compatibility/ReaderWriterLockSlim.cs | 52 ------------------- .../Compatibility/ReflectionExtensions.cs | 2 +- .../ConcurrentQueue.cs | 2 +- .../IProducerConsumerCollection.cs | 2 +- .../CollectionDebuggerView.cs | 2 +- .../System.Threading/LazyThreadSafetyMode.cs | 2 +- .../System.Threading/ManualResetEventSlim.cs | 2 +- .../System.Threading/SpinWait.cs | 2 +- .../System.Web.UI/ICallbackEventHandler.cs | 2 +- .../framework/Compatibility/System/Lazy.cs | 2 +- .../Constraints/UniqueItemsConstraint.cs | 2 +- .../framework/Internal/ExceptionHelper.cs | 4 +- .../Internal/Execution/CountdownEvent.cs | 2 +- .../Execution/ParallelWorkItemDispatcher.cs | 2 +- .../framework/Internal/Execution/WorkItem.cs | 2 +- .../framework/Internal/OSPlatform.cs | 2 +- .../framework/Internal/Reflect.cs | 4 +- .../framework/Internal/Results/TestResult.cs | 4 -- .../Internal/Results/TestSuiteResult.cs | 3 -- .../Internal/TestExecutionContext.cs | 6 +-- .../framework/Properties/AssemblyInfo.cs | 2 - src/NUnitFramework/framework/Warn.cs | 16 ------ .../framework/nunit.framework.csproj | 13 +---- .../mock-assembly/mock-assembly.csproj | 2 +- .../nunitlite-runner/nunitlite-runner.csproj | 2 +- .../nunitlite.tests/SchemaTests.cs | 6 +-- .../nunitlite.tests/nunitlite.tests.csproj | 2 +- .../nunitlite/Properties/AssemblyInfo.cs | 2 - src/NUnitFramework/nunitlite/nunitlite.csproj | 11 +--- .../slow-tests/slow-nunit-tests.csproj | 2 +- .../testdata/AssertMultipleData.cs | 4 +- src/NUnitFramework/testdata/WarningFixture.cs | 15 ------ .../testdata/nunit.testdata.csproj | 2 +- src/NUnitFramework/tests/Api/SchemaTests.cs | 6 +-- .../Assertions/AdhocTestExecutionTests.cs | 4 +- .../tests/Assertions/AssertThatTests.cs | 16 ------ .../tests/Assertions/AssertThrowsTests.cs | 2 - .../tests/Assertions/AssumeThatTests.cs | 12 ----- .../tests/Assertions/CollectionAssertTest.cs | 2 - .../tests/Assertions/LowTrustFixture.cs | 2 +- .../tests/Assertions/WarningTests.cs | 14 ----- .../CollectionEquivalentConstraintTests.cs | 2 +- .../DictionaryContainsKeyConstraintTests.cs | 8 +-- .../tests/Constraints/MsgUtilTests.cs | 2 +- .../tests/Constraints/TupleEqualityTests.cs | 2 +- .../Constraints/ValueTupleEqualityTests.cs | 4 +- .../tests/Internal/CallContextTests.cs | 3 +- .../Execution/ParallelExecutionTests.cs | 5 -- .../Internal/TestExecutionContextTests.cs | 4 +- .../tests/TestUtilities/StressUtility.cs | 4 +- .../tests/nunit.framework.tests.csproj | 8 +-- 63 files changed, 68 insertions(+), 293 deletions(-) delete mode 100644 src/NUnitFramework/framework/Compatibility/ReaderWriterLockSlim.cs diff --git a/BUILDING.md b/BUILDING.md index 20d3d8c795..a07f86646a 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -79,7 +79,7 @@ Feature constants are defined in [Directory.Build.props](src/NUnitFramework/Dire - `APARTMENT_STATE` enables control of the thread apartment state Platform constants are defined by convention by the csproj SDK, one per target framework. -For example, `NET20` or `NET45`, `NETSTANDARD1_6`, `NETCOREAPP2_0`, and so on. +For example, `NET45`, `NETSTANDARD1_6`, `NETCOREAPP2_0`, and so on. It is most helpful to call out which platforms are the exception in rather than the rule in a given scenario. Keep in mind the effect the preprocessor would have on a newly added platform. @@ -94,7 +94,7 @@ For example, rather than this code: Consider this: ```cs -#if !(NET20 || NET35 || NET40) +#if !(NET35 || NET40) // Something that .NET Framework 4.0 can't do #endif ``` diff --git a/build.cake b/build.cake index 9b50c8e331..c8b663b452 100644 --- a/build.cake +++ b/build.cake @@ -33,7 +33,6 @@ var AllFrameworks = new string[] "net45", "net40", "net35", - "net20", "netstandard1.4", "netstandard2.0" }; @@ -217,18 +216,6 @@ Task("Test35") RunTest(dir + EXECUTABLE_NUNITLITE_TESTS_EXE, dir, runtime, ref ErrorDetail); }); -Task("Test20") - .Description("Tests the .NET 2.0 version of the framework") - .IsDependentOn("Build") - .OnError(exception => { ErrorDetail.Add(exception.Message); }) - .Does(() => - { - var runtime = "net20"; - var dir = BIN_DIR + runtime + "/"; - RunNUnitTests(dir, FRAMEWORK_TESTS, runtime, ref ErrorDetail); - RunTest(dir + EXECUTABLE_NUNITLITE_TESTS_EXE, dir, runtime, ref ErrorDetail); - }); - Task("TestNetStandard14") .Description("Tests the .NET Standard 1.4 version of the framework") .IsDependentOn("Build") @@ -267,7 +254,6 @@ var RootFiles = new FilePath[] // Not all of these are present in every framework // The Microsoft and System assemblies are part of the BCL // used by the .NET 4.0 framework. 4.0 tests will not run without them. -// NUnit.System.Linq is only present for the .NET 2.0 build. var FrameworkFiles = new FilePath[] { "mock-assembly.dll", @@ -275,7 +261,6 @@ var FrameworkFiles = new FilePath[] "nunit.framework.dll", "nunit.framework.pdb", "nunit.framework.xml", - "NUnit.System.Linq.dll", "nunit.framework.tests.dll", "nunit.testdata.dll", "nunitlite.dll", @@ -368,7 +353,6 @@ Task("PackageZip") var zipFiles = GetFiles(CurrentImageDir + "*.*") + - GetFiles(CurrentImageDir + "bin/net20/**/*.*") + GetFiles(CurrentImageDir + "bin/net35/**/*.*") + GetFiles(CurrentImageDir + "bin/net40/**/*.*") + GetFiles(CurrentImageDir + "bin/net45/**/*.*") + @@ -513,7 +497,6 @@ Task("Test") .IsDependentOn("Test45") .IsDependentOn("Test40") .IsDependentOn("Test35") - .IsDependentOn("Test20") .IsDependentOn("TestNetStandard14") .IsDependentOn("TestNetStandard20"); diff --git a/nuget/framework/nunit.nuspec b/nuget/framework/nunit.nuspec index 11c9aea172..5fb1cf9c80 100644 --- a/nuget/framework/nunit.nuspec +++ b/nuget/framework/nunit.nuspec @@ -17,7 +17,7 @@ This package includes the NUnit 3 framework assembly, which is referenced by your tests. You will need to install version 3 of the nunit3-console program or a third-party runner that supports NUnit 3 in order to execute tests. Runners intended for use with NUnit 2.x will not run NUnit 3 tests correctly. Supported platforms: -- .NET Framework 2.0+ +- .NET Framework 3.5+ - .NET Standard 1.4+ - .NET Core This package includes the NUnit 3 framework assembly, which is referenced by your tests. You will need to install version 3 of the nunit3-console program or a third-party runner that supports NUnit 3 in order to execute tests. Runners intended for use with NUnit 2.x will not run NUnit 3 tests correctly. @@ -25,7 +25,6 @@ Supported platforms: nunit test testing tdd framework fluent assert theory plugin addin Copyright (c) 2018 Charlie Poole, Rob Prouse - @@ -42,10 +41,6 @@ Supported platforms: - - - - diff --git a/nuget/nunitlite/nunitlite.nuspec b/nuget/nunitlite/nunitlite.nuspec index bbc06b609e..1fd2102b65 100644 --- a/nuget/nunitlite/nunitlite.nuspec +++ b/nuget/nunitlite/nunitlite.nuspec @@ -28,9 +28,6 @@ How to use this package: test unit testing tdd framework fluent assert device phone embedded Copyright (c) 2018 Charlie Poole, Rob Prouse - - - @@ -55,8 +52,6 @@ How to use this package: - - @@ -67,8 +62,6 @@ How to use this package: - - diff --git a/src/CommonAssemblyInfo.cs b/src/CommonAssemblyInfo.cs index 0988974246..6f38ae5ab0 100644 --- a/src/CommonAssemblyInfo.cs +++ b/src/CommonAssemblyInfo.cs @@ -38,8 +38,6 @@ [assembly: AssemblyConfiguration(".NET Framework 4.0 Debug")] #elif NET35 [assembly: AssemblyConfiguration(".NET Framework 3.5 Debug")] -#elif NET20 -[assembly: AssemblyConfiguration(".NET Framework 2.0 Debug")] #elif NETSTANDARD1_4 [assembly: AssemblyConfiguration(".NET Standard 1.4 Debug")] #elif NETSTANDARD2_0 @@ -58,8 +56,6 @@ [assembly: AssemblyConfiguration(".NET Framework 4.0")] #elif NET35 [assembly: AssemblyConfiguration(".NET Framework 3.5")] -#elif NET20 -[assembly: AssemblyConfiguration(".NET Framework 2.0")] #elif NETSTANDARD1_4 [assembly: AssemblyConfiguration(".NET Standard 1.4")] #elif NETSTANDARD2_0 diff --git a/src/NUnitFramework/Directory.Build.props b/src/NUnitFramework/Directory.Build.props index b986a3a789..a6129293a6 100644 --- a/src/NUnitFramework/Directory.Build.props +++ b/src/NUnitFramework/Directory.Build.props @@ -22,8 +22,7 @@ $(DefineConstants);PARALLEL;SERIALIZATION - $(DefineConstants);ASYNC + $(DefineConstants);ASYNC . @@ -70,13 +69,11 @@ public static void That(bool condition, Func getExceptionMessage) { Assert.That(condition, Is.True, getExceptionMessage); } -#endif #endregion #region Lambda returning Boolean -#if !NET20 /// /// Asserts that a condition is true. If the condition is false the method throws /// an . @@ -109,7 +106,7 @@ public static void That(Func condition, Func getExceptionMessage) { Assert.That(condition.Invoke(), Is.True, getExceptionMessage); } -#endif + #endregion #region ActualValueDelegate @@ -145,7 +142,6 @@ public static void That(ActualValueDelegate del, IResolveConst ReportFailure(result, message, args); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. @@ -166,7 +162,6 @@ public static void That(ActualValueDelegate del, IResolveConst if (!result.IsSuccess) ReportFailure(result, getExceptionMessage()); } -#endif #endregion @@ -196,7 +191,6 @@ public static void That(TestDelegate code, IResolveConstraint constraint, string Assert.That((object)code, constraint, message, args); } -#if !NET20 /// /// Asserts that the code represented by a delegate throws an exception /// that satisfies the constraint provided. @@ -208,7 +202,6 @@ public static void That(TestDelegate code, IResolveConstraint constraint, Func(TActual actual, IResolveConstraint expression, ReportFailure(result, message, args); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an assertion exception on failure. @@ -268,7 +260,6 @@ public static void That(TActual actual, IResolveConstraint expression, if (!result.IsSuccess) ReportFailure(result, getExceptionMessage()); } -#endif #endregion diff --git a/src/NUnitFramework/framework/Assume.cs b/src/NUnitFramework/framework/Assume.cs index e3fb63f7c8..eb98f725d1 100644 --- a/src/NUnitFramework/framework/Assume.cs +++ b/src/NUnitFramework/framework/Assume.cs @@ -109,7 +109,6 @@ private static void ReportFailure(ConstraintResult result, string message, objec throw new InconclusiveException(writer.ToString()); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an InconclusiveException on failure. @@ -133,7 +132,6 @@ private static void ReportFailure(ConstraintResult result, string message, objec throw new InconclusiveException(getExceptionMessage()); } } -#endif #endregion @@ -161,7 +159,6 @@ public static void That(bool condition) Assume.That(condition, Is.True, null, null); } -#if !NET20 /// /// Asserts that a condition is true. If the condition is false the method throws /// an . @@ -172,13 +169,11 @@ public static void That(bool condition, Func getExceptionMessage) { Assume.That(condition, Is.True, getExceptionMessage); } -#endif #endregion #region Lambda returning Boolean -#if !NET20 /// /// Asserts that a condition is true. If the condition is false the method throws /// an . @@ -211,7 +206,6 @@ public static void That(Func condition, Func getExceptionMessage) { Assume.That(condition.Invoke(), Is.True, getExceptionMessage); } -#endif #endregion @@ -270,7 +264,6 @@ public static void That(TActual actual, IResolveConstraint expression, } } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and throwing an InconclusiveException on failure. @@ -294,7 +287,6 @@ public static void That(TActual actual, IResolveConstraint expression, throw new InconclusiveException(getExceptionMessage()); } } -#endif #endregion @@ -308,4 +300,4 @@ private static void CheckMultipleAssertLevel() #endregion } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs b/src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs index b7b2674d0e..22c83d7675 100644 --- a/src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestFixtureAttribute.cs @@ -46,8 +46,7 @@ public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder2, ITestFixtu /// /// Construct with a object[] representing a set of arguments. - /// In .NET 2.0, the arguments may later be separated into - /// type arguments and constructor arguments. + /// The arguments may later be separated into type arguments and constructor arguments. /// /// public TestFixtureAttribute(params object[] arguments) diff --git a/src/NUnitFramework/framework/Compatibility/ReaderWriterLockSlim.cs b/src/NUnitFramework/framework/Compatibility/ReaderWriterLockSlim.cs deleted file mode 100644 index 33fe2fdd51..0000000000 --- a/src/NUnitFramework/framework/Compatibility/ReaderWriterLockSlim.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Text; -using System.Threading; - -namespace NUnit.Compatibility -{ -#if NET20 - /// - /// - /// - public static class ReaderWriterLockExtensions - { - /// - /// - /// - /// - public static void EnterReadLock(this ReaderWriterLock rwLock) - { - rwLock.AcquireReaderLock(Timeout.Infinite); - } - - /// - /// - /// - /// - public static void EnterWriteLock(this ReaderWriterLock rwLock) - { - rwLock.AcquireWriterLock(Timeout.Infinite); - } - - /// - /// - /// - /// - public static void ExitReadLock(this ReaderWriterLock rwLock) - { - rwLock.ReleaseReaderLock(); - } - - /// - /// - /// - /// - public static void ExitWriteLock(this ReaderWriterLock rwLock) - { - rwLock.ReleaseWriterLock(); - } - } -#endif -} diff --git a/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs b/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs index f27b0d2f7d..a5475199d9 100644 --- a/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs +++ b/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if NET20 || NET35 || NET40 +#if NET35 || NET40 using System; using System.Reflection; diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs index 88445e252d..ffdc0e051d 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/ConcurrentQueue.cs @@ -1,7 +1,7 @@ // ReSharper disable InconsistentNaming // Disregarding naming convention in polyfill code -#if NET20 || NET35 +#if NET35 #pragma warning disable 0420 // ==++== diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/IProducerConsumerCollection.cs b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/IProducerConsumerCollection.cs index c025b0fc15..0077e2844b 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/IProducerConsumerCollection.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections.Concurrent/IProducerConsumerCollection.cs @@ -1,4 +1,4 @@ -#if NET20 || NET35 +#if NET35 // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs index 72547c3150..99fe620ea5 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs @@ -29,7 +29,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -#if NET20 || NET35 +#if NET35 using System; using System.Diagnostics; diff --git a/src/NUnitFramework/framework/Compatibility/System.Threading/LazyThreadSafetyMode.cs b/src/NUnitFramework/framework/Compatibility/System.Threading/LazyThreadSafetyMode.cs index 475c5f3ed7..8dbe2bca86 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Threading/LazyThreadSafetyMode.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Threading/LazyThreadSafetyMode.cs @@ -26,7 +26,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -#if NET20 || NET35 +#if NET35 using System; namespace System.Threading diff --git a/src/NUnitFramework/framework/Compatibility/System.Threading/ManualResetEventSlim.cs b/src/NUnitFramework/framework/Compatibility/System.Threading/ManualResetEventSlim.cs index 3bf3ea388c..3918294d20 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Threading/ManualResetEventSlim.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Threading/ManualResetEventSlim.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if NET20 || NET35 +#if NET35 namespace System.Threading { /// diff --git a/src/NUnitFramework/framework/Compatibility/System.Threading/SpinWait.cs b/src/NUnitFramework/framework/Compatibility/System.Threading/SpinWait.cs index 54be18d00e..fe931dfd86 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Threading/SpinWait.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Threading/SpinWait.cs @@ -1,4 +1,4 @@ -#if NET20 || NET35 +#if NET35 // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. diff --git a/src/NUnitFramework/framework/Compatibility/System.Web.UI/ICallbackEventHandler.cs b/src/NUnitFramework/framework/Compatibility/System.Web.UI/ICallbackEventHandler.cs index 04e79c8ad0..6395a1d8f5 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Web.UI/ICallbackEventHandler.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Web.UI/ICallbackEventHandler.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if !(NET20 || NET35 || NET40 || NET45) +#if !(NET35 || NET40 || NET45) namespace System.Web.UI { /// diff --git a/src/NUnitFramework/framework/Compatibility/System/Lazy.cs b/src/NUnitFramework/framework/Compatibility/System/Lazy.cs index bf1714f457..04bb4eaa01 100644 --- a/src/NUnitFramework/framework/Compatibility/System/Lazy.cs +++ b/src/NUnitFramework/framework/Compatibility/System/Lazy.cs @@ -29,7 +29,7 @@ // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -#if NET20 || NET35 +#if NET35 using System; using System.Runtime.Serialization; using System.Runtime.InteropServices; diff --git a/src/NUnitFramework/framework/Constraints/UniqueItemsConstraint.cs b/src/NUnitFramework/framework/Constraints/UniqueItemsConstraint.cs index ecf896e7a1..5723a58aa6 100644 --- a/src/NUnitFramework/framework/Constraints/UniqueItemsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/UniqueItemsConstraint.cs @@ -164,7 +164,7 @@ private Type GetGenericTypeArgument(IEnumerable actual) { if (type.FullName.StartsWith("System.Collections.Generic.IEnumerable`1")) { -#if NET20 || NET35 || NET40 +#if NET35 || NET40 return type.GetGenericArguments()[0]; #else return type.GenericTypeArguments[0]; diff --git a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs index 5960e6d7d5..1f4324ddb2 100644 --- a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs +++ b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs @@ -34,7 +34,7 @@ namespace NUnit.Framework.Internal /// public class ExceptionHelper { -#if NET20 || NET35 || NET40 +#if NET35 || NET40 private static readonly Action PreserveStackTrace; static ExceptionHelper() @@ -60,7 +60,7 @@ static ExceptionHelper() /// The exception to rethrow public static void Rethrow(Exception exception) { -#if NET20 || NET35 || NET40 +#if NET35 || NET40 PreserveStackTrace(exception); throw exception; #else diff --git a/src/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs b/src/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs index f4145db59b..20afac4985 100644 --- a/src/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs +++ b/src/NUnitFramework/framework/Internal/Execution/CountdownEvent.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if NET20 || NET35 +#if NET35 using System; using System.Threading; diff --git a/src/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs b/src/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs index d9c1d09118..cca50de7b4 100644 --- a/src/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs +++ b/src/NUnitFramework/framework/Internal/Execution/ParallelWorkItemDispatcher.cs @@ -349,7 +349,7 @@ private WorkShift SelectNextShift() #region ParallelScopeHelper Class -#if NET20 || NET35 +#if NET35 static class ParallelScopeHelper { public static bool HasFlag(this ParallelScope scope, ParallelScope value) diff --git a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs index c272ae104b..46f1c9d043 100644 --- a/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs +++ b/src/NUnitFramework/framework/Internal/Execution/WorkItem.cs @@ -571,7 +571,7 @@ static ApartmentState GetTargetApartment(ITest test) #endregion } -#if NET20 || NET35 +#if NET35 static class ActionTargetsExtensions { public static bool HasFlag(this ActionTargets targets, ActionTargets value) diff --git a/src/NUnitFramework/framework/Internal/OSPlatform.cs b/src/NUnitFramework/framework/Internal/OSPlatform.cs index d670b08be6..163b5d1fb1 100644 --- a/src/NUnitFramework/framework/Internal/OSPlatform.cs +++ b/src/NUnitFramework/framework/Internal/OSPlatform.cs @@ -73,7 +73,7 @@ public class OSPlatform /// - /// Platform ID for Unix as defined by Microsoft .NET 2.0 and greater + /// Platform ID for Unix as defined by .NET /// public static readonly PlatformID UnixPlatformID_Microsoft = (PlatformID)4; diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index ab0bbcb8db..540c26e517 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -25,7 +25,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -#if !(NET20 || NET35 || NETSTANDARD1_4) +#if !(NET35 || NETSTANDARD1_4) using System.Runtime.ExceptionServices; #endif using NUnit.Compatibility; @@ -258,7 +258,7 @@ public static object InvokeMethod(MethodInfo method, object fixture) /// The object on which to invoke the method /// The argument list for the method /// The return value from the invoked method -#if !(NET20 || NET35 || NETSTANDARD1_4) +#if !(NET35 || NETSTANDARD1_4) [HandleProcessCorruptedStateExceptions] //put here to handle C++ exceptions. #endif public static object InvokeMethod(MethodInfo method, object fixture, params object[] args) diff --git a/src/NUnitFramework/framework/Internal/Results/TestResult.cs b/src/NUnitFramework/framework/Internal/Results/TestResult.cs index 9074e5930e..1a547e43c5 100644 --- a/src/NUnitFramework/framework/Internal/Results/TestResult.cs +++ b/src/NUnitFramework/framework/Internal/Results/TestResult.cs @@ -83,11 +83,7 @@ public abstract class TestResult : LongLivedMarshalByRefObject, ITestResult /// /// ReaderWriterLock /// -#if NET20 - protected ReaderWriterLock RwLock = new ReaderWriterLock(); -#else protected ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); -#endif #endif #endregion diff --git a/src/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs b/src/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs index 3cc9721192..4b238457c7 100644 --- a/src/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs +++ b/src/NUnitFramework/framework/Internal/Results/TestSuiteResult.cs @@ -28,9 +28,6 @@ #endif using NUnit.Framework.Interfaces; using System.Threading; -#if NET20 -using NUnit.Compatibility; -#endif namespace NUnit.Framework.Internal { diff --git a/src/NUnitFramework/framework/Internal/TestExecutionContext.cs b/src/NUnitFramework/framework/Internal/TestExecutionContext.cs index 27ca0570ec..81291ae50e 100644 --- a/src/NUnitFramework/framework/Internal/TestExecutionContext.cs +++ b/src/NUnitFramework/framework/Internal/TestExecutionContext.cs @@ -37,7 +37,7 @@ using System.Security.Principal; #endif -#if NET20 || NET35 || NET40 || NET45 +#if NET35 || NET40 || NET45 using System.Runtime.Remoting.Messaging; #endif @@ -49,7 +49,7 @@ namespace NUnit.Framework.Internal /// or which might be changed by the user tests. /// public class TestExecutionContext : LongLivedMarshalByRefObject -#if NET20 || NET35 || NET40 || NET45 +#if NET35 || NET40 || NET45 , ILogicalThreadAffinative #endif { @@ -144,7 +144,7 @@ public TestExecutionContext(TestExecutionContext other) // NOTE: We use different implementations for various platforms. -#if !(NET20 || NET35 || NET40 || NET45) +#if !(NET35 || NET40 || NET45) private static readonly AsyncLocal _currentContext = new AsyncLocal(); /// /// Gets and sets the current context. diff --git a/src/NUnitFramework/framework/Properties/AssemblyInfo.cs b/src/NUnitFramework/framework/Properties/AssemblyInfo.cs index 4db23a4310..5e272dd133 100644 --- a/src/NUnitFramework/framework/Properties/AssemblyInfo.cs +++ b/src/NUnitFramework/framework/Properties/AssemblyInfo.cs @@ -56,8 +56,6 @@ [assembly: AssemblyTitle("NUnit Framework (.NET Framework 4.0)")] #elif NET35 [assembly: AssemblyTitle("NUnit Framework (.NET Framework 3.5)")] -#elif NET20 -[assembly: AssemblyTitle("NUnit Framework (.NET Framework 2.0)")] #elif NETSTANDARD1_4 [assembly: AssemblyTitle("NUnit Framework (.NET Standard 1.4)")] #elif NETSTANDARD2_0 diff --git a/src/NUnitFramework/framework/Warn.cs b/src/NUnitFramework/framework/Warn.cs index 51d3406f8d..f2fede2464 100644 --- a/src/NUnitFramework/framework/Warn.cs +++ b/src/NUnitFramework/framework/Warn.cs @@ -109,7 +109,6 @@ private static void IssueWarning(ConstraintResult result, string message, object Assert.Warn(writer.ToString()); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. @@ -131,7 +130,6 @@ private static void IssueWarning(ConstraintResult result, string message, object if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } -#endif #endregion @@ -157,7 +155,6 @@ public static void Unless(bool condition) Warn.Unless(condition, Is.True, null, null); } -#if !NET20 /// /// Asserts that a condition is true. If the condition is false a warning is issued. /// @@ -167,13 +164,11 @@ public static void Unless(bool condition, Func getExceptionMessage) { Warn.Unless(condition, Is.True, getExceptionMessage); } -#endif #endregion #region Lambda returning Boolean -#if !NET20 /// /// Asserts that a condition is true. If the condition is false the method throws /// an . @@ -206,7 +201,6 @@ public static void Unless(Func condition, Func getExceptionMessage { Warn.Unless(condition.Invoke(), Is.True, getExceptionMessage); } -#endif #endregion @@ -259,7 +253,6 @@ public static void Unless(TActual actual, IResolveConstraint expression IssueWarning(result, message, args); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. @@ -281,7 +274,6 @@ public static void Unless(TActual actual, IResolveConstraint expression if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } -#endif #endregion @@ -330,7 +322,6 @@ public static void If(ActualValueDelegate del, IResolveConstra // Assert.Warn(writer.ToString()); //} -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// fails and issuing a warning on failure. @@ -352,7 +343,6 @@ public static void If(ActualValueDelegate del, IResolveConstra if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } -#endif #endregion @@ -378,7 +368,6 @@ public static void If(bool condition) Warn.If(condition, Is.True, null, null); } -#if !NET20 /// /// Asserts that a condition is true. If the condition is false a warning is issued. /// @@ -388,13 +377,11 @@ public static void If(bool condition, Func getExceptionMessage) { Warn.If(condition, Is.True, getExceptionMessage); } -#endif #endregion #region Lambda returning Boolean -#if !NET20 /// /// Asserts that a condition is false. If the condition is true a warning is issued. /// @@ -424,7 +411,6 @@ public static void If(Func condition, Func getExceptionMessage) { Warn.If(condition.Invoke(), Is.True, getExceptionMessage); } -#endif #endregion @@ -462,7 +448,6 @@ public static void If(TActual actual, IResolveConstraint expression, st IssueWarning(result, message, args); } -#if !NET20 /// /// Apply a constraint to an actual value, succeeding if the constraint /// is satisfied and issuing a warning on failure. @@ -484,7 +469,6 @@ public static void If(TActual actual, IResolveConstraint expression, st if (!result.IsSuccess) IssueWarning(result, getExceptionMessage(), null); } -#endif #endregion diff --git a/src/NUnitFramework/framework/nunit.framework.csproj b/src/NUnitFramework/framework/nunit.framework.csproj index 3ba2ffe322..fc8c8b333d 100644 --- a/src/NUnitFramework/framework/nunit.framework.csproj +++ b/src/NUnitFramework/framework/nunit.framework.csproj @@ -1,20 +1,11 @@  - net20;net35;net40;net45;netstandard1.4;netstandard2.0 + net35;net40;net45;netstandard1.4;netstandard2.0 NUnit.Framework true - - full - true - - - - - - @@ -26,7 +17,7 @@ - + diff --git a/src/NUnitFramework/mock-assembly/mock-assembly.csproj b/src/NUnitFramework/mock-assembly/mock-assembly.csproj index e8c75fb8cc..3ce7bbbff9 100644 --- a/src/NUnitFramework/mock-assembly/mock-assembly.csproj +++ b/src/NUnitFramework/mock-assembly/mock-assembly.csproj @@ -1,7 +1,7 @@  - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + net35;net40;net45;netcoreapp1.1;netcoreapp2.0 NUnit.Tests diff --git a/src/NUnitFramework/nunitlite-runner/nunitlite-runner.csproj b/src/NUnitFramework/nunitlite-runner/nunitlite-runner.csproj index 11c2870f00..9a70a7dfb4 100644 --- a/src/NUnitFramework/nunitlite-runner/nunitlite-runner.csproj +++ b/src/NUnitFramework/nunitlite-runner/nunitlite-runner.csproj @@ -1,7 +1,7 @@  - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + net35;net40;net45;netcoreapp1.1;netcoreapp2.0 Exe NUnitLite diff --git a/src/NUnitFramework/nunitlite.tests/SchemaTests.cs b/src/NUnitFramework/nunitlite.tests/SchemaTests.cs index 04afd9d309..8c9be5b4c6 100644 --- a/src/NUnitFramework/nunitlite.tests/SchemaTests.cs +++ b/src/NUnitFramework/nunitlite.tests/SchemaTests.cs @@ -22,9 +22,9 @@ // *********************************************************************** -#if !NETCOREAPP1_1 // Schema validation doesn’t exist -#if !(NET20 || NET35) // Framework bug causes NRE: https://social.msdn.microsoft.com/Forums/en-US/53be44de-30b2-4d18-968d-d3414d0783b1 - // We don’t really need these tests to run on more than one platform. +#if !NETCOREAPP1_1 // Schema validation doesn’t exist +#if !NET35 // Framework bug causes NRE: https://social.msdn.microsoft.com/Forums/en-US/53be44de-30b2-4d18-968d-d3414d0783b1 + // We don’t really need these tests to run on more than one platform. using System.Collections.Generic; using System.IO; diff --git a/src/NUnitFramework/nunitlite.tests/nunitlite.tests.csproj b/src/NUnitFramework/nunitlite.tests/nunitlite.tests.csproj index 665abedd0e..e79407c21e 100644 --- a/src/NUnitFramework/nunitlite.tests/nunitlite.tests.csproj +++ b/src/NUnitFramework/nunitlite.tests/nunitlite.tests.csproj @@ -1,7 +1,7 @@ - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + net35;net40;net45;netcoreapp1.1;netcoreapp2.0 Exe NUnitLite.Tests Full diff --git a/src/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs b/src/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs index 0da4638e91..2bb2aa2b52 100644 --- a/src/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs +++ b/src/NUnitFramework/nunitlite/Properties/AssemblyInfo.cs @@ -38,8 +38,6 @@ [assembly: AssemblyTitle("NUnitLite Runner (.NET Framework 4.0)")] #elif NET35 [assembly: AssemblyTitle("NUnitLite Runner (.NET Framework 3.5)")] -#elif NET20 -[assembly: AssemblyTitle("NUnitLite Runner (.NET Framework 2.0)")] #elif NETSTANDARD1_4 [assembly: AssemblyTitle("NUnitLite Runner (.NET Standard 1.4)")] #elif NETSTANDARD2_0 diff --git a/src/NUnitFramework/nunitlite/nunitlite.csproj b/src/NUnitFramework/nunitlite/nunitlite.csproj index 1f016905e5..f43b7d270a 100644 --- a/src/NUnitFramework/nunitlite/nunitlite.csproj +++ b/src/NUnitFramework/nunitlite/nunitlite.csproj @@ -1,23 +1,14 @@  - net20;net35;net40;net45;netstandard1.4;netstandard2.0 + net35;net40;net45;netstandard1.4;netstandard2.0 NUnitLite - - full - true - - - - - - diff --git a/src/NUnitFramework/slow-tests/slow-nunit-tests.csproj b/src/NUnitFramework/slow-tests/slow-nunit-tests.csproj index 9c340f663e..42681b37db 100644 --- a/src/NUnitFramework/slow-tests/slow-nunit-tests.csproj +++ b/src/NUnitFramework/slow-tests/slow-nunit-tests.csproj @@ -1,7 +1,7 @@  - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + net35;net40;net45;netcoreapp1.1;netcoreapp2.0 NUnit.Tests diff --git a/src/NUnitFramework/testdata/AssertMultipleData.cs b/src/NUnitFramework/testdata/AssertMultipleData.cs index 318c4ba80b..fbb03538ac 100644 --- a/src/NUnitFramework/testdata/AssertMultipleData.cs +++ b/src/NUnitFramework/testdata/AssertMultipleData.cs @@ -11,8 +11,8 @@ namespace NUnit.TestData.AssertMultipleData { // NOTE: Some of these methods were getting optimized out of - // existence in the .NET 2.0 AppVeyor build. For that reason, - // we turned optimization off for the testdata assembly. + // existence in the AppVeyor build. For that reason, we turned + // optimization off for the testdata assembly. public class AssertMultipleFixture { diff --git a/src/NUnitFramework/testdata/WarningFixture.cs b/src/NUnitFramework/testdata/WarningFixture.cs index 75a1797772..ba8014387e 100644 --- a/src/NUnitFramework/testdata/WarningFixture.cs +++ b/src/NUnitFramework/testdata/WarningFixture.cs @@ -77,7 +77,6 @@ public void WarnIf_Passes_BooleanWithMessageAndArgs() Warn.If(2 + 2 != 4, "Not Equal to {0}", 4); } -#if !NET20 [Test] public void WarnUnless_Passes_BooleanWithMessageStringFunc() { @@ -141,7 +140,6 @@ public void WarnIf_Passes_BooleanLambdaWithWithMessageStringFunc() Func getExceptionMessage = () => string.Format("Not Equal to {0}", 4); Warn.If(() => 2 + 2 != 4, getExceptionMessage); } -#endif [Test] public void WarnUnless_Passes_ActualAndConstraint() @@ -179,7 +177,6 @@ public void WarnIf_Passes_ActualAndConstraintWithMessageAndArgs() Warn.If(2 + 2, Is.Not.EqualTo(4), "Should be {0}", 4); } -#if !NET20 [Test] public void WarnUnless_Passes_ActualAndConstraintWithMessageStringFunc() { @@ -243,7 +240,6 @@ public void WarnIf_Passes_ActualLambdaAndConstraintWithMessageStringFunc() Func getExceptionMessage = () => string.Format("Not Equal to {0}", 4); Warn.If(() => 2 + 2, Is.Not.EqualTo(4), getExceptionMessage); } -#endif [Test] public void WarnUnless_Passes_DelegateAndConstraint() @@ -281,7 +277,6 @@ public void WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs() Warn.If(new ActualValueDelegate(ReturnsFour), Is.Not.EqualTo(4), "Should be {0}", 4); } -#if !NET20 [Test] public void WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc() { @@ -295,7 +290,6 @@ public void WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc() Func getExceptionMessage = () => string.Format("Not Equal to {0}", 4); Warn.If(new ActualValueDelegate(ReturnsFour), Is.Not.EqualTo(4), getExceptionMessage); } -#endif #if ASYNC [Test] @@ -363,7 +357,6 @@ public void WarnIf_Fails_BooleanWithMessageAndArgs() Warn.If(2 + 2 != 5, "got {0}", 5); } -#if !NET20 [Test] public void WarnUnless_Fails_BooleanWithMessageStringFunc() { @@ -427,7 +420,6 @@ public void WarnIf_Fails_BooleanLambdaWithMessageStringFunc() Func getExceptionMessage = () => "got 5"; Warn.If(() => 2 + 2 != 5, getExceptionMessage); } -#endif [Test] public void WarnUnless_Fails_ActualAndConstraint() @@ -465,7 +457,6 @@ public void WarnIf_Fails_ActualAndConstraintWithMessageAndArgs() Warn.If(2 + 2, Is.Not.EqualTo(5), "Should be {0}", 5); } -#if !NET20 [Test] public void WarnUnless_Fails_ActualAndConstraintWithMessageStringFunc() { @@ -529,7 +520,6 @@ public void WarnIf_Fails_ActualLambdaAndConstraintWithMessageStringFunc() Func getExceptionMessage = () => "Should be 5"; Warn.If(() => 2 + 2, Is.Not.EqualTo(5), getExceptionMessage); } -#endif [Test] public void WarnUnless_Fails_DelegateAndConstraint() @@ -567,7 +557,6 @@ public void WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs() Warn.If(new ActualValueDelegate(ReturnsFive), Is.Not.EqualTo(4), "Should be {0}", 4); } -#if !NET20 [Test] public void WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc() { @@ -581,7 +570,6 @@ public void WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc() Func getExceptionMessage = () => "Should be 4"; Warn.If(new ActualValueDelegate(ReturnsFive), Is.Not.EqualTo(4), getExceptionMessage); } -#endif #if ASYNC [Test] @@ -656,9 +644,6 @@ public static void WarningSynchronous() Assert.Warn("(Warning message)"); } -#if NET20 - private delegate void Action(); -#endif [Test] public static void WarningInBeginInvoke() { diff --git a/src/NUnitFramework/testdata/nunit.testdata.csproj b/src/NUnitFramework/testdata/nunit.testdata.csproj index 016a887cac..4735133493 100644 --- a/src/NUnitFramework/testdata/nunit.testdata.csproj +++ b/src/NUnitFramework/testdata/nunit.testdata.csproj @@ -1,7 +1,7 @@  - net20;net35;net40;net45;netcoreapp1.1;netcoreapp2.0 + net35;net40;net45;netcoreapp1.1;netcoreapp2.0 NUnit.TestData System.Exception : Inner Exception 1 of 2" + Environment.NewLine + " ----> System.Exception : Inner Exception 2 of 2"; @@ -79,18 +75,15 @@ public void FailRecordsInnerExceptionsAsPartOfAggregateException() "ThrowsWithAggregateException"); Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.AreEqual(expectedMessage, result.Message); + Assert.That(result.Message, Does.StartWith(expectedStartOfMessage)); + Assert.That(result.Message, Does.EndWith(expectedEndOfMessage)); } [Test] public void FailRecordsNestedInnerExceptionAsPartOfAggregateException() { - string expectedMessage = -#if NETCOREAPP1_1 || NETCOREAPP2_0 - "System.AggregateException : Outer Aggregate Exception (Inner Exception)" + Environment.NewLine + -#else - "System.AggregateException : Outer Aggregate Exception" + Environment.NewLine + -#endif + string expectedStartOfMessage = "System.AggregateException : Outer Aggregate Exception"; + string expectedEndOfMessage = " ----> System.Exception : Inner Exception" + Environment.NewLine + " ----> System.Exception : Inner Inner Exception"; @@ -99,7 +92,8 @@ public void FailRecordsNestedInnerExceptionAsPartOfAggregateException() "ThrowsWithAggregateExceptionContainingNestedInnerException"); Assert.AreEqual(ResultState.Error, result.ResultState); - Assert.AreEqual(expectedMessage, result.Message); + Assert.That(result.Message, Does.StartWith(expectedStartOfMessage)); + Assert.That(result.Message, Does.EndWith(expectedEndOfMessage)); } #endif From 59af7839e798cea719b96c8273666131a20ae4af Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sat, 9 Feb 2019 22:55:10 -0500 Subject: [PATCH 103/174] Update links to HTTPS --- .editorconfig | 2 +- BUILDING.md | 6 ++--- CODE_OF_CONDUCT.md | 6 ++--- README.md | 2 +- .../CollectionDebuggerView.cs | 2 +- .../Constraints/FloatingPointNumerics.cs | 2 +- .../framework/Interfaces/TNode.cs | 2 +- .../Internal/Builders/PairwiseStrategy.cs | 4 +-- .../framework/Internal/OSPlatform.cs | 2 +- src/NUnitFramework/nunitlite/Options.cs | 2 +- .../tests/Attributes/PairwiseTests.cs | 2 +- .../tests/Constraints/ToStringTests.cs | 27 +++++++++++++++---- .../tests/Internal/SetUpFixtureTests.cs | 27 +++++++++++++++---- 13 files changed, 60 insertions(+), 26 deletions(-) diff --git a/.editorconfig b/.editorconfig index 86db43bd0e..cc01134170 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,7 +2,7 @@ # maintain consistent coding styles between # different editors and IDEs -# http://EditorConfig.org +# https://editorconfig.org # top-most EditorConfig file root = true diff --git a/BUILDING.md b/BUILDING.md index a07f86646a..1dabf601bf 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -1,6 +1,6 @@ # Building NUnit 3 -NUnit 3 consists of three separate layers: the Framework, the Engine and the Console Runner. The source code is kept in two GitHub repositories at http://github.com/nunit/nunit and http://github.com/nunit/nunit-console. +NUnit 3 consists of three separate layers: the Framework, the Engine and the Console Runner. The source code is kept in two GitHub repositories at https://github.com/nunit/nunit and https://github.com/nunit/nunit-console. There are two ways to build NUnit: using the solution file in an IDE or through the build script. See also [Building and testing for Linux on a Windows machine](#building-and-testing-for-linux-on-a-windows-machine). @@ -8,7 +8,7 @@ There are two ways to build NUnit: using the solution file in an IDE or through The framework is built using a single Visual Studio solution, `nunit.sln`, which may be built with [Visual Studio 2017](https://www.visualstudio.com/vs/) on Windows and [Visual Studio for Mac](https://www.visualstudio.com/vs/) on macOS. Currently, MonoDevelop does not support the new multi-targeted `csproj` project format. Once MonoDevelop is updated, it should start working again. Until then, we recommend [Visual Studio Code](https://code.visualstudio.com/) and compiling using the build scripts on non-Windows platforms. -On all platforms, you will need to install [.NET Core 2.0.3 SDK](https://www.microsoft.com/net/download/windows) or newer. On Mac or Linux, you will need to install [Mono 5.2.0](http://www.mono-project.com/download/). Currently (as of 5.4.1), newer versions of Mono are broken and crash during the compile. +On all platforms, you will need to install [.NET Core 2.0.3 SDK](https://www.microsoft.com/net/download/windows) or newer. On Mac or Linux, you will need to install [Mono 5.2.0](https://www.mono-project.com/download/). Currently (as of 5.4.1), newer versions of Mono are broken and crash during the compile. The solutions all place their output in a common bin directory under the solution root. @@ -23,7 +23,7 @@ Other test projects contain tests designed to fail purposely for integration tes ## Build Script -We use [Cake](http://cakebuild.net) to build NUnit for distribution. The primary script that controls building, running tests and packaging is build.cake. We modify build.cake when we need to add new targets or change the way the build is done. Normally build.cake is not invoked directly but through build.ps1 (on Windows) or build.sh (on Linux). These two scripts are provided by the Cake project and ensure that Cake is properly installed before trying to run the cake script. This helps the build to work on CI servers using newly created agents to run the build and we generally run it the same way on our own machines. +We use [Cake](https://cakebuild.net) to build NUnit for distribution. The primary script that controls building, running tests and packaging is build.cake. We modify build.cake when we need to add new targets or change the way the build is done. Normally build.cake is not invoked directly but through build.ps1 (on Windows) or build.sh (on Linux). These two scripts are provided by the Cake project and ensure that Cake is properly installed before trying to run the cake script. This helps the build to work on CI servers using newly created agents to run the build and we generally run it the same way on our own machines. The build shell script and build.cmd script are provided as an easy way to run the above commands. In addition to passing their arguments through to build.cake, they can supply added arguments through the CAKE_ARGS environment variable. The rest of this document will assume use of these commands. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index abf4262b52..bc55002c25 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -40,7 +40,7 @@ Project maintainers who do not follow or enforce the Code of Conduct in good fai ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://contributor-covenant.org/version/1/4][version] -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ +[homepage]: https://contributor-covenant.org +[version]: https://contributor-covenant.org/version/1/4/ diff --git a/README.md b/README.md index 21ef09eb01..d044e2aeca 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ set breakpoints and watch variables, [follow these steps](https://github.com/nun ## License ## -NUnit is Open Source software and NUnit 3 is released under the [MIT license](https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt). Earlier releases used the [NUnit license](http://www.nunit.org/nuget/license.html). Both of these licenses allow the use of NUnit in free and commercial applications and libraries without restrictions. +NUnit is Open Source software and NUnit 3 is released under the [MIT license](https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt). Earlier releases used the [NUnit license](https://nunit.org/nuget/license.html). Both of these licenses allow the use of NUnit in free and commercial applications and libraries without restrictions. ## NUnit Projects ## diff --git a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs index 99fe620ea5..a667bf6ae8 100644 --- a/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs +++ b/src/NUnitFramework/framework/Compatibility/System.Collections/CollectionDebuggerView.cs @@ -7,7 +7,7 @@ // Authors: // Marek Safar // -// Copyright (C) 2009 Novell, Inc (http://www.novell.com) +// Copyright (C) 2009 Novell, Inc (https://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the diff --git a/src/NUnitFramework/framework/Constraints/FloatingPointNumerics.cs b/src/NUnitFramework/framework/Constraints/FloatingPointNumerics.cs index d8821db599..d653fd5cce 100644 --- a/src/NUnitFramework/framework/Constraints/FloatingPointNumerics.cs +++ b/src/NUnitFramework/framework/Constraints/FloatingPointNumerics.cs @@ -30,7 +30,7 @@ namespace NUnit.Framework.Constraints /// /// /// The floating point comparison code is based on this excellent article: - /// http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm + /// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ /// /// /// "ULP" means Unit in the Last Place and in the context of this library refers to diff --git a/src/NUnitFramework/framework/Interfaces/TNode.cs b/src/NUnitFramework/framework/Interfaces/TNode.cs index 8fd297e3e1..8852c7dfea 100644 --- a/src/NUnitFramework/framework/Interfaces/TNode.cs +++ b/src/NUnitFramework/framework/Interfaces/TNode.cs @@ -335,7 +335,7 @@ private static string EscapeInvalidXmlCharacters(string str) if (builder != null) builder.Append(c); } - // From the XML specification: http://www.w3.org/TR/xml/#charsets + // From the XML specification: https://www.w3.org/TR/xml/#charsets // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // Any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. else if (!(0x0 <= c && c <= 0x8) && diff --git a/src/NUnitFramework/framework/Internal/Builders/PairwiseStrategy.cs b/src/NUnitFramework/framework/Internal/Builders/PairwiseStrategy.cs index 2f1a5404bf..2797d8ac0d 100644 --- a/src/NUnitFramework/framework/Internal/Builders/PairwiseStrategy.cs +++ b/src/NUnitFramework/framework/Internal/Builders/PairwiseStrategy.cs @@ -45,7 +45,7 @@ namespace NUnit.Framework.Internal.Builders /// /// /// The PairwiseStrategy code is based on "jenny" tool by Bob Jenkins: - /// http://burtleburtle.net/bob/math/jenny.html + /// https://burtleburtle.net/bob/math/jenny.html /// /// public class PairwiseStrategy : ICombiningStrategy @@ -60,7 +60,7 @@ public class PairwiseStrategy : ICombiningStrategy /// /// FleaRand is a pseudo-random number generator developed by Bob Jenkins: - /// http://burtleburtle.net/bob/rand/talksmall.html#flea + /// https://burtleburtle.net/bob/rand/talksmall.html#flea /// internal class FleaRand { diff --git a/src/NUnitFramework/framework/Internal/OSPlatform.cs b/src/NUnitFramework/framework/Internal/OSPlatform.cs index 163b5d1fb1..260aefede0 100644 --- a/src/NUnitFramework/framework/Internal/OSPlatform.cs +++ b/src/NUnitFramework/framework/Internal/OSPlatform.cs @@ -61,7 +61,7 @@ public class OSPlatform } else if (CheckIfIsMacOSX(os.Platform)) { - // Mono returns PlatformID.Unix for OSX (see http://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform) + // Mono returns PlatformID.Unix for OSX (see https://www.mono-project.com/docs/faq/technical/#how-to-detect-the-execution-platform) // The above check uses uname to confirm it is MacOSX and we change the PlatformId here. currentPlatform = new OSPlatform(PlatformID.MacOSX, os.Version); } diff --git a/src/NUnitFramework/nunitlite/Options.cs b/src/NUnitFramework/nunitlite/Options.cs index 364ecd226e..6c0cf17029 100644 --- a/src/NUnitFramework/nunitlite/Options.cs +++ b/src/NUnitFramework/nunitlite/Options.cs @@ -4,7 +4,7 @@ // Authors: // Jonathan Pryor // -// Copyright (C) 2008 Novell (http://www.novell.com) +// Copyright (C) 2008 Novell (https://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the diff --git a/src/NUnitFramework/tests/Attributes/PairwiseTests.cs b/src/NUnitFramework/tests/Attributes/PairwiseTests.cs index 315c8ed5ab..ae22c6f503 100644 --- a/src/NUnitFramework/tests/Attributes/PairwiseTests.cs +++ b/src/NUnitFramework/tests/Attributes/PairwiseTests.cs @@ -65,7 +65,7 @@ public void OneTimeTearDown() // Test data is taken from various sources. See "Lessons Learned // in Software Testing" pp 53-59, for example. For orthogonal cases, see - // http://www.freequality.org/sites/www_freequality_org/documents/tools/Tagarray_files/tamatrix.htm + // https://web.archive.org/web/20100305233703/www.freequality.org/sites/www_freequality_org/documents/tools/Tagarray_files/tamatrix.htm static internal object[] cases = new object[] { new TestCaseData( new int[] { 2, 4 }, 8, 8 ).SetName("Test 2x4"), diff --git a/src/NUnitFramework/tests/Constraints/ToStringTests.cs b/src/NUnitFramework/tests/Constraints/ToStringTests.cs index 497571d014..2c4aa50f5c 100644 --- a/src/NUnitFramework/tests/Constraints/ToStringTests.cs +++ b/src/NUnitFramework/tests/Constraints/ToStringTests.cs @@ -1,8 +1,25 @@ -// **************************************************************** -// Copyright 2010, Charlie Poole, Rob Prouse -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** +// *********************************************************************** +// Copyright (c) 2010 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** using System; diff --git a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs index e1eccdd484..192845c68f 100644 --- a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs +++ b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs @@ -1,8 +1,25 @@ -// **************************************************************** -// Copyright 2007, Charlie Poole, Rob Prouse -// This is free software licensed under the NUnit license. You may -// obtain a copy of the license at http://nunit.org -// **************************************************************** +// *********************************************************************** +// Copyright (c) 2007 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** using System.Collections.Generic; using System.Reflection; From 55be0bf35bda92621514ec834d4beb3a93b5183e Mon Sep 17 00:00:00 2001 From: Julian Verdurmen <304NotModified@users.noreply.github.com> Date: Sun, 10 Feb 2019 17:27:58 +0100 Subject: [PATCH 104/174] nunit.org url to https (#3160) --- nuget/framework/nunit.nuspec | 2 +- nuget/nunitlite/nunitlite.nuspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuget/framework/nunit.nuspec b/nuget/framework/nunit.nuspec index 5fb1cf9c80..2f4b0444a4 100644 --- a/nuget/framework/nunit.nuspec +++ b/nuget/framework/nunit.nuspec @@ -7,7 +7,7 @@ Charlie Poole, Rob Prouse Charlie Poole, Rob Prouse https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt - http://nunit.org + https://nunit.org https://cdn.rawgit.com/nunit/resources/master/images/icon/nunit_256.png false diff --git a/nuget/nunitlite/nunitlite.nuspec b/nuget/nunitlite/nunitlite.nuspec index 1fd2102b65..77e717cc02 100644 --- a/nuget/nunitlite/nunitlite.nuspec +++ b/nuget/nunitlite/nunitlite.nuspec @@ -7,7 +7,7 @@ Charlie Poole, Rob Prouse Charlie Poole, Rob Prouse https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt - http://nunit.org + https://nunit.org https://cdn.rawgit.com/nunit/resources/master/images/icon/nunit_256.png false From 70fb2913b744621749fcff0c8132064f314aac54 Mon Sep 17 00:00:00 2001 From: Joseph Musser Date: Mon, 11 Feb 2019 17:55:49 -0500 Subject: [PATCH 105/174] Autodetect indentation for all but C# files (#3164) --- .editorconfig | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.editorconfig b/.editorconfig index cc01134170..a042fda14d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,14 +9,11 @@ root = true [*] indent_style = space -indent_size = 4 insert_final_newline = true charset = utf-8 -[*.{proj,csproj,vcxproj,xproj,json,config,nuspec,xml,xsd,yml}] -indent_size = 2 - - +[*.{cs,cake}] +indent_size = 4 [*] # https://github.com/nunit/docs/wiki/Coding-Standards#namespace-class-structure-interface-enumeration-and-method-definitions From 8ffc376f51bb28adc1cdf72901e86bdc90ffcbe3 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Sat, 24 Nov 2018 08:01:29 -0500 Subject: [PATCH 106/174] Use TypeConverter when can't use Convert Add tests Add TypeConverter for netstandard 1.4 --- .../framework/Attributes/TestCaseAttribute.cs | 6 +++--- .../framework/nunit.framework.csproj | 3 ++- .../Attributes/TestCaseAttributeTests.cs | 21 +++++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs index 6df3657995..664e42e518 100644 --- a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs @@ -431,10 +431,10 @@ private static bool PerformSpecialConversion(object arg, Type targetType, out ob return true; } - // Convert.ChangeType doesn't work for TimeSpan from string - if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string) + var converter = System.ComponentModel.TypeDescriptor.GetConverter(targetType); + if (converter.CanConvertFrom(arg.GetType())) { - argAsTargetType = TimeSpan.Parse((string)arg); + argAsTargetType = converter.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, arg); return true; } diff --git a/src/NUnitFramework/framework/nunit.framework.csproj b/src/NUnitFramework/framework/nunit.framework.csproj index fc8c8b333d..0059668395 100644 --- a/src/NUnitFramework/framework/nunit.framework.csproj +++ b/src/NUnitFramework/framework/nunit.framework.csproj @@ -1,4 +1,4 @@ - + net35;net40;net45;netstandard1.4;netstandard2.0 @@ -12,6 +12,7 @@ + diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index 8b5123cce8..719d3ecf95 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -142,6 +142,27 @@ public TimeSpan CanConvertExpectedResultStringToTimeSpan(TimeSpan ts) return ts; } + [TestCase("2018-10-09 15:15:00+02:30")] + public void CanConvertStringToDateTimeOffset(DateTimeOffset offset) + { + Assert.AreEqual(2018, offset.Year); + Assert.AreEqual(10, offset.Month); + Assert.AreEqual(9, offset.Day); + + Assert.AreEqual(15, offset.Hour); + Assert.AreEqual(15, offset.Minute); + Assert.AreEqual(0, offset.Second); + + Assert.AreEqual(2, offset.Offset.Hours); + Assert.AreEqual(30, offset.Offset.Minutes); + } + + [TestCase("2018-10-09 15:15:00+02:30", ExpectedResult = "2018-10-09 15:15:00+02:30")] + public DateTimeOffset CanConvertExpectedResultStringToDateTimeOffset(DateTimeOffset offset) + { + return offset; + } + [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { From efe9765764a57db84daff389487987d908d13aaf Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 26 Nov 2018 13:16:11 -0500 Subject: [PATCH 107/174] Update test case attributes --- .../framework/Attributes/TestCaseAttribute.cs | 23 ++++++++++---- .../Attributes/TestCaseAttributeTests.cs | 30 +++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs index 664e42e518..e98934bb7a 100644 --- a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs @@ -263,7 +263,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; - + parms = new TestCaseParameters(this); // Special handling for ExpectedResult (see if it needs to be converted into method return type) @@ -288,7 +288,9 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1])) { Array array = Array.CreateInstance(elementType, 1); - array.SetValue(parms.Arguments[argsProvided - 1], 0); + var argValue = CoalesceParameterValue(parms.Arguments[argsProvided - 1], elementType); + + array.SetValue(argValue, 0); parms.Arguments[argsProvided - 1] = array; } } @@ -301,7 +303,10 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) - array.SetValue(parms.Arguments[argsNeeded + i - 1], i); + { + var argValue = CoalesceParameterValue(parms.Arguments[argsNeeded + i - 1], elementType); + array.SetValue(argValue, i); + } newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; @@ -335,9 +340,6 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) parms.Arguments = newArgList; } - //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) - // parms.Arguments = new object[]{parms.Arguments}; - // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { @@ -359,6 +361,15 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) return parms; } + private static object CoalesceParameterValue(object arg, Type targetType) + { + object argAsTargetType; + if (PerformSpecialConversion(arg, targetType, out argAsTargetType)) + return argAsTargetType; + else + return arg; + } + /// /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index 719d3ecf95..c85acb343c 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -128,6 +128,13 @@ public DateTime CanConvertExpectedResultStringToDateTime(DateTime dt) return dt; } + [TestCase("1942-10-12")] + [TestCase("1942-10-12", "1942-10-12")] + public void CanConvertStringToDateTimeAsParamArray(params DateTime[] dt) + { + CanConvertSpecialCaseToParams(dt); + } + [TestCase("4:44:15")] public void CanConvertStringToTimeSpan(TimeSpan ts) { @@ -141,6 +148,13 @@ public TimeSpan CanConvertExpectedResultStringToTimeSpan(TimeSpan ts) { return ts; } + + [TestCase("4:44:15")] + [TestCase("4:44:15", "4:44:15")] + public void CanConvertStringToTimeSpanAsParamArray(params TimeSpan[] ts) + { + CanConvertSpecialCaseToParams(ts); + } [TestCase("2018-10-09 15:15:00+02:30")] public void CanConvertStringToDateTimeOffset(DateTimeOffset offset) @@ -163,6 +177,22 @@ public DateTimeOffset CanConvertExpectedResultStringToDateTimeOffset(DateTimeOff return offset; } + [TestCase("2018-10-09 15:15:00+02:30")] + [TestCase("2018-10-09 15:15:00+02:30", "2018-10-09 15:15:00+02:30")] + public void CanConvertStringToDateTimeOffsetAsParamArray(params DateTimeOffset[] offsets) + { + CanConvertSpecialCaseToParams(offsets); + } + + private static void CanConvertSpecialCaseToParams(T[] args) + { + Assert.IsNotNull(args); + CollectionAssert.IsNotEmpty(args); + + foreach (var arg in args) + Assert.AreNotEqual(default(T), arg); + } + [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { From 37ba29a89ffe88b120be7d12b390474e05249e33 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 26 Nov 2018 13:37:29 -0500 Subject: [PATCH 108/174] DateTimeOffset as a Values[] --- .../Internal/ParamAttributeTypeConversions.cs | 7 +++++++ .../tests/Attributes/TestCaseAttributeTests.cs | 7 +++++++ .../tests/Attributes/ValuesAttributeTests.cs | 15 +++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs index 449f423892..2144d91774 100644 --- a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs +++ b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs @@ -123,6 +123,13 @@ public static bool TryConvert(object value, Type targetType, out object converte return true; } + var converter = System.ComponentModel.TypeDescriptor.GetConverter(targetType); + if (converter.CanConvertFrom(value.GetType())) + { + convertedValue = converter.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, value); + return true; + } + convertedValue = null; return false; } diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index c85acb343c..c3e8cf3e56 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -184,6 +184,13 @@ public void CanConvertStringToDateTimeOffsetAsParamArray(params DateTimeOffset[] CanConvertSpecialCaseToParams(offsets); } + [TestCase("2018-10-09 15:15:00+02:30")] + [TestCase("2018-10-09 15:15:00+02:30", "2018-10-09 15:15:00+02:30")] + public void CanConvertStringToNullableDateTimeOffsetAsParamArray(params DateTimeOffset?[] offsets) + { + CanConvertSpecialCaseToParams(offsets); + } + private static void CanConvertSpecialCaseToParams(T[] args) { Assert.IsNotNull(args); diff --git a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs index 0f3a5a9e55..4d2dfc6629 100644 --- a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs @@ -76,6 +76,21 @@ public void CanConvertStringToDecimal([Values("12.5")]decimal x) { } + [Test] + public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset? x) + { + } + + [Test] + public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) + { + } + + [Test] + public void CanConvertStringToTimeSpan([Values("4:44:15")]TimeSpan x) + { + } + #endregion #region Helper Methods From a39e3a103eb501bbf1a6773a790686505f0f1550 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 26 Nov 2018 14:06:34 -0500 Subject: [PATCH 109/174] Use ParamAttributeTypeConversions from TestCaseAttribute --- .../framework/Attributes/TestCaseAttribute.cs | 78 +------------------ .../Internal/ParamAttributeTypeConversions.cs | 26 +++++-- .../tests/Attributes/ValuesAttributeTests.cs | 26 +++++-- 3 files changed, 44 insertions(+), 86 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs index e98934bb7a..f13c525fd6 100644 --- a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs @@ -269,7 +269,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) // Special handling for ExpectedResult (see if it needs to be converted into method return type) object expectedResultInTargetType; if (parms.HasExpectedResult - && PerformSpecialConversion(parms.ExpectedResult, method.ReturnType.Type, out expectedResultInTargetType)) + && ParamAttributeTypeConversions.TryConvert(parms.ExpectedResult, method.ReturnType.Type, out expectedResultInTargetType)) { parms.ExpectedResult = expectedResultInTargetType; } @@ -288,7 +288,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1])) { Array array = Array.CreateInstance(elementType, 1); - var argValue = CoalesceParameterValue(parms.Arguments[argsProvided - 1], elementType); + var argValue = ParamAttributeTypeConversions.Convert(parms.Arguments[argsProvided - 1], elementType); array.SetValue(argValue, 0); parms.Arguments[argsProvided - 1] = array; @@ -304,7 +304,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) { - var argValue = CoalesceParameterValue(parms.Arguments[argsNeeded + i - 1], elementType); + var argValue = ParamAttributeTypeConversions.Convert(parms.Arguments[argsNeeded + i - 1], elementType); array.SetValue(argValue, i); } @@ -361,15 +361,6 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) return parms; } - private static object CoalesceParameterValue(object arg, Type targetType) - { - object argAsTargetType; - if (PerformSpecialConversion(arg, targetType, out argAsTargetType)) - return argAsTargetType; - else - return arg; - } - /// /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor @@ -384,73 +375,12 @@ private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] object arg = arglist[i]; Type targetType = parameters[i].ParameterType; object argAsTargetType; - if (PerformSpecialConversion(arg, targetType, out argAsTargetType)) + if (ParamAttributeTypeConversions.TryConvert(arg, targetType, out argAsTargetType)) { arglist[i] = argAsTargetType; } } } - - /// - /// Performs several special conversions allowed by NUnit in order to - /// permit arguments with types that cannot be used in the constructor - /// of an Attribute such as TestCaseAttribute or to simplify their use. - /// - /// The argument to be converted - /// The target in which the should be converted - /// If conversion was successfully applied, the converted into - /// - /// true if was converted and should be used; - /// false is no conversion was applied and should be ignored - /// - private static bool PerformSpecialConversion(object arg, Type targetType, out object argAsTargetType) - { - argAsTargetType = null; - if (arg == null) - return false; - - if (targetType.IsInstanceOfType(arg)) - return false; - - if (arg.GetType().FullName == "System.DBNull") - { - argAsTargetType = null; - return true; - } - - bool convert = false; - - if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) || - targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?)) - { - convert = arg is int; - } - else if (targetType == typeof(decimal) || targetType == typeof(decimal?)) - { - convert = arg is double || arg is string || arg is int; - } - else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) - { - convert = arg is string; - } - - if (convert) - { - Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? - targetType.GetGenericArguments()[0] : targetType; - argAsTargetType = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture); - return true; - } - - var converter = System.ComponentModel.TypeDescriptor.GetConverter(targetType); - if (converter.CanConvertFrom(arg.GetType())) - { - argAsTargetType = converter.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, arg); - return true; - } - - return false; - } #endregion #region ITestBuilder Members diff --git a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs index 2144d91774..aac2a675be 100644 --- a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs +++ b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs @@ -23,6 +23,7 @@ using System; using System.Collections; +using System.ComponentModel; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; @@ -86,8 +87,17 @@ public static object Convert(object value, Type targetType) } /// - /// Converts a single value to the , if it is supported. + /// Performs several special conversions allowed by NUnit in order to + /// permit arguments with types that cannot be used in the constructor + /// of an Attribute such as TestCaseAttribute or to simplify their use. /// + /// The value to be converted + /// The target in which the should be converted + /// If conversion was successfully applied, the converted into + /// + /// true if was converted and should be used; + /// false is no conversion was applied and should be ignored + /// public static bool TryConvert(object value, Type targetType, out object convertedValue) { if (targetType.IsInstanceOfType(value)) @@ -104,26 +114,30 @@ public static bool TryConvert(object value, Type targetType, out object converte bool convert = false; - if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte)) + if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) || + targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?)) { convert = value is int; } - else if (targetType == typeof(decimal)) + else if (targetType == typeof(decimal) || targetType == typeof(decimal?)) { convert = value is double || value is string || value is int; } - else if (targetType == typeof(DateTime) || targetType == typeof(TimeSpan)) + else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) { convert = value is string; } if (convert) { - convertedValue = System.Convert.ChangeType(value, targetType, System.Globalization.CultureInfo.InvariantCulture); + Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? + targetType.GetGenericArguments()[0] : targetType; + + convertedValue = System.Convert.ChangeType(value, convertTo, System.Globalization.CultureInfo.InvariantCulture); return true; } - var converter = System.ComponentModel.TypeDescriptor.GetConverter(targetType); + var converter = TypeDescriptor.GetConverter(targetType); if (converter.CanConvertFrom(value.GetType())) { convertedValue = converter.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, value); diff --git a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs index 4d2dfc6629..524e2ac14d 100644 --- a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs @@ -62,32 +62,46 @@ public void CanConvertSmallIntsToSByte([Values(5)]sbyte x) } [Test] - public void CanConvertIntToDecimal([Values(12)]decimal x) + public void CanConvertValuesToDecimal([Values(12, 12.5, "12.5")]decimal x) { } [Test] - public void CanConvertDoubleToDecimal([Values(12.5)]decimal x) + public void CanConvertValuesToNullableDecimal([Values(12, 12.5, "12.5")]decimal? x) { + Assert.IsNotNull(x); } [Test] - public void CanConvertStringToDecimal([Values("12.5")]decimal x) + public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset? x) { + Assert.IsNotNull(x); } [Test] - public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset? x) + public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) { } [Test] - public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) + public void CanConvertStringToTimeSpan([Values("4:44:15")]TimeSpan x) { } [Test] - public void CanConvertStringToTimeSpan([Values("4:44:15")]TimeSpan x) + public void CanConvertStringToNullableTimeSpan([Values("4:44:15")]TimeSpan? x) + { + Assert.IsNotNull(x); + } + + [Test] + public void CanConvertStringToNullableDateTime([Values("2018-10-10")]DateTime? x) + { + Assert.IsNotNull(x); + } + + [Test] + public void CanConvertStringToDateTime([Values("2018-10-10")]DateTime x) { } From 53e273db79d0dec97e01d29170a385cb98b75ed8 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 26 Nov 2018 14:24:38 -0500 Subject: [PATCH 110/174] Add a few tests for implicitly-allowed conversions --- .../Attributes/TestCaseAttributeTests.cs | 6 +++ .../tests/Attributes/ValuesAttributeTests.cs | 45 +++++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index c3e8cf3e56..82161021e8 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -604,6 +604,12 @@ public void CanConvertIntToNullableLong(long? x) Assert.That(x.Value, Is.EqualTo(1)); } + [TestCase(1)] + public void CanConvertIntToLong(long x) + { + Assert.That(x, Is.EqualTo(1)); + } + [TestCase("2.2", "3.3", ExpectedResult = 5.5)] public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y) { diff --git a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs index 524e2ac14d..fdaba27763 100644 --- a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs @@ -46,21 +46,50 @@ public void ValuesAttributeProvidesSpecifiedValues() #region Conversion Tests + [Test] + public void CanConvertIntsToLong([Values(5, int.MaxValue)]long x) + { + } + + [Test] + public void CanConvertIntsToNullableLong([Values(5, int.MaxValue)]long? x) + { + Assert.That(x.HasValue, Is.True); + } + [Test] public void CanConvertSmallIntsToShort([Values(5)]short x) { } + [Test] + public void CanConvertSmallIntsToNullableShort([Values(5)]short? x) + { + Assert.That(x.HasValue, Is.True); + } + [Test] public void CanConvertSmallIntsToByte([Values(5)]byte x) { } + [Test] + public void CanConvertSmallIntsToNullableByte([Values(5)]byte? x) + { + Assert.That(x.HasValue, Is.True); + } + [Test] public void CanConvertSmallIntsToSByte([Values(5)]sbyte x) { } + [Test] + public void CanConvertSmallIntsToNullableSByte([Values(5)]sbyte? x) + { + Assert.That(x.HasValue, Is.True); + } + [Test] public void CanConvertValuesToDecimal([Values(12, 12.5, "12.5")]decimal x) { @@ -69,18 +98,18 @@ public void CanConvertValuesToDecimal([Values(12, 12.5, "12.5")]decimal x) [Test] public void CanConvertValuesToNullableDecimal([Values(12, 12.5, "12.5")]decimal? x) { - Assert.IsNotNull(x); + Assert.That(x.HasValue, Is.True); } [Test] - public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset? x) + public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) { - Assert.IsNotNull(x); } [Test] - public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) + public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset? x) { + Assert.That(x.HasValue, Is.True); } [Test] @@ -91,18 +120,18 @@ public void CanConvertStringToTimeSpan([Values("4:44:15")]TimeSpan x) [Test] public void CanConvertStringToNullableTimeSpan([Values("4:44:15")]TimeSpan? x) { - Assert.IsNotNull(x); + Assert.That(x.HasValue, Is.True); } [Test] - public void CanConvertStringToNullableDateTime([Values("2018-10-10")]DateTime? x) + public void CanConvertStringToDateTime([Values("2018-10-10")]DateTime x) { - Assert.IsNotNull(x); } [Test] - public void CanConvertStringToDateTime([Values("2018-10-10")]DateTime x) + public void CanConvertStringToNullableDateTime([Values("2018-10-10")]DateTime? x) { + Assert.That(x.HasValue, Is.True); } #endregion From d351bebc3570e55e7cd6d4ff5aa89396e8958fc1 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 26 Nov 2018 14:29:18 -0500 Subject: [PATCH 111/174] Namespace cleanup --- .../framework/Internal/ParamAttributeTypeConversions.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs index aac2a675be..4ec95e56bd 100644 --- a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs +++ b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs @@ -24,6 +24,7 @@ using System; using System.Collections; using System.ComponentModel; +using System.Globalization; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; @@ -133,14 +134,14 @@ public static bool TryConvert(object value, Type targetType, out object converte Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? targetType.GetGenericArguments()[0] : targetType; - convertedValue = System.Convert.ChangeType(value, convertTo, System.Globalization.CultureInfo.InvariantCulture); + convertedValue = System.Convert.ChangeType(value, convertTo, CultureInfo.InvariantCulture); return true; } var converter = TypeDescriptor.GetConverter(targetType); if (converter.CanConvertFrom(value.GetType())) { - convertedValue = converter.ConvertFrom(null, System.Globalization.CultureInfo.InvariantCulture, value); + convertedValue = converter.ConvertFrom(null, CultureInfo.InvariantCulture, value); return true; } From 25a818889f6e6bfc8c3971c3c0c77948a9389ecf Mon Sep 17 00:00:00 2001 From: stevenaw Date: Thu, 3 Jan 2019 18:38:08 -0500 Subject: [PATCH 112/174] Remove array conversions --- .../framework/Attributes/TestCaseAttribute.cs | 9 +---- .../Attributes/TestCaseAttributeTests.cs | 39 +------------------ 2 files changed, 3 insertions(+), 45 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs index f13c525fd6..4c188161e9 100644 --- a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs @@ -288,9 +288,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) if (!lastParameterType.IsInstanceOfType(parms.Arguments[argsProvided - 1])) { Array array = Array.CreateInstance(elementType, 1); - var argValue = ParamAttributeTypeConversions.Convert(parms.Arguments[argsProvided - 1], elementType); - - array.SetValue(argValue, 0); + array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } @@ -303,10 +301,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) - { - var argValue = ParamAttributeTypeConversions.Convert(parms.Arguments[argsNeeded + i - 1], elementType); - array.SetValue(argValue, i); - } + array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index 82161021e8..6aac40cb95 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -128,13 +128,6 @@ public DateTime CanConvertExpectedResultStringToDateTime(DateTime dt) return dt; } - [TestCase("1942-10-12")] - [TestCase("1942-10-12", "1942-10-12")] - public void CanConvertStringToDateTimeAsParamArray(params DateTime[] dt) - { - CanConvertSpecialCaseToParams(dt); - } - [TestCase("4:44:15")] public void CanConvertStringToTimeSpan(TimeSpan ts) { @@ -148,13 +141,6 @@ public TimeSpan CanConvertExpectedResultStringToTimeSpan(TimeSpan ts) { return ts; } - - [TestCase("4:44:15")] - [TestCase("4:44:15", "4:44:15")] - public void CanConvertStringToTimeSpanAsParamArray(params TimeSpan[] ts) - { - CanConvertSpecialCaseToParams(ts); - } [TestCase("2018-10-09 15:15:00+02:30")] public void CanConvertStringToDateTimeOffset(DateTimeOffset offset) @@ -176,30 +162,7 @@ public DateTimeOffset CanConvertExpectedResultStringToDateTimeOffset(DateTimeOff { return offset; } - - [TestCase("2018-10-09 15:15:00+02:30")] - [TestCase("2018-10-09 15:15:00+02:30", "2018-10-09 15:15:00+02:30")] - public void CanConvertStringToDateTimeOffsetAsParamArray(params DateTimeOffset[] offsets) - { - CanConvertSpecialCaseToParams(offsets); - } - - [TestCase("2018-10-09 15:15:00+02:30")] - [TestCase("2018-10-09 15:15:00+02:30", "2018-10-09 15:15:00+02:30")] - public void CanConvertStringToNullableDateTimeOffsetAsParamArray(params DateTimeOffset?[] offsets) - { - CanConvertSpecialCaseToParams(offsets); - } - - private static void CanConvertSpecialCaseToParams(T[] args) - { - Assert.IsNotNull(args); - CollectionAssert.IsNotEmpty(args); - - foreach (var arg in args) - Assert.AreNotEqual(default(T), arg); - } - + [TestCase(null)] public void CanPassNullAsFirstArgument(object a) { From 57df4edf3ba71f51772678a5d4be17d3d067ba78 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Sat, 5 Jan 2019 10:44:21 -0500 Subject: [PATCH 113/174] Add explicit assertions to valuesattribute tests --- src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs index fdaba27763..3ac808665a 100644 --- a/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/ValuesAttributeTests.cs @@ -49,6 +49,7 @@ public void ValuesAttributeProvidesSpecifiedValues() [Test] public void CanConvertIntsToLong([Values(5, int.MaxValue)]long x) { + Assert.That(x, Is.Not.EqualTo(default(long))); } [Test] @@ -93,6 +94,7 @@ public void CanConvertSmallIntsToNullableSByte([Values(5)]sbyte? x) [Test] public void CanConvertValuesToDecimal([Values(12, 12.5, "12.5")]decimal x) { + Assert.That(x, Is.Not.EqualTo(default(decimal))); } [Test] @@ -104,6 +106,7 @@ public void CanConvertValuesToNullableDecimal([Values(12, 12.5, "12.5")]decimal? [Test] public void CanConvertStringToDateTimeOffset([Values("2018-10-09 15:15:00+02:30")]DateTimeOffset x) { + Assert.That(x, Is.Not.EqualTo(default(DateTimeOffset))); } [Test] @@ -115,6 +118,7 @@ public void CanConvertStringToNullableDateTimeOffset([Values("2018-10-09 15:15:0 [Test] public void CanConvertStringToTimeSpan([Values("4:44:15")]TimeSpan x) { + Assert.That(x, Is.Not.EqualTo(default(TimeSpan))); } [Test] @@ -126,6 +130,7 @@ public void CanConvertStringToNullableTimeSpan([Values("4:44:15")]TimeSpan? x) [Test] public void CanConvertStringToDateTime([Values("2018-10-10")]DateTime x) { + Assert.That(x, Is.Not.EqualTo(default(DateTime))); } [Test] From 161b7f9f9f049bd5e8d9e024998bb22524ab2ade Mon Sep 17 00:00:00 2001 From: stevenaw Date: Sat, 5 Jan 2019 10:50:08 -0500 Subject: [PATCH 114/174] Add nuspec reference --- nuget/framework/nunit.nuspec | 1 + 1 file changed, 1 insertion(+) diff --git a/nuget/framework/nunit.nuspec b/nuget/framework/nunit.nuspec index 2f4b0444a4..4eb0e56ddb 100644 --- a/nuget/framework/nunit.nuspec +++ b/nuget/framework/nunit.nuspec @@ -30,6 +30,7 @@ Supported platforms: + From e543ce83a176a99a37d20da247c3c221d1ee9f6d Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 18 Feb 2019 16:26:53 -0500 Subject: [PATCH 115/174] Nullable.GetUnderlyingValue() --- .../Internal/ParamAttributeTypeConversions.cs | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs index 4ec95e56bd..ad89a8d3b0 100644 --- a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs +++ b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs @@ -25,9 +25,10 @@ using System.Collections; using System.ComponentModel; using System.Globalization; + +#if !(NET35 || NET40 || NET45) using System.Reflection; -using NUnit.Compatibility; -using NUnit.Framework.Interfaces; +#endif namespace NUnit.Framework.Internal { @@ -114,31 +115,29 @@ public static bool TryConvert(object value, Type targetType, out object converte } bool convert = false; + var underlyingTargetType = Nullable.GetUnderlyingType(targetType) ?? targetType; - if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(long?) || - targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?)) + if (underlyingTargetType == typeof(short) || underlyingTargetType == typeof(byte) || underlyingTargetType == typeof(sbyte) + || targetType == typeof(long?) || targetType == typeof(double?)) { convert = value is int; } - else if (targetType == typeof(decimal) || targetType == typeof(decimal?)) + else if (underlyingTargetType == typeof(decimal)) { convert = value is double || value is string || value is int; } - else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) + else if (underlyingTargetType == typeof(DateTime)) { convert = value is string; } if (convert) { - Type convertTo = targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? - targetType.GetGenericArguments()[0] : targetType; - - convertedValue = System.Convert.ChangeType(value, convertTo, CultureInfo.InvariantCulture); + convertedValue = System.Convert.ChangeType(value, underlyingTargetType, CultureInfo.InvariantCulture); return true; } - var converter = TypeDescriptor.GetConverter(targetType); + var converter = TypeDescriptor.GetConverter(underlyingTargetType); if (converter.CanConvertFrom(value.GetType())) { convertedValue = converter.ConvertFrom(null, CultureInfo.InvariantCulture, value); From f4f22f382a50e163666dceb1a67a91077f781098 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Mon, 18 Feb 2019 16:51:14 -0500 Subject: [PATCH 116/174] Make internal nullable checks consistent - but also adds long + double from int support to RangeAttribute --- .../framework/Internal/ParamAttributeTypeConversions.cs | 2 +- src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs index ad89a8d3b0..6fd986d868 100644 --- a/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs +++ b/src/NUnitFramework/framework/Internal/ParamAttributeTypeConversions.cs @@ -118,7 +118,7 @@ public static bool TryConvert(object value, Type targetType, out object converte var underlyingTargetType = Nullable.GetUnderlyingType(targetType) ?? targetType; if (underlyingTargetType == typeof(short) || underlyingTargetType == typeof(byte) || underlyingTargetType == typeof(sbyte) - || targetType == typeof(long?) || targetType == typeof(double?)) + || underlyingTargetType == typeof(long) || underlyingTargetType == typeof(double)) { convert = value is int; } diff --git a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs index 2f0485bdbb..2e8bbe48b3 100644 --- a/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs @@ -52,7 +52,7 @@ public partial class RangeAttributeTests }; // See XML docs for the ParamAttributeTypeConversions class. - private static readonly Type[] Int32RangeConvertibleToParameterTypes = { typeof(int), typeof(sbyte), typeof(byte), typeof(short), typeof(decimal) }; + private static readonly Type[] Int32RangeConvertibleToParameterTypes = { typeof(int), typeof(sbyte), typeof(byte), typeof(short), typeof(decimal), typeof(long), typeof(double) }; private static readonly Type[] UInt32RangeConvertibleToParameterTypes = { typeof(uint) }; private static readonly Type[] Int64RangeConvertibleToParameterTypes = { typeof(long) }; private static readonly Type[] UInt64RangeConvertibleToParameterTypes = { typeof(ulong) }; From 84ed67d94c0cd01901581019bd2ea1f51cba822c Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Thu, 21 Feb 2019 15:24:49 -0500 Subject: [PATCH 117/174] Copy test fixtures with filters --- .../framework/Internal/Tests/TestFixture.cs | 10 ++++++++++ .../framework/Internal/Tests/TestSuite.cs | 4 +++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs index 65df13e401..ac18a40dfd 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs @@ -51,6 +51,16 @@ public TestFixture(ITypeInfo fixtureType, object[] arguments = null) : base(fixt CheckSetUpTearDownMethods(TearDownMethods); } + /// + /// Copy constructor style to create a filtered copy of the given test suite + /// + /// Test Suite to copy + /// Filter to be applied + public TestFixture(TestSuite suite, ITestFilter filter) + : base(suite, filter) + { + } + #endregion } } diff --git a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs index 413e49a7a4..a1e20c8383 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs @@ -117,7 +117,9 @@ public TestSuite(TestSuite suite, ITestFilter filter) { if(child.IsSuite) { - TestSuite childSuite = new TestSuite(child as TestSuite, filter); + TestSuite childSuite = child.GetType() == typeof(TestFixture) + ? new TestFixture(child as TestSuite, filter) + : new TestSuite(child as TestSuite, filter); childSuite.Parent = this; this.tests.Add(childSuite); } From 5d0a91363754c883436d28e81ff3a2e28beeff18 Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Sat, 23 Feb 2019 15:33:51 -0500 Subject: [PATCH 118/174] Generic solution for copying test suites with filters --- .../Tests/ParameterizedFixtureSuite.cs | 19 +++++++++++++++ .../Tests/ParameterizedMethodSuite.cs | 19 +++++++++++++++ .../framework/Internal/Tests/SetUpFixture.cs | 23 +++++++++++++++++++ .../framework/Internal/Tests/TestAssembly.cs | 9 ++++++++ .../framework/Internal/Tests/TestFixture.cs | 21 +++++++++++++---- .../framework/Internal/Tests/TestSuite.cs | 14 ++++++++--- 6 files changed, 98 insertions(+), 7 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs b/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs index 37338f45f2..ca13d9ca31 100644 --- a/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs @@ -42,6 +42,16 @@ public ParameterizedFixtureSuite(ITypeInfo typeInfo) : base(typeInfo.Namespace, _genericFixture = typeInfo.ContainsGenericParameters; } + /// + /// Copy constructor style to create a filtered copy of the given parameterized fixture suite + /// + /// Parameterized Fixture Suite to copy + /// Filter to be applied + public ParameterizedFixtureSuite(ParameterizedFixtureSuite suite, ITestFilter filter) + : base(suite, filter) + { + } + /// /// Gets a string representing the type of test /// @@ -54,5 +64,14 @@ public override string TestType : "ParameterizedFixture"; } } + + /// + /// Overriden to return a Parameterized Fixture Suite + /// + /// Filter to apply + public override TestSuite Copy(ITestFilter filter) + { + return new ParameterizedFixtureSuite(this, filter); + } } } diff --git a/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs b/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs index 87783a16f6..416de9cdd4 100644 --- a/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs @@ -44,6 +44,16 @@ public ParameterizedMethodSuite(IMethodInfo method) this.MaintainTestOrder = true; } + /// + /// Copy constructor style to create a filtered copy of the given parameterized method suite + /// + /// Parameterized Method Suite to copy + /// Filter to be applied + public ParameterizedMethodSuite(ParameterizedMethodSuite suite, ITestFilter filter) + : base(suite, filter) + { + } + /// /// Gets a string representing the type of test /// @@ -60,5 +70,14 @@ public override string TestType return "ParameterizedMethod"; } } + + /// + /// Overriden to return a Parameterized Method Suite + /// + /// Filter to apply + public override TestSuite Copy(ITestFilter filter) + { + return new ParameterizedMethodSuite(this, filter); + } } } diff --git a/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs b/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs index 44e0efcdcf..375e66fabd 100644 --- a/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs +++ b/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs @@ -52,6 +52,29 @@ public SetUpFixture(ITypeInfo type) : base(type) CheckSetUpTearDownMethods(OneTimeTearDownMethods); } + /// + /// Copy constructor style to create a filtered copy of the given setup fixture + /// + /// SetUp Fixture to copy + /// Filter to be applied + public SetUpFixture(SetUpFixture setUpFixture, ITestFilter filter) + : base(setUpFixture, filter) + { + } + + #endregion + + #region Test Suite Overrides + + /// + /// Overriden to return a SetUp Fixture + /// + /// Filter to apply + public override TestSuite Copy(ITestFilter filter) + { + return new SetUpFixture(this, filter); + } + #endregion } } diff --git a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs index 22cbde800f..0a04db3797 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs @@ -95,6 +95,15 @@ public override TAttr[] GetCustomAttributes(bool inherit) ? Assembly.GetAttributes() : new TAttr[0]; } + + /// + /// Overriden to return a Test Assembly + /// + /// Filter to apply + public override TestSuite Copy(ITestFilter filter) + { + return new TestAssembly(this, filter); + } } } diff --git a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs index ac18a40dfd..9bbb2e5740 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs @@ -52,15 +52,28 @@ public TestFixture(ITypeInfo fixtureType, object[] arguments = null) : base(fixt } /// - /// Copy constructor style to create a filtered copy of the given test suite + /// Copy constructor style to create a filtered copy of the given test fixture /// - /// Test Suite to copy + /// Test Fixture to copy /// Filter to be applied - public TestFixture(TestSuite suite, ITestFilter filter) - : base(suite, filter) + private TestFixture(TestFixture fixture, ITestFilter filter) + : base(fixture, filter) { } #endregion + + #region Test Suite Overrides + + /// + /// Overriden to return a Test Fixture + /// + /// Filter to apply + public override TestSuite Copy(ITestFilter filter) + { + return new TestFixture(this, filter); + } + + #endregion } } diff --git a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs index a1e20c8383..e6790e1654 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs @@ -117,9 +117,7 @@ public TestSuite(TestSuite suite, ITestFilter filter) { if(child.IsSuite) { - TestSuite childSuite = child.GetType() == typeof(TestFixture) - ? new TestFixture(child as TestSuite, filter) - : new TestSuite(child as TestSuite, filter); + TestSuite childSuite = ((TestSuite) child).Copy(filter); childSuite.Parent = this; this.tests.Add(childSuite); } @@ -181,6 +179,16 @@ public void Add(Test test) tests.Add(test); } + /// + /// Creates a filtered copy of the test suite + /// + /// Filter to apply + /// + public virtual TestSuite Copy(ITestFilter filter) + { + return new TestSuite(this, filter); + } + #endregion #region Properties From ad943eb94fe280e661fc6c690043fe8eb0a11e40 Mon Sep 17 00:00:00 2001 From: Joseph Musser Date: Sat, 23 Feb 2019 17:25:30 -0500 Subject: [PATCH 119/174] Improve user-facing messages (#3175) * Uniform obsoletion messages * Use pragma instead of marking test methods and classes obsolete * Use full sentences in some user-facing messages --- .../Api/DefaultTestAssemblyBuilder.cs | 2 +- .../framework/Api/FrameworkController.cs | 8 +- .../framework/Api/NUnitTestAssemblyRunner.cs | 22 +++-- src/NUnitFramework/framework/Assert.cs | 12 +-- .../framework/AssertionHelper.cs | 22 ++--- src/NUnitFramework/framework/Assume.cs | 24 ++--- .../framework/Attributes/DataAttribute.cs | 12 +-- .../framework/CollectionAssert.cs | 48 +++++----- .../CollectionContainsConstraint.cs | 11 ++- .../Constraints/ConstraintExpression.cs | 10 +- .../DictionaryContainsKeyConstraint.cs | 26 ++--- .../Constraints/FileExistsConstraint.cs | 5 +- .../Constraints/NUnitEqualityComparer.cs | 2 +- .../framework/DirectoryAssert.cs | 14 +-- src/NUnitFramework/framework/FileAssert.cs | 12 +-- src/NUnitFramework/framework/StringAssert.cs | 14 +-- src/NUnitFramework/framework/Warn.cs | 34 +++---- src/NUnitFramework/nunitlite/Options.cs | 2 +- .../tests/Api/FrameworkControllerTests.cs | 8 +- .../tests/Api/TestAssemblyRunnerTests.cs | 10 +- .../tests/Assertions/AssertEqualsTests.cs | 96 +++++++++---------- .../tests/Assertions/AssertionHelperTests.cs | 5 +- .../tests/Assertions/AssumeEqualsTests.cs | 6 +- .../tests/Assertions/CollectionAssertTest.cs | 4 +- .../tests/Assertions/DirectoryAssertTests.cs | 4 +- .../tests/Assertions/FileAssertTests.cs | 4 +- .../tests/Assertions/StringAssertTests.cs | 10 +- .../DictionaryContainsKeyConstraintTests.cs | 29 +++--- 28 files changed, 234 insertions(+), 222 deletions(-) diff --git a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs index c7255d510f..eea303cca3 100644 --- a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs +++ b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs @@ -254,7 +254,7 @@ private TestSuite BuildTestAssembly(Assembly assembly, string suiteName, IListThe XML result of exploring the tests public string ExploreTests(string filter) { - if (Runner.LoadedTest == null) - throw new InvalidOperationException("The Explore method was called but no test has been loaded"); - return Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml; } @@ -320,10 +317,7 @@ private void LoadTests(ICallbackEventHandler handler) private void ExploreTests(ICallbackEventHandler handler, string filter) { - if (Runner.LoadedTest == null) - throw new InvalidOperationException("The Explore method was called but no test has been loaded"); - - handler.RaiseCallbackEvent(Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml); + handler.RaiseCallbackEvent(ExploreTests(filter)); } private void RunTests(ICallbackEventHandler handler, string filter) diff --git a/src/NUnitFramework/framework/Api/NUnitTestAssemblyRunner.cs b/src/NUnitFramework/framework/Api/NUnitTestAssemblyRunner.cs index 7ef3cd2e33..ff2b8b2f06 100644 --- a/src/NUnitFramework/framework/Api/NUnitTestAssemblyRunner.cs +++ b/src/NUnitFramework/framework/Api/NUnitTestAssemblyRunner.cs @@ -181,7 +181,7 @@ public ITest Load(Assembly assembly, IDictionary settings) public int CountTestCases(ITestFilter filter) { if (LoadedTest == null) - throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded"); + throw new InvalidOperationException("Tests must be loaded before counting test cases."); return CountTestCases(LoadedTest, filter); } @@ -194,7 +194,7 @@ public int CountTestCases(ITestFilter filter) public ITest ExploreTests(ITestFilter filter) { if (LoadedTest == null) - throw new InvalidOperationException("The ExploreTests method was called but no test has been loaded"); + throw new InvalidOperationException("Tests must be loaded before exploring them."); if (filter == TestFilter.Empty) return LoadedTest; @@ -229,7 +229,7 @@ public void RunAsync(ITestListener listener, ITestFilter filter) { log.Info("Running tests"); if (LoadedTest == null) - throw new InvalidOperationException("The Run method was called but no test has been loaded"); + throw new InvalidOperationException("Tests must be loaded before running them."); _runComplete.Reset(); @@ -306,13 +306,13 @@ private void StartRun(ITestListener listener) } catch (SecurityException) { - TopLevelWorkItem.MarkNotRunnable("System.Security.Permissions.UIPermission is not set to start the debugger."); + TopLevelWorkItem.MarkNotRunnable("System.Security.Permissions.UIPermission must be granted in order to launch the debugger."); return; } //System.Diagnostics.Debugger.Launch() not implemented on mono catch (NotImplementedException) { - TopLevelWorkItem.MarkNotRunnable("Debugger unavailable on this platform."); + TopLevelWorkItem.MarkNotRunnable("This platform does not support launching the debugger."); return; } } @@ -353,7 +353,7 @@ private void CreateTestExecutionContext(ITestListener listener) (bool)Settings[FrameworkPackageSettings.RunOnMainThread]) Context.Dispatcher = new MainThreadWorkItemDispatcher(); else if (levelOfParallelism > 0) - Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism); + Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism); else Context.Dispatcher = new SimpleWorkItemDispatcher(); #endif @@ -408,8 +408,14 @@ private int GetLevelOfParallelism() private static void PauseBeforeRun() { var process = Process.GetCurrentProcess(); - string attachMessage = string.Format("Attach debugger to Process {0}.exe with Id {1} if desired.", process.ProcessName, process.Id); - MessageBox.Show(attachMessage, process.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Information); + + MessageBox.Show( + $"Pausing as requested. If you would like to attach a debugger, the process name and ID are {process.ProcessName}.exe and {process.Id}." + Environment.NewLine + + Environment.NewLine + + "Click OK when you are ready to continue.", + $"{process.ProcessName} – paused", + MessageBoxButtons.OK, + MessageBoxIcon.Information); } #endif diff --git a/src/NUnitFramework/framework/Assert.cs b/src/NUnitFramework/framework/Assert.cs index 5765b54de9..11b5e3b091 100644 --- a/src/NUnitFramework/framework/Assert.cs +++ b/src/NUnitFramework/framework/Assert.cs @@ -65,7 +65,7 @@ public abstract partial class Assert [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("Assert.Equals should not be used for Assertions, use Assert.AreEqual(...) instead."); + throw new InvalidOperationException("Assert.Equals should not be used. Use Assert.AreEqual instead."); } /// @@ -78,7 +78,7 @@ public static new bool Equals(object a, object b) [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions, use Assert.AreSame(...) instead."); + throw new InvalidOperationException("Assert.ReferenceEquals should not be used. Use Assert.AreSame instead."); } #endregion @@ -314,7 +314,7 @@ public static void Contains(object expected, ICollection actual) public static void Multiple(TestDelegate testDelegate) { TestExecutionContext context = TestExecutionContext.CurrentContext; - Guard.OperationValid(context != null, "Assert.Multiple called outside of a valid TestExecutionContext"); + Guard.OperationValid(context != null, "There is no current test execution context."); context.MultipleAssertLevel++; @@ -344,7 +344,7 @@ public static void Multiple(TestDelegate testDelegate) public static void Multiple(AsyncTestDelegate testDelegate) { TestExecutionContext context = TestExecutionContext.CurrentContext; - Guard.OperationValid(context != null, "Assert.Multiple called outside of a valid TestExecutionContext"); + Guard.OperationValid(context != null, "There is no current test execution context."); context.MultipleAssertLevel++; @@ -365,9 +365,9 @@ public static void Multiple(AsyncTestDelegate testDelegate) } #endif -#endregion + #endregion -#region Helper Methods + #region Helper Methods private static void ReportFailure(ConstraintResult result, string message) { diff --git a/src/NUnitFramework/framework/AssertionHelper.cs b/src/NUnitFramework/framework/AssertionHelper.cs index 42265f556d..6b292e7e85 100644 --- a/src/NUnitFramework/framework/AssertionHelper.cs +++ b/src/NUnitFramework/framework/AssertionHelper.cs @@ -31,8 +31,8 @@ namespace NUnit.Framework /// AssertionHelper is an optional base class for user tests, /// allowing the use of shorter names in making asserts. /// - [Obsolete("The AssertionHelper class will be removed in a coming release. " + - "Consider using the NUnit.StaticExpect NuGet package as a replacement.")] + [Obsolete("The AssertionHelper class has been deprecated and will be removed in a future release. " + + "Please consider using the NUnit.StaticExpect NuGet package instead.")] public class AssertionHelper { #region Expect @@ -730,7 +730,7 @@ public ContainsConstraint Contains(string expected) /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// - [Obsolete("Deprecated, use Contains")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Contains instead.")] public SubstringConstraint StringContaining(string expected) { return new SubstringConstraint(expected); @@ -740,7 +740,7 @@ public SubstringConstraint StringContaining(string expected) /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// - [Obsolete("Deprecated, use Contains")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Contains instead.")] public SubstringConstraint ContainsSubstring(string expected) { return new SubstringConstraint(expected); @@ -754,7 +754,7 @@ public SubstringConstraint ContainsSubstring(string expected) /// Returns a constraint that fails if the actual /// value contains the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.Not.Contain")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Not.Contain instead.")] public SubstringConstraint DoesNotContain(string expected) { return new ConstraintExpression().Not.ContainsSubstring(expected); @@ -786,7 +786,7 @@ public StartsWithConstraint StartsWith(string expected) /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.StartWith or StartsWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.StartWith or StartsWith instead.")] public StartsWithConstraint StringStarting(string expected) { return new StartsWithConstraint(expected); @@ -800,7 +800,7 @@ public StartsWithConstraint StringStarting(string expected) /// Returns a constraint that fails if the actual /// value starts with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.Not.StartWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Not.StartWith instead.")] public StartsWithConstraint DoesNotStartWith(string expected) { return new ConstraintExpression().Not.StartsWith(expected); @@ -832,7 +832,7 @@ public EndsWithConstraint EndsWith(string expected) /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.EndWith or EndsWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.EndWith or EndsWith instead.")] public EndsWithConstraint StringEnding(string expected) { return new EndsWithConstraint(expected); @@ -846,7 +846,7 @@ public EndsWithConstraint StringEnding(string expected) /// Returns a constraint that fails if the actual /// value ends with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.Not.EndWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Not.EndWith instead.")] public EndsWithConstraint DoesNotEndWith(string expected) { return new ConstraintExpression().Not.EndsWith(expected); @@ -878,7 +878,7 @@ public RegexConstraint Matches(string pattern) /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// - [Obsolete("Deprecated, use Does.Match or Matches")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Match or Matches instead.")] public RegexConstraint StringMatching(string pattern) { return new RegexConstraint(pattern); @@ -892,7 +892,7 @@ public RegexConstraint StringMatching(string pattern) /// Returns a constraint that fails if the actual /// value matches the pattern supplied as an argument. /// - [Obsolete("Deprecated, use Does.Not.Match")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Not.Match instead.")] public RegexConstraint DoesNotMatch(string pattern) { return new ConstraintExpression().Not.Matches(pattern); diff --git a/src/NUnitFramework/framework/Assume.cs b/src/NUnitFramework/framework/Assume.cs index eb98f725d1..0966eecb07 100644 --- a/src/NUnitFramework/framework/Assume.cs +++ b/src/NUnitFramework/framework/Assume.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -40,7 +40,7 @@ public class Assume /// /// DO NOT USE! - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// The left object. @@ -49,19 +49,19 @@ public class Assume [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("Assume.Equals should not be used for Assertions."); + throw new InvalidOperationException("Assume.Equals should not be used. Use Assume.That instead."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// The left object. /// The right object. public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("Assume.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("Assume.ReferenceEquals should not be used. Use Assume.That instead."); } #endregion @@ -140,7 +140,7 @@ private static void ReportFailure(ConstraintResult result, string message, objec /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// The evaluated condition /// The message to display if the condition is false /// Arguments to be used in formatting the message @@ -150,7 +150,7 @@ public static void That(bool condition, string message, params object[] args) } /// - /// Asserts that a condition is true. If the condition is false the + /// Asserts that a condition is true. If the condition is false the /// method throws an . /// /// The evaluated condition @@ -162,7 +162,7 @@ public static void That(bool condition) /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// The evaluated condition /// A function to build the message included with the Exception public static void That(bool condition, Func getExceptionMessage) @@ -177,7 +177,7 @@ public static void That(bool condition, Func getExceptionMessage) /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// A lambda that returns a Boolean /// The message to display if the condition is false /// Arguments to be used in formatting the message @@ -199,7 +199,7 @@ public static void That(Func condition) /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// A lambda that returns a Boolean /// A function to build the message included with the Exception public static void That(Func condition, Func getExceptionMessage) diff --git a/src/NUnitFramework/framework/Attributes/DataAttribute.cs b/src/NUnitFramework/framework/Attributes/DataAttribute.cs index 20d322c180..7e563e3ca3 100644 --- a/src/NUnitFramework/framework/Attributes/DataAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/DataAttribute.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2010 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -27,11 +27,11 @@ namespace NUnit.Framework { /// - /// Abstract base class for all data-providing attributes defined by NUnit. + /// Abstract base class for all data-providing attributes defined by NUnit. /// Used to select all data sources for a method, class or parameter. /// - [Obsolete("Holdover from NUnit v2. Please implement " + nameof(IParameterDataSource) + - " for your attribute instead.")] + [Obsolete("The DataAttribute class has been deprecated and will be removed in a future release. " + + "Please use " + nameof(IParameterDataSource) + " instead.")] public abstract class DataAttribute : NUnitAttribute { /// diff --git a/src/NUnitFramework/framework/CollectionAssert.cs b/src/NUnitFramework/framework/CollectionAssert.cs index a6be30be9b..023e6372f5 100644 --- a/src/NUnitFramework/framework/CollectionAssert.cs +++ b/src/NUnitFramework/framework/CollectionAssert.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -38,7 +38,7 @@ public abstract class CollectionAssert /// /// DO NOT USE! Use CollectionAssert.AreEqual(...) instead. - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -46,23 +46,23 @@ public abstract class CollectionAssert [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("CollectionAssert.Equals should not be used for Assertions, use CollectionAssert.AreEqual(...) instead."); + throw new InvalidOperationException("CollectionAssert.Equals should not be used. Use CollectionAssert.AreEqual instead."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// /// public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("CollectionAssert.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("CollectionAssert.ReferenceEquals should not be used."); } #endregion - + #region AllItemsAreInstancesOfType /// /// Asserts that all items contained in collection are of the type specified by expectedType. @@ -93,7 +93,7 @@ public static void AllItemsAreInstancesOfType (IEnumerable collection, Type expe /// Asserts that all items contained in collection are not equal to null. /// /// IEnumerable containing objects to be considered - public static void AllItemsAreNotNull (IEnumerable collection) + public static void AllItemsAreNotNull (IEnumerable collection) { AllItemsAreNotNull(collection, string.Empty, null); } @@ -104,7 +104,7 @@ public static void AllItemsAreNotNull (IEnumerable collection) /// IEnumerable of objects to be considered /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AllItemsAreNotNull (IEnumerable collection, string message, params object[] args) + public static void AllItemsAreNotNull (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.All.Not.Null, message, args); } @@ -117,11 +117,11 @@ public static void AllItemsAreNotNull (IEnumerable collection, string message, p /// once and only once. /// /// IEnumerable of objects to be considered - public static void AllItemsAreUnique (IEnumerable collection) + public static void AllItemsAreUnique (IEnumerable collection) { AllItemsAreUnique(collection, string.Empty, null); } - + /// /// Ensures that every object contained in collection exists within the collection /// once and only once. @@ -129,7 +129,7 @@ public static void AllItemsAreUnique (IEnumerable collection) /// IEnumerable of objects to be considered /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AllItemsAreUnique (IEnumerable collection, string message, params object[] args) + public static void AllItemsAreUnique (IEnumerable collection, string message, params object[] args) { Assert.That(collection, Is.Unique, message, args); } @@ -138,44 +138,44 @@ public static void AllItemsAreUnique (IEnumerable collection, string message, pa #region AreEqual /// - /// Asserts that expected and actual are exactly equal. The collections must have the same count, + /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// /// The first IEnumerable of objects to be considered /// The second IEnumerable of objects to be considered - public static void AreEqual (IEnumerable expected, IEnumerable actual) + public static void AreEqual (IEnumerable expected, IEnumerable actual) { AreEqual(expected, actual, string.Empty, null); } /// - /// Asserts that expected and actual are exactly equal. The collections must have the same count, + /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// /// The first IEnumerable of objects to be considered /// The second IEnumerable of objects to be considered /// The IComparer to use in comparing objects from each IEnumerable - public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) + public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer) { AreEqual(expected, actual, comparer, string.Empty, null); } /// - /// Asserts that expected and actual are exactly equal. The collections must have the same count, + /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// /// The first IEnumerable of objects to be considered /// The second IEnumerable of objects to be considered /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AreEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) + public static void AreEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected).AsCollection, message, args); } /// - /// Asserts that expected and actual are exactly equal. The collections must have the same count, + /// Asserts that expected and actual are exactly equal. The collections must have the same count, /// and contain the exact same objects in the same order. /// If comparer is not null then it will be used to compare the objects. /// @@ -184,7 +184,7 @@ public static void AreEqual (IEnumerable expected, IEnumerable actual, string me /// The IComparer to use in comparing objects from each IEnumerable /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) + public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer comparer, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected).Using(comparer), message, args); } @@ -197,7 +197,7 @@ public static void AreEqual (IEnumerable expected, IEnumerable actual, IComparer /// /// The first IEnumerable of objects to be considered /// The second IEnumerable of objects to be considered - public static void AreEquivalent (IEnumerable expected, IEnumerable actual) + public static void AreEquivalent (IEnumerable expected, IEnumerable actual) { AreEquivalent(expected, actual, string.Empty, null); } @@ -209,7 +209,7 @@ public static void AreEquivalent (IEnumerable expected, IEnumerable actual) /// The second IEnumerable of objects to be considered /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) + public static void AreEquivalent (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.EquivalentTo(expected), message, args); } @@ -246,7 +246,7 @@ public static void AreNotEqual (IEnumerable expected, IEnumerable actual, ICompa /// The second IEnumerable of objects to be considered /// The message that will be displayed on failure /// Arguments to be used in formatting the message - public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) + public static void AreNotEqual (IEnumerable expected, IEnumerable actual, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected).AsCollection, message, args); } @@ -485,7 +485,7 @@ public static void IsNotEmpty(IEnumerable collection) IsNotEmpty(collection, string.Empty, null); } #endregion - + #region IsOrdered /// /// Assert that an array, list or other collection is ordered diff --git a/src/NUnitFramework/framework/Constraints/CollectionContainsConstraint.cs b/src/NUnitFramework/framework/Constraints/CollectionContainsConstraint.cs index c5f6fc940f..f4a529a26e 100644 --- a/src/NUnitFramework/framework/Constraints/CollectionContainsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/CollectionContainsConstraint.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -36,14 +36,15 @@ public class CollectionContainsConstraint : CollectionItemsEqualConstraint /// Construct a CollectionContainsConstraint /// /// - [Obsolete("Deprecated, use 'new SomeItemsConstraint(new EqualConstraint(expected))' or 'Has.Some.EqualTo(expected)' instead.")] + [Obsolete("This constructor has been deprecated and will be removed in a future release. " + + "Please use 'new SomeItemsConstraint(new EqualConstraint(expected))' or 'Has.Some.EqualTo(expected)' instead.")] public CollectionContainsConstraint(object expected) : base(expected) { Expected = expected; } - /// + /// /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set @@ -94,4 +95,4 @@ protected override bool Matches(IEnumerable actual) return this; } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs b/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs index ef0ff7922b..ca7baaf411 100644 --- a/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs +++ b/src/NUnitFramework/framework/Constraints/ConstraintExpression.cs @@ -811,7 +811,7 @@ public DictionaryContainsValueConstraint ContainValue(object expected) /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// - [Obsolete("Deprecated, use Contains")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Contains instead.")] public SubstringConstraint StringContaining(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); @@ -821,7 +821,7 @@ public SubstringConstraint StringContaining(string expected) /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// - [Obsolete("Deprecated, use Contains")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Contains instead.")] public SubstringConstraint ContainsSubstring(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); @@ -853,7 +853,7 @@ public StartsWithConstraint StartsWith(string expected) /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.StartWith or StartsWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.StartWith or StartsWith instead.")] public StartsWithConstraint StringStarting(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); @@ -885,7 +885,7 @@ public EndsWithConstraint EndsWith(string expected) /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// - [Obsolete("Deprecated, use Does.EndWith or EndsWith")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.EndWith or EndsWith instead.")] public EndsWithConstraint StringEnding(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); @@ -917,7 +917,7 @@ public RegexConstraint Matches(string pattern) /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// - [Obsolete("Deprecated, use Does.Match or Matches")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use Does.Match or Matches instead.")] public RegexConstraint StringMatching(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); diff --git a/src/NUnitFramework/framework/Constraints/DictionaryContainsKeyConstraint.cs b/src/NUnitFramework/framework/Constraints/DictionaryContainsKeyConstraint.cs index 4374e2440a..43a9382aa5 100644 --- a/src/NUnitFramework/framework/Constraints/DictionaryContainsKeyConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/DictionaryContainsKeyConstraint.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -38,7 +38,9 @@ namespace NUnit.Framework.Constraints /// public class DictionaryContainsKeyConstraint : CollectionItemsEqualConstraint { - private const string ObsoleteMessage = "DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys."; + private const string ComparerMemberObsoletionMessage = "This member has been deprecated and will be removed in a future release. " + + "To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys."; + private const string ContainsMethodName = "Contains"; private bool _isDeprecatedMode = false; @@ -52,7 +54,7 @@ public DictionaryContainsKeyConstraint(object expected) Expected = expected; } - /// + /// /// The display name of this Constraint for use by ToString(). /// The default value is the name of the constraint with /// trailing "Constraint" removed. Derived classes may set @@ -77,7 +79,7 @@ public override string Description /// /// Flag the constraint to ignore case and return self. /// - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint IgnoreCase { get @@ -129,7 +131,7 @@ protected override bool Matches(IEnumerable collection) /// Flag the constraint to use the supplied predicate function /// /// The comparison function to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public DictionaryContainsKeyConstraint Using(Func comparison) { // reverse the order of the arguments to match expectations of PredicateEqualityComparer @@ -144,7 +146,7 @@ protected override bool Matches(IEnumerable collection) /// Flag the constraint to use the supplied Comparison object. /// /// The Comparison object to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(Comparison comparison) { _isDeprecatedMode = true; @@ -156,7 +158,7 @@ public new CollectionItemsEqualConstraint Using(Comparison comparison) /// Flag the constraint to use the supplied IComparer object. /// /// The IComparer object to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(IComparer comparer) { _isDeprecatedMode = true; @@ -167,7 +169,7 @@ public new CollectionItemsEqualConstraint Using(IComparer comparer) /// Flag the constraint to use the supplied IComparer object. /// /// The IComparer object to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(IComparer comparer) { _isDeprecatedMode = true; @@ -178,7 +180,7 @@ public new CollectionItemsEqualConstraint Using(IComparer comparer) /// Flag the constraint to use the supplied IEqualityComparer object. /// /// The IComparer object to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(IEqualityComparer comparer) { _isDeprecatedMode = true; @@ -189,7 +191,7 @@ public new CollectionItemsEqualConstraint Using(IEqualityComparer comparer) /// Flag the constraint to use the supplied IEqualityComparer object. /// /// The IComparer object to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(IEqualityComparer comparer) { _isDeprecatedMode = true; @@ -200,7 +202,7 @@ public new CollectionItemsEqualConstraint Using(IEqualityComparer comparer /// Flag the constraint to use the supplied boolean-returning delegate. /// /// The supplied boolean-returning delegate to use. - [Obsolete(ObsoleteMessage)] + [Obsolete(ComparerMemberObsoletionMessage)] public new CollectionItemsEqualConstraint Using(Func comparer) { _isDeprecatedMode = true; diff --git a/src/NUnitFramework/framework/Constraints/FileExistsConstraint.cs b/src/NUnitFramework/framework/Constraints/FileExistsConstraint.cs index b632aa7e3a..7c1c84174e 100644 --- a/src/NUnitFramework/framework/Constraints/FileExistsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/FileExistsConstraint.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -28,7 +28,8 @@ namespace NUnit.Framework.Constraints /// /// FileExistsConstraint is used to determine if a file exists /// - [Obsolete("FileExistsConstraint is deprecated, please use FileOrDirectoryExistsConstraint instead.")] + [Obsolete("The FileExistsConstraint class has been deprecated and will be removed in a future release. " + + "Please use " + nameof(FileOrDirectoryExistsConstraint) + " instead.")] public class FileExistsConstraint : FileOrDirectoryExistsConstraint { /// diff --git a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs index 04c8c92fe7..31dd17cca9 100644 --- a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs +++ b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs @@ -93,7 +93,7 @@ public NUnitEqualityComparer() /// /// Returns the default NUnitEqualityComparer /// - [Obsolete("Deprecated. Use the default constructor instead.")] + [Obsolete("This property has been deprecated and will be removed in a future release. Please use 'new NUnitEqualityComparer()' instead.")] public static NUnitEqualityComparer Default { get { return new NUnitEqualityComparer(); } diff --git a/src/NUnitFramework/framework/DirectoryAssert.cs b/src/NUnitFramework/framework/DirectoryAssert.cs index fc57050211..049e4d1853 100644 --- a/src/NUnitFramework/framework/DirectoryAssert.cs +++ b/src/NUnitFramework/framework/DirectoryAssert.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2006 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -37,7 +37,7 @@ public static class DirectoryAssert /// /// DO NOT USE! Use DirectoryAssert.AreEqual(...) instead. - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -45,12 +45,12 @@ public static class DirectoryAssert [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("DirectoryAssert.Equals should not be used for Assertions, use DirectoryAssert.AreEqual(...) instead."); + throw new InvalidOperationException("DirectoryAssert.Equals should not be used. Use DirectoryAssert.AreEqual instead."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -58,7 +58,7 @@ public static new bool Equals(object a, object b) [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("DirectoryAssert.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("DirectoryAssert.ReferenceEquals should not be used."); } #endregion diff --git a/src/NUnitFramework/framework/FileAssert.cs b/src/NUnitFramework/framework/FileAssert.cs index 6d5ddcb523..db803fd897 100644 --- a/src/NUnitFramework/framework/FileAssert.cs +++ b/src/NUnitFramework/framework/FileAssert.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -37,7 +37,7 @@ public static class FileAssert /// /// DO NOT USE! Use FileAssert.AreEqual(...) instead. - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -45,12 +45,12 @@ public static class FileAssert [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("FileAssert.Equals should not be used for Assertions, use FileAssert.AreEqual(...) instead."); + throw new InvalidOperationException("FileAssert.Equals should not be used. Use FileAssert.AreEqual instead."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -58,7 +58,7 @@ public static new bool Equals(object a, object b) [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("FileAssert.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("FileAssert.ReferenceEquals should not be used."); } #endregion diff --git a/src/NUnitFramework/framework/StringAssert.cs b/src/NUnitFramework/framework/StringAssert.cs index 99141d163f..c7cac24d71 100644 --- a/src/NUnitFramework/framework/StringAssert.cs +++ b/src/NUnitFramework/framework/StringAssert.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -37,7 +37,7 @@ public abstract class StringAssert /// /// DO NOT USE! Use StringAssert.AreEqualIgnoringCase(...) or Assert.AreEqual(...) instead. - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -45,12 +45,12 @@ public abstract class StringAssert [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("StringAssert.Equals should not be used for Assertions, use StringAssert.AreEqualIgnoringCase(...) or Assert.AreEqual(...) instead."); + throw new InvalidOperationException("StringAssert.Equals should not be used. Use StringAssert.AreEqualIgnoringCase or Assert.AreEqual instead."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// @@ -58,7 +58,7 @@ public static new bool Equals(object a, object b) [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("StringAssert.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("StringAssert.ReferenceEquals should not be used."); } #endregion @@ -302,7 +302,7 @@ static public void IsMatch(string pattern, string actual) static public void DoesNotMatch(string pattern, string actual, string message, params object[] args) { Assert.That(actual, Does.Not.Match(pattern), message, args); - } + } /// /// Asserts that a string does not match an expected regular expression pattern. diff --git a/src/NUnitFramework/framework/Warn.cs b/src/NUnitFramework/framework/Warn.cs index f2fede2464..799ece3fe0 100644 --- a/src/NUnitFramework/framework/Warn.cs +++ b/src/NUnitFramework/framework/Warn.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -29,7 +29,7 @@ namespace NUnit.Framework { /// - /// Provides static methods to express conditions + /// Provides static methods to express conditions /// that must be met for the test to succeed. If /// any test fails, a warning is issued. /// @@ -39,7 +39,7 @@ public class Warn /// /// DO NOT USE! - /// The Equals method throws an InvalidOperationException. This is done + /// The Equals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// The left object. @@ -48,12 +48,12 @@ public class Warn [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { - throw new InvalidOperationException("Warn.Equals should not be used for Assertions."); + throw new InvalidOperationException("Warn.Equals should not be used."); } /// /// DO NOT USE! - /// The ReferenceEquals method throws an InvalidOperationException. This is done + /// The ReferenceEquals method throws an InvalidOperationException. This is done /// to make sure there is no mistake by calling this function. /// /// The left object. @@ -61,7 +61,7 @@ public static new bool Equals(object a, object b) [EditorBrowsable(EditorBrowsableState.Never)] public static new void ReferenceEquals(object a, object b) { - throw new InvalidOperationException("Warn.ReferenceEquals should not be used for Assertions."); + throw new InvalidOperationException("Warn.ReferenceEquals should not be used."); } #endregion @@ -137,7 +137,7 @@ private static void IssueWarning(ConstraintResult result, string message, object /// /// Asserts that a condition is true. If the condition is false a warning is issued. - /// + /// /// The evaluated condition /// The message to display if the condition is false /// Arguments to be used in formatting the message @@ -147,7 +147,7 @@ public static void Unless(bool condition, string message, params object[] args) } /// - /// Asserts that a condition is true. If the condition is false a warning is issued. + /// Asserts that a condition is true. If the condition is false a warning is issued. /// /// The evaluated condition public static void Unless(bool condition) @@ -157,7 +157,7 @@ public static void Unless(bool condition) /// /// Asserts that a condition is true. If the condition is false a warning is issued. - /// + /// /// The evaluated condition /// A function to build the message included with the Exception public static void Unless(bool condition, Func getExceptionMessage) @@ -172,7 +172,7 @@ public static void Unless(bool condition, Func getExceptionMessage) /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// A lambda that returns a Boolean /// The message to display if the condition is false /// Arguments to be used in formatting the message @@ -194,7 +194,7 @@ public static void Unless(Func condition) /// /// Asserts that a condition is true. If the condition is false the method throws /// an . - /// + /// /// A lambda that returns a Boolean /// A function to build the message included with the Exception public static void Unless(Func condition, Func getExceptionMessage) @@ -350,7 +350,7 @@ public static void If(ActualValueDelegate del, IResolveConstra /// /// Asserts that a condition is true. If the condition is false a warning is issued. - /// + /// /// The evaluated condition /// The message to display if the condition is false /// Arguments to be used in formatting the message @@ -360,7 +360,7 @@ public static void If(bool condition, string message, params object[] args) } /// - /// Asserts that a condition is true. If the condition is false a warning is issued. + /// Asserts that a condition is true. If the condition is false a warning is issued. /// /// The evaluated condition public static void If(bool condition) @@ -370,7 +370,7 @@ public static void If(bool condition) /// /// Asserts that a condition is true. If the condition is false a warning is issued. - /// + /// /// The evaluated condition /// A function to build the message included with the Exception public static void If(bool condition, Func getExceptionMessage) @@ -384,7 +384,7 @@ public static void If(bool condition, Func getExceptionMessage) /// /// Asserts that a condition is false. If the condition is true a warning is issued. - /// + /// /// A lambda that returns a Boolean /// The message to display if the condition is true /// Arguments to be used in formatting the message @@ -404,7 +404,7 @@ public static void If(Func condition) /// /// Asserts that a condition is false. If the condition is true a warning is issued. - /// + /// /// A lambda that returns a Boolean /// A function to build the message included with the Exception public static void If(Func condition, Func getExceptionMessage) diff --git a/src/NUnitFramework/nunitlite/Options.cs b/src/NUnitFramework/nunitlite/Options.cs index 6c0cf17029..5e5bcb34af 100644 --- a/src/NUnitFramework/nunitlite/Options.cs +++ b/src/NUnitFramework/nunitlite/Options.cs @@ -536,7 +536,7 @@ protected override string GetKeyForItem (Option item) throw new InvalidOperationException ("Option has no names!"); } - [Obsolete ("Use KeyedCollection.this[string]")] + [Obsolete("This method has been deprecated and will be removed in a future release. Please use the default indexer instead.")] protected Option GetOptionForName (string option) { if (option == null) diff --git a/src/NUnitFramework/tests/Api/FrameworkControllerTests.cs b/src/NUnitFramework/tests/Api/FrameworkControllerTests.cs index 753d541796..f1afc15190 100644 --- a/src/NUnitFramework/tests/Api/FrameworkControllerTests.cs +++ b/src/NUnitFramework/tests/Api/FrameworkControllerTests.cs @@ -364,7 +364,7 @@ public void ExploreTestsAction_WithoutLoad_ThrowsInvalidOperationException() { var ex = Assert.Throws( () => new FrameworkController.ExploreTestsAction(_controller, EMPTY_FILTER, _handler)); - Assert.That(ex.Message, Is.EqualTo("The Explore method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before exploring them.")); } [Test] @@ -421,7 +421,7 @@ public void CountTestsAction_WithoutLoad_ThrowsInvalidOperation() { var ex = Assert.Throws( () => new FrameworkController.CountTestsAction(_controller, EMPTY_FILTER, _handler)); - Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before counting test cases.")); } [Test] @@ -475,7 +475,7 @@ public void RunTestsAction_WithoutLoad_ReturnsError() { var ex = Assert.Throws( () => new FrameworkController.RunTestsAction(_controller, EMPTY_FILTER, _handler)); - Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before running them.")); } [Test] @@ -545,7 +545,7 @@ public void RunAsyncAction_WithoutLoad_ReturnsError() { var ex = Assert.Throws( () => new FrameworkController.RunAsyncAction(_controller, EMPTY_FILTER, _handler)); - Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before running them.")); } [Test] diff --git a/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs b/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs index ee41641cea..8652ce5be6 100644 --- a/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs +++ b/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs @@ -138,7 +138,7 @@ public void CountTestCases_WithoutLoad_ThrowsInvalidOperation() { var ex = Assert.Throws( () => _runner.CountTestCases(TestFilter.Empty)); - Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before counting test cases.")); } [Test] @@ -163,7 +163,7 @@ public void ExploreTests_WithoutLoad_ThrowsInvalidOperation() { var ex = Assert.Throws( () => _runner.ExploreTests(TestFilter.Empty)); - Assert.That(ex.Message, Is.EqualTo("The ExploreTests method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before exploring them.")); } [Test] @@ -279,7 +279,7 @@ public void Run_WithoutLoad_ReturnsError() { var ex = Assert.Throws( () => _runner.Run(TestListener.NULL, TestFilter.Empty)); - Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before running them.")); } [Test, SetUICulture("en-US")] @@ -393,7 +393,7 @@ public void RunAsync_WithoutLoad_ReturnsError() { var ex = Assert.Throws( () => _runner.RunAsync(TestListener.NULL, TestFilter.Empty)); - Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded")); + Assert.That(ex.Message, Is.EqualTo("Tests must be loaded before running them.")); } [Test, SetUICulture("en-US")] @@ -538,7 +538,7 @@ public void TestOutput(TestOutput output) /// A TestMessage object containing the text to send public void SendMessage(TestMessage message) { - + } #endregion diff --git a/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs b/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs index c7f56d47e2..5c82443457 100644 --- a/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertEqualsTests.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -42,11 +42,11 @@ public void Equals() } [Test] - public void EqualsNull() + public void EqualsNull() { Assert.AreEqual(null, null); } - + [Test] public void Bug575936Int32Int64Comparison() { @@ -90,7 +90,7 @@ public void IntegerEquals() Assert.AreEqual(val, 42); } - + [Test] public void EqualsFail() { @@ -106,21 +106,21 @@ public void EqualsFail() var ex = Assert.Throws(() => Assert.AreEqual(expected, junitString)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } - + [Test] - public void EqualsNaNFails() + public void EqualsNaNFails() { var expectedMessage = " Expected: 1.234d +/- 0.0d" + Environment.NewLine + " But was: " + Double.NaN + Environment.NewLine; - + var ex = Assert.Throws(() => Assert.AreEqual(1.234, Double.NaN, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); - } + } [Test] - public void NanEqualsFails() + public void NanEqualsFails() { var expectedMessage = " Expected: " + Double.NaN + Environment.NewLine + @@ -128,55 +128,55 @@ public void NanEqualsFails() var ex = Assert.Throws(() => Assert.AreEqual(Double.NaN, 1.234, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); - } - + } + [Test] - public void NanEqualsNaNSucceeds() + public void NanEqualsNaNSucceeds() { Assert.AreEqual(Double.NaN, Double.NaN, 0.0); - } + } [Test] - public void NegInfinityEqualsInfinity() + public void NegInfinityEqualsInfinity() { Assert.AreEqual(Double.NegativeInfinity, Double.NegativeInfinity, 0.0); } [Test] - public void PosInfinityEqualsInfinity() + public void PosInfinityEqualsInfinity() { Assert.AreEqual(Double.PositiveInfinity, Double.PositiveInfinity, 0.0); } - + [Test] - public void PosInfinityNotEquals() + public void PosInfinityNotEquals() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: 1.23d" + Environment.NewLine; - + var ex = Assert.Throws(() => Assert.AreEqual(Double.PositiveInfinity, 1.23, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] - public void PosInfinityNotEqualsNegInfinity() + public void PosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: " + Double.NegativeInfinity + Environment.NewLine; - + var ex = Assert.Throws(() => Assert.AreEqual(Double.PositiveInfinity, Double.NegativeInfinity, 0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } - [Test] - public void SinglePosInfinityNotEqualsNegInfinity() + [Test] + public void SinglePosInfinityNotEqualsNegInfinity() { var expectedMessage = " Expected: " + Double.PositiveInfinity + Environment.NewLine + " But was: " + Double.NegativeInfinity + Environment.NewLine; - + var ex = Assert.Throws(() => Assert.AreEqual(float.PositiveInfinity, float.NegativeInfinity, (float)0.0)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } @@ -194,9 +194,9 @@ public void ReferenceEqualsThrowsException() object o = new object(); Assert.Throws(() => Assert.ReferenceEquals(o, o)); } - + [Test] - public void Float() + public void Float() { float val = (float)1.0; float expected = val; @@ -207,7 +207,7 @@ public void Float() } [Test] - public void Byte() + public void Byte() { byte val = 1; byte expected = val; @@ -218,7 +218,7 @@ public void Byte() } [Test] - public void String() + public void String() { string s1 = "test"; string s2 = new System.Text.StringBuilder(s1).ToString(); @@ -228,7 +228,7 @@ public void String() } [Test] - public void Short() + public void Short() { short val = 1; short expected = val; @@ -239,7 +239,7 @@ public void Short() } [Test] - public void Int() + public void Int() { int val = 1; int expected = val; @@ -250,7 +250,7 @@ public void Int() } [Test] - public void UInt() + public void UInt() { uint val = 1; uint expected = val; @@ -261,7 +261,7 @@ public void UInt() } [Test] - public void Decimal() + public void Decimal() { decimal expected = 100m; decimal actual = 100.0m; @@ -276,13 +276,13 @@ public void Decimal() } - + /// /// Checks to see that a value comparison works with all types. /// Current version has problems when value is the same but the /// types are different...C# is not like Java, and doesn't automatically /// perform value type conversion to simplify this type of comparison. - /// + /// /// Related to Bug575936Int32Int64Comparison, but covers all numeric /// types. /// @@ -301,17 +301,17 @@ public void EqualsSameTypes() ushort us11 = 35; char c1 = '3'; char c2 = 'a'; - - System.Byte b12 = 35; - System.SByte sb13 = 35; - System.Decimal d14 = 35; - System.Double d15 = 35; - System.Single s16 = 35; - System.Int32 i17 = 35; - System.UInt32 ui18 = 35; - System.Int64 i19 = 35; - System.UInt64 ui20 = 35; - System.Int16 i21 = 35; + + System.Byte b12 = 35; + System.SByte sb13 = 35; + System.Decimal d14 = 35; + System.Double d15 = 35; + System.Single s16 = 35; + System.Int32 i17 = 35; + System.UInt32 ui18 = 35; + System.Int64 i19 = 35; + System.UInt64 ui20 = 35; + System.Int16 i21 = 35; System.UInt16 i22 = 35; System.Char c12 = '3'; System.Char c22 = 'a'; @@ -328,7 +328,7 @@ public void EqualsSameTypes() Assert.AreEqual(35, us11); Assert.AreEqual('3', c1); Assert.AreEqual('a', c2); - + Assert.AreEqual( 35, b12 ); Assert.AreEqual( 35, sb13 ); Assert.AreEqual( 35, d14 ); @@ -552,14 +552,14 @@ public void IEquatableSuccess_ConstraintSyntax() public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => Assert.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("Assert.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("Assert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => Assert.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("Assert.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("Assert.ReferenceEquals should not be used.")); } [Test] diff --git a/src/NUnitFramework/tests/Assertions/AssertionHelperTests.cs b/src/NUnitFramework/tests/Assertions/AssertionHelperTests.cs index ee144e559a..0dd7481bd0 100644 --- a/src/NUnitFramework/tests/Assertions/AssertionHelperTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertionHelperTests.cs @@ -3,9 +3,10 @@ using NUnit.Framework.Constraints; using NUnit.TestUtilities.Comparers; +#pragma warning disable CS0618 // AssertionHelper is obsolete + namespace NUnit.Framework.Syntax { - [Obsolete("Test of Obsolete AssertionHelper class")] class AssertionHelperTests : AssertionHelper { private static readonly string DEFAULT_PATH_CASE = Path.DirectorySeparatorChar == '\\' ? "ignorecase" : "respectcase"; @@ -309,7 +310,7 @@ public void NaNTest() #endregion #region After - + [Test] public void After() { diff --git a/src/NUnitFramework/tests/Assertions/AssumeEqualsTests.cs b/src/NUnitFramework/tests/Assertions/AssumeEqualsTests.cs index 81a549247d..84395747bd 100644 --- a/src/NUnitFramework/tests/Assertions/AssumeEqualsTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssumeEqualsTests.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace NUnit.Framework.Assertions { @@ -9,14 +9,14 @@ public class AssumeEqualsTests public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => Assume.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("Assume.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("Assume.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => Assume.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("Assume.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("Assume.ReferenceEquals should not be used.")); } } } diff --git a/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs b/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs index 1e1e16b57b..c0036eca6d 100644 --- a/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs +++ b/src/NUnitFramework/tests/Assertions/CollectionAssertTest.cs @@ -736,14 +736,14 @@ public void IsOrdered_Handles_custom_comparison2() public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => CollectionAssert.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used.")); } #endregion diff --git a/src/NUnitFramework/tests/Assertions/DirectoryAssertTests.cs b/src/NUnitFramework/tests/Assertions/DirectoryAssertTests.cs index 3985ecd570..413272b138 100644 --- a/src/NUnitFramework/tests/Assertions/DirectoryAssertTests.cs +++ b/src/NUnitFramework/tests/Assertions/DirectoryAssertTests.cs @@ -235,14 +235,14 @@ public void DoesNotExistFailsWhenStringIsEmpty() public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => DirectoryAssert.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("DirectoryAssert.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("DirectoryAssert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => DirectoryAssert.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("DirectoryAssert.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("DirectoryAssert.ReferenceEquals should not be used.")); } #endregion diff --git a/src/NUnitFramework/tests/Assertions/FileAssertTests.cs b/src/NUnitFramework/tests/Assertions/FileAssertTests.cs index cfd0546a64..f299f12a40 100644 --- a/src/NUnitFramework/tests/Assertions/FileAssertTests.cs +++ b/src/NUnitFramework/tests/Assertions/FileAssertTests.cs @@ -465,14 +465,14 @@ public void DoesNotExistFailsWhenStringIsEmpty() public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => FileAssert.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("FileAssert.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("FileAssert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => FileAssert.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("FileAssert.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("FileAssert.ReferenceEquals should not be used.")); } #endregion diff --git a/src/NUnitFramework/tests/Assertions/StringAssertTests.cs b/src/NUnitFramework/tests/Assertions/StringAssertTests.cs index 740e327bd5..8986143713 100644 --- a/src/NUnitFramework/tests/Assertions/StringAssertTests.cs +++ b/src/NUnitFramework/tests/Assertions/StringAssertTests.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -135,7 +135,7 @@ public void CaseInsensitiveCompareFails() Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } - [Test] + [Test] public void IsMatch() { StringAssert.IsMatch( "a?bc", "12a3bc45" ); @@ -166,14 +166,14 @@ public void DifferentEncodingsOfSameStringAreNotEqual() public void EqualsFailsWhenUsed() { var ex = Assert.Throws(() => StringAssert.Equals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("StringAssert.Equals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("StringAssert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws(() => StringAssert.ReferenceEquals(string.Empty, string.Empty)); - Assert.That(ex.Message, Does.StartWith("StringAssert.ReferenceEquals should not be used for Assertions")); + Assert.That(ex.Message, Does.StartWith("StringAssert.ReferenceEquals should not be used.")); } } } diff --git a/src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs b/src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs index 4335e968c2..79877b270f 100644 --- a/src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/DictionaryContainsKeyConstraintTests.cs @@ -8,10 +8,10 @@ // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: -// +// // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -85,7 +85,8 @@ public void WorksWithNonGenericDictionary() } #endif - [Test, Obsolete] +#pragma warning disable CS0618 // DictionaryContainsKeyConstraint.IgnoreCase and .Using are deprecated + public void IgnoreCaseIsHonored() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -93,7 +94,7 @@ public void IgnoreCaseIsHonored() Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").IgnoreCase); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingIsHonored() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -101,7 +102,7 @@ public void UsingIsHonored() Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").Using((x, y) => StringUtil.Compare(x, y, true))); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void SucceedsWhenKeyIsPresentWhenDictionaryUsingCustomComparer() { var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -109,6 +110,8 @@ public void SucceedsWhenKeyIsPresentWhenDictionaryUsingCustomComparer() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello")); } +#pragma warning restore CS0618 + [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenDictionaryUsingCustomComparer() { @@ -245,7 +248,9 @@ public void ShouldCallContainsKeysMethodOnLookupInterface() Assert.That(dictionary, !Does.ContainKey(43)); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] +#pragma warning disable CS0618 // DictionaryContainsKeyConstraint.Using is obsolete + + [Test] public void UsingDictionaryContainsKeyConstraintComparisonFunc() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -253,7 +258,7 @@ public void UsingDictionaryContainsKeyConstraintComparisonFunc() Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").Using((x, y) => x.ToUpper().Equals(y.ToUpper()))); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingBaseCollectionItemsEqualConstraintNonGenericComparer() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -261,7 +266,7 @@ public void UsingBaseCollectionItemsEqualConstraintNonGenericComparer() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hola").Using((IComparer)StringComparer.OrdinalIgnoreCase)); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingBaseCollectionItemsEqualConstraintGenericComparer() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -269,7 +274,7 @@ public void UsingBaseCollectionItemsEqualConstraintGenericComparer() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hola").Using((IComparer)StringComparer.OrdinalIgnoreCase)); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingBaseCollectionItemsEqualConstraintNonGenericEqualityComparer() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -277,7 +282,7 @@ public void UsingBaseCollectionItemsEqualConstraintNonGenericEqualityComparer() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using((IEqualityComparer)StringComparer.OrdinalIgnoreCase)); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingBaseCollectionItemsEqualConstraintGenericEqualityComparer() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -285,7 +290,7 @@ public void UsingBaseCollectionItemsEqualConstraintGenericEqualityComparer() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using((IEqualityComparer)StringComparer.OrdinalIgnoreCase)); } - [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] + [Test] public void UsingBaseCollectionItemsEqualConstraintComparerFunc() { var dictionary = new Dictionary { { "Hello", "World" }, { "Hola", "Mundo" } }; @@ -293,6 +298,8 @@ public void UsingBaseCollectionItemsEqualConstraintComparerFunc() Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using((x, y) => x.ToLower().Equals(y.ToLower()))); } +#pragma warning restore CS0618 + #region Test Assets public class TestPlainContainsKey From ae8175c68c757e890f32dfd5902b1aea1c370bc1 Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Mon, 25 Feb 2019 10:48:54 -0500 Subject: [PATCH 120/174] Clean up doc comments based on PR feedback --- .../Internal/Tests/ParameterizedFixtureSuite.cs | 10 +++++----- .../Internal/Tests/ParameterizedMethodSuite.cs | 10 +++++----- .../framework/Internal/Tests/SetUpFixture.cs | 10 +++++----- .../framework/Internal/Tests/TestAssembly.cs | 11 +++++------ .../framework/Internal/Tests/TestFixture.cs | 10 +++++----- .../framework/Internal/Tests/TestSuite.cs | 13 ++++++------- 6 files changed, 31 insertions(+), 33 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs b/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs index ca13d9ca31..27193968c1 100644 --- a/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/ParameterizedFixtureSuite.cs @@ -43,10 +43,10 @@ public ParameterizedFixtureSuite(ITypeInfo typeInfo) : base(typeInfo.Namespace, } /// - /// Copy constructor style to create a filtered copy of the given parameterized fixture suite + /// Creates a copy of the given suite with only the descendants that pass the specified filter. /// - /// Parameterized Fixture Suite to copy - /// Filter to be applied + /// The to copy. + /// Determines which descendants are copied. public ParameterizedFixtureSuite(ParameterizedFixtureSuite suite, ITestFilter filter) : base(suite, filter) { @@ -66,9 +66,9 @@ public override string TestType } /// - /// Overriden to return a Parameterized Fixture Suite + /// Creates a filtered copy of the test suite. /// - /// Filter to apply + /// Determines which descendants are copied. public override TestSuite Copy(ITestFilter filter) { return new ParameterizedFixtureSuite(this, filter); diff --git a/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs b/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs index 416de9cdd4..e377c99d37 100644 --- a/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/ParameterizedMethodSuite.cs @@ -45,10 +45,10 @@ public ParameterizedMethodSuite(IMethodInfo method) } /// - /// Copy constructor style to create a filtered copy of the given parameterized method suite + /// Creates a copy of the given suite with only the descendants that pass the specified filter. /// - /// Parameterized Method Suite to copy - /// Filter to be applied + /// The to copy. + /// Determines which descendants are copied. public ParameterizedMethodSuite(ParameterizedMethodSuite suite, ITestFilter filter) : base(suite, filter) { @@ -72,9 +72,9 @@ public override string TestType } /// - /// Overriden to return a Parameterized Method Suite + /// Creates a filtered copy of the test suite. /// - /// Filter to apply + /// Determines which descendants are copied. public override TestSuite Copy(ITestFilter filter) { return new ParameterizedMethodSuite(this, filter); diff --git a/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs b/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs index 375e66fabd..8b34a102ac 100644 --- a/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs +++ b/src/NUnitFramework/framework/Internal/Tests/SetUpFixture.cs @@ -53,10 +53,10 @@ public SetUpFixture(ITypeInfo type) : base(type) } /// - /// Copy constructor style to create a filtered copy of the given setup fixture + /// Creates a copy of the given suite with only the descendants that pass the specified filter. /// - /// SetUp Fixture to copy - /// Filter to be applied + /// The to copy. + /// Determines which descendants are copied. public SetUpFixture(SetUpFixture setUpFixture, ITestFilter filter) : base(setUpFixture, filter) { @@ -67,9 +67,9 @@ public SetUpFixture(SetUpFixture setUpFixture, ITestFilter filter) #region Test Suite Overrides /// - /// Overriden to return a SetUp Fixture + /// Creates a filtered copy of the test suite. /// - /// Filter to apply + /// Determines which descendants are copied. public override TestSuite Copy(ITestFilter filter) { return new SetUpFixture(this, filter); diff --git a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs index 0a04db3797..7ac3a0d416 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs @@ -57,11 +57,10 @@ public TestAssembly(string name) : base(name) } /// - /// Copy-constructor style to create a filtered copy of the test assemblies - /// test cases + /// Creates a copy of the given assembly with only the descendants that pass the specified filter. /// - /// - /// + /// The to copy. + /// Determines which descendants are copied. public TestAssembly(TestAssembly assembly, ITestFilter filter) : base(assembly as TestSuite, filter) { @@ -97,9 +96,9 @@ public override TAttr[] GetCustomAttributes(bool inherit) } /// - /// Overriden to return a Test Assembly + /// Creates a filtered copy of the test suite. /// - /// Filter to apply + /// Determines which descendants are copied. public override TestSuite Copy(ITestFilter filter) { return new TestAssembly(this, filter); diff --git a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs index 9bbb2e5740..23b6f8e0d2 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestFixture.cs @@ -52,10 +52,10 @@ public TestFixture(ITypeInfo fixtureType, object[] arguments = null) : base(fixt } /// - /// Copy constructor style to create a filtered copy of the given test fixture + /// Creates a copy of the given suite with only the descendants that pass the specified filter. /// - /// Test Fixture to copy - /// Filter to be applied + /// The to copy. + /// Determines which descendants are copied. private TestFixture(TestFixture fixture, ITestFilter filter) : base(fixture, filter) { @@ -66,9 +66,9 @@ private TestFixture(TestFixture fixture, ITestFilter filter) #region Test Suite Overrides /// - /// Overriden to return a Test Fixture + /// Creates a filtered copy of the test suite. /// - /// Filter to apply + /// Determines which descendants are copied. public override TestSuite Copy(ITestFilter filter) { return new TestFixture(this, filter); diff --git a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs index e6790e1654..b39bbf8bbe 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs @@ -99,10 +99,10 @@ public TestSuite(Type fixtureType) } /// - /// Copy constructor style to create a filtered copy of the given test suite + /// Creates a copy of the given suite with only the descendants that pass the specified filter. /// - /// Test Suite to copy - /// Filter to be applied + /// The to copy. + /// Determines which descendants are copied. public TestSuite(TestSuite suite, ITestFilter filter) : base(suite.Name) { @@ -117,7 +117,7 @@ public TestSuite(TestSuite suite, ITestFilter filter) { if(child.IsSuite) { - TestSuite childSuite = ((TestSuite) child).Copy(filter); + TestSuite childSuite = ((TestSuite)child).Copy(filter); childSuite.Parent = this; this.tests.Add(childSuite); } @@ -180,10 +180,9 @@ public void Add(Test test) } /// - /// Creates a filtered copy of the test suite + /// Creates a filtered copy of the test suite. /// - /// Filter to apply - /// + /// Determines which descendants are copied. public virtual TestSuite Copy(ITestFilter filter) { return new TestSuite(this, filter); From 5541de5f95b5b6bf4a1906c48256488d8847228f Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Mon, 25 Feb 2019 13:42:02 -0500 Subject: [PATCH 121/174] Add tests to cover TestSuite.Copy --- .../tests/Internal/TestSuiteCopyTests.cs | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs diff --git a/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs new file mode 100644 index 0000000000..5c5921f5b9 --- /dev/null +++ b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs @@ -0,0 +1,66 @@ +using NUnit.Framework.Api; +using NUnit.TestData.OneTimeSetUpTearDownData; +using NUnit.TestData.TestFixtureSourceData; +using NUnit.TestUtilities; + +namespace NUnit.Framework.Internal +{ + // Tests that Copy is properly overridden for all types extending TestSuite - #3171 + public class TestSuiteCopyTests + { + [Test] + public void CopyTestSuiteReturnsCorrectType() + { + TestSuite testSuite = + new TestSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); + var copiedTestSuite = testSuite.Copy(TestFilter.Empty); + Assert.AreEqual(copiedTestSuite.GetType(), typeof(TestSuite)); + } + + [Test] + public void CopyParameterizedTestFixtureReturnsCorrectType() + { + TestSuite parameterizedTestFixture = + new ParameterizedFixtureSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); + var copiedParameterizedTestFixture = parameterizedTestFixture.Copy(TestFilter.Empty); + Assert.AreEqual(copiedParameterizedTestFixture.GetType(), typeof(ParameterizedFixtureSuite)); + } + + [Test] + public void CopyParameterizedMethodSuiteReturnsCorrectType() + { + TestSuite parameterizedMethodSuite = new ParameterizedMethodSuite(new MethodWrapper( + typeof(NUnit.TestData.ParameterizedTestFixture), + nameof(NUnit.TestData.ParameterizedTestFixture.MethodWithParams))); + var copiedparameterizedMethodSuite = parameterizedMethodSuite.Copy(TestFilter.Empty); + Assert.AreEqual(copiedparameterizedMethodSuite.GetType(), typeof(ParameterizedMethodSuite)); + } + + [Test] + public void CopyTestFixtureReturnsCorrectType() + { + TestSuite testFixture = TestBuilder.MakeFixture(typeof(FixtureWithNoTests)); + var copiedTestFixture = testFixture.Copy(TestFilter.Empty); + Assert.AreEqual(copiedTestFixture.GetType(), typeof(TestFixture)); + } + + [Test] + public void CopySetUpFixtureReturnsCorrectType() + { + TestSuite setUpFixture = + new SetUpFixture( + new TypeWrapper(typeof(NUnit.TestData.SetupFixture.Namespace1.NUnitNamespaceSetUpFixture1))); + var copiedSetupFixture = setUpFixture.Copy(TestFilter.Empty); + Assert.AreEqual(copiedSetupFixture.GetType(), typeof(SetUpFixture)); + } + + [Test] + public void CopyTestAssemblyReturnsCorrectType() + { + var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); + TestSuite assembly = new TestAssembly(AssemblyHelper.Load("mock-assembly.dll"), "mock-assembly"); + var copiedAssembly = assembly.Copy(TestFilter.Empty); + Assert.AreEqual(copiedAssembly.GetType(), typeof(TestAssembly)); + } + } +} From 1d686734f5700b87fa016b52b1b27fd97a843b98 Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Mon, 25 Feb 2019 14:16:09 -0500 Subject: [PATCH 122/174] Fix CopyTestAssemblyReturnsCorrectType - load assembly relative to current test context --- src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs index 5c5921f5b9..2d3f527c70 100644 --- a/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs +++ b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs @@ -1,7 +1,7 @@ using NUnit.Framework.Api; using NUnit.TestData.OneTimeSetUpTearDownData; -using NUnit.TestData.TestFixtureSourceData; using NUnit.TestUtilities; +using System.IO; namespace NUnit.Framework.Internal { @@ -58,7 +58,10 @@ public void CopySetUpFixtureReturnsCorrectType() public void CopyTestAssemblyReturnsCorrectType() { var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); - TestSuite assembly = new TestAssembly(AssemblyHelper.Load("mock-assembly.dll"), "mock-assembly"); + TestSuite assembly = + new TestAssembly( + AssemblyHelper.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll")), + "mock-assembly"); var copiedAssembly = assembly.Copy(TestFilter.Empty); Assert.AreEqual(copiedAssembly.GetType(), typeof(TestAssembly)); } From adf3d4916c0909a399d2f6e88c78f96f093701cc Mon Sep 17 00:00:00 2001 From: "drew.burlingame" Date: Sat, 9 Mar 2019 21:37:24 +0000 Subject: [PATCH 123/174] Include ex.Data values in failure message (#3145) Capture exception in ExceptionResult, enabling extensions to perform more in-depth analysis & reporting for failures When value is null, replace with "" --- .../framework/Internal/ExceptionHelper.cs | 33 ++++ .../framework/Internal/Results/TestResult.cs | 7 +- ...ExceptionHelperOutputExceptionDataTests.cs | 162 ++++++++++++++++++ 3 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs diff --git a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs index 1f4324ddb2..519a8401b5 100644 --- a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs +++ b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs @@ -22,8 +22,10 @@ // *********************************************************************** using System; +using System.Collections; using System.Globalization; using System.Collections.Generic; +using System.Linq; using System.Reflection; using System.Text; @@ -34,6 +36,11 @@ namespace NUnit.Framework.Internal /// public class ExceptionHelper { + /// + /// When true, each entry in Exception.Data is included in the exception message + /// + public static bool OutputExceptionDataProperty { get; set; } = true; + #if NET35 || NET40 private static readonly Action PreserveStackTrace; @@ -84,6 +91,10 @@ public static string BuildMessage(Exception exception, bool excludeExceptionName if (!excludeExceptionNames) sb.AppendFormat("{0} : ", exception.GetType()); sb.Append(GetExceptionMessage(exception)); + if (OutputExceptionDataProperty) + { + AppendExceptionDataContents(exception, sb); + } foreach (Exception inner in FlattenExceptionHierarchy(exception)) { @@ -92,6 +103,10 @@ public static string BuildMessage(Exception exception, bool excludeExceptionName if (!excludeExceptionNames) sb.AppendFormat("{0} : ", inner.GetType()); sb.Append(GetExceptionMessage(inner)); + if (OutputExceptionDataProperty) + { + AppendExceptionDataContents(inner, sb); + } } return sb.ToString(); @@ -151,6 +166,24 @@ private static string GetExceptionMessage(Exception ex) return ex.Message; } + private static void AppendExceptionDataContents(Exception ex, StringBuilder sb) + { + if (ex.Data.Count == 0) + { + return; + } + + sb.AppendLine(); + sb.AppendLine("Data:"); + foreach (DictionaryEntry kvp in ex.Data) + { + sb.Append(" "); + sb.Append(kvp.Key); + sb.Append(": "); + sb.AppendLine(kvp.Value?.ToString() ?? ""); + } + } + private static List FlattenExceptionHierarchy(Exception exception) { var result = new List(); diff --git a/src/NUnitFramework/framework/Internal/Results/TestResult.cs b/src/NUnitFramework/framework/Internal/Results/TestResult.cs index 1a547e43c5..2ea0bcfc0a 100644 --- a/src/NUnitFramework/framework/Internal/Results/TestResult.cs +++ b/src/NUnitFramework/framework/Internal/Results/TestResult.cs @@ -571,11 +571,14 @@ private struct ExceptionResult { public ResultState ResultState { get; } public string Message { get; } - public string StackTrace { get; } + public string StackTrace { get; } + public Exception Exception { get; } public ExceptionResult(Exception ex, FailureSite site) { - ex = ValidateAndUnwrap(ex); + ex = ValidateAndUnwrap(ex); + + Exception = ex; if (ex is ResultStateException) { diff --git a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs new file mode 100644 index 0000000000..1f0013eaa7 --- /dev/null +++ b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs @@ -0,0 +1,162 @@ +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Specialized; + +namespace NUnit.Framework.Internal { + public static class ExceptionHelperOutputExceptionDataTests + { + + [Test] + public static void AppendsDataItemsToExceptionMessage() + { + var exception = new Exception("blah"); + exception.Data["data-prop"] = "data-value"; + + var message = ExceptionHelper.BuildMessage(exception); + Assert.That(message, Contains.Substring("data-prop")); + Assert.That(message, Contains.Substring("data-value")); + } + + [Test] + public static void CanDisable() + { + var exception = new Exception("blah"); + exception.Data["data-prop"] = "data-value"; + + string message; + try + { + ExceptionHelper.OutputExceptionDataProperty = false; + message = ExceptionHelper.BuildMessage(exception); + } + finally + { + ExceptionHelper.OutputExceptionDataProperty = true; + } + + Assert.That(message, !Contains.Substring("data-prop")); + Assert.That(message, !Contains.Substring("data-value")); + } + + [Test] + public static void IncludesNullProperties() + { + var exception = new Exception("blah"); + exception.Data["data-prop"] = null; + + var message = ExceptionHelper.BuildMessage(exception); + Assert.That(message, Contains.Substring("data-prop")); + Assert.That(message, Contains.Substring("")); + } + } +} From 423a6275c12b48bc0b95522ef7b97544705ae61d Mon Sep 17 00:00:00 2001 From: "drew.burlingame" Date: Sat, 9 Mar 2019 22:10:45 +0000 Subject: [PATCH 124/174] fix formatting snafu --- src/NUnitFramework/framework/Internal/ExceptionHelper.cs | 2 +- .../Internal/ExceptionHelperOutputExceptionDataTests.cs | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs index 519a8401b5..277cff38c5 100644 --- a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs +++ b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs @@ -37,7 +37,7 @@ namespace NUnit.Framework.Internal public class ExceptionHelper { /// - /// When true, each entry in Exception.Data is included in the exception message + /// When true, each entry in Exception.Data is included in the exception message. /// public static bool OutputExceptionDataProperty { get; set; } = true; diff --git a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs index 1f0013eaa7..f112bba3fc 100644 --- a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs +++ b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs @@ -110,12 +110,11 @@ // *********************************************************************** using System; -using System.Collections.Specialized; -namespace NUnit.Framework.Internal { +namespace NUnit.Framework.Internal +{ public static class ExceptionHelperOutputExceptionDataTests { - [Test] public static void AppendsDataItemsToExceptionMessage() { From d56424858f97e19a5fe64905e42adf798ca655d1 Mon Sep 17 00:00:00 2001 From: Tony Hallett Date: Mon, 11 Mar 2019 22:26:32 +0000 Subject: [PATCH 125/174] Closes #3181 --- src/NUnitFramework/framework/Internal/TestNameGenerator.cs | 2 +- src/NUnitFramework/tests/Internal/TestNameGeneratorTests.cs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Internal/TestNameGenerator.cs b/src/NUnitFramework/framework/Internal/TestNameGenerator.cs index 9278cda1c4..31c98fdcf7 100644 --- a/src/NUnitFramework/framework/Internal/TestNameGenerator.cs +++ b/src/NUnitFramework/framework/Internal/TestNameGenerator.cs @@ -154,7 +154,7 @@ private static List BuildFragmentList(string pattern) case "{8}": case "{9}": int index = token[1] - '0'; - fragments.Add(new ArgumentFragment(index, 40)); + fragments.Add(new ArgumentFragment(index, 0)); break; default: char c = token[1]; diff --git a/src/NUnitFramework/tests/Internal/TestNameGeneratorTests.cs b/src/NUnitFramework/tests/Internal/TestNameGeneratorTests.cs index a6f16a4df6..f3b5902c30 100644 --- a/src/NUnitFramework/tests/Internal/TestNameGeneratorTests.cs +++ b/src/NUnitFramework/tests/Internal/TestNameGeneratorTests.cs @@ -79,6 +79,8 @@ public string SimpleTestNames(string pattern) [TestCase("{m}({3})", new object[] { 1, 2, 3 }, ExpectedResult = "TestMethod()")] [TestCase("{m}({1:20})", new object[] { 42, "Now is the time for all good men to come to the aid of their country.", 5.2 }, ExpectedResult = "TestMethod(\"Now is the time f...\")")] + [TestCase("{m}({0})", new object[] { "Now is the time for all good men to come to the aid of their country." }, + ExpectedResult = "TestMethod(\"Now is the time for all good men to come to the aid of their country.\")")] public string ParameterizedTests(string pattern, object[] args) { return new TestNameGenerator(pattern).GetDisplayName(_simpleTest, args); From 24c6138cec16481f88dfa59046bef28ed50e24c2 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 16 Mar 2019 23:48:50 +0100 Subject: [PATCH 126/174] Add failing tests (The only problem is that they are not failing on my machine) --- .../Internal/Commands/TimeoutCommand.cs | 2 +- .../tests/Attributes/TimeoutTests.cs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs index 6f614d530e..568c68a460 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TimeoutCommand.cs @@ -31,7 +31,7 @@ namespace NUnit.Framework.Internal.Commands { /// - /// TimeoutCommand creates a timer in order to cancel + /// creates a timer in order to cancel /// a test if it exceeds a specified time and adjusts /// the test result if it did time out. /// diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 0282d04d09..c2de0ef98f 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -22,6 +22,7 @@ // *********************************************************************** using System; +using System.Globalization; using System.Linq; using System.Threading; using NUnit.Framework; @@ -35,6 +36,19 @@ namespace NUnit.Framework.Attributes [NonParallelizable] public class TimeoutTests : ThreadingTests { + [Test, Timeout(500), SetCulture("fr-BE"), SetUICulture("es-BO")] + public void TestWithTimeoutRespectsCulture() + { + Assert.That(CultureInfo.CurrentCulture.Name, Is.EqualTo("fr-BE")); + Assert.That(CultureInfo.CurrentUICulture.Name, Is.EqualTo("es-BO")); + } + + [Test, Timeout(500)] + public void TestWithTimeoutCurrentContextIsNotAnAdhocContext() + { + Assert.That(TestExecutionContext.CurrentContext, Is.Not.TypeOf()); + } + #if PLATFORM_DETECTION && THREAD_ABORT [Test, Timeout(500)] public void TestWithTimeoutRunsOnSameThread() @@ -169,7 +183,7 @@ public void TimeoutWithMessagePumpShouldAbort() } #endif -#if !THREAD_ABORT && !(NET20 || NET35) +#if !THREAD_ABORT [Timeout(50)] public void TestTimeoutAndReportsTimeoutFailure() { From ca33b5aaeae2de00dd447a5ee86348716dbe55a6 Mon Sep 17 00:00:00 2001 From: Carlos Parra Date: Sun, 17 Mar 2019 12:51:17 -0400 Subject: [PATCH 127/174] updated nuspec files to use new license tag --- nuget/framework/nunit.nuspec | 2 +- nuget/nunitlite/nunitlite.nuspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nuget/framework/nunit.nuspec b/nuget/framework/nunit.nuspec index 2f4b0444a4..aa67fdf15a 100644 --- a/nuget/framework/nunit.nuspec +++ b/nuget/framework/nunit.nuspec @@ -6,7 +6,7 @@ $version$ Charlie Poole, Rob Prouse Charlie Poole, Rob Prouse - https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt + LICENSE.txt https://nunit.org https://cdn.rawgit.com/nunit/resources/master/images/icon/nunit_256.png diff --git a/nuget/nunitlite/nunitlite.nuspec b/nuget/nunitlite/nunitlite.nuspec index 77e717cc02..cdbfb4da1f 100644 --- a/nuget/nunitlite/nunitlite.nuspec +++ b/nuget/nunitlite/nunitlite.nuspec @@ -6,7 +6,7 @@ $version$ Charlie Poole, Rob Prouse Charlie Poole, Rob Prouse - https://raw.githubusercontent.com/nunit/nunit/master/LICENSE.txt + LICENSE.txt https://nunit.org https://cdn.rawgit.com/nunit/resources/master/images/icon/nunit_256.png From c5e4ae69831a0bab8f8c560788606372c663c7bb Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Sun, 17 Mar 2019 16:33:06 -0700 Subject: [PATCH 128/174] Find the correct location for MSBUILD in Visual Studio 2019 --- build.cake | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/build.cake b/build.cake index 90ed58b630..cfb78e6971 100644 --- a/build.cake +++ b/build.cake @@ -159,17 +159,29 @@ Task("Build") MSBuildSettings CreateSettings() { - var settings = new MSBuildSettings { Verbosity = Verbosity.Minimal, Configuration = configuration }; + // Find MSBuild for Visual Studio 2017 + DirectoryPath vsLatest = VSWhereLatest(); + FilePath msBuildPathX64 = (vsLatest==null) ? null + : vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe"); - // Only needed when packaging - settings.WithProperty("DebugType", "pdbonly"); + // Find MSBuild for Visual Studio 2019 + if ( msBuildPathX64 != null && !FileExists(msBuildPathX64)) + msBuildPathX64 = vsLatest.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); - if (IsRunningOnWindows()) - settings.ToolVersion = MSBuildToolVersion.VS2017; - else - settings.ToolPath = Context.Tools.Resolve("msbuild"); + // Have we found MSBuild yet? + if ( !FileExists(msBuildPathX64) ) + { + throw new Exception($"Failed to find MSBuild: {msBuildPathX64}"); + } - return settings; + Information("Building using MSBuild at " + msBuildPathX64); + + return new MSBuildSettings { ToolPath = msBuildPathX64 } + .SetConfiguration(configuration) + .WithProperty("DebugType", "pdbonly") + .SetVerbosity(Verbosity.Minimal) + // Workaround for https://github.com/Microsoft/msbuild/issues/3626 + .WithProperty("AddSyntheticProjectReferencesForSolutionDependencies", "false"); } ////////////////////////////////////////////////////////////////////// From 3cc61d037fa093a0f2121997612e851afd76f2e7 Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Sun, 17 Mar 2019 16:57:09 -0700 Subject: [PATCH 129/174] Rework to build on Linux --- build.cake | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/build.cake b/build.cake index cfb78e6971..b3e6493326 100644 --- a/build.cake +++ b/build.cake @@ -159,29 +159,35 @@ Task("Build") MSBuildSettings CreateSettings() { - // Find MSBuild for Visual Studio 2017 - DirectoryPath vsLatest = VSWhereLatest(); - FilePath msBuildPathX64 = (vsLatest==null) ? null - : vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe"); + var settings = new MSBuildSettings { Verbosity = Verbosity.Minimal, Configuration = configuration }; - // Find MSBuild for Visual Studio 2019 - if ( msBuildPathX64 != null && !FileExists(msBuildPathX64)) - msBuildPathX64 = vsLatest.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); + // Only needed when packaging + settings.WithProperty("DebugType", "pdbonly"); - // Have we found MSBuild yet? - if ( !FileExists(msBuildPathX64) ) + if (IsRunningOnWindows()) { - throw new Exception($"Failed to find MSBuild: {msBuildPathX64}"); - } + // Find MSBuild for Visual Studio 2017 + DirectoryPath vsLatest = VSWhereLatest(); + FilePath msBuildPathX64 = (vsLatest==null) ? null + : vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe"); + + // Find MSBuild for Visual Studio 2019 + if ( msBuildPathX64 != null && !FileExists(msBuildPathX64)) + msBuildPathX64 = vsLatest.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); - Information("Building using MSBuild at " + msBuildPathX64); + // Have we found MSBuild yet? + if ( !FileExists(msBuildPathX64) ) + { + throw new Exception($"Failed to find MSBuild: {msBuildPathX64}"); + } - return new MSBuildSettings { ToolPath = msBuildPathX64 } - .SetConfiguration(configuration) - .WithProperty("DebugType", "pdbonly") - .SetVerbosity(Verbosity.Minimal) - // Workaround for https://github.com/Microsoft/msbuild/issues/3626 - .WithProperty("AddSyntheticProjectReferencesForSolutionDependencies", "false"); + Information("Building using MSBuild at " + msBuildPathX64); + settings.ToolPath = msBuildPathX64; + } + else + settings.ToolPath = Context.Tools.Resolve("msbuild"); + + return settings; } ////////////////////////////////////////////////////////////////////// From 87bc1722d49da627704d6aa474621ce89c551473 Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Mon, 18 Mar 2019 08:44:53 -0700 Subject: [PATCH 130/174] Changes in response to code reviews --- build.cake | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/build.cake b/build.cake index b3e6493326..7b2db3deb4 100644 --- a/build.cake +++ b/build.cake @@ -166,23 +166,22 @@ MSBuildSettings CreateSettings() if (IsRunningOnWindows()) { - // Find MSBuild for Visual Studio 2017 + // Find MSBuild for Visual Studio 2019 and newer DirectoryPath vsLatest = VSWhereLatest(); - FilePath msBuildPathX64 = (vsLatest==null) ? null - : vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe"); + FilePath msBuildPath = vsLatest?.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); - // Find MSBuild for Visual Studio 2019 - if ( msBuildPathX64 != null && !FileExists(msBuildPathX64)) - msBuildPathX64 = vsLatest.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); + // Find MSBuild for Visual Studio 2017 + if (msBuildPath != null && !FileExists(msBuildPath)) + msBuildPath = vsLatest.CombineWithFilePath("./MSBuild/15.0/Bin/MSBuild.exe"); // Have we found MSBuild yet? - if ( !FileExists(msBuildPathX64) ) + if (!FileExists(msBuildPath)) { - throw new Exception($"Failed to find MSBuild: {msBuildPathX64}"); + throw new Exception($"Failed to find MSBuild: {msBuildPath}"); } - Information("Building using MSBuild at " + msBuildPathX64); - settings.ToolPath = msBuildPathX64; + Information("Building using MSBuild at " + msBuildPath); + settings.ToolPath = msBuildPath; } else settings.ToolPath = Context.Tools.Resolve("msbuild"); From 4580c663f5348816d0b97617059a4de4d215b80d Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Mon, 18 Mar 2019 08:50:34 -0700 Subject: [PATCH 131/174] Remove extra whitespace --- build.cake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.cake b/build.cake index 7b2db3deb4..dffd75853a 100644 --- a/build.cake +++ b/build.cake @@ -167,7 +167,7 @@ MSBuildSettings CreateSettings() if (IsRunningOnWindows()) { // Find MSBuild for Visual Studio 2019 and newer - DirectoryPath vsLatest = VSWhereLatest(); + DirectoryPath vsLatest = VSWhereLatest(); FilePath msBuildPath = vsLatest?.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe"); // Find MSBuild for Visual Studio 2017 From 0cf22b06fe98b75bb74e58be4ead4a705bbf4fbd Mon Sep 17 00:00:00 2001 From: Conrad Rybka Date: Thu, 21 Mar 2019 10:17:29 -0400 Subject: [PATCH 132/174] Fix test assertions --- .../tests/Internal/TestSuiteCopyTests.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs index 2d3f527c70..9f9957771e 100644 --- a/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs +++ b/src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs @@ -14,7 +14,7 @@ public void CopyTestSuiteReturnsCorrectType() TestSuite testSuite = new TestSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); var copiedTestSuite = testSuite.Copy(TestFilter.Empty); - Assert.AreEqual(copiedTestSuite.GetType(), typeof(TestSuite)); + Assert.That(copiedTestSuite, Is.TypeOf()); } [Test] @@ -23,7 +23,7 @@ public void CopyParameterizedTestFixtureReturnsCorrectType() TestSuite parameterizedTestFixture = new ParameterizedFixtureSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture))); var copiedParameterizedTestFixture = parameterizedTestFixture.Copy(TestFilter.Empty); - Assert.AreEqual(copiedParameterizedTestFixture.GetType(), typeof(ParameterizedFixtureSuite)); + Assert.That(copiedParameterizedTestFixture, Is.TypeOf()); } [Test] @@ -33,7 +33,8 @@ public void CopyParameterizedMethodSuiteReturnsCorrectType() typeof(NUnit.TestData.ParameterizedTestFixture), nameof(NUnit.TestData.ParameterizedTestFixture.MethodWithParams))); var copiedparameterizedMethodSuite = parameterizedMethodSuite.Copy(TestFilter.Empty); - Assert.AreEqual(copiedparameterizedMethodSuite.GetType(), typeof(ParameterizedMethodSuite)); + Assert.That(copiedparameterizedMethodSuite, Is.TypeOf()); + } [Test] @@ -41,7 +42,7 @@ public void CopyTestFixtureReturnsCorrectType() { TestSuite testFixture = TestBuilder.MakeFixture(typeof(FixtureWithNoTests)); var copiedTestFixture = testFixture.Copy(TestFilter.Empty); - Assert.AreEqual(copiedTestFixture.GetType(), typeof(TestFixture)); + Assert.That(copiedTestFixture, Is.TypeOf()); } [Test] @@ -51,7 +52,7 @@ public void CopySetUpFixtureReturnsCorrectType() new SetUpFixture( new TypeWrapper(typeof(NUnit.TestData.SetupFixture.Namespace1.NUnitNamespaceSetUpFixture1))); var copiedSetupFixture = setUpFixture.Copy(TestFilter.Empty); - Assert.AreEqual(copiedSetupFixture.GetType(), typeof(SetUpFixture)); + Assert.That(copiedSetupFixture, Is.TypeOf()); } [Test] @@ -63,7 +64,7 @@ public void CopyTestAssemblyReturnsCorrectType() AssemblyHelper.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll")), "mock-assembly"); var copiedAssembly = assembly.Copy(TestFilter.Empty); - Assert.AreEqual(copiedAssembly.GetType(), typeof(TestAssembly)); + Assert.That(copiedAssembly, Is.TypeOf()); } } } From 1abd5cf6af420460d30eff9b866dd3235566eca0 Mon Sep 17 00:00:00 2001 From: stevenaw Date: Thu, 21 Mar 2019 19:31:32 -0400 Subject: [PATCH 133/174] Remove whitespace --- src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs index 4c188161e9..08649a799c 100644 --- a/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/TestCaseAttribute.cs @@ -263,7 +263,7 @@ private TestCaseParameters GetParametersForTestCase(IMethodInfo method) IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; - + parms = new TestCaseParameters(this); // Special handling for ExpectedResult (see if it needs to be converted into method return type) From 9f12840f7f40d5761ec03d63ed3a5ea3858358d0 Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Fri, 22 Mar 2019 23:45:11 +0100 Subject: [PATCH 134/174] Avoid busy loop --- src/NUnitFramework/tests/Attributes/TimeoutTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index c2de0ef98f..5d45d7500f 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -187,7 +187,7 @@ public void TimeoutWithMessagePumpShouldAbort() [Timeout(50)] public void TestTimeoutAndReportsTimeoutFailure() { - while (true) { } + Thread.Sleep(Timeout.Infinite); } [Test, Timeout(100)] From a6ad654f84ad3d0c7244f9a8201ee80642a40313 Mon Sep 17 00:00:00 2001 From: "drew.burlingame" Date: Sun, 24 Mar 2019 18:35:56 +0000 Subject: [PATCH 135/174] remove static OutputExceptionDataProperty switch default is to always use this, based on comments from #3145 also added explicit testing for emtpy .Data property --- .../framework/Internal/ExceptionHelper.cs | 21 +++----------- ...ExceptionHelperOutputExceptionDataTests.cs | 29 +++++++------------ 2 files changed, 14 insertions(+), 36 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs index 277cff38c5..4dee039a99 100644 --- a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs +++ b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs @@ -36,11 +36,6 @@ namespace NUnit.Framework.Internal /// public class ExceptionHelper { - /// - /// When true, each entry in Exception.Data is included in the exception message. - /// - public static bool OutputExceptionDataProperty { get; set; } = true; - #if NET35 || NET40 private static readonly Action PreserveStackTrace; @@ -91,10 +86,7 @@ public static string BuildMessage(Exception exception, bool excludeExceptionName if (!excludeExceptionNames) sb.AppendFormat("{0} : ", exception.GetType()); sb.Append(GetExceptionMessage(exception)); - if (OutputExceptionDataProperty) - { - AppendExceptionDataContents(exception, sb); - } + AppendExceptionDataContents(exception, sb); foreach (Exception inner in FlattenExceptionHierarchy(exception)) { @@ -103,10 +95,7 @@ public static string BuildMessage(Exception exception, bool excludeExceptionName if (!excludeExceptionNames) sb.AppendFormat("{0} : ", inner.GetType()); sb.Append(GetExceptionMessage(inner)); - if (OutputExceptionDataProperty) - { - AppendExceptionDataContents(inner, sb); - } + AppendExceptionDataContents(inner, sb); } return sb.ToString(); @@ -177,10 +166,8 @@ private static void AppendExceptionDataContents(Exception ex, StringBuilder sb) sb.AppendLine("Data:"); foreach (DictionaryEntry kvp in ex.Data) { - sb.Append(" "); - sb.Append(kvp.Key); - sb.Append(": "); - sb.AppendLine(kvp.Value?.ToString() ?? ""); + sb.AppendFormat(" {0}: {1}", kvp.Key, kvp.Value?.ToString() ?? ""); + sb.AppendLine(); } } diff --git a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs index f112bba3fc..6d090e2934 100644 --- a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs +++ b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs @@ -122,40 +122,31 @@ public static void AppendsDataItemsToExceptionMessage() exception.Data["data-prop"] = "data-value"; var message = ExceptionHelper.BuildMessage(exception); + Assert.That(message, Contains.Substring("blah")); Assert.That(message, Contains.Substring("data-prop")); Assert.That(message, Contains.Substring("data-value")); } [Test] - public static void CanDisable() + public static void IncludesNullProperties() { var exception = new Exception("blah"); - exception.Data["data-prop"] = "data-value"; - - string message; - try - { - ExceptionHelper.OutputExceptionDataProperty = false; - message = ExceptionHelper.BuildMessage(exception); - } - finally - { - ExceptionHelper.OutputExceptionDataProperty = true; - } + exception.Data["data-prop"] = null; - Assert.That(message, !Contains.Substring("data-prop")); - Assert.That(message, !Contains.Substring("data-value")); + var message = ExceptionHelper.BuildMessage(exception); + Assert.That(message, Contains.Substring("blah")); + Assert.That(message, Contains.Substring("data-prop")); + Assert.That(message, Contains.Substring("")); } [Test] - public static void IncludesNullProperties() + public static void SkipsDataSectionOnEmptyData() { var exception = new Exception("blah"); - exception.Data["data-prop"] = null; var message = ExceptionHelper.BuildMessage(exception); - Assert.That(message, Contains.Substring("data-prop")); - Assert.That(message, Contains.Substring("")); + Assert.That(message, Contains.Substring("blah")); + Assert.That(message, !Contains.Substring("Data")); } } } From 5ae108f7d7d23c511a51a6424f96eeff0fa41cfd Mon Sep 17 00:00:00 2001 From: "drew.burlingame" Date: Tue, 26 Mar 2019 10:42:04 +0000 Subject: [PATCH 136/174] fix copyright header --- ...ExceptionHelperOutputExceptionDataTests.cs | 90 +------------------ 1 file changed, 1 insertion(+), 89 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs index 6d090e2934..2832196e74 100644 --- a/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs +++ b/src/NUnitFramework/tests/Internal/ExceptionHelperOutputExceptionDataTests.cs @@ -1,93 +1,5 @@ // *********************************************************************** -// Copyright (c) 2019 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -// *********************************************************************** -// Copyright (c) 2019 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -// *********************************************************************** -// Copyright (c) 2019 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -// *********************************************************************** -// Copyright (c) 2019 Charlie Poole -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// *********************************************************************** -// *********************************************************************** -// Copyright (c) 2019 Charlie Poole +// Copyright (c) 2019 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the From 8b2b70f55facd4937ab114511966db65128cb2b9 Mon Sep 17 00:00:00 2001 From: Charlie Poole Date: Thu, 4 Apr 2019 11:57:25 +0100 Subject: [PATCH 137/174] Add more event tests --- .../tests/Api/TestAssemblyRunnerTests.cs | 7 +++- .../Internal/TestProgressReporterTests.cs | 39 +++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs b/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs index 8652ce5be6..ae6f1de099 100644 --- a/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs +++ b/src/NUnitFramework/tests/Api/TestAssemblyRunnerTests.cs @@ -58,6 +58,7 @@ public class TestAssemblyRunnerTests : ITestListener private ITestAssemblyRunner _runner; + private int _suiteStartedCount; private int _testStartedCount; private int _testFinishedCount; private int _testOutputCount; @@ -71,6 +72,7 @@ public void CreateRunner() { _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); + _suiteStartedCount = 0; _testStartedCount = 0; _testFinishedCount = 0; _testOutputCount = 0; @@ -264,6 +266,7 @@ public void Run_AfterLoad_SendsExpectedEvents() LoadMockAssembly(); _runner.Run(this, TestFilter.Empty); + Assert.That(_suiteStartedCount, Is.EqualTo(MockAssembly.Suites)); Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.TestStartedEvents)); Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.TestFinishedEvents)); Assert.That(_testOutputCount, Is.EqualTo(MockAssembly.TestOutputEvents)); @@ -495,7 +498,9 @@ public void CancelRun_WhenTestIsRunning_StopsTest() void ITestListener.TestStarted(ITest test) { - if (!test.IsSuite) + if (test.IsSuite) + _suiteStartedCount++; + else _testStartedCount++; } diff --git a/src/NUnitFramework/tests/Internal/TestProgressReporterTests.cs b/src/NUnitFramework/tests/Internal/TestProgressReporterTests.cs index 5d463f5f00..41e005b945 100644 --- a/src/NUnitFramework/tests/Internal/TestProgressReporterTests.cs +++ b/src/NUnitFramework/tests/Internal/TestProgressReporterTests.cs @@ -1,4 +1,4 @@ -// *********************************************************************** +// *********************************************************************** // Copyright (c) 2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -47,7 +47,39 @@ public void Setup() _listener.Reports.Clear(); } - [Test] + [Test] + public void TestStarted_AssemblyEmitsSingleStartSuiteElement() + { + var work = TestBuilder.CreateWorkItem(new TestAssembly("mytest.dll")); + work.Context.Listener = _reporter; + + TestBuilder.ExecuteWorkItem(work); + + var startReport = _listener.Reports.FirstOrDefault(); + Assert.NotNull(startReport); + Assert.That(startReport, Does.StartWith(" x.StartsWith(" x.StartsWith(" Date: Sun, 21 Apr 2019 23:16:25 +0200 Subject: [PATCH 138/174] Bump Ubuntu version (#3212) The Linux build has started to fail in a similar manner to nunit/nunit-console#611, so we bump the Ubuntu version. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 08479f4297..41fe67b720 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,7 @@ mono: 5.10.0 # Need 5.2+ for the included MSBuild. matrix: include: - - os: linux + - dist: xenial install: - sudo apt-get install dotnet-sharedframework-microsoft.netcore.app-1.1.6 From 161d63d516bf722ac35c04ad5711034e4c367f76 Mon Sep 17 00:00:00 2001 From: heshamamin Date: Mon, 22 Apr 2019 20:49:48 +0200 Subject: [PATCH 139/174] Supporting Fields in Is.Ordered.By --- .../CollectionOrderedConstraint.cs | 30 ++++-- .../CollectionOrderedConstraintTests.cs | 97 ++++++++++++++++++- 2 files changed, 114 insertions(+), 13 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs index 683014dcaf..379b038347 100644 --- a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs @@ -223,15 +223,9 @@ protected override bool Matches(IEnumerable actual) { string propertyName = step.PropertyName; - PropertyInfo previousProp = previous.GetType().GetProperty(propertyName); - if (previousProp == null) - throw new ArgumentException($"Property {propertyName} not found at index {_breakingIndex - 1}", nameof(actual)); - var previousValue = previousProp.GetValue(previous, null); + object previousValue = ExtractValue(actual, previous, propertyName, _breakingIndex - 1); - PropertyInfo prop = current.GetType().GetProperty(propertyName); - if (prop == null) - throw new ArgumentException($"Property {propertyName} not found at index {_breakingIndex}", nameof(actual)); - var currentValue = prop.GetValue(current, null); + object currentValue = ExtractValue(actual, current, propertyName, _breakingIndex); int comparisonResult = step.Comparer.Compare(previousValue, currentValue); @@ -297,6 +291,26 @@ private void CreateNextStep(string propertyName) _steps.Add(_activeStep); } + private object ExtractValue(IEnumerable actual, object item, string propertyName, int index) + { + object value; + PropertyInfo property = item.GetType().GetProperty(propertyName); + if (property == null) + { + FieldInfo field = item.GetType().GetField(propertyName); + if (field == null) + { + throw new ArgumentException($"Property {propertyName} not found at index {index}", nameof(actual)); + } + value = field.GetValue(item); + } + else + { + value = property.GetValue(item, null); + } + return value; + } + #region Internal OrderingStep Class /// diff --git a/src/NUnitFramework/tests/Constraints/CollectionOrderedConstraintTests.cs b/src/NUnitFramework/tests/Constraints/CollectionOrderedConstraintTests.cs index f1a3bd50df..9b6c517533 100644 --- a/src/NUnitFramework/tests/Constraints/CollectionOrderedConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/CollectionOrderedConstraintTests.cs @@ -133,7 +133,66 @@ public void IsOrderedBy(IEnumerable collection, Constraint constraint) Is.Ordered.By("A").Descending.Then.By("B").Descending ), new TestCaseData( new[] { new TestClass3("XYZ", 2), new TestClass3("ABC", 42), new TestClass3("ABC", 1) }, - Is.Ordered.Descending.By("A").Then.Descending.By("B") ) + Is.Ordered.Descending.By("A").Then.Descending.By("B") ), + // Ordered by Single Field + new TestCaseData( + new[] { new TestClass5(10), new TestClass5(20), new TestClass5(30) }, + Is.Ordered.By("Value") ), + new TestCaseData( + new[] { new TestClass5(10), new TestClass5(20), new TestClass5(30) }, + Is.Ordered.By("Value").Ascending ), + new TestCaseData( + new[] { new TestClass5(10), new TestClass5(20), new TestClass5(30) }, + Is.Ordered.Ascending.By("Value") ), + new TestCaseData( + new[] { new TestClass5(30), new TestClass5(20), new TestClass5(10) }, + Is.Ordered.By("Value").Descending ), + new TestCaseData( + new[] { new TestClass5(30), new TestClass5(20), new TestClass5(10) }, + Is.Ordered.Descending.By("Value") ), + new TestCaseData( + new[] { new TestClass5(10), new TestClass5(20), new TestClass5(30) }, + Is.Ordered.By("Value").Using(ObjectComparer.Default) ), + new TestCaseData( + new object[] { new TestClass5(10), new TestClass2(20) }, + Is.Ordered.By("Value") ), + // Ordered By Two Fields + new TestCaseData( + new [] { new TestClass6("ABC", 10), new TestClass6("ABC", 420), new TestClass6("XYZ", 20) }, + Is.Ordered.By("A").By("B") ), + new TestCaseData( + new [] { new TestClass6("ABC", 10), new TestClass6("ABC", 420), new TestClass6("XYZ", 20) }, + Is.Ordered.By("A").Then.By("B") ), + new TestCaseData( + new [] { new TestClass6("ABC", 10), new TestClass6("ABC", 420), new TestClass6("XYZ", 20) }, + Is.Ordered.Ascending.By("A").Then.Ascending.By("B") ), + new TestCaseData( + new [] { new TestClass6("ABC", 10), new TestClass6("ABC", 420), new TestClass6("XYZ", 20) }, + Is.Ordered.By("A").Ascending.Then.By("B").Ascending ), + new TestCaseData( + new [] { new TestClass6("ABC", 420), new TestClass6("XYZ", 990), new TestClass6("XYZ", 20) }, + Is.Not.Ordered.By("A").Then.By("B") ), + new TestCaseData( + new [] { new TestClass6("XYZ", 20), new TestClass6("ABC", 10), new TestClass6("ABC", 420) }, + Is.Ordered.By("A").Descending.Then.By("B") ), + new TestCaseData( + new [] { new TestClass6("XYZ", 20), new TestClass6("ABC", 10), new TestClass6("ABC", 420) }, + Is.Ordered.Descending.By("A").Then.By("B") ), + new TestCaseData( + new [] { new TestClass6("ABC", 420), new TestClass6("ABC", 10), new TestClass6("XYZ", 20) }, + Is.Ordered.By("A").Ascending.Then.By("B").Descending ), + new TestCaseData( + new [] { new TestClass6("ABC", 420), new TestClass6("ABC", 10), new TestClass6("XYZ", 20) }, + Is.Ordered.Ascending.By("A").Then.Descending.By("B") ), + new TestCaseData( + new [] { new TestClass6("ABC", 420), new TestClass6("ABC", 10), new TestClass6("XYZ", 20) }, + Is.Not.Ordered.By("A").Then.By("B") ), + new TestCaseData( + new[] { new TestClass6("XYZ", 20), new TestClass6("ABC", 420), new TestClass6("ABC", 10) }, + Is.Ordered.By("A").Descending.Then.By("B").Descending ), + new TestCaseData( + new[] { new TestClass6("XYZ", 20), new TestClass6("ABC", 420), new TestClass6("ABC", 10) }, + Is.Ordered.Descending.By("A").Then.Descending.By("B") ), }; #endregion @@ -295,10 +354,6 @@ public void IsOrdered_ThrowsOnMissingProperty(object[] collection, string proper new object [] { new TestClass3("a", 1), "b" }, "A", "index 1"), - new TestCaseData( - new object [] { new TestClass3("a", 1), new TestClass3("b", 1), new TestClass4("c") }, - "A", - "index 2"), }; #endregion @@ -367,6 +422,38 @@ public override string ToString() } } + public class TestClass5 + { + public int Value; + + public TestClass5(int value) + { + Value = value; + } + + public override string ToString() + { + return Value.ToString(); + } + } + + public class TestClass6 + { + public string A; + public int B; + + public TestClass6(string a, int b) + { + A = a; + B = b; + } + + public override string ToString() + { + return A.ToString() + "," + B.ToString(); + } + } + #endregion } } From 2570e3d1f7d2c4f619d0c1b7850285e19911178a Mon Sep 17 00:00:00 2001 From: heshamamin Date: Mon, 22 Apr 2019 21:01:44 +0200 Subject: [PATCH 140/174] Update exception message --- .../framework/Constraints/CollectionOrderedConstraint.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs index 379b038347..c643d75909 100644 --- a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs @@ -300,7 +300,7 @@ private object ExtractValue(IEnumerable actual, object item, string propertyName FieldInfo field = item.GetType().GetField(propertyName); if (field == null) { - throw new ArgumentException($"Property {propertyName} not found at index {index}", nameof(actual)); + throw new ArgumentException($"No property or field with name {propertyName} was found at index {index}", nameof(actual)); } value = field.GetValue(item); } From 1cacd96d21d34a26aa05c6506266e9fd744d1208 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 23 Apr 2019 23:55:31 -0400 Subject: [PATCH 141/174] Failing tests for full assembly paths in test results --- src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs index 192845c68f..0461b1e1c3 100644 --- a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs +++ b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs @@ -34,7 +34,6 @@ namespace NUnit.Framework.Internal public class SetUpFixtureTests { private static readonly string ASSEMBLY_PATH = AssemblyHelper.GetAssemblyPath(typeof(NUnit.TestData.SetupFixture.Namespace1.SomeFixture).GetTypeInfo().Assembly); - private static readonly string SUITE_NAME = System.IO.Path.GetFileName(ASSEMBLY_PATH); ITestAssemblyBuilder builder; ITestAssemblyRunner runner; @@ -85,7 +84,7 @@ public void NamespaceSetUpFixtureReplacesNamespaceNodeInTree() Assert.IsNotNull(suite); - Assert.AreEqual(SUITE_NAME, suite.FullName); + Assert.AreEqual(ASSEMBLY_PATH, suite.FullName); Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count"); string[] nameSpaceBits = nameSpace.Split('.'); @@ -134,7 +133,7 @@ public void InvalidAssemblySetUpFixtureIsLoadedCorrectly() Assert.IsNotNull(suite); - Assert.AreEqual(SUITE_NAME, suite.FullName); + Assert.AreEqual(ASSEMBLY_PATH, suite.FullName); Assert.AreEqual(1, suite.Tests.Count, "Error in top level test count"); Assert.AreEqual(RunState.Runnable, suite.RunState); From 9e03cd8363eedc4ec64ee0fad4a8250a1f48be48 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 23 Apr 2019 23:55:36 -0400 Subject: [PATCH 142/174] Restore full assembly paths in test results --- .../Api/DefaultTestAssemblyBuilder.cs | 16 ++++++++-------- .../framework/Internal/Tests/TestAssembly.cs | 19 +++++++++++-------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs index eea303cca3..31018e7359 100644 --- a/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs +++ b/src/NUnitFramework/framework/Api/DefaultTestAssemblyBuilder.cs @@ -85,7 +85,7 @@ public ITest Build(Assembly assembly, IDictionary options) string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly); string suiteName = assemblyPath.Equals("") ? AssemblyHelper.GetAssemblyName(assembly).FullName - : Path.GetFileName(assemblyPath); + : assemblyPath; return Build(assembly, suiteName, options); } @@ -111,18 +111,18 @@ public ITest Build(string assemblyNameOrPath, IDictionary option try { var assembly = AssemblyHelper.Load(assemblyNameOrPath); - testAssembly = Build(assembly, Path.GetFileName(assemblyNameOrPath), options); + testAssembly = Build(assembly, assemblyNameOrPath, options); } catch (Exception ex) { - testAssembly = new TestAssembly(Path.GetFileName(assemblyNameOrPath)); + testAssembly = new TestAssembly(assemblyNameOrPath); testAssembly.MakeInvalid(ExceptionHelper.BuildMessage(ex, true)); } return testAssembly; } - private TestSuite Build(Assembly assembly, string suiteName, IDictionary options) + private TestSuite Build(Assembly assembly, string assemblyNameOrPath, IDictionary options) { TestSuite testAssembly = null; @@ -176,11 +176,11 @@ private TestSuite Build(Assembly assembly, string suiteName, IDictionary GetCandidateFixtureTypes(Assembly assembly) // Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather // than a 'SecurityCriticalAttribute' and allow use by security transparent callers. [SecuritySafeCritical] - private TestSuite BuildTestAssembly(Assembly assembly, string suiteName, IList fixtures) + private TestSuite BuildTestAssembly(Assembly assembly, string assemblyNameOrPath, IList fixtures) { - TestSuite testAssembly = new TestAssembly(assembly, suiteName); + TestSuite testAssembly = new TestAssembly(assembly, assemblyNameOrPath); if (fixtures.Count == 0) { diff --git a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs index 7ac3a0d416..a6c5b4eada 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestAssembly.cs @@ -21,8 +21,8 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +using System.IO; using System.Reflection; - using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal @@ -38,22 +38,25 @@ public class TestAssembly : TestSuite /// specifying the Assembly and the suite name. /// /// The assembly this test represents. - /// The desired name for the test suite. - public TestAssembly(Assembly assembly, string name) - : base(name) + /// + /// This becomes the full name of the suite and the filename part is used as the suite name. + /// + public TestAssembly(Assembly assembly, string assemblyNameOrPath) + : this(assemblyNameOrPath) { this.Assembly = assembly; - this.Name = name; } /// /// Initializes a new instance of the class /// specifying the suite name for an assembly that could not be loaded. /// - /// The desired name for the test suite. - public TestAssembly(string name) : base(name) + /// + /// This becomes the full name of the suite and the filename part is used as the suite name. + /// + public TestAssembly(string assemblyNameOrPath) : base(assemblyNameOrPath) { - this.Name = name; + this.Name = Path.GetFileName(assemblyNameOrPath); } /// From 299aa9688996ec1b7ab72c88793a379a331c5ded Mon Sep 17 00:00:00 2001 From: heshamamin Date: Thu, 25 Apr 2019 17:27:46 +0200 Subject: [PATCH 143/174] Reduce nesting in the check for property or field --- .../CollectionOrderedConstraint.cs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs index c643d75909..377185b92a 100644 --- a/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/CollectionOrderedConstraint.cs @@ -293,22 +293,19 @@ private void CreateNextStep(string propertyName) private object ExtractValue(IEnumerable actual, object item, string propertyName, int index) { - object value; PropertyInfo property = item.GetType().GetProperty(propertyName); - if (property == null) + if (property != null) { - FieldInfo field = item.GetType().GetField(propertyName); - if (field == null) - { - throw new ArgumentException($"No property or field with name {propertyName} was found at index {index}", nameof(actual)); - } - value = field.GetValue(item); + return property.GetValue(item, null); } - else + + FieldInfo field = item.GetType().GetField(propertyName); + if (field != null) { - value = property.GetValue(item, null); + return field.GetValue(item); } - return value; + + throw new ArgumentException($"No property or field with name {propertyName} was found at index {index}", nameof(actual)); } #region Internal OrderingStep Class From 51f02de2686cbd9a4892c89aab155b526eb4e2c7 Mon Sep 17 00:00:00 2001 From: Chris Maddock Date: Thu, 25 Apr 2019 21:23:47 +0100 Subject: [PATCH 144/174] Fix logging (#3211) * Fix logging * Review comments --- src/NUnitFramework/framework/Internal/Execution/EventPump.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Execution/EventPump.cs b/src/NUnitFramework/framework/Internal/Execution/EventPump.cs index 8585307712..c9bc3a13cf 100644 --- a/src/NUnitFramework/framework/Internal/Execution/EventPump.cs +++ b/src/NUnitFramework/framework/Internal/Execution/EventPump.cs @@ -185,13 +185,13 @@ private void PumpThreadProc() } catch (Exception ex) { - log.Error( "Exception in event handler\r\n {0}", ex ); + log.Error("Exception in event handler {0}", ExceptionHelper.BuildStackTrace(ex)); } } } catch (Exception ex) { - log.Error( "Exception in pump thread", ex ); + log.Error("Exception in pump thread {0}", ExceptionHelper.BuildStackTrace(ex)); } finally { From b18eccf474d5a19550c49bff790bdf89381a6e0e Mon Sep 17 00:00:00 2001 From: stevenaw Date: Thu, 25 Apr 2019 20:32:56 -0400 Subject: [PATCH 145/174] Support static setup fixtures --- .../Attributes/SetUpFixtureAttribute.cs | 21 ++++--- .../testdata/SetUpFixtureData.cs | 56 +++++++++++++++++++ .../Attributes/SetUpFixtureAttributeTests.cs | 33 +++++++++++ .../tests/Internal/SetUpFixtureTests.cs | 13 +++++ 4 files changed, 114 insertions(+), 9 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/SetUpFixtureAttribute.cs b/src/NUnitFramework/framework/Attributes/SetUpFixtureAttribute.cs index 62fc9dd7e9..7ebb1841ed 100644 --- a/src/NUnitFramework/framework/Attributes/SetUpFixtureAttribute.cs +++ b/src/NUnitFramework/framework/Attributes/SetUpFixtureAttribute.cs @@ -36,7 +36,7 @@ namespace NUnit.Framework /// methods for all the test fixtures /// under a given namespace. /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)] + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class SetUpFixtureAttribute : NUnitAttribute, IFixtureBuilder { #region ISuiteBuilder Members @@ -67,16 +67,19 @@ public IEnumerable BuildFrom(ITypeInfo typeInfo) private static bool IsValidFixtureType(ITypeInfo typeInfo, ref string reason) { - if (typeInfo.IsAbstract) + if (!typeInfo.IsStaticClass) { - reason = string.Format("{0} is an abstract class", typeInfo.FullName); - return false; - } + if (typeInfo.IsAbstract) + { + reason = string.Format("{0} is an abstract class", typeInfo.FullName); + return false; + } - if (!typeInfo.HasConstructor(new Type[0])) - { - reason = string.Format("{0} does not have a default constructor", typeInfo.FullName); - return false; + if (!typeInfo.HasConstructor(new Type[0])) + { + reason = string.Format("{0} does not have a default constructor", typeInfo.FullName); + return false; + } } var invalidAttributes = new Type[] { diff --git a/src/NUnitFramework/testdata/SetUpFixtureData.cs b/src/NUnitFramework/testdata/SetUpFixtureData.cs index d5eb5f82b5..3109d0f376 100644 --- a/src/NUnitFramework/testdata/SetUpFixtureData.cs +++ b/src/NUnitFramework/testdata/SetUpFixtureData.cs @@ -167,6 +167,62 @@ public static void Clear() namespace NUnit.TestData.SetupFixture { + namespace StaticFixture + { + #region SomeFixture + [TestFixture] + public class TestSetupFixtureStuff + { + [OneTimeSetUp] + public void FixtureSetup() + { + TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.Fixture.SetUp"); + } + + [SetUp] + public void Setup() + { + TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.Test.SetUp"); + } + + [Test] + public void Test() + { + TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.Test"); + } + + [TearDown] + public void TearDown() + { + TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.Test.TearDown"); + } + + [OneTimeTearDown] + public void FixtureTearDown() + { + TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.Fixture.TearDown"); + } + } + #endregion SomeFixture + + + [SetUpFixture] + public static class StaticSetupTeardown + { + [OneTimeSetUp] + public static void DoNamespaceSetUp() + { + NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.OneTimeSetUp"); + } + + [OneTimeTearDown] + public static void DoNamespaceTearDown() + { + NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("StaticFixture.OneTimeTearDown"); + } + } + } + namespace Namespace1 { #region SomeFixture diff --git a/src/NUnitFramework/tests/Attributes/SetUpFixtureAttributeTests.cs b/src/NUnitFramework/tests/Attributes/SetUpFixtureAttributeTests.cs index 23cc1a7af8..8b03fd0c18 100644 --- a/src/NUnitFramework/tests/Attributes/SetUpFixtureAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/SetUpFixtureAttributeTests.cs @@ -64,6 +64,39 @@ public void CertainAttributesAreNotAllowed(Type type) Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable)); } + [Test] + public void AbstractClassNotAllowed() + { + var abstractType = typeof(AbstractSetupClass); + var fixtures = new SetUpFixtureAttribute().BuildFrom(new TypeWrapper(abstractType)); + foreach (var fixture in fixtures) + Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable)); + } + + [Test] + public void StaticClassIsAllowed() + { + var abstractType = typeof(StaticSetupClass); + var fixtures = new SetUpFixtureAttribute().BuildFrom(new TypeWrapper(abstractType)); + foreach (var fixture in fixtures) + Assert.That(fixture.RunState, Is.EqualTo(RunState.Runnable)); + } + + private static class StaticSetupClass + { + [OneTimeSetUp] + public static void SomeSetUpMethod() { } + + [OneTimeTearDown] + public static void SomeTearDownMethod() { } + } + + private abstract class AbstractSetupClass + { + [OneTimeSetUp] + public void SomeSetUpMethod() { } + } + private class TestSetupClass { [SetUp] diff --git a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs index 192845c68f..2730562095 100644 --- a/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs +++ b/src/NUnitFramework/tests/Internal/SetUpFixtureTests.cs @@ -184,6 +184,19 @@ public void NamespaceSetUpMethodsMayBeStatic() "NS5.Fixture.TearDown", "NS5.OneTimeTearDown"); } + + [Test] + public void NamespaceSetUpFixtureMayBeStatic() + { + Assert.That(RunTests("NUnit.TestData.SetupFixture.StaticFixture").ResultState.Status, Is.EqualTo(TestStatus.Passed)); + TestUtilities.SimpleEventRecorder.Verify("StaticFixture.OneTimeSetUp", + "StaticFixture.Fixture.SetUp", + "StaticFixture.Test.SetUp", + "StaticFixture.Test", + "StaticFixture.Test.TearDown", + "StaticFixture.Fixture.TearDown", + "StaticFixture.OneTimeTearDown"); + } #endregion #region TwoTestFixtures From b3ec2e5f508be25b1ab6f169453c71c36d507bcc Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 27 Apr 2019 19:42:48 +0200 Subject: [PATCH 146/174] Correction from review --- src/NUnitFramework/framework/Attributes/ParallelScope.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/framework/Attributes/ParallelScope.cs b/src/NUnitFramework/framework/Attributes/ParallelScope.cs index ab67e2cb01..7172e8a373 100644 --- a/src/NUnitFramework/framework/Attributes/ParallelScope.cs +++ b/src/NUnitFramework/framework/Attributes/ParallelScope.cs @@ -41,7 +41,7 @@ public enum ParallelScope /// /// The test may be run in parallel with others at the same level. - /// Valid on classes and methods but not assemblies. + /// Valid on classes and methods but has no effect on assemblies. /// Self = 1, @@ -81,7 +81,9 @@ public enum ParallelScope /// /// The test and its descendants may be run in parallel with others at - /// the same level. Valid on classes, parameterized methods, and assemblies. + /// the same level. Valid on classes and parameterized methods. + /// For assemblies it is recommended to use + /// instead, as has no effect on assemblies. /// All = Self + Children } From 8de9af1d695d42d2d85604a100ff9f6c00e5728f Mon Sep 17 00:00:00 2001 From: Mikkel Nylander Bundgaard Date: Sat, 27 Apr 2019 21:52:39 +0200 Subject: [PATCH 147/174] Remove todos from the code base --- .../framework/Constraints/NUnitEqualityComparer.cs | 3 --- .../Internal/Commands/DelegatingTestCommand.cs | 4 ++-- .../framework/Internal/Commands/MaxTimeCommand.cs | 10 +++++----- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs index 31dd17cca9..411b296936 100644 --- a/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs +++ b/src/NUnitFramework/framework/Constraints/NUnitEqualityComparer.cs @@ -128,9 +128,6 @@ public IList ExternalComparers get { return externalComparers; } } - // TODO: Define some sort of FailurePoint struct or otherwise - // eliminate the type-unsafeness of the current approach - /// /// Gets the list of failure points for the last Match performed. /// The list consists of objects to be interpreted by the caller. diff --git a/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs b/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs index b6d39de7a2..b10399f92f 100644 --- a/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/DelegatingTestCommand.cs @@ -38,9 +38,9 @@ public abstract class DelegatingTestCommand : TestCommand #pragma warning restore IDE1006 /// - /// TODO: Documentation needed for constructor + /// Initializes a new instance of the class. /// - /// + /// The inner command. protected DelegatingTestCommand(TestCommand innerCommand) : base(innerCommand.Test) { diff --git a/src/NUnitFramework/framework/Internal/Commands/MaxTimeCommand.cs b/src/NUnitFramework/framework/Internal/Commands/MaxTimeCommand.cs index 0759a18eaa..64d2448b39 100644 --- a/src/NUnitFramework/framework/Internal/Commands/MaxTimeCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/MaxTimeCommand.cs @@ -1,4 +1,4 @@ - // *********************************************************************** + // *********************************************************************** // Copyright (c) 2010-2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining @@ -21,15 +21,15 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -using System; using System.Diagnostics; -using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Commands { /// - /// TODO: Documentation needed for class + /// adjusts the result of a successful test + /// to a failure if the elapsed time has exceeded the specified maximum + /// time allowed. /// public class MaxTimeCommand : AfterTestCommand { @@ -67,4 +67,4 @@ public MaxTimeCommand(TestCommand innerCommand, int maxTime) }; } } -} \ No newline at end of file +} From 282159e8878df78056838810e6c80b979ad3c953 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 29 Apr 2019 20:38:44 -0400 Subject: [PATCH 148/174] Fix typo excluding test --- src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs b/src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs index 0f36089ae9..52f2f8f000 100644 --- a/src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs +++ b/src/NUnitFramework/tests/Internal/ThreadUtilityTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if PARALLEL && PLATFORM_DETECTIONN && THREAD_ABORT +#if PARALLEL && PLATFORM_DETECTION && THREAD_ABORT using System.Runtime.InteropServices; using System.Threading; using NUnit.TestUtilities; From daae6351309a4d0ce80c61fb9aa60692b37af2aa Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 29 Apr 2019 20:47:15 -0400 Subject: [PATCH 149/174] =?UTF-8?q?If=20you=20can=E2=80=99t=20beat=20?= =?UTF-8?q?=E2=80=99em,=20join=20=E2=80=99em?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/NUnitFramework/tests/Attributes/TimeoutTests.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 5d45d7500f..5b2aa7b0ee 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -50,6 +50,9 @@ public void TestWithTimeoutCurrentContextIsNotAnAdhocContext() } #if PLATFORM_DETECTION && THREAD_ABORT + // Most recent version of Mono tested: 5.20.1 + private const string MonoFailsToAbortThreadReason = "ThreadAbortException is never thrown on Mono"; + [Test, Timeout(500)] public void TestWithTimeoutRunsOnSameThread() { @@ -63,7 +66,7 @@ public void TestWithTimeoutRunsSetUpAndTestOnSameThread() } [Test] - [Platform(Exclude = "Mono", Reason = "Runner hangs at end when this is run")] + [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TestTimesOutAndTearDownIsRun() { TimeoutFixture fixture = new TimeoutFixture(); @@ -88,7 +91,7 @@ public void SetUpTimesOutAndTearDownIsRun() } [Test] - [Platform(Exclude = "Mono", Reason = "Test never aborts on Mono (tested 5.4–5.12)")] + [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TearDownTimesOutAndNoFurtherTearDownIsRun() { TimeoutFixture fixture = new TimeoutFixtureWithTimeoutInTearDown(); @@ -101,7 +104,7 @@ public void TearDownTimesOutAndNoFurtherTearDownIsRun() } [Test] - [Platform(Exclude = "Mono", Reason = "Runner hangs at end when this is run")] + [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TimeoutCanBeSetOnTestFixture() { ITestResult suiteResult = TestBuilder.RunTestFixture(typeof(TimeoutFixtureWithTimeoutOnFixture)); @@ -172,6 +175,7 @@ public void TestTimeOutTestCaseWithOutElapsed() } [Test, Platform("Win")] + [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TimeoutWithMessagePumpShouldAbort() { ITestResult result = TestBuilder.RunTest( From 07104f79bb6130346f1ad0074738ebf5db3164c5 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sat, 26 May 2018 21:49:19 -0400 Subject: [PATCH 150/174] Use AwaitAdapter to obtain results also (temporarily drops support for Task<>) --- .../framework/Internal/AsyncToSyncAdapter.cs | 45 +------------------ .../framework/Internal/AwaitAdapter.cs | 13 ++++++ 2 files changed, 15 insertions(+), 43 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs index 749acaf53a..24db6d3254 100644 --- a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs @@ -22,7 +22,6 @@ // *********************************************************************** using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security; @@ -60,54 +59,22 @@ private static bool IsTaskType(Type type) } #if ASYNC - private const string TaskWaitMethod = "Wait"; - private const string TaskResultProperty = "Result"; - private const string VoidTaskResultType = "VoidTaskResult"; - private const string SystemAggregateException = "System.AggregateException"; - private const string InnerExceptionsProperty = "InnerExceptions"; - private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.Instance | BindingFlags.Public; - public static object Await(Func invoke) { Guard.ArgumentNotNull(invoke, nameof(invoke)); - object invocationResult; using (InitializeExecutionEnvironment()) { - invocationResult = invoke.Invoke(); - if (invocationResult == null || !IsTaskType(invocationResult.GetType())) - throw new InvalidOperationException("The delegate did not return a Task."); // General awaitable support coming soon. - - var awaitAdapter = AwaitAdapter.FromAwaitable(invocationResult); + var awaitAdapter = AwaitAdapter.FromAwaitable(invoke.Invoke()); if (!awaitAdapter.IsCompleted) { var waitStrategy = MessagePumpStrategy.FromCurrentSynchronizationContext(); waitStrategy.WaitForCompletion(awaitAdapter); } - } - // Future: instead of Wait(), use GetAwaiter() to check awaiter.IsCompleted above - // and use awaiter.OnCompleted/awaiter.GetResult below. - // (Implement a ReflectionAwaitAdapter) - try - { - invocationResult.GetType().GetMethod(TaskWaitMethod, new Type[0]).Invoke(invocationResult, null); - } - catch (TargetInvocationException e) - { - IList innerExceptions = GetAllExceptions(e.InnerException); - ExceptionHelper.Rethrow(innerExceptions[0]); - } - var genericArguments = invocationResult.GetType().GetGenericArguments(); - if (genericArguments.Length == 1 && genericArguments[0].Name == VoidTaskResultType) - { - return null; + return awaitAdapter.GetResult(); } - - PropertyInfo taskResultProperty = invocationResult.GetType().GetProperty(TaskResultProperty, TaskResultPropertyBindingFlags); - - return taskResultProperty != null ? taskResultProperty.GetValue(invocationResult, null) : invocationResult; } private static IDisposable InitializeExecutionEnvironment() @@ -137,14 +104,6 @@ private static void SetSynchronizationContext(SynchronizationContext syncContext { SynchronizationContext.SetSynchronizationContext(syncContext); } - - private static IList GetAllExceptions(Exception exception) - { - if (SystemAggregateException.Equals(exception.GetType().FullName)) - return (IList)exception.GetType().GetProperty(InnerExceptionsProperty).GetValue(exception, null); - - return new Exception[] { exception }; - } #endif } } diff --git a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs index b76e6f2858..f4f565ecba 100644 --- a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs @@ -34,6 +34,7 @@ internal abstract class AwaitAdapter public abstract bool IsCompleted { get; } public abstract void OnCompleted(Action action); public abstract void BlockUntilCompleted(); + public abstract object GetResult(); public static AwaitAdapter FromAwaitable(object awaitable) { @@ -89,6 +90,12 @@ public override void BlockUntilCompleted() ExceptionHelper.Rethrow(ex.InnerException); } } + + public override object GetResult() + { + BlockUntilCompleted(); // Throw exceptions, if any + return null; + } } #else private sealed class TaskAwaitAdapter : AwaitAdapter @@ -107,6 +114,12 @@ public TaskAwaitAdapter(Task task) // Assumption that GetResult blocks until complete is only valid for System.Threading.Tasks.Task. public override void BlockUntilCompleted() => _awaiter.GetResult(); + + public override object GetResult() + { + _awaiter.GetResult(); // Throw exceptions, if any + return null; + } } #endif } From 406a35c1471a3aaea85d2b9e2a44cbc3f3b1c899 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sat, 26 May 2018 22:41:31 -0400 Subject: [PATCH 151/174] Re-establish support for Task<> (via more efficient special cases) --- .../framework/Internal/AwaitAdapter.cs | 77 +-------- .../Internal/Net40BclTaskAwaitAdapter.cs | 154 ++++++++++++++++++ .../framework/Internal/Reflect.cs | 8 + .../framework/Internal/TaskAwaitAdapter.cs | 104 ++++++++++++ 4 files changed, 268 insertions(+), 75 deletions(-) create mode 100644 src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs create mode 100644 src/NUnitFramework/framework/Internal/TaskAwaitAdapter.cs diff --git a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs index f4f565ecba..afb13bea6a 100644 --- a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs @@ -23,8 +23,6 @@ #if ASYNC using System; -using System.Runtime.CompilerServices; -using System.Security; using System.Threading.Tasks; namespace NUnit.Framework.Internal @@ -46,82 +44,11 @@ public static AwaitAdapter FromAwaitable(object awaitable) #if NET40 // TODO: use the general reflection-based awaiter if net40 build is running against a newer BCL - return new Net40BclTaskAwaitAdapter(task); + return Net40BclTaskAwaitAdapter.Create(task); #else - return new TaskAwaitAdapter(task); + return TaskAwaitAdapter.Create(task); #endif } - -#if NET40 - private sealed class Net40BclTaskAwaitAdapter : AwaitAdapter - { - private readonly Task _task; - - public Net40BclTaskAwaitAdapter(Task task) - { - _task = task; - } - - public override bool IsCompleted => _task.IsCompleted; - - public override void OnCompleted(Action action) - { - if (action == null) return; - - // Normally we would call TaskAwaiter.UnsafeOnCompleted (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) - // We will have to polyfill on top of the TPL API. - // Compare TaskAwaiter.OnCompletedInternal from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. - - _task.ContinueWith(_ => action.Invoke(), TaskScheduler.FromCurrentSynchronizationContext()); - } - - public override void BlockUntilCompleted() - { - // Normally we would call TaskAwaiter.GetResult (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) - // We will have to polyfill on top of the TPL API. - // Compare TaskAwaiter.ValidateEnd from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. - - try - { - _task.Wait(); // Wait even if the task is completed so that an exception is thrown for cancellation or failure. - } - catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) // Task.Wait wraps every exception - { - ExceptionHelper.Rethrow(ex.InnerException); - } - } - - public override object GetResult() - { - BlockUntilCompleted(); // Throw exceptions, if any - return null; - } - } -#else - private sealed class TaskAwaitAdapter : AwaitAdapter - { - private readonly TaskAwaiter _awaiter; - - public TaskAwaitAdapter(Task task) - { - _awaiter = task.GetAwaiter(); - } - - public override bool IsCompleted => _awaiter.IsCompleted; - - [SecuritySafeCritical] - public override void OnCompleted(Action action) => _awaiter.UnsafeOnCompleted(action); - - // Assumption that GetResult blocks until complete is only valid for System.Threading.Tasks.Task. - public override void BlockUntilCompleted() => _awaiter.GetResult(); - - public override object GetResult() - { - _awaiter.GetResult(); // Throw exceptions, if any - return null; - } - } -#endif } } #endif diff --git a/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs new file mode 100644 index 0000000000..cd7cf8fedd --- /dev/null +++ b/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs @@ -0,0 +1,154 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if NET40 +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace NUnit.Framework.Internal +{ + internal static class Net40BclTaskAwaitAdapter + { + public static AwaitAdapter Create(Task task) + { + var genericTaskType = task + .GetType() + .TypeAndBaseTypes() + .FirstOrDefault(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Task<>)); + + if (genericTaskType != null) + { + var typeArgument = genericTaskType.GetGenericArguments()[0]; + return (AwaitAdapter)typeof(GenericAdapter<>) + .MakeGenericType(typeArgument) + .GetConstructor(new[] { typeof(Task<>).MakeGenericType(typeArgument) }) + .Invoke(new object[] { task }); + } + + return new NonGenericAdapter(task); + } + + private class NonGenericAdapter : AwaitAdapter + { + private readonly Task _task; + + public NonGenericAdapter(Task task) + { + _task = task; + } + + public override bool IsCompleted => _task.IsCompleted; + + public override void OnCompleted(Action action) + { + if (action == null) return; + + // Normally we would call TaskAwaiter.UnsafeOnCompleted (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) + // We will have to polyfill on top of the TPL API. + // Compare TaskAwaiter.OnCompletedInternal from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. + + _task.ContinueWith(_ => action.Invoke(), TaskScheduler.FromCurrentSynchronizationContext()); + } + + public override void BlockUntilCompleted() + { + // Normally we would call TaskAwaiter.GetResult (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) + // We will have to polyfill on top of the TPL API. + // Compare TaskAwaiter.ValidateEnd from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. + + try + { + _task.Wait(); // Wait even if the task is completed so that an exception is thrown for cancellation or failure. + } + catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) // Task.Wait wraps every exception + { + ExceptionHelper.Rethrow(ex.InnerException); + } + } + + public override object GetResult() + { + BlockUntilCompleted(); // Throw exceptions, if any + return null; + } + } + + private sealed class GenericAdapter : AwaitAdapter + { + private readonly Task _task; + + public GenericAdapter(Task task) + { + _task = task; + } + + public override bool IsCompleted => _task.IsCompleted; + + public override void OnCompleted(Action action) + { + if (action == null) return; + + // Normally we would call TaskAwaiter.UnsafeOnCompleted (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) + // We will have to polyfill on top of the TPL API. + // Compare TaskAwaiter.OnCompletedInternal from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. + + _task.ContinueWith(_ => action.Invoke(), TaskScheduler.FromCurrentSynchronizationContext()); + } + + public override void BlockUntilCompleted() + { + // Normally we would call TaskAwaiter.GetResult (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) + // We will have to polyfill on top of the TPL API. + // Compare TaskAwaiter.ValidateEnd from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. + + try + { + _task.Wait(); // Wait even if the task is completed so that an exception is thrown for cancellation or failure. + } + catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) // Task.Wait wraps every exception + { + ExceptionHelper.Rethrow(ex.InnerException); + } + } + + public override object GetResult() + { + // Normally we would call TaskAwaiter.GetResult (https://source.dot.net/#System.Private.CoreLib/src/System/Runtime/CompilerServices/TaskAwaiter.cs) + // We will have to polyfill on top of the TPL API. + // Compare TaskAwaiter.ValidateEnd from Microsoft.Threading.Tasks.dll in Microsoft.Bcl.Async.nupkg. + + try + { + return _task.Result; + } + catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) // Task.Wait wraps every exception + { + ExceptionHelper.Rethrow(ex.InnerException); + throw null; // Rethrow’s return type would be `never` if C# could express that. + } + } + } + } +} +#endif diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index 540c26e517..9ad32d4faf 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -375,5 +375,13 @@ private static bool IsNullable(Type type) && !type.GetTypeInfo().IsGenericTypeDefinition && ReferenceEquals(type.GetGenericTypeDefinition(), typeof(Nullable<>)); } + + internal static IEnumerable TypeAndBaseTypes(this Type type) + { + for (; type != null; type = type.GetTypeInfo().BaseType) + { + yield return type; + } + } } } diff --git a/src/NUnitFramework/framework/Internal/TaskAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/TaskAwaitAdapter.cs new file mode 100644 index 0000000000..eed2d93607 --- /dev/null +++ b/src/NUnitFramework/framework/Internal/TaskAwaitAdapter.cs @@ -0,0 +1,104 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if ASYNC && !NET40 +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Threading.Tasks; +using NUnit.Compatibility; + +namespace NUnit.Framework.Internal +{ + internal static class TaskAwaitAdapter + { + public static AwaitAdapter Create(Task task) + { + var genericTaskType = task + .GetType() + .TypeAndBaseTypes() + .FirstOrDefault(t => t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == typeof(Task<>)); + + if (genericTaskType != null) + { + var typeArgument = genericTaskType.GetGenericArguments()[0]; + return (AwaitAdapter)typeof(GenericAdapter<>) + .MakeGenericType(typeArgument) + .GetConstructor(new[] { typeof(Task<>).MakeGenericType(typeArgument) }) + .Invoke(new object[] { task }); + } + + return new NonGenericAdapter(task); + } + + private sealed class NonGenericAdapter : AwaitAdapter + { + private readonly TaskAwaiter _awaiter; + + public NonGenericAdapter(Task task) + { + _awaiter = task.GetAwaiter(); + } + + public override bool IsCompleted => _awaiter.IsCompleted; + + [SecuritySafeCritical] + public override void OnCompleted(Action action) => _awaiter.UnsafeOnCompleted(action); + + // Assumption that GetResult blocks until complete is only valid for System.Threading.Tasks.Task. + public override void BlockUntilCompleted() => _awaiter.GetResult(); + + public override object GetResult() + { + _awaiter.GetResult(); // Throws exceptions, if any + return null; + } + } + + private sealed class GenericAdapter : AwaitAdapter + { + private readonly TaskAwaiter _awaiter; + + public GenericAdapter(Task task) + { + _awaiter = task.GetAwaiter(); + } + + public override bool IsCompleted => _awaiter.IsCompleted; + + [SecuritySafeCritical] + public override void OnCompleted(Action action) => _awaiter.UnsafeOnCompleted(action); + + // Assumption that GetResult blocks until complete is only valid for System.Threading.Tasks.Task. + public override void BlockUntilCompleted() => _awaiter.GetResult(); + + public override object GetResult() + { + return _awaiter.GetResult(); // Throws exceptions, if any + } + } + } +} +#endif From 65cbd180831c04b365acf3e09d9cae2f5e91ab9a Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sat, 26 May 2018 22:44:17 -0400 Subject: [PATCH 152/174] Add support for custom C# awaitable types --- .../Compatibility/ReflectionExtensions.cs | 8 ++ .../framework/Internal/AwaitAdapter.cs | 29 +++-- .../CSharpPatternBasedAwaitAdapter.cs | 114 ++++++++++++++++++ .../Internal/DefaultBlockingAwaitAdapter.cs | 71 +++++++++++ .../framework/Internal/Reflect.cs | 73 +++++++++++ 5 files changed, 288 insertions(+), 7 deletions(-) create mode 100644 src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs create mode 100644 src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs diff --git a/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs b/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs index a5475199d9..11ffc179e3 100644 --- a/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs +++ b/src/NUnitFramework/framework/Compatibility/ReflectionExtensions.cs @@ -89,6 +89,14 @@ public static Delegate CreateDelegate(this MethodInfo method, Type type) { return Delegate.CreateDelegate(type, method); } + + /// + /// See . + /// + public static Delegate CreateDelegate(this MethodInfo method, Type type, object target) + { + return Delegate.CreateDelegate(type, target, method); + } } } #endif diff --git a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs index afb13bea6a..1dd243496f 100644 --- a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs @@ -36,18 +36,33 @@ internal abstract class AwaitAdapter public static AwaitAdapter FromAwaitable(object awaitable) { - if (awaitable == null) throw new ArgumentNullException(nameof(awaitable)); + if (awaitable == null) + throw new InvalidOperationException("A null reference cannot be awaited."); +#if !NET40 + // TaskAwaitAdapter is more efficient because it can rely on Task’s + // special quality of blocking until complete in GetResult. + // As long as the pattern-based adapters are reflection-based, this + // is much more efficient as well. var task = awaitable as Task; - if (task == null) - throw new NotImplementedException("Proper awaitable implementation to follow."); + if (task != null) return TaskAwaitAdapter.Create(task); +#endif + + // Await all the (C#) things + var patternBasedAdapter = CSharpPatternBasedAwaitAdapter.TryCreate(awaitable); + if (patternBasedAdapter != null) return patternBasedAdapter; #if NET40 - // TODO: use the general reflection-based awaiter if net40 build is running against a newer BCL - return Net40BclTaskAwaitAdapter.Create(task); -#else - return TaskAwaitAdapter.Create(task); + // If System.Threading.Tasks.Task does not have a GetAwaiter instance method + // (we don’t heuristically search for AsyncBridge-style extension methods), + // we still need to be able to await it to preserve NUnit behavior on machines + // which have a max .NET Framework version of 4.0 installed, such as the default + // for versions of Windows earlier than 8. + var task = awaitable as Task; + if (task != null) return Net40BclTaskAwaitAdapter.Create(task); #endif + + throw new NotSupportedException("NUnit can only await objects which follow the C# specification for awaitable expressions."); } } } diff --git a/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs new file mode 100644 index 0000000000..69dceb1550 --- /dev/null +++ b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs @@ -0,0 +1,114 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if ASYNC +using System; +using System.Collections.Concurrent; +using System.Reflection; +using NUnit.Compatibility; + +namespace NUnit.Framework.Internal +{ + internal static class CSharpPatternBasedAwaitAdapter + { + private static readonly ConcurrentDictionary> ConstructorsByType = new ConcurrentDictionary>(); + + public static AwaitAdapter TryCreate(object awaitable) + { + if (awaitable == null) return null; + + var constructor = ConstructorsByType.GetOrAdd(awaitable.GetType(), CompileAdapter); + + return constructor?.Invoke(awaitable); + } + + private static Func CompileAdapter(Type awaitableType) + { + // See https://docs.microsoft.com/dotnet/csharp/language-reference/language-specification/expressions#awaitable-expressions + // This section was first established in C# 5 and has not been updated as of C# 7.3. + + // Something we might consider doing is checking to see if the Microsoft.CSharp assembly is loadable + // and then driving it via reflection as though we were generating `return await ((dynamic)awaitable);`. + // That would automatically opt into future changes to the spec, if any, but hardly seems worthwhile + // since this code is needed as a fallback anyway. + + var getAwaiterMethod = awaitableType.GetNonGenericPublicInstanceMethod("GetAwaiter", Type.EmptyTypes); + if (getAwaiterMethod == null || getAwaiterMethod.GetGenericArguments().Length != 0) return null; + + var awaiterType = getAwaiterMethod.ReturnType; + var notifyCompletionInterface = awaiterType.GetTypeInfo().GetInterface("System.Runtime.CompilerServices.INotifyCompletion"); + if (notifyCompletionInterface == null) return null; + var onCompletedMethod = notifyCompletionInterface.GetNonGenericPublicInstanceMethod("OnCompleted", new[] {typeof(Action)}); + if (onCompletedMethod == null) return null; + + var isCompletedProperty = awaiterType.GetPublicInstanceProperty("IsCompleted", Type.EmptyTypes); + if (isCompletedProperty == null || isCompletedProperty.PropertyType != typeof(bool)) return null; + var isCompletedGetter = isCompletedProperty.GetGetMethod(); + if (isCompletedGetter == null) return null; + + var getResultMethod = awaiterType.GetNonGenericPublicInstanceMethod("GetResult", Type.EmptyTypes); + if (getResultMethod == null) return null; + + // At this point, we know we have a C# awaitable instance. + + var criticalNotifyCompletionInterface = awaiterType.GetTypeInfo().GetInterface("System.Runtime.CompilerServices.ICriticalNotifyCompletion"); + var unsafeOnCompletedMethod = criticalNotifyCompletionInterface?.GetNonGenericPublicInstanceMethod("UnsafeOnCompleted", new[] {typeof(Action)}); + + // We could emit ideal implementations of AwaitAdapter, customized to each awaitable type. + // But generating executable code at runtime is unsupported by design on some platforms. + // By the same token, MakeGenericMethod is not supported for types not included at compile time. + + // So let’s start with a less efficient, reflection-based approach which works anywhere + // and is much easier to follow, and add the complex thing only if we need to hit a perf goal. + + return awaitable => new ReflectionAdapter( + getAwaiterMethod.InvokeWithTransparentExceptions(awaitable), + isCompletedGetter, + unsafeOnCompletedMethod ?? onCompletedMethod, + getResultMethod); + } + + private sealed class ReflectionAdapter : DefaultBlockingAwaitAdapter + { + private readonly object _awaiter; + private readonly Func _awaiterIsCompleted; + private readonly Action _awaiterOnCompleted; + private readonly MethodInfo _getResultMethod; + + public ReflectionAdapter(object awaiter, MethodInfo isCompletedGetter, MethodInfo onCompletedMethod, MethodInfo getResultMethod) + { + _awaiter = awaiter; + _awaiterIsCompleted = (Func)isCompletedGetter.CreateDelegate(typeof(Func), awaiter); + _awaiterOnCompleted = (Action)onCompletedMethod.CreateDelegate(typeof(Action), awaiter); + _getResultMethod = getResultMethod; + } + + public override bool IsCompleted => _awaiterIsCompleted.Invoke(); + + public override void OnCompleted(Action action) => _awaiterOnCompleted.Invoke(action); + + public override object GetResult() => _getResultMethod.InvokeWithTransparentExceptions(_awaiter); + } + } +} +#endif diff --git a/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs new file mode 100644 index 0000000000..4ca229250a --- /dev/null +++ b/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs @@ -0,0 +1,71 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +#if ASYNC +using System.Threading; + +namespace NUnit.Framework.Internal +{ + /// + /// Useful when wrapping awaitables whose GetResult method does not block until complete. + /// Contains a default mechanism to implement + /// via and . + /// + internal abstract class DefaultBlockingAwaitAdapter : AwaitAdapter + { + private volatile ManualResetEventSlim _completedEvent; + + public sealed override void BlockUntilCompleted() + { + if (IsCompleted) return; + + var completedEvent = _completedEvent; // Volatile read (would be Volatile.Read if not for net40 support) + if (completedEvent == null) + { + completedEvent = new ManualResetEventSlim(); + +#pragma warning disable 420 // Taking a ref to a volatile field is fine if the ref is only used by Interlocked or Volatile methods. + var previous = Interlocked.CompareExchange(ref _completedEvent, completedEvent, null); +#pragma warning restore 420 + + if (previous == null) + { + // We are the first thread. (Though by this time, other threads may now be + // waiting on this ManualResetEvent.) Register to signal the event on completion. + // If completion has already happened by this time, OnCompleted is still obligated + // to execute the action we pass. + OnCompleted(completedEvent.Set); + } + else + { + // We lost a race with another thread. + completedEvent.Dispose(); + completedEvent = previous; + } + } + + completedEvent.Wait(); + } + } +} +#endif diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index 9ad32d4faf..f9bcd2e8cb 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -383,5 +383,78 @@ internal static IEnumerable TypeAndBaseTypes(this Type type) yield return type; } } + + /// + /// Same as GetMethod(, | + /// , , , + /// ) except that it also chooses only non-generic methods. + /// Useful for avoiding the you can have with GetMethod. + /// + internal static MethodInfo GetNonGenericPublicInstanceMethod(this Type type, string name, Type[] parameterTypes) + { + for (var currentType = type; currentType != null; currentType = currentType.GetTypeInfo().BaseType) + { + var method = currentType + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .SingleOrDefault(candidate => + { + if (candidate.Name != name || candidate.GetGenericArguments().Length != 0) return false; + + var parameters = candidate.GetParameters(); + if (parameters.Length != parameterTypes.Length) return false; + + for (var i = 0; i < parameterTypes.Length; i++) + if (parameters[i].ParameterType != parameterTypes[i]) + return false; + + return true; + }); + + if (method != null) return method; + } + + return null; + } + + internal static PropertyInfo GetPublicInstanceProperty(this Type type, string name, Type[] indexParameterTypes) + { + for (var currentType = type; currentType != null; currentType = currentType.GetTypeInfo().BaseType) + { + var property = currentType + .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .SingleOrDefault(candidate => + { + if (candidate.Name != name) return false; + + var indexParameters = candidate.GetIndexParameters(); + if (indexParameters.Length != indexParameterTypes.Length) return false; + + for (var i = 0; i < indexParameterTypes.Length; i++) + if (indexParameters[i].ParameterType != indexParameterTypes[i]) return false; + + return true; + }); + + if (property != null) return property; + } + + return null; + } + + internal static object InvokeWithTransparentExceptions(this MethodBase methodBase, object instance) + { + // If we ever target .NET Core 2.1, we can keep from mucking with the exception stack trace + // using BindingFlags.DoNotWrapExceptions rather than try…catch. + + try + { + return methodBase.Invoke(instance, null); + } + catch (TargetInvocationException ex) + { + ExceptionHelper.Rethrow(ex.InnerException); + throw null; // Rethrow’s return type would be `never` if C# could express that. + } + } } } From 8df37f2024108b8d53d5dbbd7a8d3e518ad2e54a Mon Sep 17 00:00:00 2001 From: jnm2 Date: Mon, 28 May 2018 17:34:55 -0400 Subject: [PATCH 153/174] Unblock types other than Task from being awaited --- .../framework/Constraints/Constraint.cs | 3 +- .../Constraints/DelayedConstraint.cs | 2 - .../framework/Constraints/ThrowsConstraint.cs | 151 +----------------- .../Constraints/ThrowsExceptionConstraint.cs | 48 +----- .../Constraints/ThrowsNothingConstraint.cs | 10 +- .../framework/Internal/AsyncToSyncAdapter.cs | 21 +-- .../framework/Internal/AwaitAdapter.cs | 19 ++- .../Internal/Builders/NUnitTestCaseBuilder.cs | 20 +-- ...PatternBasedAwaitAdapter.AwaitShapeInfo.cs | 103 ++++++++++++ ...ternBasedAwaitAdapter.ReflectionAdapter.cs | 54 +++++++ .../CSharpPatternBasedAwaitAdapter.cs | 90 +++-------- .../Internal/Commands/SetUpTearDownItem.cs | 3 +- .../Internal/Commands/TestMethodCommand.cs | 3 +- .../Internal/DefaultBlockingAwaitAdapter.cs | 2 - .../framework/Internal/ExceptionHelper.cs | 44 +++++ .../framework/Internal/MessagePumpStrategy.cs | 2 - .../framework/Internal/Reflect.cs | 21 +++ .../framework/Internal/Tests/TestSuite.cs | 40 +++-- src/NUnitFramework/tests/HelperConstraints.cs | 2 - 19 files changed, 311 insertions(+), 327 deletions(-) create mode 100644 src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.AwaitShapeInfo.cs create mode 100644 src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.ReflectionAdapter.cs diff --git a/src/NUnitFramework/framework/Constraints/Constraint.cs b/src/NUnitFramework/framework/Constraints/Constraint.cs index be5fd89577..7fc50fa2c1 100644 --- a/src/NUnitFramework/framework/Constraints/Constraint.cs +++ b/src/NUnitFramework/framework/Constraints/Constraint.cs @@ -116,10 +116,9 @@ protected Constraint(params object[] args) /// A ConstraintResult public virtual ConstraintResult ApplyTo(ActualValueDelegate del) { -#if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(del)) return ApplyTo(AsyncToSyncAdapter.Await(() => del.Invoke())); -#endif + return ApplyTo(GetTestObject(del)); } diff --git a/src/NUnitFramework/framework/Constraints/DelayedConstraint.cs b/src/NUnitFramework/framework/Constraints/DelayedConstraint.cs index 62e8b85d38..2932a90817 100644 --- a/src/NUnitFramework/framework/Constraints/DelayedConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/DelayedConstraint.cs @@ -349,10 +349,8 @@ public override ConstraintResult ApplyTo(ref TActual actual) private static object InvokeDelegate(ActualValueDelegate del) { -#if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(del)) return AsyncToSyncAdapter.Await(() => del.Invoke()); -#endif return del(); } diff --git a/src/NUnitFramework/framework/Constraints/ThrowsConstraint.cs b/src/NUnitFramework/framework/Constraints/ThrowsConstraint.cs index 5c8f9562bf..862f6b8e8c 100644 --- a/src/NUnitFramework/framework/Constraints/ThrowsConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ThrowsConstraint.cs @@ -69,23 +69,9 @@ public override string Description /// True if an exception is thrown and the constraint succeeds, otherwise false public override ConstraintResult ApplyTo(TActual actual) { - //TestDelegate code = actual as TestDelegate; - //if (code == null) - // throw new ArgumentException( - // string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual"); + var @delegate = ConstraintUtils.RequireActual(actual, nameof(actual)); - //caughtException = null; - - //try - //{ - // code(); - //} - //catch (Exception ex) - //{ - // caughtException = ex; - //} - - caughtException = ExceptionInterceptor.Intercept(actual); + caughtException = ExceptionHelper.RecordException(@delegate, nameof(actual)); return new ThrowsConstraintResult( this, @@ -103,9 +89,7 @@ public override ConstraintResult ApplyTo(TActual actual) /// public override ConstraintResult ApplyTo(ActualValueDelegate del) { - //TestDelegate testDelegate = new TestDelegate(delegate { del(); }); - //return ApplyTo((object)testDelegate); - return ApplyTo(new GenericInvocationDescriptor(del)); + return ApplyTo((Delegate)del); } #endregion @@ -145,134 +129,5 @@ public override void WriteActualValueTo(MessageWriter writer) } #endregion - - #region ExceptionInterceptor - - internal sealed class ExceptionInterceptor - { - private ExceptionInterceptor() { } - - internal static Exception Intercept(object invocation) - { - var invocationDescriptor = GetInvocationDescriptor(invocation); - -#if ASYNC - if (AsyncToSyncAdapter.IsAsyncOperation(invocationDescriptor.Delegate)) - { - try - { - AsyncToSyncAdapter.Await(invocationDescriptor.Invoke); - return null; - } - catch (Exception ex) - { - return ex; - } - } -#endif - { - using (new TestExecutionContext.IsolatedContext()) - { - try - { - invocationDescriptor.Invoke(); - return null; - } - catch (Exception ex) - { - return ex; - } - } - } - } - - private static IInvocationDescriptor GetInvocationDescriptor(object actual) - { - var invocationDescriptor = actual as IInvocationDescriptor; - - if (invocationDescriptor == null) - { - var testDelegate = actual as TestDelegate; - - if (testDelegate != null) - { - Guard.ArgumentNotAsyncVoid(testDelegate, nameof(actual)); - invocationDescriptor = new VoidInvocationDescriptor(testDelegate); - } - -#if ASYNC - else - { - var asyncTestDelegate = actual as AsyncTestDelegate; - if (asyncTestDelegate != null) - { - invocationDescriptor = new GenericInvocationDescriptor(() => asyncTestDelegate()); - } - } -#endif - } - if (invocationDescriptor == null) - throw new ArgumentException( - String.Format( - "The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", - actual.GetType().Name), - nameof(actual)); - - return invocationDescriptor; - } - } - -#endregion - -#region InvocationDescriptor - - internal sealed class GenericInvocationDescriptor : IInvocationDescriptor - { - private readonly ActualValueDelegate _del; - - public GenericInvocationDescriptor(ActualValueDelegate del) - { - _del = del; - } - - public object Invoke() - { - return _del(); - } - - public Delegate Delegate - { - get { return _del; } - } - } - - private interface IInvocationDescriptor - { - Delegate Delegate { get; } - object Invoke(); - } - - private sealed class VoidInvocationDescriptor : IInvocationDescriptor - { - private readonly TestDelegate _del; - - public VoidInvocationDescriptor(TestDelegate del) - { - _del = del; - } - - public object Invoke() - { - _del(); - return null; - } - - public Delegate Delegate - { - get { return _del; } - } - } - -#endregion } } diff --git a/src/NUnitFramework/framework/Constraints/ThrowsExceptionConstraint.cs b/src/NUnitFramework/framework/Constraints/ThrowsExceptionConstraint.cs index 5fdb164e6a..9c57929bf9 100644 --- a/src/NUnitFramework/framework/Constraints/ThrowsExceptionConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ThrowsExceptionConstraint.cs @@ -23,11 +23,7 @@ using System; using System.Reflection; - -#if ASYNC -using System.Threading.Tasks; using NUnit.Framework.Internal; -#endif namespace NUnit.Framework.Constraints { @@ -53,41 +49,11 @@ public override string Description /// True if an exception is thrown, otherwise false public override ConstraintResult ApplyTo(TActual actual) { - TestDelegate code = actual as TestDelegate; - Exception caughtException = null; + var @delegate = ConstraintUtils.RequireActual(actual, nameof(actual)); - if (code != null) - { - try - { - code(); - } - catch (Exception ex) - { - caughtException = ex; - } - } -#if ASYNC - AsyncTestDelegate asyncCode = actual as AsyncTestDelegate; - if (asyncCode != null) - { - try - { - AsyncToSyncAdapter.Await(asyncCode.Invoke); - } - catch (Exception ex) - { - caughtException = ex; - } - } - if (code == null && asyncCode == null) -#else - else -#endif - { - throw new ArgumentException(string.Format("The actual value must be a TestDelegate or AsyncTestDelegate but was {0}", actual.GetType().Name), nameof(actual)); - } - return new ThrowsExceptionConstraintResult(this, caughtException); + var exception = ExceptionHelper.RecordException(@delegate, nameof(actual)); + + return new ThrowsExceptionConstraintResult(this, exception); } /// @@ -98,11 +64,7 @@ public override ConstraintResult ApplyTo(TActual actual) /// public override ConstraintResult ApplyTo(ActualValueDelegate del) { -#if ASYNC - if (typeof(Task).IsAssignableFrom(typeof(TActual))) - return ApplyTo(new AsyncTestDelegate(() => (Task)(object)del.Invoke())); -#endif - return ApplyTo(new TestDelegate(() => del.Invoke())); + return ApplyTo((Delegate)del); } #region Nested Result Class diff --git a/src/NUnitFramework/framework/Constraints/ThrowsNothingConstraint.cs b/src/NUnitFramework/framework/Constraints/ThrowsNothingConstraint.cs index 600bf35196..90fc0d7de5 100644 --- a/src/NUnitFramework/framework/Constraints/ThrowsNothingConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/ThrowsNothingConstraint.cs @@ -22,6 +22,7 @@ // *********************************************************************** using System; +using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { @@ -49,7 +50,10 @@ public override string Description /// True if no exception is thrown, otherwise false public override ConstraintResult ApplyTo(TActual actual) { - caughtException = ThrowsConstraint.ExceptionInterceptor.Intercept(actual); + var @delegate = ConstraintUtils.RequireActual(actual, nameof(actual)); + + caughtException = ExceptionHelper.RecordException(@delegate, nameof(actual)); + return new ConstraintResult(this, caughtException, caughtException == null); } @@ -63,7 +67,7 @@ public override ConstraintResult ApplyTo(TActual actual) /// A ConstraintResult public override ConstraintResult ApplyTo(ActualValueDelegate del) { - return ApplyTo(new ThrowsConstraint.GenericInvocationDescriptor(del)); + return ApplyTo((Delegate)del); } } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs index 24db6d3254..f951732157 100644 --- a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs @@ -34,8 +34,8 @@ internal static class AsyncToSyncAdapter { public static bool IsAsyncOperation(MethodInfo method) { - return IsTaskType(method.ReturnType) || - method.GetCustomAttributes(false).Any(attr => attr.GetType().FullName == "System.Runtime.CompilerServices.AsyncStateMachineAttribute"); + return AwaitAdapter.IsAwaitable(method.ReturnType) + || method.GetCustomAttributes(false).Any(attr => attr.GetType().FullName == "System.Runtime.CompilerServices.AsyncStateMachineAttribute"); } public static bool IsAsyncOperation(Delegate @delegate) @@ -43,22 +43,6 @@ public static bool IsAsyncOperation(Delegate @delegate) return IsAsyncOperation(@delegate.GetMethodInfo()); } - private static bool IsTaskType(Type type) - { - for (; type != null; type = type.GetTypeInfo().BaseType) - { - if (type.GetTypeInfo().IsGenericType - ? type.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1" - : type.FullName == "System.Threading.Tasks.Task") - { - return true; - } - } - - return false; - } - -#if ASYNC public static object Await(Func invoke) { Guard.ArgumentNotNull(invoke, nameof(invoke)); @@ -104,6 +88,5 @@ private static void SetSynchronizationContext(SynchronizationContext syncContext { SynchronizationContext.SetSynchronizationContext(syncContext); } -#endif } } diff --git a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs index 1dd243496f..0517a6c47e 100644 --- a/src/NUnitFramework/framework/Internal/AwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AwaitAdapter.cs @@ -21,9 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC using System; -using System.Threading.Tasks; namespace NUnit.Framework.Internal { @@ -34,17 +32,27 @@ internal abstract class AwaitAdapter public abstract void BlockUntilCompleted(); public abstract object GetResult(); + public static bool IsAwaitable(Type awaitableType) + { + return CSharpPatternBasedAwaitAdapter.IsAwaitable(awaitableType); + } + + public static Type GetResultType(Type awaitableType) + { + return CSharpPatternBasedAwaitAdapter.GetResultType(awaitableType); + } + public static AwaitAdapter FromAwaitable(object awaitable) { if (awaitable == null) throw new InvalidOperationException("A null reference cannot be awaited."); -#if !NET40 +#if !(NET35 || NET40) // TaskAwaitAdapter is more efficient because it can rely on Task’s // special quality of blocking until complete in GetResult. // As long as the pattern-based adapters are reflection-based, this // is much more efficient as well. - var task = awaitable as Task; + var task = awaitable as System.Threading.Tasks.Task; if (task != null) return TaskAwaitAdapter.Create(task); #endif @@ -58,7 +66,7 @@ public static AwaitAdapter FromAwaitable(object awaitable) // we still need to be able to await it to preserve NUnit behavior on machines // which have a max .NET Framework version of 4.0 installed, such as the default // for versions of Windows earlier than 8. - var task = awaitable as Task; + var task = awaitable as System.Threading.Tasks.Task; if (task != null) return Net40BclTaskAwaitAdapter.Create(task); #endif @@ -66,4 +74,3 @@ public static AwaitAdapter FromAwaitable(object awaitable) } } } -#endif diff --git a/src/NUnitFramework/framework/Internal/Builders/NUnitTestCaseBuilder.cs b/src/NUnitFramework/framework/Internal/Builders/NUnitTestCaseBuilder.cs index 34f4fb1ab6..c5acbb8ecd 100644 --- a/src/NUnitFramework/framework/Internal/Builders/NUnitTestCaseBuilder.cs +++ b/src/NUnitFramework/framework/Internal/Builders/NUnitTestCaseBuilder.cs @@ -177,28 +177,24 @@ private static bool CheckTestMethodSignature(TestMethod testMethod, TestCasePara return false; } - ITypeInfo returnType = testMethod.Method.ReturnType; + var returnType = testMethod.Method.ReturnType.Type; -#if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(testMethod.Method.MethodInfo)) { - if (returnType.IsType(typeof(void))) + if (returnType == typeof(void)) return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type"); - var returnsGenericTask = returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>); + var voidResult = AwaitAdapter.GetResultType(returnType) == typeof(void); - if (returnsGenericTask && (parms == null || !parms.HasExpectedResult)) + if (!voidResult && (parms == null || !parms.HasExpectedResult)) return MarkAsNotRunnable(testMethod, - "Async test method must have non-generic Task return type when no result is expected"); + "Async test method must return an awaitable with a void result when no result is expected"); - if (!returnsGenericTask && parms != null && parms.HasExpectedResult) + if (voidResult && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, - "Async test method must have Task return type when a result is expected"); + "Async test method must return an awaitable with a non-void result when a result is expected"); } - else -#endif - if (returnType.IsType(typeof(void))) + else if (returnType == typeof(void)) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); diff --git a/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.AwaitShapeInfo.cs b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.AwaitShapeInfo.cs new file mode 100644 index 0000000000..cb94c0b4f8 --- /dev/null +++ b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.AwaitShapeInfo.cs @@ -0,0 +1,103 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using NUnit.Compatibility; + +namespace NUnit.Framework.Internal +{ + internal static partial class CSharpPatternBasedAwaitAdapter + { + private sealed class AwaitShapeInfo + { + private readonly MethodInfo _getAwaiterMethod; + private readonly MethodInfo _isCompletedGetter; + private readonly MethodInfo _onCompletedMethod; + private readonly MethodInfo _getResultMethod; + + public AwaitShapeInfo(MethodInfo getAwaiterMethod, MethodInfo isCompletedGetter, MethodInfo onCompletedMethod, MethodInfo getResultMethod) + { + _getAwaiterMethod = getAwaiterMethod; + _isCompletedGetter = isCompletedGetter; + _onCompletedMethod = onCompletedMethod; + _getResultMethod = getResultMethod; + } + + public static AwaitShapeInfo TryCreate(Type awaitableType) + { + // See https://docs.microsoft.com/dotnet/csharp/language-reference/language-specification/expressions#awaitable-expressions + // This section was first established in C# 5 and has not been updated as of C# 7.3. + + // Something we might consider doing is checking to see if the Microsoft.CSharp assembly is loadable + // and then driving it via reflection as though we were generating `return await ((dynamic)awaitable);`. + // That would automatically opt into future changes to the spec, if any, but hardly seems worthwhile + // since this code is needed as a fallback anyway. + + var getAwaiterMethod = awaitableType.GetNonGenericPublicInstanceMethod("GetAwaiter", Type.EmptyTypes); + if (getAwaiterMethod == null || getAwaiterMethod.GetGenericArguments().Length != 0) return null; + + var awaiterType = getAwaiterMethod.ReturnType; + var notifyCompletionInterface = awaiterType.GetInterface("System.Runtime.CompilerServices.INotifyCompletion"); + if (notifyCompletionInterface == null) return null; + var onCompletedMethod = notifyCompletionInterface.GetNonGenericPublicInstanceMethod("OnCompleted", new[] { typeof(Action) }); + if (onCompletedMethod == null) return null; + + var isCompletedProperty = awaiterType.GetPublicInstanceProperty("IsCompleted", Type.EmptyTypes); + if (isCompletedProperty == null || isCompletedProperty.PropertyType != typeof(bool)) return null; + var isCompletedGetter = isCompletedProperty.GetGetMethod(); + if (isCompletedGetter == null) return null; + + var getResultMethod = awaiterType.GetNonGenericPublicInstanceMethod("GetResult", Type.EmptyTypes); + if (getResultMethod == null) return null; + + var criticalNotifyCompletionInterface = awaiterType.GetInterface("System.Runtime.CompilerServices.ICriticalNotifyCompletion"); + var unsafeOnCompletedMethod = criticalNotifyCompletionInterface?.GetNonGenericPublicInstanceMethod("UnsafeOnCompleted", new[] { typeof(Action) }); + + return new AwaitShapeInfo( + getAwaiterMethod, + isCompletedGetter, + unsafeOnCompletedMethod ?? onCompletedMethod, + getResultMethod); + } + + public AwaitAdapter CreateAwaitAdapter(object awaitable) + { + // We could emit ideal implementations of AwaitAdapter, customized to each awaitable type. + // But generating executable code at runtime is unsupported by design on some platforms. + // By the same token, MakeGenericMethod is not supported for types not included at compile time. + + // So let’s start with a less efficient, reflection-based approach which works anywhere + // and is much easier to follow, and add the complex thing only if we need to hit a perf goal. + + return new ReflectionAdapter( + _getAwaiterMethod.InvokeWithTransparentExceptions(awaitable), + _isCompletedGetter, + _onCompletedMethod, + _getResultMethod); + } + + public Type ResultType => _getResultMethod.ReturnType; + } + } +} diff --git a/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.ReflectionAdapter.cs b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.ReflectionAdapter.cs new file mode 100644 index 0000000000..8bcd76dc40 --- /dev/null +++ b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.ReflectionAdapter.cs @@ -0,0 +1,54 @@ +// *********************************************************************** +// Copyright (c) 2018 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Reflection; +using NUnit.Compatibility; + +namespace NUnit.Framework.Internal +{ + internal static partial class CSharpPatternBasedAwaitAdapter + { + private sealed class ReflectionAdapter : DefaultBlockingAwaitAdapter + { + private readonly object _awaiter; + private readonly Func _awaiterIsCompleted; + private readonly Action _awaiterOnCompleted; + private readonly MethodInfo _getResultMethod; + + public ReflectionAdapter(object awaiter, MethodInfo isCompletedGetter, MethodInfo onCompletedMethod, MethodInfo getResultMethod) + { + _awaiter = awaiter; + _awaiterIsCompleted = (Func)isCompletedGetter.CreateDelegate(typeof(Func), awaiter); + _awaiterOnCompleted = (Action)onCompletedMethod.CreateDelegate(typeof(Action), awaiter); + _getResultMethod = getResultMethod; + } + + public override bool IsCompleted => _awaiterIsCompleted.Invoke(); + + public override void OnCompleted(Action action) => _awaiterOnCompleted.Invoke(action); + + public override object GetResult() => _getResultMethod.InvokeWithTransparentExceptions(_awaiter); + } + } +} diff --git a/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs index 69dceb1550..39c2683624 100644 --- a/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/CSharpPatternBasedAwaitAdapter.cs @@ -21,94 +21,52 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC using System; using System.Collections.Concurrent; -using System.Reflection; -using NUnit.Compatibility; +using System.Collections.Generic; namespace NUnit.Framework.Internal { - internal static class CSharpPatternBasedAwaitAdapter + internal static partial class CSharpPatternBasedAwaitAdapter { - private static readonly ConcurrentDictionary> ConstructorsByType = new ConcurrentDictionary>(); +#if NET35 + private static readonly Dictionary ShapeInfoByType = new Dictionary(); +#else + private static readonly ConcurrentDictionary ShapeInfoByType = new ConcurrentDictionary(); +#endif public static AwaitAdapter TryCreate(object awaitable) { if (awaitable == null) return null; - var constructor = ConstructorsByType.GetOrAdd(awaitable.GetType(), CompileAdapter); - - return constructor?.Invoke(awaitable); + return GetShapeInfo(awaitable.GetType())?.CreateAwaitAdapter(awaitable); } - private static Func CompileAdapter(Type awaitableType) + public static bool IsAwaitable(Type awaitableType) { - // See https://docs.microsoft.com/dotnet/csharp/language-reference/language-specification/expressions#awaitable-expressions - // This section was first established in C# 5 and has not been updated as of C# 7.3. - - // Something we might consider doing is checking to see if the Microsoft.CSharp assembly is loadable - // and then driving it via reflection as though we were generating `return await ((dynamic)awaitable);`. - // That would automatically opt into future changes to the spec, if any, but hardly seems worthwhile - // since this code is needed as a fallback anyway. - - var getAwaiterMethod = awaitableType.GetNonGenericPublicInstanceMethod("GetAwaiter", Type.EmptyTypes); - if (getAwaiterMethod == null || getAwaiterMethod.GetGenericArguments().Length != 0) return null; - - var awaiterType = getAwaiterMethod.ReturnType; - var notifyCompletionInterface = awaiterType.GetTypeInfo().GetInterface("System.Runtime.CompilerServices.INotifyCompletion"); - if (notifyCompletionInterface == null) return null; - var onCompletedMethod = notifyCompletionInterface.GetNonGenericPublicInstanceMethod("OnCompleted", new[] {typeof(Action)}); - if (onCompletedMethod == null) return null; - - var isCompletedProperty = awaiterType.GetPublicInstanceProperty("IsCompleted", Type.EmptyTypes); - if (isCompletedProperty == null || isCompletedProperty.PropertyType != typeof(bool)) return null; - var isCompletedGetter = isCompletedProperty.GetGetMethod(); - if (isCompletedGetter == null) return null; - - var getResultMethod = awaiterType.GetNonGenericPublicInstanceMethod("GetResult", Type.EmptyTypes); - if (getResultMethod == null) return null; - - // At this point, we know we have a C# awaitable instance. - - var criticalNotifyCompletionInterface = awaiterType.GetTypeInfo().GetInterface("System.Runtime.CompilerServices.ICriticalNotifyCompletion"); - var unsafeOnCompletedMethod = criticalNotifyCompletionInterface?.GetNonGenericPublicInstanceMethod("UnsafeOnCompleted", new[] {typeof(Action)}); - - // We could emit ideal implementations of AwaitAdapter, customized to each awaitable type. - // But generating executable code at runtime is unsupported by design on some platforms. - // By the same token, MakeGenericMethod is not supported for types not included at compile time. - - // So let’s start with a less efficient, reflection-based approach which works anywhere - // and is much easier to follow, and add the complex thing only if we need to hit a perf goal. + return GetShapeInfo(awaitableType) != null; + } - return awaitable => new ReflectionAdapter( - getAwaiterMethod.InvokeWithTransparentExceptions(awaitable), - isCompletedGetter, - unsafeOnCompletedMethod ?? onCompletedMethod, - getResultMethod); + public static Type GetResultType(Type awaitableType) + { + return GetShapeInfo(awaitableType)?.ResultType; } - private sealed class ReflectionAdapter : DefaultBlockingAwaitAdapter + private static AwaitShapeInfo GetShapeInfo(Type type) { - private readonly object _awaiter; - private readonly Func _awaiterIsCompleted; - private readonly Action _awaiterOnCompleted; - private readonly MethodInfo _getResultMethod; +#if NET35 + AwaitShapeInfo info; - public ReflectionAdapter(object awaiter, MethodInfo isCompletedGetter, MethodInfo onCompletedMethod, MethodInfo getResultMethod) + lock (ShapeInfoByType) { - _awaiter = awaiter; - _awaiterIsCompleted = (Func)isCompletedGetter.CreateDelegate(typeof(Func), awaiter); - _awaiterOnCompleted = (Action)onCompletedMethod.CreateDelegate(typeof(Action), awaiter); - _getResultMethod = getResultMethod; + if (!ShapeInfoByType.TryGetValue(type, out info)) + ShapeInfoByType.Add(type, info = AwaitShapeInfo.TryCreate(type)); } - public override bool IsCompleted => _awaiterIsCompleted.Invoke(); - - public override void OnCompleted(Action action) => _awaiterOnCompleted.Invoke(action); - - public override object GetResult() => _getResultMethod.InvokeWithTransparentExceptions(_awaiter); + return info; +#else + return ShapeInfoByType.GetOrAdd(type, AwaitShapeInfo.TryCreate); +#endif } } } -#endif diff --git a/src/NUnitFramework/framework/Internal/Commands/SetUpTearDownItem.cs b/src/NUnitFramework/framework/Internal/Commands/SetUpTearDownItem.cs index d4d0d3e687..35d9d15001 100644 --- a/src/NUnitFramework/framework/Internal/Commands/SetUpTearDownItem.cs +++ b/src/NUnitFramework/framework/Internal/Commands/SetUpTearDownItem.cs @@ -103,11 +103,10 @@ public void RunTearDown(TestExecutionContext context) private static void RunSetUpOrTearDownMethod(TestExecutionContext context, MethodInfo method) { Guard.ArgumentNotAsyncVoid(method, nameof(method)); -#if ASYNC + if (AsyncToSyncAdapter.IsAsyncOperation(method)) AsyncToSyncAdapter.Await(() => InvokeMethod(method, context)); else -#endif InvokeMethod(method, context); } diff --git a/src/NUnitFramework/framework/Internal/Commands/TestMethodCommand.cs b/src/NUnitFramework/framework/Internal/Commands/TestMethodCommand.cs index 72c5fc63f9..81ea787886 100644 --- a/src/NUnitFramework/framework/Internal/Commands/TestMethodCommand.cs +++ b/src/NUnitFramework/framework/Internal/Commands/TestMethodCommand.cs @@ -76,12 +76,11 @@ public override TestResult Execute(TestExecutionContext context) private object RunTestMethod(TestExecutionContext context) { -#if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(testMethod.Method.MethodInfo)) { return AsyncToSyncAdapter.Await(() => InvokeTestMethod(context)); } -#endif + return InvokeTestMethod(context); } diff --git a/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs index 4ca229250a..f95522221a 100644 --- a/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/DefaultBlockingAwaitAdapter.cs @@ -21,7 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC using System.Threading; namespace NUnit.Framework.Internal @@ -68,4 +67,3 @@ public sealed override void BlockUntilCompleted() } } } -#endif diff --git a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs index 4dee039a99..280796aca1 100644 --- a/src/NUnitFramework/framework/Internal/ExceptionHelper.cs +++ b/src/NUnitFramework/framework/Internal/ExceptionHelper.cs @@ -28,6 +28,7 @@ using System.Linq; using System.Reflection; using System.Text; +using NUnit.Compatibility; namespace NUnit.Framework.Internal { @@ -202,5 +203,48 @@ private static List FlattenExceptionHierarchy(Exception exception) return result; } + + /// + /// Executes a parameterless synchronous or async delegate and returns the exception it throws, if any. + /// + internal static Exception RecordException(Delegate parameterlessDelegate, string parameterName) + { + Guard.ArgumentNotNull(parameterlessDelegate, parameterName); + + Guard.ArgumentValid( + parameterlessDelegate.GetMethodInfo().GetParameters().Length == 0, + $"The actual value must be a parameterless delegate but was {parameterlessDelegate.GetType().Name}.", + nameof(parameterName)); + + Guard.ArgumentNotAsyncVoid(parameterlessDelegate, parameterName); + + using (new TestExecutionContext.IsolatedContext()) + { + if (AsyncToSyncAdapter.IsAsyncOperation(parameterlessDelegate)) + { + try + { + AsyncToSyncAdapter.Await(parameterlessDelegate.DynamicInvokeWithTransparentExceptions); + } + catch (Exception ex) + { + return ex; + } + } + else + { + try + { + parameterlessDelegate.DynamicInvokeWithTransparentExceptions(); + } + catch (Exception ex) + { + return ex; + } + } + } + + return null; + } } } diff --git a/src/NUnitFramework/framework/Internal/MessagePumpStrategy.cs b/src/NUnitFramework/framework/Internal/MessagePumpStrategy.cs index 99b2eb01b4..1ac0bfcc44 100644 --- a/src/NUnitFramework/framework/Internal/MessagePumpStrategy.cs +++ b/src/NUnitFramework/framework/Internal/MessagePumpStrategy.cs @@ -21,7 +21,6 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC using System; using System.Security; using System.Threading; @@ -170,4 +169,3 @@ private static void ContinueOnSameSynchronizationContext(AwaitAdapter adapter, A } } } -#endif diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index f9bcd2e8cb..811664a6f5 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -384,6 +384,14 @@ internal static IEnumerable TypeAndBaseTypes(this Type type) } } +#if NETSTANDARD1_4 + internal static Type GetInterface(this Type type, string name) + { + return type.GetTypeInfo().ImplementedInterfaces + .SingleOrDefault(implementedInterface => implementedInterface.FullName == name); + } +#endif + /// /// Same as GetMethod(, | /// , , , @@ -456,5 +464,18 @@ internal static object InvokeWithTransparentExceptions(this MethodBase methodBas throw null; // Rethrow’s return type would be `never` if C# could express that. } } + + internal static object DynamicInvokeWithTransparentExceptions(this Delegate @delegate) + { + try + { + return @delegate.DynamicInvoke(); + } + catch (TargetInvocationException ex) + { + ExceptionHelper.Rethrow(ex.InnerException); + throw null; // Rethrow’s return type would be `never` if C# could express that. + } + } } } diff --git a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs index b39bbf8bbe..2ddb90837b 100644 --- a/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs +++ b/src/NUnitFramework/framework/Internal/Tests/TestSuite.cs @@ -25,11 +25,6 @@ using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; -using NUnit.Framework.Internal.Commands; - -#if ASYNC -using System.Threading.Tasks; -#endif namespace NUnit.Framework.Internal { @@ -309,19 +304,32 @@ public override TNode AddToXml(TNode parentNode, bool recursive) protected void CheckSetUpTearDownMethods(MethodInfo[] methods) { foreach (MethodInfo method in methods) - if (method.IsAbstract || - !method.IsPublic && !method.IsFamily || - method.GetParameters().Length > 0 || - method.ReturnType != typeof(void) -#if ASYNC - && - method.ReturnType != typeof(Task) -#endif - ) + { + if (method.IsAbstract) { - this.MakeInvalid(string.Format("Invalid signature for SetUp or TearDown method: {0}", method.Name)); - break; + MakeInvalid("An abstract SetUp and TearDown methods cannot be run: " + method.Name); } + else if (!(method.IsPublic || method.IsFamily)) + { + MakeInvalid("SetUp and TearDown methods must be public or internal: " + method.Name); + } + else if (method.GetParameters().Length != 0) + { + MakeInvalid("SetUp and TearDown methods must not have parameters: " + method.Name); + } + else if (AsyncToSyncAdapter.IsAsyncOperation(method)) + { + if (method.ReturnType == typeof(void)) + MakeInvalid("SetUp and TearDown methods must not be async void: " + method.Name); + else if (AwaitAdapter.GetResultType(method.ReturnType) != typeof(void)) + MakeInvalid("SetUp and TearDown methods must return void or an awaitable type with a void result: " + method.Name); + } + else + { + if (method.ReturnType != typeof(void)) + MakeInvalid("SetUp and TearDown methods must return void or an awaitable type with a void result: " + method.Name); + } + } } #endregion } diff --git a/src/NUnitFramework/tests/HelperConstraints.cs b/src/NUnitFramework/tests/HelperConstraints.cs index 1e508cfedb..868d1e60c3 100644 --- a/src/NUnitFramework/tests/HelperConstraints.cs +++ b/src/NUnitFramework/tests/HelperConstraints.cs @@ -62,7 +62,6 @@ public override ConstraintResult ApplyTo(TActual actual) var stopwatch = new System.Diagnostics.Stopwatch(); -#if ASYNC if (AsyncToSyncAdapter.IsAsyncOperation(@delegate)) { stopwatch.Start(); @@ -70,7 +69,6 @@ public override ConstraintResult ApplyTo(TActual actual) stopwatch.Stop(); } else -#endif { stopwatch.Start(); @delegate.DynamicInvoke(); From 8cf9f99b9178a2e662757c4068c9059f4ea27ea4 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Fri, 23 Nov 2018 19:54:46 -0500 Subject: [PATCH 154/174] =?UTF-8?q?These=20weren=E2=80=99t=20related=20to?= =?UTF-8?q?=20async?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/NUnitFramework/tests/Internal/PlatformDetectionTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/tests/Internal/PlatformDetectionTests.cs b/src/NUnitFramework/tests/Internal/PlatformDetectionTests.cs index c2ee560ad1..c07be6be5a 100644 --- a/src/NUnitFramework/tests/Internal/PlatformDetectionTests.cs +++ b/src/NUnitFramework/tests/Internal/PlatformDetectionTests.cs @@ -431,13 +431,13 @@ public void PlatformAttribute_ProcessBitNess() bool is64BitProcess = helper.IsPlatformSupported(attr64); Assert.False(is32BitProcess & is64BitProcess, "Process cannot be both 32 and 64 bit"); -#if ASYNC +#if !NET35 // For .NET 4.0 and 4.5, we can check further Assert.That(is64BitProcess, Is.EqualTo(Environment.Is64BitProcess)); #endif } -#if ASYNC +#if !NET35 [Test] public void PlatformAttribute_OperatingSystemBitNess() { From 97e8cde7a69e3577b57b72d006abbc9225b89369 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Fri, 23 Nov 2018 21:50:23 -0500 Subject: [PATCH 155/174] Added consistency tests across all awaitable return types with a void result --- src/NUnitFramework/testdata/AsyncWorkload.cs | 56 +++++ .../testdata/AwaitableReturnTypeFixture.cs | 198 ++++++++++++++++ src/NUnitFramework/testdata/Polyfills.cs | 18 ++ .../tests/AwaitableReturnTypeTests.cs | 222 ++++++++++++++++++ 4 files changed, 494 insertions(+) create mode 100644 src/NUnitFramework/testdata/AsyncWorkload.cs create mode 100644 src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs create mode 100644 src/NUnitFramework/testdata/Polyfills.cs create mode 100644 src/NUnitFramework/tests/AwaitableReturnTypeTests.cs diff --git a/src/NUnitFramework/testdata/AsyncWorkload.cs b/src/NUnitFramework/testdata/AsyncWorkload.cs new file mode 100644 index 0000000000..909193052c --- /dev/null +++ b/src/NUnitFramework/testdata/AsyncWorkload.cs @@ -0,0 +1,56 @@ +using System; + +namespace NUnit.TestData +{ + public struct AsyncWorkload + { + private readonly Action _beforeReturningAwaitable; + private readonly Action _beforeReturningAwaiter; + private readonly Func _isCompleted; + private readonly Action _onCompleted; + private readonly Func _getResult; + + public AsyncWorkload(bool isCompleted, Action onCompleted, Func getResult) + : this(null, null, () => isCompleted, onCompleted, getResult) + { + } + + public AsyncWorkload(Func isCompleted, Action onCompleted, Func getResult) + : this(null, null, isCompleted, onCompleted, getResult) + { + } + + public AsyncWorkload( + Action beforeReturningAwaitable, + Action beforeReturningAwaiter, + Func isCompleted, + Action onCompleted, + Func getResult) + { + _beforeReturningAwaitable = beforeReturningAwaitable; + _beforeReturningAwaiter = beforeReturningAwaiter; + _isCompleted = isCompleted; + _onCompleted = onCompleted; + _getResult = getResult; + } + + public void BeforeReturningAwaitable() => _beforeReturningAwaitable?.Invoke(); + + public void BeforeReturningAwaiter() => _beforeReturningAwaiter?.Invoke(); + + public bool IsCompleted => _isCompleted.Invoke(); + + public void OnCompleted(Action continuation) + { + if (IsCompleted) + continuation.Invoke(); + else + _onCompleted.Invoke(continuation); + } + + public object GetResult() + { + return _getResult.Invoke(); + } + } +} diff --git a/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs b/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs new file mode 100644 index 0000000000..a23f18fc8d --- /dev/null +++ b/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs @@ -0,0 +1,198 @@ +using System; +using System.Runtime.CompilerServices; +using NUnit.Framework; + +#if ASYNC +using System.Threading.Tasks; +#endif + +namespace NUnit.TestData +{ + public sealed class AwaitableReturnTypeFixture + { + private readonly AsyncWorkload _workload; + + public AwaitableReturnTypeFixture(AsyncWorkload workload) + { + _workload = workload; + } + +#if ASYNC +#pragma warning disable 1998 + public Task ReturnsTask() +#pragma warning restore 1998 + { + _workload.BeforeReturningAwaitable(); + _workload.BeforeReturningAwaiter(); + + var source = new TaskCompletionSource(); + + var complete = new Action(() => + { + try + { + _workload.GetResult(); + source.SetResult(null); + } + catch (Exception ex) + { + source.SetException(ex); + } + }); + + if (_workload.IsCompleted) + complete.Invoke(); + else + _workload.OnCompleted(complete); + + return source.Task; + } + + public CustomTask ReturnsCustomTask() + { + _workload.BeforeReturningAwaitable(); + _workload.BeforeReturningAwaiter(); + + var task = new CustomTask(() => _workload.GetResult()); + + if (_workload.IsCompleted) + task.Start(); + else + _workload.OnCompleted(task.Start); + + return task; + } + + public sealed class CustomTask : Task + { + public CustomTask(Action action) : base(action) + { + } + } +#endif + + public CustomAwaitable ReturnsCustomAwaitable() + { + _workload.BeforeReturningAwaitable(); + return new CustomAwaitable(_workload); + } + + public struct CustomAwaitable + { + private readonly AsyncWorkload _workload; + + public CustomAwaitable(AsyncWorkload workload) + { + _workload = workload; + } + + public CustomAwaiter GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new CustomAwaiter(_workload); + } + + public struct CustomAwaiter : ICriticalNotifyCompletion + { + private readonly AsyncWorkload _workload; + + public CustomAwaiter(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + public void OnCompleted(Action continuation) + { + Assert.Fail("This method should not be used because UnsafeOnCompleted is available."); + } + + public void UnsafeOnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public void GetResult() => _workload.GetResult(); + } + } + + public CustomAwaitableWithImplicitOnCompleted ReturnsCustomAwaitableWithImplicitOnCompleted() + { + _workload.BeforeReturningAwaitable(); + return new CustomAwaitableWithImplicitOnCompleted(_workload); + } + + public struct CustomAwaitableWithImplicitOnCompleted + { + private readonly AsyncWorkload _workload; + + public CustomAwaitableWithImplicitOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public CustomAwaiterWithImplicitOnCompleted GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new CustomAwaiterWithImplicitOnCompleted(_workload); + } + + public struct CustomAwaiterWithImplicitOnCompleted : INotifyCompletion + { + private readonly AsyncWorkload _workload; + + public CustomAwaiterWithImplicitOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + void INotifyCompletion.OnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public void GetResult() => _workload.GetResult(); + } + } + + public CustomAwaitableWithImplicitUnsafeOnCompleted ReturnsCustomAwaitableWithImplicitUnsafeOnCompleted() + { + _workload.BeforeReturningAwaitable(); + return new CustomAwaitableWithImplicitUnsafeOnCompleted(_workload); + } + + public struct CustomAwaitableWithImplicitUnsafeOnCompleted + { + private readonly AsyncWorkload _workload; + + public CustomAwaitableWithImplicitUnsafeOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public CustomAwaiterWithImplicitUnsafeOnCompleted GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new CustomAwaiterWithImplicitUnsafeOnCompleted(_workload); + } + + public struct CustomAwaiterWithImplicitUnsafeOnCompleted : ICriticalNotifyCompletion + { + private readonly AsyncWorkload _workload; + + public CustomAwaiterWithImplicitUnsafeOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + public void OnCompleted(Action continuation) + { + Assert.Fail("This method should not be used because UnsafeOnCompleted is available."); + } + + void ICriticalNotifyCompletion.UnsafeOnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public void GetResult() => _workload.GetResult(); + } + } + } +} diff --git a/src/NUnitFramework/testdata/Polyfills.cs b/src/NUnitFramework/testdata/Polyfills.cs new file mode 100644 index 0000000000..26725197d1 --- /dev/null +++ b/src/NUnitFramework/testdata/Polyfills.cs @@ -0,0 +1,18 @@ +#if NET35 + +// ReSharper disable CheckNamespace + +namespace System.Runtime.CompilerServices +{ + internal interface INotifyCompletion + { + void OnCompleted(Action continuation); + } + + internal interface ICriticalNotifyCompletion : INotifyCompletion + { + void UnsafeOnCompleted(Action continuation); + } +} + +#endif diff --git a/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs new file mode 100644 index 0000000000..b8de2f2ab3 --- /dev/null +++ b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs @@ -0,0 +1,222 @@ +using System; +using System.Threading; +using NUnit.Framework.Interfaces; +using NUnit.TestData; +using NUnit.TestUtilities; +using F = NUnit.TestData.AwaitableReturnTypeFixture; + +namespace NUnit.Framework +{ +#if ASYNC + [TestFixture(nameof(F.ReturnsTask))] + [TestFixture(nameof(F.ReturnsCustomTask))] +#endif + [TestFixture(nameof(F.ReturnsCustomAwaitable))] + [TestFixture(nameof(F.ReturnsCustomAwaitableWithImplicitOnCompleted))] + [TestFixture(nameof(F.ReturnsCustomAwaitableWithImplicitUnsafeOnCompleted))] + public sealed class AwaitableReturnTypeTests + { + private readonly string _methodName; + + public AwaitableReturnTypeTests(string methodName) + { + _methodName = methodName; + } + + private ITestResult RunCurrentTestMethod(AsyncWorkload workload) + { + var test = TestBuilder.MakeTestFromMethod(typeof(F), _methodName); + + return TestBuilder.RunTest(test, new F(workload)); + } + + [Test] + public void GetResultIsCalledSynchronouslyIfIsCompleteIsFalse() + { + var wasCalled = false; + + RunCurrentTestMethod(new AsyncWorkload( + isCompleted: true, + onCompleted: continuation => Assert.Fail("OnCompleted should not be called when IsCompleted is true."), + getResult: () => wasCalled = true) + ).AssertPassed(); + + Assert.That(wasCalled); + } + + [Test] + public void GetResultIsCalledSynchronouslyWhenContinued() + { + var wasCalled = false; + + RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: continuation => continuation.Invoke(), + getResult: () => wasCalled = true) + ).AssertPassed(); + + Assert.That(wasCalled); + } + + [Test] + public void GetResultIsNotCalledUntilContinued() + { + var wasCalled = false; + var continuation = (Action)null; + var result = (ITestResult)null; + + ThreadPool.QueueUserWorkItem(state => + { + result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: action => continuation = action, + getResult: () => wasCalled = true) + ); + }); + + SpinWait.SpinUntil(() => continuation != null); + + Assert.That(wasCalled, Is.False, "GetResult was called before the continuation passed to OnCompleted was invoked."); + + continuation.Invoke(); + + if (!SpinWait.SpinUntil(() => wasCalled, 1000)) + { + Assert.Fail("GetResult was not called after the continuation passed to OnCompleted was invoked."); + } + + SpinWait.SpinUntil(() => result != null); + result.AssertPassed(); + } + + [Test] + public void ExceptionThrownBeforeReturningAwaitableShouldBeHandled() + { + var getAwaiterWasCalled = false; + var isCompletedWasCalled = false; + var onCompletedWasCalled = false; + var getResultWasCalled = false; + + var result = RunCurrentTestMethod(new AsyncWorkload( + beforeReturningAwaitable: () => { throw new OddlyNamedException("Failure message"); }, + beforeReturningAwaiter: () => getAwaiterWasCalled = true, + isCompleted: () => isCompletedWasCalled = true, + onCompleted: continuation => onCompletedWasCalled = true, + getResult: () => getResultWasCalled = true)); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OddlyNamedException")); + Assert.That(result.Message, Contains.Substring("Failure message")); + + Assert.That(getAwaiterWasCalled, Is.False); + Assert.That(isCompletedWasCalled, Is.False); + Assert.That(onCompletedWasCalled, Is.False); + Assert.That(getResultWasCalled, Is.False); + } + + [Test] + public void ExceptionThrownInGetAwaiterShouldBeHandled() + { + var isCompletedWasCalled = false; + var onCompletedWasCalled = false; + var getResultWasCalled = false; + + var result = RunCurrentTestMethod(new AsyncWorkload( + beforeReturningAwaitable: null, + beforeReturningAwaiter: () => { throw new OddlyNamedException("Failure message"); }, + isCompleted: () => isCompletedWasCalled = true, + onCompleted: continuation => onCompletedWasCalled = true, + getResult: () => getResultWasCalled = true)); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OddlyNamedException")); + Assert.That(result.Message, Contains.Substring("Failure message")); + + Assert.That(isCompletedWasCalled, Is.False); + Assert.That(onCompletedWasCalled, Is.False); + Assert.That(getResultWasCalled, Is.False); + } + + [Test] + public void ExceptionThrownInIsCompletedShouldBeHandled() + { + var onCompletedWasCalled = false; + var getResultWasCalled = false; + + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: () => { throw new OddlyNamedException("Failure message"); }, + onCompleted: continuation => onCompletedWasCalled = true, + getResult: () => getResultWasCalled = true)); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OddlyNamedException")); + Assert.That(result.Message, Contains.Substring("Failure message")); + + Assert.That(onCompletedWasCalled, Is.False); + Assert.That(getResultWasCalled, Is.False); + } + + [Test] + public void ExceptionThrownInOnCompletedShouldBeHandled() + { + var getResultWasCalled = false; + + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: continuation => { throw new OddlyNamedException("Failure message"); }, + getResult: () => getResultWasCalled = true)); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OddlyNamedException")); + Assert.That(result.Message, Contains.Substring("Failure message")); + + Assert.That(getResultWasCalled, Is.False); + } + + [Test] + public void ExceptionThrownInGetResultShouldBeHandled() + { + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: continuation => continuation.Invoke(), + getResult: () => { throw new OddlyNamedException("Failure message"); })); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OddlyNamedException")); + Assert.That(result.Message, Contains.Substring("Failure message")); + } + + private sealed class OddlyNamedException : Exception + { + public OddlyNamedException(string message) : base(message) + { + } + } + + [Test] + public void OperationCanceledExceptionThrownInGetResultShouldBeReportedAsSuch() + { + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: continuation => continuation.Invoke(), + getResult: () => { throw new OperationCanceledException(); })); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("OperationCanceledException")); + } + +#if ASYNC + [Test] + public void TaskCanceledExceptionThrownInGetResultShouldBeReportedAsSuch() + { + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: false, + onCompleted: continuation => continuation.Invoke(), + getResult: () => { throw new System.Threading.Tasks.TaskCanceledException(); })); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("TaskCanceledException")); + } +#endif + } +} From 7c0ca07f602bfae74d5e0effde53714ef5aa2e5b Mon Sep 17 00:00:00 2001 From: jnm2 Date: Fri, 23 Nov 2018 22:31:44 -0500 Subject: [PATCH 156/174] Added consistency tests across all awaitable return types with a non-void result --- .../testdata/AwaitableReturnTypeFixture.cs | 190 ++++++++++++++++++ .../tests/AwaitableReturnTypeTests.cs | 10 +- .../NonVoidResultAwaitableReturnTypeTests.cs | 35 ++++ 3 files changed, 230 insertions(+), 5 deletions(-) create mode 100644 src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs diff --git a/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs b/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs index a23f18fc8d..79405d62b0 100644 --- a/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs +++ b/src/NUnitFramework/testdata/AwaitableReturnTypeFixture.cs @@ -17,6 +17,8 @@ public AwaitableReturnTypeFixture(AsyncWorkload workload) _workload = workload; } + #region Void result + #if ASYNC #pragma warning disable 1998 public Task ReturnsTask() @@ -194,5 +196,193 @@ public void OnCompleted(Action continuation) public void GetResult() => _workload.GetResult(); } } + + #endregion + + #region Non-void result + +#if ASYNC +#pragma warning disable 1998 + [Test(ExpectedResult = 42)] + public Task ReturnsNonVoidResultTask() +#pragma warning restore 1998 + { + _workload.BeforeReturningAwaitable(); + _workload.BeforeReturningAwaiter(); + + var source = new TaskCompletionSource(); + + var complete = new Action(() => + { + try + { + source.SetResult(_workload.GetResult()); + } + catch (Exception ex) + { + source.SetException(ex); + } + }); + + if (_workload.IsCompleted) + complete.Invoke(); + else + _workload.OnCompleted(complete); + + return source.Task; + } + + [Test(ExpectedResult = 42)] + public NonVoidResultCustomTask ReturnsNonVoidResultCustomTask() + { + _workload.BeforeReturningAwaitable(); + _workload.BeforeReturningAwaiter(); + + var task = new NonVoidResultCustomTask(_workload.GetResult); + + if (_workload.IsCompleted) + task.Start(); + else + _workload.OnCompleted(task.Start); + + return task; + } + + public sealed class NonVoidResultCustomTask : Task + { + public NonVoidResultCustomTask(Func function) : base(function) + { + } + } +#endif + + [Test(ExpectedResult = 42)] + public NonVoidResultCustomAwaitable ReturnsNonVoidResultCustomAwaitable() + { + _workload.BeforeReturningAwaitable(); + return new NonVoidResultCustomAwaitable(_workload); + } + + public struct NonVoidResultCustomAwaitable + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaitable(AsyncWorkload workload) + { + _workload = workload; + } + + public NonVoidResultCustomAwaiter GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new NonVoidResultCustomAwaiter(_workload); + } + + public struct NonVoidResultCustomAwaiter : ICriticalNotifyCompletion + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaiter(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + public void OnCompleted(Action continuation) + { + Assert.Fail("This method should not be used because UnsafeOnCompleted is available."); + } + + public void UnsafeOnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public object GetResult() => _workload.GetResult(); + } + } + + [Test(ExpectedResult = 42)] + public NonVoidResultCustomAwaitableWithImplicitOnCompleted ReturnsNonVoidResultCustomAwaitableWithImplicitOnCompleted() + { + _workload.BeforeReturningAwaitable(); + return new NonVoidResultCustomAwaitableWithImplicitOnCompleted(_workload); + } + + public struct NonVoidResultCustomAwaitableWithImplicitOnCompleted + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaitableWithImplicitOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public NonVoidResultCustomAwaiterWithImplicitOnCompleted GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new NonVoidResultCustomAwaiterWithImplicitOnCompleted(_workload); + } + + public struct NonVoidResultCustomAwaiterWithImplicitOnCompleted : INotifyCompletion + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaiterWithImplicitOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + void INotifyCompletion.OnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public object GetResult() => _workload.GetResult(); + } + } + + [Test(ExpectedResult = 42)] + public NonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted ReturnsNonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted() + { + _workload.BeforeReturningAwaitable(); + return new NonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted(_workload); + } + + public struct NonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public NonVoidResultCustomAwaiterWithImplicitUnsafeOnCompleted GetAwaiter() + { + _workload.BeforeReturningAwaiter(); + return new NonVoidResultCustomAwaiterWithImplicitUnsafeOnCompleted(_workload); + } + + public struct NonVoidResultCustomAwaiterWithImplicitUnsafeOnCompleted : ICriticalNotifyCompletion + { + private readonly AsyncWorkload _workload; + + public NonVoidResultCustomAwaiterWithImplicitUnsafeOnCompleted(AsyncWorkload workload) + { + _workload = workload; + } + + public bool IsCompleted => _workload.IsCompleted; + + public void OnCompleted(Action continuation) + { + Assert.Fail("This method should not be used because UnsafeOnCompleted is available."); + } + + void ICriticalNotifyCompletion.UnsafeOnCompleted(Action continuation) => _workload.OnCompleted(continuation); + + public object GetResult() => _workload.GetResult(); + } + } + + #endregion } } diff --git a/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs index b8de2f2ab3..4a2874d53c 100644 --- a/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs +++ b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs @@ -14,7 +14,7 @@ namespace NUnit.Framework [TestFixture(nameof(F.ReturnsCustomAwaitable))] [TestFixture(nameof(F.ReturnsCustomAwaitableWithImplicitOnCompleted))] [TestFixture(nameof(F.ReturnsCustomAwaitableWithImplicitUnsafeOnCompleted))] - public sealed class AwaitableReturnTypeTests + public class AwaitableReturnTypeTests { private readonly string _methodName; @@ -23,7 +23,7 @@ public AwaitableReturnTypeTests(string methodName) _methodName = methodName; } - private ITestResult RunCurrentTestMethod(AsyncWorkload workload) + protected ITestResult RunCurrentTestMethod(AsyncWorkload workload) { var test = TestBuilder.MakeTestFromMethod(typeof(F), _methodName); @@ -38,7 +38,7 @@ public void GetResultIsCalledSynchronouslyIfIsCompleteIsFalse() RunCurrentTestMethod(new AsyncWorkload( isCompleted: true, onCompleted: continuation => Assert.Fail("OnCompleted should not be called when IsCompleted is true."), - getResult: () => wasCalled = true) + getResult: () => { wasCalled = true; return 42; }) ).AssertPassed(); Assert.That(wasCalled); @@ -52,7 +52,7 @@ public void GetResultIsCalledSynchronouslyWhenContinued() RunCurrentTestMethod(new AsyncWorkload( isCompleted: false, onCompleted: continuation => continuation.Invoke(), - getResult: () => wasCalled = true) + getResult: () => { wasCalled = true; return 42; }) ).AssertPassed(); Assert.That(wasCalled); @@ -70,7 +70,7 @@ public void GetResultIsNotCalledUntilContinued() result = RunCurrentTestMethod(new AsyncWorkload( isCompleted: false, onCompleted: action => continuation = action, - getResult: () => wasCalled = true) + getResult: () => { wasCalled = true; return 42; }) ); }); diff --git a/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs b/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs new file mode 100644 index 0000000000..54c89c4a7f --- /dev/null +++ b/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs @@ -0,0 +1,35 @@ +using NUnit.Framework.Interfaces; +using NUnit.TestData; +using F = NUnit.TestData.AwaitableReturnTypeFixture; + +namespace NUnit.Framework +{ +#if ASYNC + [TestFixture(nameof(F.ReturnsNonVoidResultTask))] + [TestFixture(nameof(F.ReturnsNonVoidResultCustomTask))] +#endif + [TestFixture(nameof(F.ReturnsNonVoidResultCustomAwaitable))] + [TestFixture(nameof(F.ReturnsNonVoidResultCustomAwaitableWithImplicitOnCompleted))] + [TestFixture(nameof(F.ReturnsNonVoidResultCustomAwaitableWithImplicitUnsafeOnCompleted))] + public sealed class NonVoidResultAwaitableReturnTypeTests : AwaitableReturnTypeTests + { + public NonVoidResultAwaitableReturnTypeTests(string methodName) + : base(methodName) + { + + } + + [Test] + public void ResultMustMatchExpectedResult() + { + var result = RunCurrentTestMethod(new AsyncWorkload( + isCompleted: true, + onCompleted: continuation => continuation.Invoke(), + getResult: () => 41)); + + Assert.That(result.ResultState.Status, Is.EqualTo(TestStatus.Failed)); + Assert.That(result.Message, Contains.Substring("41")); + Assert.That(result.Message, Contains.Substring("42")); + } + } +} From 69e4c09081cdbd6fd348a582fa2859155cdb3b40 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Fri, 23 Nov 2018 23:26:42 -0500 Subject: [PATCH 157/174] Remaining ASYNC usages actually mean TASK_PARALLEL_LIBRARY_API --- BUILDING.md | 2 +- src/NUnitFramework/Directory.Build.props | 2 +- .../framework/Assert.Exceptions.Async.cs | 2 +- src/NUnitFramework/framework/Assert.cs | 4 +- .../framework/Internal/ExceptionHelper.cs | 2 +- .../framework/Internal/TaskAwaitAdapter.cs | 2 +- .../testdata/AssertMultipleData.cs | 4 +- .../testdata/AsyncDummyFixture.cs | 2 +- .../AsyncExecutionApiAdapter.Fixture-based.cs | 2 +- .../testdata/AsyncRealFixture.cs | 2 +- .../testdata/AsyncSetupTearDownFixture.cs | 2 +- .../testdata/AwaitableReturnTypeFixture.cs | 6 +-- .../testdata/UnexpectedExceptionFixture.cs | 2 +- src/NUnitFramework/testdata/WarningFixture.cs | 10 ++--- .../tests/Assertions/AssertMultipleTests.cs | 4 +- .../tests/Assertions/AssertThatTests.cs | 4 +- .../Assertions/AssertThrowsAsyncTests.cs | 2 +- .../tests/Assertions/AssumeThatTests.cs | 4 +- .../tests/Assertions/AsyncThrowsTests.cs | 2 +- .../tests/Assertions/WarningTests.cs | 10 ++--- .../AsyncExecutionApiAdapter.Assert-based.cs | 2 +- ...yncExecutionApiAdapter.Constraint-based.cs | 2 +- .../AsyncExecutionApiAdapter.Fixture-based.cs | 2 +- .../tests/AsyncExecutionApiAdapter.cs | 2 +- .../tests/AsyncExecutionApiAdapterTests.cs | 2 +- .../Attributes/TestCaseAttributeTests.cs | 4 +- .../tests/AwaitableReturnTypeTests.cs | 4 +- .../AsyncDelayedConstraintTests.cs | 2 +- .../ThrowsExceptionConstraintTests.cs | 4 +- .../tests/Internal/AsyncSetupTeardownTests.cs | 2 +- .../tests/Internal/AsyncTestMethodTests.cs | 2 +- .../Internal/NUnitTestCaseBuilderTests.cs | 2 +- .../Internal/RealAsyncSetupTeardownTests.cs | 2 +- .../Internal/Results/TestResultApiTests.cs | 2 +- .../Internal/TestExecutionContextTests.cs | 42 +++++++++---------- .../Internal/UnexpectedExceptionTests.cs | 2 +- .../NonVoidResultAwaitableReturnTypeTests.cs | 2 +- .../tests/SynchronizationContextTests.cs | 2 +- src/NUnitFramework/tests/TestContextTests.cs | 4 +- .../tests/TestUtilities/AsyncTestDelegates.cs | 2 +- 40 files changed, 79 insertions(+), 79 deletions(-) diff --git a/BUILDING.md b/BUILDING.md index 1dabf601bf..3e0ac05e2e 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -72,7 +72,7 @@ This brings clarity to the code and makes it easy to change the mapping between Feature constants are defined in [Directory.Build.props](src/NUnitFramework/Directory.Build.props): - - `ASYNC` enables asynchrony + - `TASK_PARALLEL_LIBRARY_API` exposes NUnit APIs which depend on the TPL framework types - `PARALLEL` enables running tests in parallel - `PLATFORM_DETECTION` enables platform detection - `THREAD_ABORT` enables timeouts and forcible cancellation diff --git a/src/NUnitFramework/Directory.Build.props b/src/NUnitFramework/Directory.Build.props index e5137b5516..b7420cd325 100644 --- a/src/NUnitFramework/Directory.Build.props +++ b/src/NUnitFramework/Directory.Build.props @@ -22,7 +22,7 @@ $(DefineConstants);PARALLEL;SERIALIZATION - $(DefineConstants);ASYNC + $(DefineConstants);TASK_PARALLEL_LIBRARY_API (ReturnsFour), Is.Not.EqualTo(4), getExceptionMessage); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void WarnUnless_Passes_Async() { @@ -571,7 +571,7 @@ public void WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc() Warn.If(new ActualValueDelegate(ReturnsFive), Is.Not.EqualTo(4), getExceptionMessage); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void WarnUnless_Fails_Async() { @@ -627,7 +627,7 @@ private int ReturnsFive() return 5; } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API private static Task One() { return Task.Run(() => 1); @@ -709,7 +709,7 @@ public static void WarningInThreadPoolQueueUserWorkItem() } } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public static void WarningInTaskRun() { diff --git a/src/NUnitFramework/tests/Assertions/AssertMultipleTests.cs b/src/NUnitFramework/tests/Assertions/AssertMultipleTests.cs index 1ea47c1a3d..71b8998714 100644 --- a/src/NUnitFramework/tests/Assertions/AssertMultipleTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertMultipleTests.cs @@ -42,7 +42,7 @@ public class AssertMultipleTests [TestCase(nameof(AM.NestedBlocksInMethodCalls), 3)] [TestCase(nameof(AM.ThreeWarnIf_AllPass), 3)] [TestCase(nameof(AM.ThreeWarnUnless_AllPass), 3)] -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(nameof(AM.ThreeAssertsSucceed_Async), 3)] [TestCase(nameof(AM.NestedBlock_ThreeAssertsSucceed_Async), 3)] [TestCase(nameof(AM.TwoNestedBlocks_ThreeAssertsSucceed_Async), 3)] @@ -63,7 +63,7 @@ public void AssertMultipleSucceeds(string methodName, int asserts) [TestCase(nameof(AM.MethodCallsFailAfterTwoAssertsFail), 2, "Expected: 5", "ImaginaryPart", "Message from Assert.Fail")] [TestCase(nameof(AM.TwoAssertsFailAfterWarning), 2, "WARNING", "Expected: 5", "ImaginaryPart")] [TestCase(nameof(AM.WarningAfterTwoAssertsFail), 2, "Expected: 5", "ImaginaryPart", "WARNING")] -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(nameof(AM.TwoAsserts_BothAssertsFail_Async), 2, "RealPart", "ImaginaryPart")] [TestCase(nameof(AM.TwoNestedBlocks_TwoAssertsFail_Async), 3, "Expected: 5", "ImaginaryPart")] #endif diff --git a/src/NUnitFramework/tests/Assertions/AssertThatTests.cs b/src/NUnitFramework/tests/Assertions/AssertThatTests.cs index 0d7d0a8025..8550c64aeb 100644 --- a/src/NUnitFramework/tests/Assertions/AssertThatTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertThatTests.cs @@ -27,7 +27,7 @@ using NUnit.TestData; using NUnit.TestUtilities; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading.Tasks; #endif @@ -318,7 +318,7 @@ private int ReturnsFive() return 5; } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void AssertThatSuccess() { diff --git a/src/NUnitFramework/tests/Assertions/AssertThrowsAsyncTests.cs b/src/NUnitFramework/tests/Assertions/AssertThrowsAsyncTests.cs index fa3ef62c26..da48f58eb5 100644 --- a/src/NUnitFramework/tests/Assertions/AssertThrowsAsyncTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssertThrowsAsyncTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading.Tasks; using NUnit.Framework.Internal; diff --git a/src/NUnitFramework/tests/Assertions/AssumeThatTests.cs b/src/NUnitFramework/tests/Assertions/AssumeThatTests.cs index 96266ac395..138898f7ef 100644 --- a/src/NUnitFramework/tests/Assertions/AssumeThatTests.cs +++ b/src/NUnitFramework/tests/Assertions/AssumeThatTests.cs @@ -24,7 +24,7 @@ using System; using NUnit.Framework.Constraints; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; #endif @@ -351,7 +351,7 @@ private int ReturnsFive() return 5; } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void AssumeThatSuccess() { diff --git a/src/NUnitFramework/tests/Assertions/AsyncThrowsTests.cs b/src/NUnitFramework/tests/Assertions/AsyncThrowsTests.cs index 7d620fa007..e16992c456 100644 --- a/src/NUnitFramework/tests/Assertions/AsyncThrowsTests.cs +++ b/src/NUnitFramework/tests/Assertions/AsyncThrowsTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading.Tasks; using NUnit.Framework.Constraints; diff --git a/src/NUnitFramework/tests/Assertions/WarningTests.cs b/src/NUnitFramework/tests/Assertions/WarningTests.cs index d390ffface..f085798b52 100644 --- a/src/NUnitFramework/tests/Assertions/WarningTests.cs +++ b/src/NUnitFramework/tests/Assertions/WarningTests.cs @@ -29,7 +29,7 @@ using NUnit.TestData; using NUnit.TestUtilities; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; #endif @@ -82,7 +82,7 @@ public class WarningTests [TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs))] [TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc))] [TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc))] -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(nameof(WarningFixture.WarnUnless_Passes_Async))] [TestCase(nameof(WarningFixture.WarnIf_Passes_Async))] #endif @@ -135,7 +135,7 @@ public void WarningPasses(string methodName) [TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs), "Should be 4")] [TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")] [TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")] -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(nameof(WarningFixture.WarnUnless_Fails_Async), null)] [TestCase(nameof(WarningFixture.WarnIf_Fails_Async), null)] #endif @@ -219,7 +219,7 @@ public void FailingWarning_CallsExceptionStringFunc() Assert.That(funcWasCalled, "The getExceptionMessage function was not called when it should have been."); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void WarnUnless_Async_Error() { @@ -271,7 +271,7 @@ private static async Task ThrowExceptionGenericTask() [TestCase(nameof(WarningFixture.WarningInBeginInvoke), 5, ExcludePlatform = "mono", Reason = "Warning has no effect inside BeginInvoke on Mono")] #endif [TestCase(nameof(WarningFixture.WarningInThreadPoolQueueUserWorkItem), 2)] -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(nameof(WarningFixture.WarningInTaskRun), 4)] [TestCase(nameof(WarningFixture.WarningAfterAwaitTaskDelay), 5)] #endif diff --git a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Assert-based.cs b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Assert-based.cs index b7ca4f9088..6eed2d67ec 100644 --- a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Assert-based.cs +++ b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Assert-based.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using NUnit.Framework.Internal; diff --git a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Constraint-based.cs b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Constraint-based.cs index 47bbba7da6..7b0e2a41fc 100644 --- a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Constraint-based.cs +++ b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Constraint-based.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using NUnit.Framework.Constraints; using NUnit.TestUtilities; diff --git a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Fixture-based.cs b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Fixture-based.cs index 072469338f..2fe0abcb24 100644 --- a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Fixture-based.cs +++ b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.Fixture-based.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; diff --git a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.cs b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.cs index f4f2d55f94..5d0a32f712 100644 --- a/src/NUnitFramework/tests/AsyncExecutionApiAdapter.cs +++ b/src/NUnitFramework/tests/AsyncExecutionApiAdapter.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Collections.Generic; namespace NUnit.Framework diff --git a/src/NUnitFramework/tests/AsyncExecutionApiAdapterTests.cs b/src/NUnitFramework/tests/AsyncExecutionApiAdapterTests.cs index f1440faa53..9b77bfbc76 100644 --- a/src/NUnitFramework/tests/AsyncExecutionApiAdapterTests.cs +++ b/src/NUnitFramework/tests/AsyncExecutionApiAdapterTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; namespace NUnit.Framework diff --git a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs index 6aac40cb95..740c4dd3eb 100644 --- a/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs +++ b/src/NUnitFramework/tests/Attributes/TestCaseAttributeTests.cs @@ -29,7 +29,7 @@ using NUnit.TestData.TestCaseAttributeFixture; using NUnit.TestUtilities; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; #endif @@ -670,7 +670,7 @@ public T TestWithGenericReturnType(T arg1) return arg1; } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestCase(1, ExpectedResult = 1)] public async Task TestWithAsyncGenericReturnType(T arg1) { diff --git a/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs index 4a2874d53c..e3a3e05891 100644 --- a/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs +++ b/src/NUnitFramework/tests/AwaitableReturnTypeTests.cs @@ -7,7 +7,7 @@ namespace NUnit.Framework { -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestFixture(nameof(F.ReturnsTask))] [TestFixture(nameof(F.ReturnsCustomTask))] #endif @@ -205,7 +205,7 @@ public void OperationCanceledExceptionThrownInGetResultShouldBeReportedAsSuch() Assert.That(result.Message, Contains.Substring("OperationCanceledException")); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void TaskCanceledExceptionThrownInGetResultShouldBeReportedAsSuch() { diff --git a/src/NUnitFramework/tests/Constraints/AsyncDelayedConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AsyncDelayedConstraintTests.cs index 799b8e62d1..a0398cc87a 100644 --- a/src/NUnitFramework/tests/Constraints/AsyncDelayedConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AsyncDelayedConstraintTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading.Tasks; diff --git a/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs b/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs index f5e16a0b5f..5dbcbdf996 100644 --- a/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/ThrowsExceptionConstraintTests.cs @@ -24,7 +24,7 @@ using NUnit.Framework.Internal; using NUnit.TestUtilities; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading; using System.Threading.Tasks; @@ -65,7 +65,7 @@ public void SucceedsWithNonVoidReturningFunction() new TestCaseData( new TestDelegate( TestDelegates.ThrowsNothing ), "no exception thrown" ), }; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public static void CatchesAsyncException() { diff --git a/src/NUnitFramework/tests/Internal/AsyncSetupTeardownTests.cs b/src/NUnitFramework/tests/Internal/AsyncSetupTeardownTests.cs index 7846c0d46a..d1f04a65c0 100644 --- a/src/NUnitFramework/tests/Internal/AsyncSetupTeardownTests.cs +++ b/src/NUnitFramework/tests/Internal/AsyncSetupTeardownTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Collections.Generic; using System.Linq; diff --git a/src/NUnitFramework/tests/Internal/AsyncTestMethodTests.cs b/src/NUnitFramework/tests/Internal/AsyncTestMethodTests.cs index cc0d957091..4578ff8ed9 100644 --- a/src/NUnitFramework/tests/Internal/AsyncTestMethodTests.cs +++ b/src/NUnitFramework/tests/Internal/AsyncTestMethodTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Collections; using System.Reflection; using NUnit.Framework.Interfaces; diff --git a/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs b/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs index d8c971a46a..438e802ecb 100644 --- a/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs +++ b/src/NUnitFramework/tests/Internal/NUnitTestCaseBuilderTests.cs @@ -31,7 +31,7 @@ namespace NUnit.Framework.Internal [TestFixture] public class NUnitTestCaseBuilderTests { -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API #pragma warning disable IDE1006 // Naming Styles private readonly Type fixtureType = typeof(AsyncDummyFixture); #pragma warning restore IDE1006 // Naming Styles diff --git a/src/NUnitFramework/tests/Internal/RealAsyncSetupTeardownTests.cs b/src/NUnitFramework/tests/Internal/RealAsyncSetupTeardownTests.cs index b46554f26a..78279bc19f 100644 --- a/src/NUnitFramework/tests/Internal/RealAsyncSetupTeardownTests.cs +++ b/src/NUnitFramework/tests/Internal/RealAsyncSetupTeardownTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; namespace NUnit.Framework.Internal diff --git a/src/NUnitFramework/tests/Internal/Results/TestResultApiTests.cs b/src/NUnitFramework/tests/Internal/Results/TestResultApiTests.cs index 001a610d0f..6674b55588 100644 --- a/src/NUnitFramework/tests/Internal/Results/TestResultApiTests.cs +++ b/src/NUnitFramework/tests/Internal/Results/TestResultApiTests.cs @@ -63,7 +63,7 @@ public void DoesNotThrowForMissingInnerException() { new NUnitException(), new TargetInvocationException(null), -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API new AggregateException() #endif }; diff --git a/src/NUnitFramework/tests/Internal/TestExecutionContextTests.cs b/src/NUnitFramework/tests/Internal/TestExecutionContextTests.cs index 28482a1662..99cea46d17 100644 --- a/src/NUnitFramework/tests/Internal/TestExecutionContextTests.cs +++ b/src/NUnitFramework/tests/Internal/TestExecutionContextTests.cs @@ -32,7 +32,7 @@ using NUnit.Framework.Interfaces; using System.Security.Principal; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; #endif @@ -118,7 +118,7 @@ public void Cleanup() #region CurrentContext -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CurrentContextFlowsWithAsyncExecution() { @@ -262,7 +262,7 @@ public void TestCanAccessItsOwnArguments(int i, string s) Assert.That(TestExecutionContext.CurrentContext.CurrentTest.Arguments, Is.EqualTo(new object[] {123, "abc"})); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task AsyncTestCanAccessItsOwnName() { @@ -366,7 +366,7 @@ public void CanAccessResultState() Assert.That(TestExecutionContext.CurrentContext.CurrentResult.ResultState, Is.EqualTo(ResultState.Inconclusive)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessResultName_Async() { @@ -416,7 +416,7 @@ public void CanAccessStartTime() Assert.That(TestExecutionContext.CurrentContext.StartTime, Is.GreaterThanOrEqualTo(_setupContext.StartTime)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessStartTime_Async() { @@ -439,7 +439,7 @@ public void CanAccessStartTicks() Assert.That(TestExecutionContext.CurrentContext.StartTicks, Is.GreaterThanOrEqualTo(_setupContext.StartTicks)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task AsyncTestCanAccessStartTicks() { @@ -462,7 +462,7 @@ public void CanAccessOutWriter() Assert.That(TestExecutionContext.CurrentContext.OutWriter, Is.SameAs(_setupContext.OutWriter)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task AsyncTestCanAccessOutWriter() { @@ -485,7 +485,7 @@ public void CanAccessTestObject() Assert.That(TestExecutionContext.CurrentContext.TestObject, Is.SameAs(_setupContext.TestObject)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessTestObject_Async() { @@ -507,7 +507,7 @@ public void CanAccessStopOnError() Assert.That(TestExecutionContext.CurrentContext.StopOnError, Is.EqualTo(_setupContext.StopOnError)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessStopOnError_Async() { @@ -530,7 +530,7 @@ public void CanAccessListener() Assert.That(TestExecutionContext.CurrentContext.Listener, Is.SameAs(_setupContext.Listener)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessListener_Async() { @@ -553,7 +553,7 @@ public void CanAccessDispatcher() Assert.That(TestExecutionContext.CurrentContext.Dispatcher, Is.SameAs(_setupContext.Dispatcher)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessDispatcher_Async() { @@ -576,7 +576,7 @@ public void CanAccessParallelScope() Assert.That(TestExecutionContext.CurrentContext.ParallelScope, Is.EqualTo(scope)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessParallelScope_Async() { @@ -603,7 +603,7 @@ public void CanAccessTestWorker() } } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessTestWorker_Async() { @@ -627,7 +627,7 @@ public void CanAccessRandomGenerator() Assert.That(TestExecutionContext.CurrentContext.RandomGenerator, Is.SameAs(_setupContext.RandomGenerator)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessRandomGenerator_Async() { @@ -652,7 +652,7 @@ public void CanAccessAssertCount() Assert.That(TestExecutionContext.CurrentContext.AssertCount, Is.EqualTo(4)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessAssertCount_Async() { @@ -680,7 +680,7 @@ public void CanAccessMultipleAssertLevel() }); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessMultipleAssertLevel_Async() { @@ -706,7 +706,7 @@ public void CanAccessTestCaseTimeout() Assert.That(TestExecutionContext.CurrentContext.TestCaseTimeout, Is.EqualTo(timeout)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessTestCaseTimeout_Async() { @@ -729,7 +729,7 @@ public void CanAccessUpstreamActions() Assert.That(TestExecutionContext.CurrentContext.UpstreamActions, Is.EqualTo(actions)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessUpstreamAcxtions_Async() { @@ -761,7 +761,7 @@ public void CanAccessCurrentUICulture() Assert.That(TestExecutionContext.CurrentContext.CurrentUICulture, Is.EqualTo(CultureInfo.CurrentUICulture)); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessCurrentCulture_Async() { @@ -840,7 +840,7 @@ public void CanAccessCurrentPrincipal() Assert.That(TestExecutionContext.CurrentContext.CurrentPrincipal, Is.SameAs(expectedInstance), "Test"); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task CanAccessCurrentPrincipal_Async() { @@ -998,7 +998,7 @@ public void CanAccessCurrentRepeatCount() #region Helper Methods -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API private async Task YieldAsync() { #if NET40 diff --git a/src/NUnitFramework/tests/Internal/UnexpectedExceptionTests.cs b/src/NUnitFramework/tests/Internal/UnexpectedExceptionTests.cs index b085cc847d..6d4d323e42 100644 --- a/src/NUnitFramework/tests/Internal/UnexpectedExceptionTests.cs +++ b/src/NUnitFramework/tests/Internal/UnexpectedExceptionTests.cs @@ -61,7 +61,7 @@ public void FailRecordsNestedInnerException() Assert.AreEqual(expectedMessage, result.Message); } -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public void FailRecordsInnerExceptionsAsPartOfAggregateException() { diff --git a/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs b/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs index 54c89c4a7f..397b5f1d61 100644 --- a/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs +++ b/src/NUnitFramework/tests/NonVoidResultAwaitableReturnTypeTests.cs @@ -4,7 +4,7 @@ namespace NUnit.Framework { -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [TestFixture(nameof(F.ReturnsNonVoidResultTask))] [TestFixture(nameof(F.ReturnsNonVoidResultCustomTask))] #endif diff --git a/src/NUnitFramework/tests/SynchronizationContextTests.cs b/src/NUnitFramework/tests/SynchronizationContextTests.cs index 62809e5b47..1abcc7d1dc 100644 --- a/src/NUnitFramework/tests/SynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/SynchronizationContextTests.cs @@ -21,7 +21,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Collections.Generic; using System.Linq; diff --git a/src/NUnitFramework/tests/TestContextTests.cs b/src/NUnitFramework/tests/TestContextTests.cs index b4ce6d2386..3fef617479 100644 --- a/src/NUnitFramework/tests/TestContextTests.cs +++ b/src/NUnitFramework/tests/TestContextTests.cs @@ -25,7 +25,7 @@ using System.IO; using System.Collections.Generic; using System.Linq; -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System.Threading.Tasks; #endif using NUnit.Framework.Interfaces; @@ -340,7 +340,7 @@ public void TestContextStoresFailureInfoForOneTimeTearDown() #region Out -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API [Test] public async Task TestContextOut_ShouldFlowWithAsyncExecution() { diff --git a/src/NUnitFramework/tests/TestUtilities/AsyncTestDelegates.cs b/src/NUnitFramework/tests/TestUtilities/AsyncTestDelegates.cs index b75cbd409e..1af5155f72 100644 --- a/src/NUnitFramework/tests/TestUtilities/AsyncTestDelegates.cs +++ b/src/NUnitFramework/tests/TestUtilities/AsyncTestDelegates.cs @@ -1,4 +1,4 @@ -#if ASYNC +#if TASK_PARALLEL_LIBRARY_API using System; using System.Threading.Tasks; From 7ce7f2a2f9bdc1c4fa435d1f36a0ab161a888d10 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 23 Apr 2019 21:36:05 -0400 Subject: [PATCH 158/174] ReSharper upgrade --- NUnit.sln.DotSettings | 1 + 1 file changed, 1 insertion(+) diff --git a/NUnit.sln.DotSettings b/NUnit.sln.DotSettings index d8f7a5b5cf..d7fe019de8 100644 --- a/NUnit.sln.DotSettings +++ b/NUnit.sln.DotSettings @@ -70,6 +70,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. True True True + True True True True From 1916cdfd9d912283a076ed33a240c6531a5dd8d5 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 23 Apr 2019 21:36:41 -0400 Subject: [PATCH 159/174] Address review feedback --- .../framework/Internal/Net40BclTaskAwaitAdapter.cs | 4 +++- src/NUnitFramework/framework/Internal/Reflect.cs | 10 +++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs b/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs index cd7cf8fedd..1134f55f80 100644 --- a/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs +++ b/src/NUnitFramework/framework/Internal/Net40BclTaskAwaitAdapter.cs @@ -145,7 +145,9 @@ public override object GetResult() catch (AggregateException ex) when (ex.InnerExceptions.Count == 1) // Task.Wait wraps every exception { ExceptionHelper.Rethrow(ex.InnerException); - throw null; // Rethrow’s return type would be `never` if C# could express that. + + // If this line is reached, ExceptionHelper.Rethrow is very broken. + throw new InvalidOperationException("ExceptionHelper.Rethrow failed to throw an exception."); } } } diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index 811664a6f5..6752f10225 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -400,7 +400,7 @@ internal static Type GetInterface(this Type type, string name) /// internal static MethodInfo GetNonGenericPublicInstanceMethod(this Type type, string name, Type[] parameterTypes) { - for (var currentType = type; currentType != null; currentType = currentType.GetTypeInfo().BaseType) + foreach (var currentType in type.TypeAndBaseTypes()) { var method = currentType .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) @@ -461,7 +461,9 @@ internal static object InvokeWithTransparentExceptions(this MethodBase methodBas catch (TargetInvocationException ex) { ExceptionHelper.Rethrow(ex.InnerException); - throw null; // Rethrow’s return type would be `never` if C# could express that. + + // If this line is reached, ExceptionHelper.Rethrow is very broken. + throw new InvalidOperationException("ExceptionHelper.Rethrow failed to throw an exception."); } } @@ -474,7 +476,9 @@ internal static object DynamicInvokeWithTransparentExceptions(this Delegate @del catch (TargetInvocationException ex) { ExceptionHelper.Rethrow(ex.InnerException); - throw null; // Rethrow’s return type would be `never` if C# could express that. + + // If this line is reached, ExceptionHelper.Rethrow is very broken. + throw new InvalidOperationException("ExceptionHelper.Rethrow failed to throw an exception."); } } } From 9c2a4b5c3204d799e0f780ee65feea91bed35332 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 23 Apr 2019 22:40:49 -0400 Subject: [PATCH 160/174] Add tests on helper methods --- .../tests/Internal/ReflectTests.cs | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 src/NUnitFramework/tests/Internal/ReflectTests.cs diff --git a/src/NUnitFramework/tests/Internal/ReflectTests.cs b/src/NUnitFramework/tests/Internal/ReflectTests.cs new file mode 100644 index 0000000000..6b729d1b83 --- /dev/null +++ b/src/NUnitFramework/tests/Internal/ReflectTests.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NUnit.Framework.Internal +{ + public static class ReflectTests + { + [Test] + public static void TypeAndBaseTypesReturnsEmptyForNull() + { + Assert.That(((Type)null).TypeAndBaseTypes(), Is.Empty); + } + + [Test] + public static void TypeAndBaseTypesReturnsSingleTypeForSystemObject() + { + Assert.That(typeof(object).TypeAndBaseTypes(), Is.EqualTo(new[] { typeof(object) })); + } + + [Test] + public static void TypeAndBaseTypesReturnsSingleTypeForInterface() + { + Assert.That(typeof(IDisposable).TypeAndBaseTypes(), Is.EqualTo(new[] { typeof(IDisposable) })); + } + + [Test] + public static void TypeAndBaseTypesStartsWithSpecifiedClassAndTraversesAllBaseClasses() + { + Assert.That(typeof(InheritsFromExternalClass).TypeAndBaseTypes(), Is.EqualTo(new[] + { + typeof(InheritsFromExternalClass), + typeof(List), + typeof(object) + })); + } + + private class InheritsFromExternalClass : List + { + } + +#if NETCOREAPP1_1 + [Test] + public static void GetInterfaceMatchesByFullName() + { + Assert.That( + Reflect.GetInterface(typeof(List), typeof(IEnumerable).FullName), + Is.EqualTo(typeof(IEnumerable))); + } +#endif + + [Test] + public static void GetNonGenericPublicInstanceMethodSearchesBaseClasses() + { + Assert.That( + typeof(B).GetNonGenericPublicInstanceMethod(nameof(A.InstanceMethod), Type.EmptyTypes), + Is.EqualTo(typeof(A).GetMethod(nameof(A.InstanceMethod)))); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodIgnoresGenericOverloads() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.HasGenericOverloads), Type.EmptyTypes), + Is.EqualTo(typeof(A).GetMethods().Single(m => + m.Name == nameof(A.HasGenericOverloads) + && !m.IsGenericMethod))); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodIgnoresGenericMethods() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.GenericMethod), Type.EmptyTypes), + Is.Null); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodIgnoresStaticMethod() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.StaticMethod), Type.EmptyTypes), + Is.Null); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodIgnoresInternalMethod() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.InternalMethod), Type.EmptyTypes), + Is.Null); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodChoosesCorrectOverload() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.OverloadedMethod), new[] { typeof(object) }), + Is.EqualTo(typeof(A).GetMethod(nameof(A.OverloadedMethod), new[] { typeof(object) }))); + } + + [Test] + public static void GetNonGenericPublicInstanceMethodRequiresExactParameterTypes() + { + Assert.That( + typeof(A).GetNonGenericPublicInstanceMethod(nameof(A.HasOptionalParameter), new[] { typeof(int) }), + Is.Null); + } + + [Test] + public static void GetPublicInstancePropertySearchesBaseClasses() + { + Assert.That( + typeof(B).GetPublicInstanceProperty(nameof(A.InstanceProperty), Type.EmptyTypes), + Is.EqualTo(typeof(A).GetProperty(nameof(A.InstanceProperty)))); + } + + [Test] + public static void GetPublicInstancePropertyIgnoresStaticProperty() + { + Assert.That( + typeof(A).GetPublicInstanceProperty(nameof(A.StaticProperty), Type.EmptyTypes), + Is.Null); + } + + [Test] + public static void GetPublicInstancePropertyIgnoresInternalProperty() + { + Assert.That( + typeof(A).GetPublicInstanceProperty(nameof(A.InternalProperty), Type.EmptyTypes), + Is.Null); + } + + [Test] + public static void GetPublicInstancePropertyChoosesCorrectOverload() + { + Assert.That( + typeof(A).GetPublicInstanceProperty("Item", new[] { typeof(object) }), + Is.EqualTo(typeof(A).GetProperty("Item", typeof(int), new[] { typeof(object) }))); + } + + [Test] + public static void GetPublicInstancePropertyRequiresExactParameterTypes() + { + Assert.That( + typeof(A).GetPublicInstanceProperty("Item", new[] { typeof(byte) }), + Is.Null); + } + + private class A + { + public void InstanceMethod() { } + + public void HasGenericOverloads() { } + public void HasGenericOverloads() { } + public void HasGenericOverloads() { } + + public void GenericMethod() { } + + public static void StaticMethod() { } + + internal void InternalMethod() { } + + public void OverloadedMethod(object arg) { } + + public void OverloadedMethod(int arg) { } + + public void HasOptionalParameter(int a, int b = 42) { } + + public int InstanceProperty { get; set; } + + public static int StaticProperty { get; set; } + + internal int InternalProperty { get; set; } + + public int this[object arg] { get { return 0; } set { } } + public int this[int arg] { get { return 0; } set { } } + public int this[byte a, byte b = 42] { get { return 0; } set { } } + } + + private class B : A + { + } + + [Test] + public static void InvokeWithTransparentExceptionsReturnsCorrectValue() + { + Assert.That( + typeof(ReflectTests) + .GetMethod(nameof(MethodReturning42), BindingFlags.Static | BindingFlags.NonPublic) + .InvokeWithTransparentExceptions(instance: null), + Is.EqualTo(42)); + } + + [Test] + public static void DynamicInvokeWithTransparentExceptionsReturnsCorrectValue() + { + Assert.That( + new Func(MethodReturning42).DynamicInvokeWithTransparentExceptions(), + Is.EqualTo(42)); + } + + [Test] + public static void InvokeWithTransparentExceptionsDoesNotWrap() + { + Assert.That( + () => typeof(ReflectTests) + .GetMethod(nameof(MethodThrowingException), BindingFlags.Static | BindingFlags.NonPublic) + .InvokeWithTransparentExceptions(instance: null), + Throws.TypeOf()); + } + + [Test] + public static void DynamicInvokeWithTransparentExceptionsDoesNotWrap() + { + Assert.That( + () => new Func(MethodThrowingException).DynamicInvokeWithTransparentExceptions(), + Throws.TypeOf()); + } + + [Test] + public static void InvokeWithTransparentExceptionsDoesNotUnwrap() + { + Assert.That( + () => typeof(ReflectTests) + .GetMethod(nameof(MethodThrowingTargetInvocationException), BindingFlags.Static | BindingFlags.NonPublic) + .InvokeWithTransparentExceptions(instance: null), + Throws.TypeOf()); + } + + [Test] + public static void DynamicInvokeWithTransparentExceptionsDoesNotUnwrap() + { + Assert.That( + () => new Func(MethodThrowingTargetInvocationException).DynamicInvokeWithTransparentExceptions(), + Throws.TypeOf()); + } + + [Test] + public static void InvokeWithTransparentExceptionsPreservesStackTrace() + { + Assert.That( + () => typeof(ReflectTests) + .GetMethod(nameof(MethodThrowingTargetInvocationException), BindingFlags.Static | BindingFlags.NonPublic) + .InvokeWithTransparentExceptions(instance: null), + Throws.Exception + .With.Property(nameof(Exception.StackTrace)) + .Contains(nameof(MethodThrowingTargetInvocationException))); + } + + [Test] + public static void DynamicInvokeWithTransparentExceptionsPreservesStackTrace() + { + Assert.That( + () => new Func(MethodThrowingTargetInvocationException).DynamicInvokeWithTransparentExceptions(), + Throws.Exception + .With.Property(nameof(Exception.StackTrace)) + .Contains(nameof(MethodThrowingTargetInvocationException))); + } + + private static int MethodReturning42() => 42; + + private static int MethodThrowingException() + { + throw new Exception(); + } + + private static int MethodThrowingTargetInvocationException() + { + throw new TargetInvocationException(new Exception()); + } + } +} From d45f9397091d9c67463a485c00dc555d2123c41a Mon Sep 17 00:00:00 2001 From: Charlie Poole Date: Sun, 5 May 2019 22:33:06 +0100 Subject: [PATCH 161/174] Handle nested not filters correctly --- .../framework/Internal/Filters/NotFilter.cs | 14 ++-- .../Filters/DoubleNegativeFilterTests.cs | 73 +++++++++++++++++++ 2 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 src/NUnitFramework/tests/Internal/Filters/DoubleNegativeFilterTests.cs diff --git a/src/NUnitFramework/framework/Internal/Filters/NotFilter.cs b/src/NUnitFramework/framework/Internal/Filters/NotFilter.cs index e31a543dbd..1e51cdaef6 100644 --- a/src/NUnitFramework/framework/Internal/Filters/NotFilter.cs +++ b/src/NUnitFramework/framework/Internal/Filters/NotFilter.cs @@ -46,17 +46,21 @@ public NotFilter( TestFilter baseFilter) public TestFilter BaseFilter { get; } /// - /// Determine if a particular test passes the filter criteria. The default - /// implementation checks the test itself, its parents and any descendants. + /// Determine if a particular test passes the filter criteria. /// - /// Derived classes may override this method or any of the Match methods - /// to change the behavior of the filter. + /// Overriden in NotFilter so that + /// 1. Two nested NotFilters are simply ignored + /// 2. Otherwise, we only look at the test itself and parents, ignoring + /// any child test matches. /// /// The test to which the filter is applied /// True if the test passes the filter, otherwise false public override bool Pass(ITest test) { - return !BaseFilter.Match (test) && !BaseFilter.MatchParent (test); + var secondNotFilter = BaseFilter as NotFilter; + return secondNotFilter != null + ? secondNotFilter.BaseFilter.Pass(test) + : !BaseFilter.Match (test) && !BaseFilter.MatchParent (test); } /// diff --git a/src/NUnitFramework/tests/Internal/Filters/DoubleNegativeFilterTests.cs b/src/NUnitFramework/tests/Internal/Filters/DoubleNegativeFilterTests.cs new file mode 100644 index 0000000000..bf17633b23 --- /dev/null +++ b/src/NUnitFramework/tests/Internal/Filters/DoubleNegativeFilterTests.cs @@ -0,0 +1,73 @@ +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Collections.Generic; +using System.Text; + +namespace NUnit.Framework.Internal.Filters +{ + [TestFixture("TestFilterTests+DummyFixture", false)] + [TestFixture("Dummy", true)] + public class DoubleNegativeFilterTests : TestFilterTests + { + private readonly TestFilter _filter; + + public DoubleNegativeFilterTests(string value, bool isRegex) + { + _filter = new NotFilter(new NotFilter(new TestNameFilter(value) { IsRegex = isRegex })); + } + + [Test] + public void IsNotEmpty() + { + Assert.False(_filter.IsEmpty); + } + + [Test] + public void MatchTest() + { + Assert.That(_filter.Match(_dummyFixture)); + Assert.False(_filter.Match(_anotherFixture)); + } + + [Test] + public void PassTest() + { + Assert.That(_filter.Pass(_topLevelSuite)); + Assert.That(_filter.Pass(_dummyFixture)); + Assert.That(_filter.Pass(_dummyFixture.Tests[0])); + + Assert.False(_filter.Pass(_anotherFixture)); + } + + public void ExplicitMatchTest() + { + Assert.That(_filter.IsExplicitMatch(_topLevelSuite)); + Assert.That(_filter.IsExplicitMatch(_dummyFixture)); + Assert.False(_filter.IsExplicitMatch(_dummyFixture.Tests[0])); + + Assert.False(_filter.IsExplicitMatch(_anotherFixture)); + } + } +} From dc9e3cf8e152687c8f88d3dccbe805594b2fa857 Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Mon, 6 May 2019 14:47:18 +0300 Subject: [PATCH 162/174] AndContstraint should log additional information from failed constraint --- .../framework/Constraints/AndConstraint.cs | 14 ++++++++-- .../tests/Constraints/AndConstraintTests.cs | 26 ++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Constraints/AndConstraint.cs b/src/NUnitFramework/framework/Constraints/AndConstraint.cs index b401ea10cd..7eed268146 100644 --- a/src/NUnitFramework/framework/Constraints/AndConstraint.cs +++ b/src/NUnitFramework/framework/Constraints/AndConstraint.cs @@ -76,7 +76,7 @@ class AndConstraintResult : ConstraintResult private readonly ConstraintResult rightResult; public AndConstraintResult(AndConstraint constraint, object actual, ConstraintResult leftResult, ConstraintResult rightResult) - : base(constraint, actual, leftResult.IsSuccess && rightResult.IsSuccess) + : base(constraint, actual, leftResult.IsSuccess && rightResult.IsSuccess) { this.leftResult = leftResult; this.rightResult = rightResult; @@ -98,8 +98,18 @@ public override void WriteActualValueTo(MessageWriter writer) else rightResult.WriteActualValueTo(writer); } + + public override void WriteAdditionalLinesTo(MessageWriter writer) + { + if (this.IsSuccess) + base.WriteAdditionalLinesTo(writer); + else if (!leftResult.IsSuccess) + leftResult.WriteAdditionalLinesTo(writer); + else + rightResult.WriteAdditionalLinesTo(writer); + } } #endregion } -} \ No newline at end of file +} diff --git a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs index 335841e953..78365ba769 100644 --- a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs @@ -21,6 +21,9 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** +using System; +using NUnit.Framework.Internal; + namespace NUnit.Framework.Constraints { [TestFixture] @@ -53,8 +56,25 @@ public void HandlesFirstPartFailing() var constraint = expression.Resolve(); var constraintResult = constraint.ApplyTo(test); - Assert.That( constraintResult.IsSuccess, Is.False ); - Assert.That( constraintResult.Description, Is.EqualTo( "String starting with \"Could not load\" and containing \"c:\\myfile.txt\"" ) ); + Assert.That(constraintResult.IsSuccess, Is.False); + Assert.That(constraintResult.Description, Is.EqualTo("String starting with \"Could not load\" and containing \"c:\\myfile.txt\"")); + } + + [Test] + public void ShouldIncludeAdditionalInformationFromFailedConstraint() + { + var constraint = new AndConstraint(Is.Ordered, Is.EquivalentTo(new[] { 1, 2, 3 })); + + string expectedMsg = + " Expected: collection ordered and equivalent to < 1, 2, 3 >" + Environment.NewLine + + " But was: < 1, 2 >" + Environment.NewLine + + " Missing (1): < 3 >" + Environment.NewLine; + + var constraintResult = constraint.ApplyTo(new[] { 1, 2 }); + var messageWriter = new TextMessageWriter(); + constraintResult.WriteMessageTo(messageWriter); + + Assert.That(messageWriter.ToString(), Is.EqualTo(expectedMsg)); } } -} \ No newline at end of file +} From 3b6e51905ee709f82f178f7cdd03fc2b2227d061 Mon Sep 17 00:00:00 2001 From: Oleksandr Liakhevych Date: Wed, 8 May 2019 12:44:56 +0300 Subject: [PATCH 163/174] Add tests --- .../tests/Constraints/AndConstraintTests.cs | 44 ++++++++++++++++++- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs index 78365ba769..2f652c881a 100644 --- a/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs +++ b/src/NUnitFramework/tests/Constraints/AndConstraintTests.cs @@ -29,12 +29,15 @@ namespace NUnit.Framework.Constraints [TestFixture] public class AndConstraintTests : ConstraintTestBase { + private TextMessageWriter messageWriter; + [SetUp] public void SetUp() { TheConstraint = new AndConstraint(new GreaterThanConstraint(40), new LessThanConstraint(50)); ExpectedDescription = "greater than 40 and less than 50"; StringRepresentation = " >"; + messageWriter = new TextMessageWriter(); } static object[] SuccessData = new object[] { 42 }; @@ -61,7 +64,7 @@ public void HandlesFirstPartFailing() } [Test] - public void ShouldIncludeAdditionalInformationFromFailedConstraint() + public void ShouldIncludeAdditionalInformationFromFailedConstraint_Right() { var constraint = new AndConstraint(Is.Ordered, Is.EquivalentTo(new[] { 1, 2, 3 })); @@ -71,9 +74,46 @@ public void ShouldIncludeAdditionalInformationFromFailedConstraint() " Missing (1): < 3 >" + Environment.NewLine; var constraintResult = constraint.ApplyTo(new[] { 1, 2 }); - var messageWriter = new TextMessageWriter(); + + Assert.That(constraintResult.IsSuccess, Is.False); + constraintResult.WriteMessageTo(messageWriter); + Assert.That(messageWriter.ToString(), Is.EqualTo(expectedMsg)); + } + + [Test] + public void ShouldIncludeAdditionalInformationFromFailedConstraint_Left() + { + var constraint = new AndConstraint(Is.EquivalentTo(new[] { 1, 2, 3 }), Is.Ordered); + + string expectedMsg = + " Expected: equivalent to < 1, 2, 3 > and collection ordered" + Environment.NewLine + + " But was: < 1, 2 >" + Environment.NewLine + + " Missing (1): < 3 >" + Environment.NewLine; + + var constraintResult = constraint.ApplyTo(new[] { 1, 2 }); + Assert.That(constraintResult.IsSuccess, Is.False); + + constraintResult.WriteMessageTo(messageWriter); + Assert.That(messageWriter.ToString(), Is.EqualTo(expectedMsg)); + } + + [Test] + public void ShouldIncludeAdditionalInformationFromFailedConstraint_Both() + { + var constraint = new AndConstraint(Is.EquivalentTo(new[] { 1, 2, 3 }), Is.Ordered); + + string expectedMsg = + " Expected: equivalent to < 1, 2, 3 > and collection ordered" + Environment.NewLine + + " But was: < 2, 1 >" + Environment.NewLine + + " Missing (1): < 3 >" + Environment.NewLine; + + var constraintResult = constraint.ApplyTo(new[] { 2, 1 }); + + Assert.That(constraintResult.IsSuccess, Is.False); + + constraintResult.WriteMessageTo(messageWriter); Assert.That(messageWriter.ToString(), Is.EqualTo(expectedMsg)); } } From e7e80be0232f892aba3cd452af1302f9e198c911 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sat, 11 May 2019 22:34:53 -0400 Subject: [PATCH 164/174] Workaround for Mono 5.18.1's thread abort bug --- .../framework/Internal/Reflect.cs | 18 +++++++++++------- .../tests/Attributes/TimeoutTests.cs | 7 ------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/Reflect.cs b/src/NUnitFramework/framework/Internal/Reflect.cs index 6752f10225..f6a6e4ad1f 100644 --- a/src/NUnitFramework/framework/Internal/Reflect.cs +++ b/src/NUnitFramework/framework/Internal/Reflect.cs @@ -269,18 +269,22 @@ public static object InvokeMethod(MethodInfo method, object fixture, params obje { return method.Invoke(fixture, args); } -#if THREAD_ABORT - catch (System.Threading.ThreadAbortException) - { - // No need to wrap or rethrow ThreadAbortException - return null; - } -#endif catch (TargetInvocationException e) { throw new NUnitException("Rethrown", e.InnerException); } catch (Exception e) +#if THREAD_ABORT + // If ThreadAbortException is caught, it must be rethrown or else Mono 5.18.1 + // will not rethrow at the end of the catch block. Instead, it will resurrect + // the ThreadAbortException at the end of the next unrelated catch block that + // executes on the same thread after handling an unrelated exception. + // The end result is that an unrelated test will error with the message "Test + // cancelled by user." + + // This is just cleaner than catching and rethrowing: + when (!(e is System.Threading.ThreadAbortException)) +#endif { throw new NUnitException("Rethrown", e); } diff --git a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs index 5b2aa7b0ee..3d20b83aef 100644 --- a/src/NUnitFramework/tests/Attributes/TimeoutTests.cs +++ b/src/NUnitFramework/tests/Attributes/TimeoutTests.cs @@ -50,9 +50,6 @@ public void TestWithTimeoutCurrentContextIsNotAnAdhocContext() } #if PLATFORM_DETECTION && THREAD_ABORT - // Most recent version of Mono tested: 5.20.1 - private const string MonoFailsToAbortThreadReason = "ThreadAbortException is never thrown on Mono"; - [Test, Timeout(500)] public void TestWithTimeoutRunsOnSameThread() { @@ -66,7 +63,6 @@ public void TestWithTimeoutRunsSetUpAndTestOnSameThread() } [Test] - [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TestTimesOutAndTearDownIsRun() { TimeoutFixture fixture = new TimeoutFixture(); @@ -91,7 +87,6 @@ public void SetUpTimesOutAndTearDownIsRun() } [Test] - [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TearDownTimesOutAndNoFurtherTearDownIsRun() { TimeoutFixture fixture = new TimeoutFixtureWithTimeoutInTearDown(); @@ -104,7 +99,6 @@ public void TearDownTimesOutAndNoFurtherTearDownIsRun() } [Test] - [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TimeoutCanBeSetOnTestFixture() { ITestResult suiteResult = TestBuilder.RunTestFixture(typeof(TimeoutFixtureWithTimeoutOnFixture)); @@ -175,7 +169,6 @@ public void TestTimeOutTestCaseWithOutElapsed() } [Test, Platform("Win")] - [Platform(Exclude = "Mono", Reason = MonoFailsToAbortThreadReason)] public void TimeoutWithMessagePumpShouldAbort() { ITestResult result = TestBuilder.RunTest( From af920708bafcd8d3f954a5ae67caf98514b08833 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 19:57:39 -0400 Subject: [PATCH 165/174] Move TemporarySynchronizationContext to TestUtils.cs --- .../tests/SynchronizationContextTests.cs | 23 +++------- .../tests/TestUtilities/TestUtils.cs | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+), 18 deletions(-) create mode 100644 src/NUnitFramework/tests/TestUtilities/TestUtils.cs diff --git a/src/NUnitFramework/tests/SynchronizationContextTests.cs b/src/NUnitFramework/tests/SynchronizationContextTests.cs index 62809e5b47..9d40cc74ed 100644 --- a/src/NUnitFramework/tests/SynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/SynchronizationContextTests.cs @@ -41,7 +41,7 @@ public static class SynchronizationContextTests [Test] public static void SynchronizationContextIsRestoredBetweenTestCases() { - using (RestoreSynchronizationContext()) // Restore the synchronization context so as not to affect other tests if this test fails + using (TestUtils.RestoreSynchronizationContext()) // Restore the synchronization context so as not to affect other tests if this test fails { var result = TestBuilder.RunParameterizedMethodSuite( typeof(SynchronizationContextFixture), @@ -54,7 +54,7 @@ public static void SynchronizationContextIsRestoredBetweenTestCases() [Test] public static void SynchronizationContextIsRestoredBetweenTestCaseSources() { - using (RestoreSynchronizationContext()) // Restore the synchronization context so as not to affect other tests if this test fails + using (TestUtils.RestoreSynchronizationContext()) // Restore the synchronization context so as not to affect other tests if this test fails { var fixture = TestBuilder.MakeFixture(typeof(SynchronizationContextFixture)); @@ -143,7 +143,7 @@ private static SynchronizationContext CreateSynchronizationContext(Type knownSyn { var createdOnThisThread = CreateSynchronizationContext(knownSynchronizationContextType); - using (TemporarySynchronizationContext(createdOnThisThread)) + using (TestUtils.TemporarySynchronizationContext(createdOnThisThread)) { apiAdapter.Execute(async () => await TaskEx.Yield()); } @@ -156,7 +156,7 @@ private static SynchronizationContext CreateSynchronizationContext(Type knownSyn { var createdOnThisThread = CreateSynchronizationContext(knownSynchronizationContextType); - using (TemporarySynchronizationContext(createdOnThisThread)) + using (TestUtils.TemporarySynchronizationContext(createdOnThisThread)) { apiAdapter.Execute(() => { @@ -173,7 +173,7 @@ private static SynchronizationContext CreateSynchronizationContext(Type knownSyn { var createdOnThisThread = CreateSynchronizationContext(knownSynchronizationContextType); - using (TemporarySynchronizationContext(createdOnThisThread)) + using (TestUtils.TemporarySynchronizationContext(createdOnThisThread)) { apiAdapter.Execute(async () => await TaskEx.Yield()); @@ -181,19 +181,6 @@ private static SynchronizationContext CreateSynchronizationContext(Type knownSyn } } #endif - - private static IDisposable TemporarySynchronizationContext(SynchronizationContext synchronizationContext) - { - var restore = RestoreSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext(synchronizationContext); - return restore; - } - - private static IDisposable RestoreSynchronizationContext() - { - var originalContext = SynchronizationContext.Current; - return On.Dispose(() => SynchronizationContext.SetSynchronizationContext(originalContext)); - } } } #endif diff --git a/src/NUnitFramework/tests/TestUtilities/TestUtils.cs b/src/NUnitFramework/tests/TestUtilities/TestUtils.cs new file mode 100644 index 0000000000..d5853db70e --- /dev/null +++ b/src/NUnitFramework/tests/TestUtilities/TestUtils.cs @@ -0,0 +1,45 @@ +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Threading; +using NUnit.Framework.Internal; + +namespace NUnit.TestUtilities +{ + internal static class TestUtils + { + public static IDisposable TemporarySynchronizationContext(SynchronizationContext synchronizationContext) + { + var restore = RestoreSynchronizationContext(); + SynchronizationContext.SetSynchronizationContext(synchronizationContext); + return restore; + } + + public static IDisposable RestoreSynchronizationContext() + { + var originalContext = SynchronizationContext.Current; + return On.Dispose(() => SynchronizationContext.SetSynchronizationContext(originalContext)); + } + } +} From 7748fcb132471656ca48f5aaa87a9ec9cd10429b Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 20:02:44 -0400 Subject: [PATCH 166/174] Failing tests for work that is present at shutdown --- ...ThreadedTestSynchronizationContextTests.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs new file mode 100644 index 0000000000..b88b528e17 --- /dev/null +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -0,0 +1,77 @@ +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using System.Diagnostics; +using System.Threading; + +namespace NUnit.Framework.Internal +{ + public static class SingleThreadedTestSynchronizationContextTests + { + [Test] + public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() + { + using (var context = new SingleThreadedTestSynchronizationContext()) + using (TestUtils.TemporarySynchronizationContext(context)) + { + var wasExecuted = false; + + context.Post(state => + { + context.Post(_ => Thread.Sleep(TimeSpan.FromSeconds(0.5)), null); + context.Post(_ => wasExecuted = true, null); + + context.ShutDown(); + }, null); + + context.Run(); + Assert.That(wasExecuted); + } + } + + [Test] + public static void RecursivelyPostedWorkIsStillExecutedWithinTimeout() + { + using (var context = new SingleThreadedTestSynchronizationContext()) + using (TestUtils.TemporarySynchronizationContext(context)) + { + context.Post(_ => + { + ScheduleWorkRecursively(Stopwatch.StartNew(), until: TimeSpan.FromSeconds(0.5)); + + context.ShutDown(); + }, null); + + context.Run(); + } + } + + private static void ScheduleWorkRecursively(Stopwatch stopwatch, TimeSpan until) + { + if (stopwatch.Elapsed >= until) return; + + SynchronizationContext.Current.Post(_ => ScheduleWorkRecursively(stopwatch, until), null); + } + } +} From db3bcdf9e0bd8bfcadc14f0da954eedaf84f8349 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 20:45:14 -0400 Subject: [PATCH 167/174] Allow work to be dequeued within timeout after shutdown --- .../framework/Internal/AsyncToSyncAdapter.cs | 4 +- .../SingleThreadedSynchronizationContext.cs | 46 ++++++++++++++----- ...ThreadedTestSynchronizationContextTests.cs | 4 +- 3 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs index 749acaf53a..f7eaf63d93 100644 --- a/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs +++ b/src/NUnitFramework/framework/Internal/AsyncToSyncAdapter.cs @@ -118,7 +118,9 @@ private static IDisposable InitializeExecutionEnvironment() var context = SynchronizationContext.Current; if (context == null || context.GetType() == typeof(SynchronizationContext)) { - var singleThreadedContext = new SingleThreadedTestSynchronizationContext(); + var singleThreadedContext = new SingleThreadedTestSynchronizationContext( + shutdownTimeout: TimeSpan.FromSeconds(10)); + SetSynchronizationContext(singleThreadedContext); return On.Dispose(() => diff --git a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs index 756c6cdb47..6d8a3cf843 100644 --- a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs +++ b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs @@ -1,5 +1,5 @@ // *********************************************************************** -// Copyright (c) 2018 Charlie Poole, Rob Prouse +// Copyright (c) 2018–2019 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the @@ -23,14 +23,26 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Threading; +using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { internal sealed partial class SingleThreadedTestSynchronizationContext : SynchronizationContext, IDisposable { + private const string ShutdownTimeoutMessage = + "Work posted to the synchronization context did not complete within ten seconds. Consider explicitly waiting for the work to complete."; + + private readonly TimeSpan _shutdownTimeout; private readonly Queue _queue = new Queue(); - private Status status; + private Status _status; + private Stopwatch _timeSinceShutdown; + + public SingleThreadedTestSynchronizationContext(TimeSpan shutdownTimeout) + { + _shutdownTimeout = shutdownTimeout; + } private enum Status { @@ -74,7 +86,11 @@ private void AddWork(ScheduledWork work) { lock (_queue) { - if (status == Status.ShutDown) throw CreateInvalidWhenShutDownException(); + if (_status == Status.ShutDown) + { + throw CreateInvalidWhenShutDownException(); + } + _queue.Enqueue(work); Monitor.Pulse(_queue); } @@ -87,11 +103,9 @@ public void ShutDown() { lock (_queue) { - status = Status.ShutDown; + _timeSinceShutdown = Stopwatch.StartNew(); + _status = Status.ShutDown; Monitor.Pulse(_queue); - - if (_queue.Count != 0) - throw new InvalidOperationException("Shutting down SingleThreadedTestSynchronizationContext with work still in the queue."); } } @@ -107,7 +121,7 @@ public void Run() { lock (_queue) { - switch (status) + switch (_status) { case Status.Running: throw new InvalidOperationException("SingleThreadedTestSynchronizationContext.Run may not be reentered."); @@ -115,7 +129,7 @@ public void Run() throw CreateInvalidWhenShutDownException(); } - status = Status.Running; + _status = Status.Running; } ScheduledWork scheduledWork; @@ -127,18 +141,26 @@ private bool TryTake(out ScheduledWork scheduledWork) { lock (_queue) { - for (;;) + while (_queue.Count == 0) { - if (status == Status.ShutDown) + if (_status == Status.ShutDown) { scheduledWork = default(ScheduledWork); return false; } - if (_queue.Count != 0) break; Monitor.Wait(_queue); } + if (_status == Status.ShutDown && _timeSinceShutdown.Elapsed > _shutdownTimeout) + { + var testExecutionContext = TestExecutionContext.CurrentContext; + + testExecutionContext?.CurrentResult.RecordAssertion(AssertionStatus.Error, ShutdownTimeoutMessage); + + throw new InvalidOperationException(ShutdownTimeoutMessage); + } + scheduledWork = _queue.Dequeue(); } diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs index b88b528e17..034da0fb94 100644 --- a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -32,7 +32,7 @@ public static class SingleThreadedTestSynchronizationContextTests [Test] public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() { - using (var context = new SingleThreadedTestSynchronizationContext()) + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) using (TestUtils.TemporarySynchronizationContext(context)) { var wasExecuted = false; @@ -53,7 +53,7 @@ public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() [Test] public static void RecursivelyPostedWorkIsStillExecutedWithinTimeout() { - using (var context = new SingleThreadedTestSynchronizationContext()) + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) using (TestUtils.TemporarySynchronizationContext(context)) { context.Post(_ => From 1fc8dc3448f43d67a150e71a1f615d496c8214be Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 20:50:57 -0400 Subject: [PATCH 168/174] Test that recursively posted work actually happens --- ...ThreadedTestSynchronizationContextTests.cs | 26 +++-- .../tests/TestUtilities/CallbackWatcher.cs | 107 ++++++++++++++++++ 2 files changed, 124 insertions(+), 9 deletions(-) create mode 100644 src/NUnitFramework/tests/TestUtilities/CallbackWatcher.cs diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs index 034da0fb94..e9da7c0b79 100644 --- a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -24,6 +24,7 @@ using System; using System.Diagnostics; using System.Threading; +using NUnit.TestUtilities; namespace NUnit.Framework.Internal { @@ -35,18 +36,18 @@ public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) using (TestUtils.TemporarySynchronizationContext(context)) { - var wasExecuted = false; + var wasExecuted = new CallbackWatcher(); context.Post(state => { context.Post(_ => Thread.Sleep(TimeSpan.FromSeconds(0.5)), null); - context.Post(_ => wasExecuted = true, null); + context.Post(_ => wasExecuted.OnCallback(), null); context.ShutDown(); }, null); - context.Run(); - Assert.That(wasExecuted); + using (wasExecuted.ExpectCallback()) + context.Run(); } } @@ -56,22 +57,29 @@ public static void RecursivelyPostedWorkIsStillExecutedWithinTimeout() using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) using (TestUtils.TemporarySynchronizationContext(context)) { + var wasExecuted = new CallbackWatcher(); + context.Post(_ => { - ScheduleWorkRecursively(Stopwatch.StartNew(), until: TimeSpan.FromSeconds(0.5)); + ScheduleWorkRecursively(Stopwatch.StartNew(), until: TimeSpan.FromSeconds(0.5), wasExecuted: wasExecuted); context.ShutDown(); }, null); - context.Run(); + using (wasExecuted.ExpectCallback()) + context.Run(); } } - private static void ScheduleWorkRecursively(Stopwatch stopwatch, TimeSpan until) + private static void ScheduleWorkRecursively(Stopwatch stopwatch, TimeSpan until, CallbackWatcher wasExecuted) { - if (stopwatch.Elapsed >= until) return; + if (stopwatch.Elapsed >= until) + { + wasExecuted.OnCallback(); + return; + } - SynchronizationContext.Current.Post(_ => ScheduleWorkRecursively(stopwatch, until), null); + SynchronizationContext.Current.Post(_ => ScheduleWorkRecursively(stopwatch, until, wasExecuted), null); } } } diff --git a/src/NUnitFramework/tests/TestUtilities/CallbackWatcher.cs b/src/NUnitFramework/tests/TestUtilities/CallbackWatcher.cs new file mode 100644 index 0000000000..6f1101541b --- /dev/null +++ b/src/NUnitFramework/tests/TestUtilities/CallbackWatcher.cs @@ -0,0 +1,107 @@ +// *********************************************************************** +// Copyright (c) 2019 Charlie Poole, Rob Prouse +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// *********************************************************************** + +using System; +using NUnit.Framework; +using NUnit.Framework.Internal; + +namespace NUnit.TestUtilities +{ + /// + /// Provides idiomatic callback-based assertions. + /// + /// + /// + /// var watcher = new CallbackWatcher(); + /// + /// systemUnderTest.PropertyChanged += (sender, e) => watcher.OnCallback(); + /// + /// using (watcher.ExpectCallback()) + /// { + /// systemUnderTest.SomeProperty = 42; + /// } // Fails if PropertyChanged did not fire + /// + /// systemUnderTest.SomeProperty = 42; // Fails if PropertyChanged fires + /// + /// + public sealed class CallbackWatcher + { + private int _expectedCount; + private int _actualCount; + + /// + /// Begins expecting callbacks. When the returned scope is disposed, stops expecting callbacks and throws + /// if was not called the expected number of times between beginning and ending. + /// + /// + /// The number of times that is expected to be called before the returned scope is disposed. + /// + /// Thrown when is less than 1. + /// Thrown when the returned scope from the previous call has not been disposed. + /// Thrown when was not called the expected number of times between beginning and ending. + public IDisposable ExpectCallback(int count = 1) + { + if (count < 0) + throw new ArgumentOutOfRangeException(nameof(count), _expectedCount, "Expected callback count must be greater than or equal to zero."); + + if (_expectedCount != 0) + throw new InvalidOperationException($"The previous {nameof(ExpectCallback)} scope must be disposed before calling again."); + + _expectedCount = count; + _actualCount = 0; + + return On.Dispose(() => + { + try + { + if (_actualCount < _expectedCount) + Assert.Fail($"Expected {(_expectedCount == 1 ? "a single call" : _expectedCount + " calls")}, but there {(_actualCount == 1 ? "was" : "were")} {_actualCount}."); + } + finally + { + _expectedCount = 0; + } + }); + } + + /// + /// Call this from the callback being tested. + /// Throws if this watcher is not currently expecting a callback + /// (see ) or if the expected number of callbacks has been exceeded. + /// + /// + /// Thrown when this watcher is not currently expecting a callback (see ) + /// or if the expected number of callbacks has been exceeded. + /// + public void OnCallback() + { + _actualCount++; + if (_actualCount > _expectedCount) + { + Assert.Fail(_expectedCount == 0 + ? "Expected no callback." + : $"Expected {(_expectedCount == 1 ? "a single call" : _expectedCount + " calls")}, but there were more."); + } + } + } +} From 594248b22c63435b91d2c9af2909bf1c4d1ef43b Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 21:03:12 -0400 Subject: [PATCH 169/174] Enable work to be posted recursively within timeout --- .../SingleThreadedSynchronizationContext.cs | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs index 6d8a3cf843..4666876788 100644 --- a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs +++ b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs @@ -48,6 +48,7 @@ private enum Status { NotStarted, Running, + ShuttingDown, ShutDown } @@ -86,9 +87,14 @@ private void AddWork(ScheduledWork work) { lock (_queue) { - if (_status == Status.ShutDown) + switch (_status) { - throw CreateInvalidWhenShutDownException(); + case Status.ShuttingDown: + if (_timeSinceShutdown.Elapsed < _shutdownTimeout) break; + goto case Status.ShutDown; + + case Status.ShutDown: + throw CreateInvalidWhenShutDownException(); } _queue.Enqueue(work); @@ -103,8 +109,15 @@ public void ShutDown() { lock (_queue) { + switch (_status) + { + case Status.ShuttingDown: + case Status.ShutDown: + break; + } + _timeSinceShutdown = Stopwatch.StartNew(); - _status = Status.ShutDown; + _status = Status.ShuttingDown; Monitor.Pulse(_queue); } } @@ -125,6 +138,8 @@ public void Run() { case Status.Running: throw new InvalidOperationException("SingleThreadedTestSynchronizationContext.Run may not be reentered."); + + case Status.ShuttingDown: case Status.ShutDown: throw CreateInvalidWhenShutDownException(); } @@ -143,8 +158,9 @@ private bool TryTake(out ScheduledWork scheduledWork) { while (_queue.Count == 0) { - if (_status == Status.ShutDown) + if (_status == Status.ShuttingDown) { + _status = Status.ShutDown; scheduledWork = default(ScheduledWork); return false; } @@ -152,8 +168,10 @@ private bool TryTake(out ScheduledWork scheduledWork) Monitor.Wait(_queue); } - if (_status == Status.ShutDown && _timeSinceShutdown.Elapsed > _shutdownTimeout) + if (_status == Status.ShuttingDown && _timeSinceShutdown.Elapsed > _shutdownTimeout) { + _status = Status.ShutDown; + var testExecutionContext = TestExecutionContext.CurrentContext; testExecutionContext?.CurrentResult.RecordAssertion(AssertionStatus.Error, ShutdownTimeoutMessage); From 831347328f69b5678e03dd36439f24cf9aeace2d Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 22:23:31 -0400 Subject: [PATCH 170/174] Handle queue timeouts properly --- .../SingleThreadedSynchronizationContext.cs | 25 +++--- ...ThreadedTestSynchronizationContextTests.cs | 88 +++++++++++++++++++ 2 files changed, 100 insertions(+), 13 deletions(-) diff --git a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs index 4666876788..61fd832520 100644 --- a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs +++ b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs @@ -94,7 +94,7 @@ private void AddWork(ScheduledWork work) goto case Status.ShutDown; case Status.ShutDown: - throw CreateInvalidWhenShutDownException(); + throw ErrorAndGetExceptionForShutdownTimeout(); } _queue.Enqueue(work); @@ -122,11 +122,6 @@ public void ShutDown() } } - private static InvalidOperationException CreateInvalidWhenShutDownException() - { - return new InvalidOperationException("This SingleThreadedTestSynchronizationContext has been shut down."); - } - /// /// May be called from any thread, but may only be called once. /// @@ -141,7 +136,7 @@ public void Run() case Status.ShuttingDown: case Status.ShutDown: - throw CreateInvalidWhenShutDownException(); + throw new InvalidOperationException("This SingleThreadedTestSynchronizationContext has been shut down."); } _status = Status.Running; @@ -171,12 +166,7 @@ private bool TryTake(out ScheduledWork scheduledWork) if (_status == Status.ShuttingDown && _timeSinceShutdown.Elapsed > _shutdownTimeout) { _status = Status.ShutDown; - - var testExecutionContext = TestExecutionContext.CurrentContext; - - testExecutionContext?.CurrentResult.RecordAssertion(AssertionStatus.Error, ShutdownTimeoutMessage); - - throw new InvalidOperationException(ShutdownTimeoutMessage); + throw ErrorAndGetExceptionForShutdownTimeout(); } scheduledWork = _queue.Dequeue(); @@ -185,6 +175,15 @@ private bool TryTake(out ScheduledWork scheduledWork) return true; } + private static Exception ErrorAndGetExceptionForShutdownTimeout() + { + var testExecutionContext = TestExecutionContext.CurrentContext; + + testExecutionContext?.CurrentResult.RecordAssertion(AssertionStatus.Error, ShutdownTimeoutMessage); + + return new InvalidOperationException(ShutdownTimeoutMessage); + } + public void Dispose() { ShutDown(); diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs index e9da7c0b79..28a488ed32 100644 --- a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -24,10 +24,12 @@ using System; using System.Diagnostics; using System.Threading; +using NUnit.Framework.Interfaces; using NUnit.TestUtilities; namespace NUnit.Framework.Internal { + [Parallelizable(ParallelScope.Children)] public static class SingleThreadedTestSynchronizationContextTests { [Test] @@ -51,6 +53,92 @@ public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() } } + [Test] + public static void WorkInQueueAfterTimeoutIsDiscardedAndCausesRunToThrowAndError() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + using (TestUtils.TemporarySynchronizationContext(context)) + { + var wasExecuted = new CallbackWatcher(); + + context.Post(state => + { + context.Post(_ => Thread.Sleep(TimeSpan.FromSeconds(1.5)), null); + context.Post(_ => wasExecuted.OnCallback(), null); + + context.ShutDown(); + }, null); + + TestResult testResult; + Exception exception; + + using (wasExecuted.ExpectCallback(count: 0)) // Work is discarded + using (new TestExecutionContext.IsolatedContext()) + { + try + { + context.Run(); + exception = null; + } + catch (Exception ex) + { + exception = ex; + } + + testResult = TestExecutionContext.CurrentContext.CurrentResult; + } + + Assert.That(exception, Is.InstanceOf()); // Run() throws + + Assert.That(testResult.WorstAssertionStatus, Is.EqualTo(AssertionStatus.Error)); // Run() errors + } + } + + [Test] + public static void PostAfterTimeoutDiscardsWorkAndThrowsAndErrors() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + using (TestUtils.TemporarySynchronizationContext(context)) + { + var wasExecuted = new CallbackWatcher(); + + var testResult = (TestResult)null; + var exception = (Exception)null; + + context.Post(state => + { + context.Post(_ => + { + Thread.Sleep(TimeSpan.FromSeconds(1.5)); + + try + { + context.Post(__ => wasExecuted.OnCallback(), null); + exception = null; + } + catch (Exception ex) + { + exception = ex; + } + + testResult = TestExecutionContext.CurrentContext.CurrentResult; + }, null); + + context.ShutDown(); + }, null); + + using (wasExecuted.ExpectCallback(count: 0)) // Work is discarded + using (new TestExecutionContext.IsolatedContext()) + { + context.Run(); + } + + Assert.That(exception, Is.InstanceOf()); // Run() throws + + Assert.That(testResult.WorstAssertionStatus, Is.EqualTo(AssertionStatus.Error)); // Run() errors + } + } + [Test] public static void RecursivelyPostedWorkIsStillExecutedWithinTimeout() { From 39cfe28b99fbc5deab0ab9d40b106d10104610c3 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Tue, 7 May 2019 22:45:30 -0400 Subject: [PATCH 171/174] Increase test coverage of SingleThreadedTestSynchronizationContext --- ...ThreadedTestSynchronizationContextTests.cs | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs index 28a488ed32..4c15115b4c 100644 --- a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -32,6 +32,72 @@ namespace NUnit.Framework.Internal [Parallelizable(ParallelScope.Children)] public static class SingleThreadedTestSynchronizationContextTests { + [Test] + public static void RunWaitsWhenQueueIsEmptyUntilShutdown() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + { + var thread = new Thread(context.Run); + + using (var queueRunning = new ManualResetEventSlim()) + { + context.Post(_ => queueRunning.Set(), null); + thread.Start(); + Assert.That(queueRunning.Wait(1000), Is.True); + } + + Assert.That(thread.Join(10), Is.False); + + context.ShutDown(); + + Assert.That(thread.Join(1000), Is.True); + } + } + + [Test] + public static void RunWaitsWhenQueueIsEmptyUntilPostAndExecutesPostedWork() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + { + var thread = new Thread(context.Run); + thread.Start(); + + using (var workExecuted = new ManualResetEventSlim()) + { + Thread.Sleep(100); + context.Post(_ => workExecuted.Set(), null); + + Assert.That(workExecuted.Wait(1000), Is.True); + } + } + } + + [Test] + public static void RunAfterShutdownThrowsInvalidOperationException() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + { + context.ShutDown(); + + Assert.That(context.Run, Throws.InvalidOperationException); + } + } + + [Test] + public static void ReenteringRunThrowsInvalidOperationException() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1))) + { + context.Post(_ => + { + Assert.That(context.Run, Throws.InvalidOperationException); + context.ShutDown(); + }, null); + + context.Run(); + } + } + [Test] public static void RecursivelyPostedWorkIsStillExecutedIfStartedWithinTimeout() { From eda78fdfb453028ad7ed7a8656363201ebd8d960 Mon Sep 17 00:00:00 2001 From: jnm2 Date: Sun, 12 May 2019 21:44:19 -0400 Subject: [PATCH 172/174] Fix accidental break instead of return and protect with test --- .../SingleThreadedSynchronizationContext.cs | 2 +- ...ThreadedTestSynchronizationContextTests.cs | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs index 61fd832520..9eab82da00 100644 --- a/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs +++ b/src/NUnitFramework/framework/Internal/SingleThreadedSynchronizationContext.cs @@ -113,7 +113,7 @@ public void ShutDown() { case Status.ShuttingDown: case Status.ShutDown: - break; + return; } _timeSinceShutdown = Stopwatch.StartNew(); diff --git a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs index 4c15115b4c..5a64341e08 100644 --- a/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs +++ b/src/NUnitFramework/tests/Internal/SingleThreadedTestSynchronizationContextTests.cs @@ -235,5 +235,27 @@ private static void ScheduleWorkRecursively(Stopwatch stopwatch, TimeSpan until, SynchronizationContext.Current.Post(_ => ScheduleWorkRecursively(stopwatch, until, wasExecuted), null); } + + [Test] + public static void Duplicate_shutdown_call_does_not_extend_shutdown_time() + { + using (var context = new SingleThreadedTestSynchronizationContext(shutdownTimeout: TimeSpan.FromSeconds(1.5))) + using (TestUtils.TemporarySynchronizationContext(context)) + { + var wasExecuted = new CallbackWatcher(); + + context.Post(_ => + { + context.ShutDown(); + Thread.Sleep(TimeSpan.FromSeconds(1)); + context.ShutDown(); + }, null); + context.Post(_ => Thread.Sleep(TimeSpan.FromSeconds(1)), null); + context.Post(_ => wasExecuted.OnCallback(), null); + + using (wasExecuted.ExpectCallback(count: 0)) + Assert.That(context.Run, Throws.InvalidOperationException); + } + } } } From c375f06f2c48a859058a731c96aae43f8702891c Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Mon, 13 May 2019 20:45:44 -0400 Subject: [PATCH 173/174] Update changes.md for the 3.12 release --- CHANGES.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index ba8e5f41bd..b0a2028d73 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,77 @@ +### NUnit 3.12 - May 14, 2019 + +This release of NUnit finally drops support for .NET 2.0. If your application still +targets .NET 2.0, your tests will need to target at least .NET 3.5. Microsoft ended +support for .NET 2.0 on July 12, 2011. Microsoft recommends that everyone migrate +to at least .NET Framework 3.5 SP1 for security and performance fixes. + +This release dramatically improves NUnit support for async tests including returning +ValueTask and custom tasks from tests, improved handling of SynchronizationContexts +and better exception handling. + +The .NET Standard 2.0 version of NUnit continues to gain more functionality that +is found in the .NET 4.5 version of the framework like setting the ApartmentState +and enabling Timeout on tests. + +#### Issues Resolved + + * 474 TypeHelperTests.cs is orphaned + * 999 Support multiple TestOf attributes per test + * 1638 TimeoutAttribute not available when targeting netcoreapp framework + * 2168 ThrowsAsync reports OperationCanceledException as TaskCanceledException + * 2194 How to use `Contains.Substring` with `And` + * 2286 Add support for custom Task (i.e. ValueTask) + * 2579 AppVeyor Test Failures under .NET 3.5 + * 2614 TestExecutionContext.CurrentContext is saved in Remoting CallContext between test runs + * 2696 Getting WorkerId fails in debug + * 2772 Random failing of parallel test run: Unhandled Exception: System.InvalidOperationException: Stack empty. + * 2975 ComparisonConstraints are allocating string on construction + * 3014 Timeout failures on MacOS + * 3023 NUnit runner fails when test method returns ValueTask<> + * 3035 Apartment state can't be used for .NET Standard 2.0 tests + * 3036 Apartment state can't be used for .NET Standard 2.0 tests + * 3038 TestName in TestCase attribute not validated to be not empty + * 3042 RequiresThreadAttribute allows ApartmentState.Unknown, unlike ApartmentAttribute + * 3048 Add .idea folder to .gitignore + * 3053 Conversion from TestCase string parameter to DateTimeOffset + * 3059 Constraint Throws.Exception does not work with async return value + * 3068 First Chance Exception in RuntimeFramework + * 3070 End support for .NET Framework 2.0 (released in 2005) + * 3073 CollectionAssert.AreEquivalent fails for ValueTuple Wrapped Dictionary + * 3079 Regression from 3.10 to 3.11: Range in bytes + * 3082 Is.Ordered.By + * 3085 XML Test-Suite Assembly does not contain DLL path anymore + * 3089 Remove outdated comment + * 3093 Tests having TaskLike objects as their return type throws Exception + * 3094 Bad error message if collections have different types + * 3104 Removed NET20 compile output + * 3105 Add tests for use of ApartmentState.Unknown in RequiresThreadAttribute + * 3107 Declare class in Program.cs provided with NUnitLite Nuget package static + * 3109 Azure DevOps build fails in Save package artifacts + * 3124 Switch copyright notice + * 3128 Correct documentation on ParallelScope + * 3137 Fix doc-comments in NUnitTestAssemblyRunner + * 3138 Assert.Ignore breaks when a Task is returned w/o using async/await + * 3139 Add Azure pipelines badge to frontpage + * 3144 Retry attribute should not derive from PropertyAttribute + * 3145 Capture additional exception details in the test output + * 3156 UnexpectedExceptionTests should tolerate Mono on Azure DevOps Ubuntu + * 3159 Make tests more tolerant + * 3161 https url repo + * 3166 Allow static SetUpFixture classes + * 3171 Incorrect type for Test Fixtures when using running explore with a filter + * 3175 Improve user-facing messages + * 3181 Template Based Test Naming - Incorrect truncation for individual arguments + * 3186 Fix licenseUrl element in nuspec, will be deprecated + * 3193 Cake Build Fails with Visual Studio 2019 + * 3195 Drop or at least make Travis not required? + * 3231 Breaking change in filter functionality between framework 2.7 and 3.11 + * 3209 Test fail when posting to SynchronizationContext.Current + * 3211 Fix logging + * 3218 Remove todos from the code base + * 3222 Our build script tests hang when run with Mono on Windows + * 3233 AndConstraint should write additional information from failed constraint + ### NUnit 3.11 - October 6, 2018 * More informative assertion messages From 735ecc59fd5da568cff421f6e41b228db9e24257 Mon Sep 17 00:00:00 2001 From: Rob Prouse Date: Mon, 13 May 2019 20:52:25 -0400 Subject: [PATCH 174/174] Updates copyright to 2019 --- LICENSE.txt | 2 +- nuget/framework/nunit.nuspec | 2 +- nuget/nunitlite/nunitlite.nuspec | 2 +- src/CommonAssemblyInfo.cs | 2 +- src/NUnitFramework/nunitlite/TextUI.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index d1fc75345e..b029a77c34 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2018 Charlie Poole, Rob Prouse +Copyright (c) 2019 Charlie Poole, Rob Prouse Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/nuget/framework/nunit.nuspec b/nuget/framework/nunit.nuspec index cdc006f0be..6111c27749 100644 --- a/nuget/framework/nunit.nuspec +++ b/nuget/framework/nunit.nuspec @@ -23,7 +23,7 @@ Supported platforms: This package includes the NUnit 3 framework assembly, which is referenced by your tests. You will need to install version 3 of the nunit3-console program or a third-party runner that supports NUnit 3 in order to execute tests. Runners intended for use with NUnit 2.x will not run NUnit 3 tests correctly. en-US nunit test testing tdd framework fluent assert theory plugin addin - Copyright (c) 2018 Charlie Poole, Rob Prouse + Copyright (c) 2019 Charlie Poole, Rob Prouse diff --git a/nuget/nunitlite/nunitlite.nuspec b/nuget/nunitlite/nunitlite.nuspec index cdbfb4da1f..f1106fa239 100644 --- a/nuget/nunitlite/nunitlite.nuspec +++ b/nuget/nunitlite/nunitlite.nuspec @@ -26,7 +26,7 @@ How to use this package: 3. Add your tests to the test project and simply start the project to execute them. en-US test unit testing tdd framework fluent assert device phone embedded - Copyright (c) 2018 Charlie Poole, Rob Prouse + Copyright (c) 2019 Charlie Poole, Rob Prouse diff --git a/src/CommonAssemblyInfo.cs b/src/CommonAssemblyInfo.cs index 6f38ae5ab0..02a7009ba9 100644 --- a/src/CommonAssemblyInfo.cs +++ b/src/CommonAssemblyInfo.cs @@ -28,7 +28,7 @@ // [assembly: AssemblyCompany("NUnit Software")] [assembly: AssemblyProduct("NUnit 3")] -[assembly: AssemblyCopyright("Copyright (c) 2018 Charlie Poole, Rob Prouse")] +[assembly: AssemblyCopyright("Copyright (c) 2019 Charlie Poole, Rob Prouse")] [assembly: AssemblyTrademark("NUnit is a trademark of NUnit Software")] #if DEBUG diff --git a/src/NUnitFramework/nunitlite/TextUI.cs b/src/NUnitFramework/nunitlite/TextUI.cs index c4451950f8..bca4cd9f25 100644 --- a/src/NUnitFramework/nunitlite/TextUI.cs +++ b/src/NUnitFramework/nunitlite/TextUI.cs @@ -73,7 +73,7 @@ public void DisplayHeader() Assembly executingAssembly = GetType().GetTypeInfo().Assembly; AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); Version version = assemblyName.Version; - string copyright = "Copyright (C) 2018 Charlie Poole, Rob Prouse"; + string copyright = "Copyright (C) 2019 Charlie Poole, Rob Prouse"; string build = ""; var copyrightAttr = executingAssembly.GetCustomAttribute();