From 025480b9e1304ed6b41805047a4b84d8425d0f6b Mon Sep 17 00:00:00 2001 From: martincostello Date: Sun, 19 Jan 2025 18:57:38 +0000 Subject: [PATCH 1/3] Remove FluentAssertions Complete migration from FluentAssertions to Shouldly. Resolves #2450. --- eng/Test.targets | 2 + test/Polly.Core.Tests/Polly.Core.Tests.csproj | 2 - .../Polly.Extensions.Tests.csproj | 2 - .../Polly.RateLimiting.Tests.csproj | 4 - .../Bulkhead/BulkheadAsyncSpecs.cs | 33 +- test/Polly.Specs/Bulkhead/BulkheadSpecs.cs | 33 +- .../Polly.Specs/Bulkhead/BulkheadSpecsBase.cs | 2 +- .../Bulkhead/BulkheadTResultAsyncSpecs.cs | 39 +- .../Bulkhead/BulkheadTResultSpecs.cs | 39 +- .../Bulkhead/IBulkheadPolicySpecs.cs | 4 +- test/Polly.Specs/Caching/AbsoluteTtlSpecs.cs | 10 +- .../AsyncSerializingCacheProviderSpecs.cs | 144 +- test/Polly.Specs/Caching/CacheAsyncSpecs.cs | 370 ++-- test/Polly.Specs/Caching/CacheSpecs.cs | 358 ++-- .../Caching/CacheTResultAsyncSpecs.cs | 226 ++- test/Polly.Specs/Caching/CacheTResultSpecs.cs | 568 +++--- .../Polly.Specs/Caching/ContextualTtlSpecs.cs | 28 +- .../Caching/DefaultCacheKeyStrategySpecs.cs | 4 +- .../Caching/GenericCacheProviderAsyncSpecs.cs | 16 +- .../Caching/GenericCacheProviderSpecs.cs | 16 +- test/Polly.Specs/Caching/RelativeTtlSpecs.cs | 14 +- test/Polly.Specs/Caching/ResultTtlSpecs.cs | 16 +- .../Caching/SerializingCacheProviderSpecs.cs | 144 +- test/Polly.Specs/Caching/SlidingTtlSpecs.cs | 10 +- .../AdvancedCircuitBreakerAsyncSpecs.cs | 1721 +++++++---------- .../AdvancedCircuitBreakerSpecs.cs | 1681 +++++++--------- .../CircuitBreakerAsyncSpecs.cs | 862 ++++----- .../CircuitBreaker/CircuitBreakerSpecs.cs | 819 ++++---- .../CircuitBreakerTResultAsyncSpecs.cs | 795 ++++---- ...BreakerTResultMixedResultExceptionSpecs.cs | 369 ++-- .../CircuitBreakerTResultSpecs.cs | 774 ++++---- .../ICircuitBreakerPolicySpecs.cs | 10 +- .../ICircuitBreakerTResultPolicySpecs.cs | 2 +- test/Polly.Specs/ContextSpecs.cs | 16 +- test/Polly.Specs/Custom/CustomAsyncSpecs.cs | 43 +- test/Polly.Specs/Custom/CustomSpecs.cs | 29 +- .../Custom/CustomTResultAsyncSpecs.cs | 23 +- test/Polly.Specs/Custom/CustomTResultSpecs.cs | 25 +- .../Fallback/FallbackAsyncSpecs.cs | 283 ++- test/Polly.Specs/Fallback/FallbackSpecs.cs | 561 +++--- .../Fallback/FallbackTResultAsyncSpecs.cs | 310 ++- .../Fallback/FallbackTResultSpecs.cs | 230 +-- .../RateLimit/IRateLimiterExtensions.cs | 10 +- .../IAsyncPolicyExtensionsSpecs.cs | 6 +- .../Polly.Specs/ISyncPolicyExtensionsSpecs.cs | 6 +- test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs | 18 +- test/Polly.Specs/NoOp/NoOpSpecs.cs | 18 +- .../Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs | 24 +- test/Polly.Specs/NoOp/NoOpTResultSpecs.cs | 20 +- test/Polly.Specs/PolicyAsyncSpecs.cs | 122 +- test/Polly.Specs/PolicyKeyAsyncSpecs.cs | 34 +- test/Polly.Specs/PolicyKeySpecs.cs | 28 +- test/Polly.Specs/PolicySpecs.cs | 124 +- test/Polly.Specs/PolicyTResultAsyncSpecs.cs | 70 +- .../Polly.Specs/PolicyTResultKeyAsyncSpecs.cs | 28 +- test/Polly.Specs/PolicyTResultKeySpecs.cs | 24 +- test/Polly.Specs/PolicyTResultSpecs.cs | 75 +- test/Polly.Specs/Polly.Specs.csproj | 4 - .../RateLimit/AsyncRateLimitPolicySpecs.cs | 8 +- .../AsyncRateLimitPolicyTResultSpecs.cs | 8 +- .../RateLimit/RateLimitPolicySpecs.cs | 8 +- .../RateLimit/RateLimitPolicySpecsBase.cs | 36 +- .../RateLimit/RateLimitPolicyTResultSpecs.cs | 8 +- .../RateLimitPolicyTResultSpecsBase.cs | 8 +- .../RateLimitRejectedExceptionTests.cs | 26 +- .../RateLimit/RateLimitSpecsBase.cs | 2 +- .../TokenBucketRateLimiterTestsBase.cs | 8 +- .../Registry/ConcurrentPolicyRegistrySpecs.cs | 70 +- .../Registry/PolicyRegistrySpecs.cs | 156 +- .../Registry/ReadOnlyPolicyRegistrySpecs.cs | 98 +- ...liencePipelineConversionExtensionsTests.cs | 25 +- test/Polly.Specs/Retry/RetryAsyncSpecs.cs | 229 +-- .../Retry/RetryForeverAsyncSpecs.cs | 137 +- test/Polly.Specs/Retry/RetryForeverSpecs.cs | 67 +- test/Polly.Specs/Retry/RetrySpecs.cs | 226 +-- .../Retry/RetryTResultAsyncSpecs.cs | 290 +-- .../RetryTResultMixedResultExceptionSpecs.cs | 35 +- test/Polly.Specs/Retry/RetryTResultSpecs.cs | 302 +-- .../Retry/WaitAndRetryAsyncSpecs.cs | 569 +++--- .../Retry/WaitAndRetryForeverAsyncSpecs.cs | 209 +- .../Retry/WaitAndRetryForeverSpecs.cs | 100 +- .../WaitAndRetryForeverTResultAsyncSpecs.cs | 6 +- .../Retry/WaitAndRetryForeverTResultSpecs.cs | 7 +- test/Polly.Specs/Retry/WaitAndRetrySpecs.cs | 706 ++++--- .../Retry/WaitAndRetryTResultAsyncSpecs.cs | 18 +- .../Retry/WaitAndRetryTResultSpecs.cs | 6 +- test/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs | 307 ++- test/Polly.Specs/Timeout/TimeoutSpecs.cs | 273 ++- .../Timeout/TimeoutTResultAsyncSpecs.cs | 275 ++- .../Timeout/TimeoutTResultSpecs.cs | 376 ++-- .../Utilities/LockTimeoutExceptionTests.cs | 8 +- .../Polly.Specs/Utilities/SystemClockSpecs.cs | 32 +- .../Wrap/IPolicyWrapExtensionSpecs.cs | 84 +- test/Polly.Specs/Wrap/PolicyWrapAsyncSpecs.cs | 194 +- .../Wrap/PolicyWrapContextAndKeyAsyncSpecs.cs | 96 +- .../Wrap/PolicyWrapContextAndKeySpecs.cs | 81 +- test/Polly.Specs/Wrap/PolicyWrapSpecs.cs | 192 +- .../Polly.Testing.Tests.csproj | 4 - 98 files changed, 7679 insertions(+), 8859 deletions(-) diff --git a/eng/Test.targets b/eng/Test.targets index cefc8e70e7..e80cc4b30b 100644 --- a/eng/Test.targets +++ b/eng/Test.targets @@ -6,6 +6,7 @@ + @@ -15,6 +16,7 @@ + diff --git a/test/Polly.Core.Tests/Polly.Core.Tests.csproj b/test/Polly.Core.Tests/Polly.Core.Tests.csproj index dd5681d5a5..bceada5ec7 100644 --- a/test/Polly.Core.Tests/Polly.Core.Tests.csproj +++ b/test/Polly.Core.Tests/Polly.Core.Tests.csproj @@ -15,7 +15,6 @@ - @@ -31,6 +30,5 @@ - diff --git a/test/Polly.Extensions.Tests/Polly.Extensions.Tests.csproj b/test/Polly.Extensions.Tests/Polly.Extensions.Tests.csproj index 914fb1c13c..7db495410f 100644 --- a/test/Polly.Extensions.Tests/Polly.Extensions.Tests.csproj +++ b/test/Polly.Extensions.Tests/Polly.Extensions.Tests.csproj @@ -15,13 +15,11 @@ - - diff --git a/test/Polly.RateLimiting.Tests/Polly.RateLimiting.Tests.csproj b/test/Polly.RateLimiting.Tests/Polly.RateLimiting.Tests.csproj index 127282bb40..23cf116606 100644 --- a/test/Polly.RateLimiting.Tests/Polly.RateLimiting.Tests.csproj +++ b/test/Polly.RateLimiting.Tests/Polly.RateLimiting.Tests.csproj @@ -16,9 +16,5 @@ - - - - diff --git a/test/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs b/test/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs index 1ae18c9dbb..4417d3598e 100644 --- a/test/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs +++ b/test/Polly.Specs/Bulkhead/BulkheadAsyncSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -39,8 +39,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero_and_no_ma Action policy = () => Policy .BulkheadAsync(0); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -49,8 +49,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero() Action policy = () => Policy .BulkheadAsync(0, 1); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -59,8 +59,8 @@ public void Should_throw_when_maxQueuingActions_less_than_zero() Action policy = () => Policy .BulkheadAsync(1, -1); - policy.Should().Throw().And - .ParamName.Should().Be("maxQueuingActions"); + Should.Throw(policy) + .ParamName.ShouldBe("maxQueuingActions"); } [Fact] @@ -69,8 +69,8 @@ public void Should_throw_when_onBulkheadRejected_is_null() Action policy = () => Policy .BulkheadAsync(1, 0, null!); - policy.Should().Throw().And - .ParamName.Should().Be("onBulkheadRejectedAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onBulkheadRejectedAsync"); } #endregion @@ -94,7 +94,8 @@ public async Task Should_call_onBulkheadRejected_with_passed_context() Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - await bulkhead.Awaiting(b => b.ExecuteAsync(_ => TaskHelper.EmptyTask, contextPassedToExecute)).Should().ThrowAsync(); + await Should.ThrowAsync( + () => bulkhead.ExecuteAsync(_ => TaskHelper.EmptyTask, contextPassedToExecute)); cancellationSource.Cancel(); @@ -105,9 +106,9 @@ public async Task Should_call_onBulkheadRejected_with_passed_context() #endif } - contextPassedToOnRejected!.Should().NotBeNull(); - contextPassedToOnRejected!.OperationKey.Should().Be(operationKey); - contextPassedToOnRejected!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnRejected!.ShouldNotBeNull(); + contextPassedToOnRejected!.OperationKey.ShouldBe(operationKey); + contextPassedToOnRejected!.ShouldBeSameAs(contextPassedToExecute); } #endregion diff --git a/test/Polly.Specs/Bulkhead/BulkheadSpecs.cs b/test/Polly.Specs/Bulkhead/BulkheadSpecs.cs index ca443a9466..3d9b77e3dc 100644 --- a/test/Polly.Specs/Bulkhead/BulkheadSpecs.cs +++ b/test/Polly.Specs/Bulkhead/BulkheadSpecs.cs @@ -32,10 +32,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -44,8 +44,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero_and_no_ma Action policy = () => Policy .Bulkhead(0); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -54,8 +54,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero() Action policy = () => Policy .Bulkhead(0, 1); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -64,8 +64,8 @@ public void Should_throw_when_maxQueuedActions_less_than_zero() Action policy = () => Policy .Bulkhead(1, -1); - policy.Should().Throw().And - .ParamName.Should().Be("maxQueuingActions"); + Should.Throw(policy) + .ParamName.ShouldBe("maxQueuingActions"); } [Fact] @@ -74,8 +74,8 @@ public void Should_throw_when_onBulkheadRejected_is_null() Action policy = () => Policy .Bulkhead(1, 0, null!); - policy.Should().Throw().And - .ParamName.Should().Be("onBulkheadRejected"); + Should.Throw(policy) + .ParamName.ShouldBe("onBulkheadRejected"); } #endregion @@ -99,8 +99,7 @@ public void Should_call_onBulkheadRejected_with_passed_context() // Time for the other thread to kick up and take the bulkhead. Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - bulkhead.Invoking(b => b.Execute(_ => { }, contextPassedToExecute)).Should() - .Throw(); + Should.Throw(() => bulkhead.Execute(_ => { }, contextPassedToExecute)); #if NET tcs.SetCanceled(CancellationToken); @@ -108,9 +107,9 @@ public void Should_call_onBulkheadRejected_with_passed_context() tcs.SetCanceled(); #endif - contextPassedToOnRejected!.Should().NotBeNull(); - contextPassedToOnRejected!.OperationKey.Should().Be(operationKey); - contextPassedToOnRejected!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnRejected!.ShouldNotBeNull(); + contextPassedToOnRejected!.OperationKey.ShouldBe(operationKey); + contextPassedToOnRejected!.ShouldBeSameAs(contextPassedToExecute); } #endregion diff --git a/test/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs b/test/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs index d8b0244238..a7570fa40d 100644 --- a/test/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs +++ b/test/Polly.Specs/Bulkhead/BulkheadSpecsBase.cs @@ -334,7 +334,7 @@ protected void Within(TimeSpan timeSpan, Func actionContainin if (watch.Elapsed > permitted) { TestOutputHelper.WriteLine("Failing assertion on: {0}", potentialFailure.Measure); - potentialFailure.Actual.Should().Be(potentialFailure.Expected, $"for '{potentialFailure.Measure}', in scenario: {Scenario}"); + potentialFailure.Actual.ShouldBe(potentialFailure.Expected, $"for '{potentialFailure.Measure}', in scenario: {Scenario}"); throw new InvalidOperationException("Code should never reach here. Preceding assertion should fail."); } diff --git a/test/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs b/test/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs index 5a0110f16d..6d317344f8 100644 --- a/test/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Bulkhead/BulkheadTResultAsyncSpecs.cs @@ -1,13 +1,8 @@ namespace Polly.Specs.Bulkhead; [Collection(Constants.ParallelThreadDependentTestCollection)] -public class BulkheadTResultAsyncSpecs : BulkheadSpecsBase +public class BulkheadTResultAsyncSpecs(ITestOutputHelper testOutputHelper) : BulkheadSpecsBase(testOutputHelper) { - public BulkheadTResultAsyncSpecs(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - #region Configuration [Fact] @@ -31,10 +26,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -43,8 +38,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero_and_no_ma Action policy = () => Policy .BulkheadAsync(0); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -53,8 +48,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero() Action policy = () => Policy .BulkheadAsync(0, 1); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -63,8 +58,8 @@ public void Should_throw_when_maxQueuingActions_less_than_zero() Action policy = () => Policy .BulkheadAsync(1, -1); - policy.Should().Throw().And - .ParamName.Should().Be("maxQueuingActions"); + Should.Throw(policy) + .ParamName.ShouldBe("maxQueuingActions"); } [Fact] @@ -73,8 +68,8 @@ public void Should_throw_when_onBulkheadRejected_is_null() Action policy = () => Policy .BulkheadAsync(1, 0, null!); - policy.Should().Throw().And - .ParamName.Should().Be("onBulkheadRejectedAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onBulkheadRejectedAsync"); } #endregion @@ -105,7 +100,7 @@ public async Task Should_call_onBulkheadRejected_with_passed_context() Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - await bulkhead.Awaiting(b => b.ExecuteAsync(_ => Task.FromResult(1), contextPassedToExecute)).Should().ThrowAsync(); + await Should.ThrowAsync(() => bulkhead.ExecuteAsync(_ => Task.FromResult(1), contextPassedToExecute)); cancellationSource.Cancel(); @@ -116,9 +111,9 @@ public async Task Should_call_onBulkheadRejected_with_passed_context() #endif } - contextPassedToOnRejected!.Should().NotBeNull(); - contextPassedToOnRejected!.OperationKey.Should().Be(operationKey); - contextPassedToOnRejected!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnRejected.ShouldNotBeNull(); + contextPassedToOnRejected.OperationKey.ShouldBe(operationKey); + contextPassedToOnRejected.ShouldBeSameAs(contextPassedToExecute); } #endregion diff --git a/test/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs b/test/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs index 1ec23064c7..94994fcdb6 100644 --- a/test/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs +++ b/test/Polly.Specs/Bulkhead/BulkheadTResultSpecs.cs @@ -1,13 +1,8 @@ namespace Polly.Specs.Bulkhead; [Collection(Constants.ParallelThreadDependentTestCollection)] -public class BulkheadTResultSpecs : BulkheadSpecsBase +public class BulkheadTResultSpecs(ITestOutputHelper testOutputHelper) : BulkheadSpecsBase(testOutputHelper) { - public BulkheadTResultSpecs(ITestOutputHelper testOutputHelper) - : base(testOutputHelper) - { - } - #region Configuration [Fact] @@ -31,10 +26,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -43,8 +38,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero_and_no_ma Action policy = () => Policy .Bulkhead(0); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -53,8 +48,8 @@ public void Should_throw_when_maxParallelization_less_or_equal_to_zero() Action policy = () => Policy .Bulkhead(0, 1); - policy.Should().Throw().And - .ParamName.Should().Be("maxParallelization"); + Should.Throw(policy) + .ParamName.ShouldBe("maxParallelization"); } [Fact] @@ -63,8 +58,8 @@ public void Should_throw_when_maxQueuingActions_less_than_zero() Action policy = () => Policy .Bulkhead(1, -1); - policy.Should().Throw().And - .ParamName.Should().Be("maxQueuingActions"); + Should.Throw(policy) + .ParamName.ShouldBe("maxQueuingActions"); } [Fact] @@ -73,8 +68,8 @@ public void Should_throw_when_onBulkheadRejected_is_null() Action policy = () => Policy .Bulkhead(1, 0, null!); - policy.Should().Throw().And - .ParamName.Should().Be("onBulkheadRejected"); + Should.Throw(policy) + .ParamName.ShouldBe("onBulkheadRejected"); } #endregion @@ -105,7 +100,7 @@ public void Should_call_onBulkheadRejected_with_passed_context() Within(CohesionTimeLimit, () => Expect(0, () => bulkhead.BulkheadAvailableCount, nameof(bulkhead.BulkheadAvailableCount))); - bulkhead.Invoking(b => b.Execute(_ => 1, contextPassedToExecute)).Should().Throw(); + Should.Throw(() => bulkhead.Execute(_ => 1, contextPassedToExecute)); cancellationSource.Cancel(); @@ -116,9 +111,9 @@ public void Should_call_onBulkheadRejected_with_passed_context() #endif } - contextPassedToOnRejected!.Should().NotBeNull(); - contextPassedToOnRejected!.OperationKey.Should().Be(operationKey); - contextPassedToOnRejected!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnRejected!.ShouldNotBeNull(); + contextPassedToOnRejected!.OperationKey.ShouldBe(operationKey); + contextPassedToOnRejected!.ShouldBeSameAs(contextPassedToExecute); } #endregion diff --git a/test/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs b/test/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs index 56f4c5fbba..8b31ef3a62 100644 --- a/test/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs +++ b/test/Polly.Specs/Bulkhead/IBulkheadPolicySpecs.cs @@ -7,7 +7,7 @@ public void Should_be_able_to_use_BulkheadAvailableCount_via_interface() { IBulkheadPolicy bulkhead = Policy.Bulkhead(20, 10); - bulkhead.BulkheadAvailableCount.Should().Be(20); + bulkhead.BulkheadAvailableCount.ShouldBe(20); } [Fact] @@ -15,6 +15,6 @@ public void Should_be_able_to_use_QueueAvailableCount_via_interface() { IBulkheadPolicy bulkhead = Policy.Bulkhead(20, 10); - bulkhead.QueueAvailableCount.Should().Be(10); + bulkhead.QueueAvailableCount.ShouldBe(10); } } diff --git a/test/Polly.Specs/Caching/AbsoluteTtlSpecs.cs b/test/Polly.Specs/Caching/AbsoluteTtlSpecs.cs index 86679a7cb0..fc69ee2694 100644 --- a/test/Polly.Specs/Caching/AbsoluteTtlSpecs.cs +++ b/test/Polly.Specs/Caching/AbsoluteTtlSpecs.cs @@ -8,7 +8,7 @@ public void Should_be_able_to_configure_for_near_future_time() { Action configure = () => _ = new AbsoluteTtl(DateTimeOffset.UtcNow.Date.AddDays(1)); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -16,7 +16,7 @@ public void Should_be_able_to_configure_for_far_future() { Action configure = () => _ = new AbsoluteTtl(DateTimeOffset.MaxValue); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -24,7 +24,7 @@ public void Should_be_able_to_configure_for_past() { Action configure = () => _ = new AbsoluteTtl(DateTimeOffset.MinValue); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -32,7 +32,7 @@ public void Should_return_zero_ttl_if_configured_to_expire_in_past() { AbsoluteTtl ttlStrategy = new AbsoluteTtl(SystemClock.DateTimeOffsetUtcNow().Subtract(TimeSpan.FromTicks(1))); - ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.Should().Be(TimeSpan.Zero); + ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.ShouldBe(TimeSpan.Zero); } [Fact] @@ -44,7 +44,7 @@ public void Should_return_timespan_reflecting_time_until_expiry() AbsoluteTtl ttlStrategy = new AbsoluteTtl(tomorrow); SystemClock.DateTimeOffsetUtcNow = () => today; - ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.Should().Be(TimeSpan.FromDays(1)); + ttlStrategy.GetTtl(new Context("someOperationKey"), null).Timespan.ShouldBe(TimeSpan.FromDays(1)); } public void Dispose() => diff --git a/test/Polly.Specs/Caching/AsyncSerializingCacheProviderSpecs.cs b/test/Polly.Specs/Caching/AsyncSerializingCacheProviderSpecs.cs index 00d606f5cc..c809c59dbe 100644 --- a/test/Polly.Specs/Caching/AsyncSerializingCacheProviderSpecs.cs +++ b/test/Polly.Specs/Caching/AsyncSerializingCacheProviderSpecs.cs @@ -15,8 +15,8 @@ public void Single_generic_constructor_should_throw_on_no_wrapped_cache_provider Action configure = () => _ = new AsyncSerializingCacheProvider(null!, stubObjectSerializer); - configure.Should().Throw() - .And.ParamName.Should().Be("wrappedCacheProvider"); + Should.Throw(configure) + .ParamName.ShouldBe("wrappedCacheProvider"); } [Fact] @@ -24,8 +24,8 @@ public void Single_generic_constructor_should_throw_on_no_serializer() { Action configure = () => _ = new AsyncSerializingCacheProvider(new StubCacheProvider().AsyncFor(), null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -33,8 +33,8 @@ public void Single_generic_extension_syntax_should_throw_on_no_serializer() { Action configure = () => new StubCacheProvider().AsyncFor().WithSerializer(null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -51,13 +51,13 @@ public async Task Single_generic_SerializingCacheProvider_should_serialize_on_pu AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -74,13 +74,13 @@ public async Task Single_generic_SerializingCacheProvider_should_serialize_on_pu AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -100,9 +100,9 @@ public async Task Single_generic_SerializingCacheProvider_should_deserialize_on_ AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); (bool cacheHit, object? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -115,14 +115,14 @@ public async Task Single_generic_SerializingCacheProvider_should_not_deserialize var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); AsyncSerializingCacheProvider serializingCacheProvider = new AsyncSerializingCacheProvider(stubCacheProvider.AsyncFor(), stubSerializer); (bool cacheHit, object? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(default); } [Fact] @@ -139,13 +139,13 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -162,13 +162,13 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -188,9 +188,9 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); (bool cacheHit, object? fromCache) = await serializingCacheProvider.TryGetAsync(key, cancellationToken, false); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -203,14 +203,14 @@ public async Task Single_generic_SerializingCacheProvider_from_extension_syntax_ var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); AsyncSerializingCacheProvider serializingCacheProvider = stubCacheProvider.AsyncFor().WithSerializer(stubSerializer); (bool cacheHit, object? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(default); } #endregion @@ -226,8 +226,8 @@ public void Double_generic_constructor_should_throw_on_no_wrapped_cache_provider Action configure = () => _ = new AsyncSerializingCacheProvider>(null!, stubTResultSerializer); - configure.Should().Throw() - .And.ParamName.Should().Be("wrappedCacheProvider"); + Should.Throw(configure) + .ParamName.ShouldBe("wrappedCacheProvider"); } [Fact] @@ -235,8 +235,8 @@ public void Double_generic_constructor_should_throw_on_no_serializer() { Action configure = () => _ = new AsyncSerializingCacheProvider(new StubCacheProvider().AsyncFor(), null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -244,8 +244,8 @@ public void Double_generic_extension_syntax_should_throw_on_no_serializer() { Action configure = () => new StubCacheProvider().AsyncFor().WithSerializer(null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -262,13 +262,13 @@ public async Task Double_generic_SerializingCacheProvider_should_serialize_on_pu AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -285,13 +285,13 @@ public async Task Double_generic_SerializingCacheProvider_should_serialize_on_pu AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -310,9 +310,9 @@ public async Task Double_generic_SerializingCacheProvider_should_deserialize_on_ await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); (bool cacheHit, object? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -325,14 +325,14 @@ public async Task Double_generic_SerializingCacheProvider_should_not_deserialize var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); AsyncSerializingCacheProvider> serializingCacheProvider = new AsyncSerializingCacheProvider>(stubCacheProvider.AsyncFor>(), stubTResultSerializer); (bool cacheHit, ResultPrimitive? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(ResultPrimitive.Undefined); } [Fact] @@ -350,12 +350,12 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -373,13 +373,13 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); await serializingCacheProvider.PutAsync(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -399,9 +399,9 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ await stubCacheProvider.PutAsync(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1)), CancellationToken, false); (bool cacheHit, ResultPrimitive? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -414,15 +414,15 @@ public async Task Double_generic_SerializingCacheProvider_from_extension_syntax_ var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); AsyncSerializingCacheProvider> serializingCacheProvider = stubCacheProvider.AsyncFor>().WithSerializer(stubTResultSerializer); (bool cacheHit, ResultPrimitive? fromCache) = await serializingCacheProvider.TryGetAsync(key, CancellationToken, false); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(ResultPrimitive.Undefined); } #endregion diff --git a/test/Polly.Specs/Caching/CacheAsyncSpecs.cs b/test/Polly.Specs/Caching/CacheAsyncSpecs.cs index 578b2a572a..535bdab48e 100644 --- a/test/Polly.Specs/Caching/CacheAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/CacheAsyncSpecs.cs @@ -45,19 +45,19 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task" }); func = () => methodInfo.Invoke(instance, [actionVoid, new Context(), CancellationToken, false]); - exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -73,46 +73,46 @@ public void Should_throw_when_cache_provider_is_null() const string CacheProviderExpected = "cacheProvider"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); } [Fact] public void Should_throw_when_ttl_strategy_is_null() { - IAsyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ITtlStrategy ttlStrategy = null!; ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); Func cacheKeyStrategyFunc = (_) => string.Empty; @@ -121,28 +121,28 @@ public void Should_throw_when_ttl_strategy_is_null() const string TtlStrategyExpected = "ttlStrategy"; Action action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); } [Fact] public void Should_throw_when_cache_key_strategy_is_null() { - IAsyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); ICacheKeyStrategy cacheKeyStrategy = null!; @@ -152,16 +152,16 @@ public void Should_throw_when_cache_key_strategy_is_null() const string CacheKeyStrategyExpected = "cacheKeyStrategy"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync( cacheProvider, @@ -172,7 +172,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync( cacheProvider, @@ -183,7 +183,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync( cacheProvider, @@ -194,7 +194,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync( cacheProvider, @@ -205,13 +205,13 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); } [Fact] public void Should_throw_when_on_cache_get_is_null() { - IAsyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); @@ -222,31 +222,31 @@ public void Should_throw_when_on_cache_get_is_null() const string OnCacheGetExpected = "onCacheGet"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); } [Fact] public void Should_throw_when_on_cache_miss_is_null() { - IAsyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); - ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); + var cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); Func cacheKeyStrategyFunc = (_) => string.Empty; Action onCacheMiss = null!; Action onCache = (_, _) => { }; @@ -254,22 +254,22 @@ public void Should_throw_when_on_cache_miss_is_null() const string OnCacheMissExpected = "onCacheMiss"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); } [Fact] @@ -286,22 +286,22 @@ public void Should_throw_when_on_cache_put_is_null() const string OnCachePutExpected = "onCachePut"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); } [Fact] @@ -311,10 +311,10 @@ public void Should_throw_when_policies_is_null() IAsyncPolicy[] policiesGeneric = null!; Action action = () => Policy.WrapAsync(policies); - action.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(action).ParamName.ShouldBe("policies"); action = () => Policy.WrapAsync(policiesGeneric); - action.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(action).ParamName.ShouldBe("policies"); } #endregion @@ -327,7 +327,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -339,9 +339,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -350,18 +350,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } [Fact] @@ -370,13 +370,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - TimeSpan ttl = TimeSpan.FromMinutes(30); + var stubCacheProvider = new StubCacheProvider(); + var ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); int delegateInvocations = 0; Func> func = async _ => @@ -390,24 +390,24 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); // Second execution (before cache expires) should get it from the cache - no further delegate execution. // (Manipulate time so just prior cache expiry). SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); // Manipulate time to force cache expiry. SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1); // Third execution (cache expired) should not get it from the cache - should cause further delegate execution. - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(2); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -416,18 +416,18 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } [Fact] @@ -446,20 +446,20 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); } [Fact] public async Task Should_allow_custom_FuncCacheKeyStrategy() { - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); object person1 = new(); @@ -470,11 +470,11 @@ public async Task Should_allow_custom_FuncCacheKeyStrategy() bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new object(); }; - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } [Fact] @@ -483,8 +483,8 @@ public async Task Should_allow_custom_ICacheKeyStrategy() Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); + var stubCacheProvider = new StubCacheProvider(); + var cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); object person1 = new(); @@ -495,11 +495,11 @@ public async Task Should_allow_custom_ICacheKeyStrategy() bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new object(); }; - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } #endregion @@ -512,18 +512,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n ResultClass? valueToReturn = null; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -533,7 +533,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -545,9 +545,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return valueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -556,18 +556,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n ResultPrimitive valueToReturn = default; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -575,10 +575,10 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { ResultPrimitive valueToReturnFromCache = default; ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; - valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); + valueToReturnFromExecution.ShouldNotBe(valueToReturnFromCache); const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -590,9 +590,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return valueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -606,7 +606,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(cache, noop); @@ -621,9 +621,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -633,7 +633,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache); @@ -648,9 +648,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -660,7 +660,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache, noop); @@ -675,9 +675,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -699,11 +699,11 @@ public async Task Should_always_execute_delegate_if_execution_key_not_set() return valueToReturn; }; - (await cache.ExecuteAsync(func /*, no operation key */)).Should().Be(valueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func /*, no operation key */)).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func /*, no operation key */)).Should().Be(valueToReturn); - delegateInvocations.Should().Be(2); + (await cache.ExecuteAsync(func /*, no operation key */)).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -717,10 +717,10 @@ public void Should_always_execute_delegate_if_execution_is_void_returning() Func action = async _ => { delegateInvocations++; await TaskHelper.EmptyTask; }; cache.ExecuteAsync(action, new Context(operationKey)); - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); cache.ExecuteAsync(action, new Context(operationKey)); - delegateInvocations.Should().Be(2); + delegateInvocations.ShouldBe(2); } #endregion @@ -733,7 +733,7 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); + var policy = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); int delegateInvocations = 0; @@ -747,16 +747,15 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); tokenSource.Cancel(); - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)); } - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); } [Fact] @@ -765,8 +764,8 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); + var stubCacheProvider = new StubCacheProvider(); + var policy = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); using (var tokenSource = new CancellationTokenSource()) { @@ -778,13 +777,12 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p return ValueToReturn; }; - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)); } (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); } #endregion @@ -795,7 +793,7 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p public async Task Should_call_onError_delegate_if_cache_get_errors() { Exception ex = new Exception(); - IAsyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); + var stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); Exception? exceptionFromCacheProvider = null; @@ -819,18 +817,18 @@ public async Task Should_call_onError_delegate_if_cache_get_errors() return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromExecution); - delegateExecuted.Should().BeTrue(); + .ShouldBe(ValueToReturnFromExecution); + delegateExecuted.ShouldBeTrue(); // And error should be captured by onError delegate. - exceptionFromCacheProvider.Should().Be(ex); + exceptionFromCacheProvider.ShouldBe(ex); } [Fact] public async Task Should_call_onError_delegate_if_cache_put_errors() { - Exception ex = new Exception(); - IAsyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); + var ex = new Exception(); + var stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); Exception? exceptionFromCacheProvider = null; @@ -842,18 +840,18 @@ public async Task Should_call_onError_delegate_if_cache_put_errors() var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).ShouldBe(ValueToReturn); // error should be captured by onError delegate. - exceptionFromCacheProvider.Should().Be(ex); + exceptionFromCacheProvider.ShouldBe(ex); // failed to put it in the cache (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } [Fact] @@ -872,7 +870,7 @@ public async Task Should_execute_oncacheget_after_got_from_cache() Action emptyDelegate = (_, _) => { }; Action onCacheAction = (ctx, key) => { contextPassedToDelegate = ctx; keyPassedToDelegate = key; }; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -883,11 +881,11 @@ public async Task Should_execute_oncacheget_after_got_from_cache() await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, contextToExecute)) - .Should().Be(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + .ShouldBe(ValueToReturnFromCache); + delegateExecuted.ShouldBeFalse(); - contextPassedToDelegate.Should().BeSameAs(contextToExecute); - keyPassedToDelegate.Should().Be(OperationKey); + contextPassedToDelegate.ShouldBeSameAs(contextToExecute); + keyPassedToDelegate.ShouldBe(OperationKey); } [Fact] @@ -908,23 +906,23 @@ public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_ho Action onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; }; Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); - contextPassedToOnCachePut.Should().BeSameAs(contextToExecute); - keyPassedToOnCachePut.Should().Be(OperationKey); - contextPassedToOnCacheMiss.Should().NotBeNull(); - keyPassedToOnCacheMiss.Should().Be("SomeOperationKey"); + contextPassedToOnCachePut.ShouldBeSameAs(contextToExecute); + keyPassedToOnCachePut.ShouldBe(OperationKey); + contextPassedToOnCacheMiss.ShouldNotBeNull(); + keyPassedToOnCacheMiss.ShouldBe("SomeOperationKey"); } [Fact] @@ -945,19 +943,19 @@ public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_no Action onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; }; Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).ShouldBe(ValueToReturn); - contextPassedToOnCachePut.Should().BeNull(); - keyPassedToOnCachePut.Should().BeNull(); - contextPassedToOnCacheMiss.Should().BeEmpty(); - keyPassedToOnCacheMiss.Should().Be("SomeOperationKey"); + contextPassedToOnCachePut.ShouldBeNull(); + keyPassedToOnCachePut.ShouldBeNull(); + contextPassedToOnCacheMiss.ShouldBeEmpty(); + keyPassedToOnCacheMiss.ShouldBe("SomeOperationKey"); } [Fact] @@ -978,9 +976,9 @@ public async Task Should_not_execute_oncachemiss_if_dont_query_cache_because_cac await TaskHelper.EmptyTask; return valueToReturn; } /*, no operation key */)) - .Should().Be(valueToReturn); + .ShouldBe(valueToReturn); - onCacheMissExecuted.Should().BeFalse(); + onCacheMissExecuted.ShouldBeFalse(); } #endregion diff --git a/test/Polly.Specs/Caching/CacheSpecs.cs b/test/Polly.Specs/Caching/CacheSpecs.cs index 69aabd8b2c..31b06bc23b 100644 --- a/test/Polly.Specs/Caching/CacheSpecs.cs +++ b/test/Polly.Specs/Caching/CacheSpecs.cs @@ -44,19 +44,19 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), cancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "Void" }); func = () => methodInfo.Invoke(instance, [actionVoid, new Context(), cancellationToken]); - exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -72,40 +72,40 @@ public void Should_throw_when_cache_provider_is_null() const string CacheProviderExpected = "cacheProvider"; Action action = () => Policy.Cache(cacheProvider, ttl, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); } [Fact] @@ -120,22 +120,22 @@ public void Should_throw_when_ttl_strategy_is_null() const string TtlStrategyExpected = "ttlStrategy"; Action action = () => Policy.Cache(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); } [Fact] @@ -151,16 +151,16 @@ public void Should_throw_when_cache_key_strategy_is_null() const string CacheKeyStrategyExpected = "cacheKeyStrategy"; Action action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -171,7 +171,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -182,7 +182,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -193,7 +193,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -204,7 +204,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); } [Fact] @@ -221,22 +221,22 @@ public void Should_throw_when_on_cache_get_is_null() const string OnCacheGetExpected = "onCacheGet"; Action action = () => Policy.Cache(cacheProvider, ttl, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheGet, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); } [Fact] @@ -253,22 +253,22 @@ public void Should_throw_when_on_cache_miss_is_null() const string OnCacheMissExpected = "onCacheMiss"; Action action = () => Policy.Cache(cacheProvider, ttl, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCacheMiss, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); } [Fact] @@ -285,22 +285,22 @@ public void Should_throw_when_on_cache_put_is_null() const string OnCachePutExpected = "onCachePut"; Action action = () => Policy.Cache(cacheProvider, ttl, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCache, onCache, onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); } [Fact] @@ -310,10 +310,10 @@ public void Should_throw_when_policies_is_null() ISyncPolicy[] policiesGeneric = null!; Action action = () => Policy.Wrap(policies); - action.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(action).ParamName.ShouldBe("policies"); action = () => Policy.Wrap(policiesGeneric); - action.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(action).ParamName.ShouldBe("policies"); } #endregion @@ -327,7 +327,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -338,9 +338,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -349,18 +349,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } [Fact] @@ -369,13 +369,13 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - TimeSpan ttl = TimeSpan.FromMinutes(30); + var stubCacheProvider = new StubCacheProvider(); + var ttl = TimeSpan.FromMinutes(30); CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); int delegateInvocations = 0; Func func = _ => @@ -388,25 +388,25 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); // Second execution (before cache expires) should get it from the cache - no further delegate execution. // (Manipulate time so just prior cache expiry). SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); // Manipulate time to force cache expiry. SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1); // Third execution (cache expired) should not get it from the cache - should cause further delegate execution. - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(2); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -415,18 +415,18 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } [Fact] @@ -444,20 +444,20 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe return ValueToReturn; }; - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); } [Fact] public void Should_allow_custom_FuncCacheKeyStrategy() { - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); object person1 = new(); @@ -468,11 +468,11 @@ public void Should_allow_custom_FuncCacheKeyStrategy() bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new object(); }; - cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } [Fact] @@ -481,8 +481,8 @@ public void Should_allow_custom_ICacheKeyStrategy() Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); + var stubCacheProvider = new StubCacheProvider(); + var cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); object person1 = new(); @@ -493,11 +493,11 @@ public void Should_allow_custom_ICacheKeyStrategy() bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new object(); }; - cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } #endregion @@ -510,18 +510,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol ResultClass? valueToReturn = null; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -531,7 +531,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -542,9 +542,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return valueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -553,18 +553,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol ResultPrimitive valueToReturn = default; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -572,10 +572,10 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { ResultPrimitive valueToReturnFromCache = default; ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; - valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); + valueToReturnFromExecution.ShouldNotBe(valueToReturnFromCache); const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -586,9 +586,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return valueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -602,7 +602,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(cache, noop); @@ -616,9 +616,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -628,7 +628,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache); @@ -642,9 +642,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -654,7 +654,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache, noop); @@ -668,9 +668,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -691,11 +691,11 @@ public void Should_always_execute_delegate_if_execution_key_not_set() return valueToReturn; }; - cache.Execute(func /*, no operation key */).Should().Be(valueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func /*, no operation key */).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func /*, no operation key */).Should().Be(valueToReturn); - delegateInvocations.Should().Be(2); + cache.Execute(func /*, no operation key */).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -709,10 +709,10 @@ public void Should_always_execute_delegate_if_execution_is_void_returning() Action action = _ => { delegateInvocations++; }; cache.Execute(action, new Context(operationKey)); - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); cache.Execute(action, new Context(operationKey)); - delegateInvocations.Should().Be(2); + delegateInvocations.ShouldBe(2); } #endregion @@ -725,7 +725,7 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy policy = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); int delegateInvocations = 0; @@ -738,16 +738,15 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() return ValueToReturn; }; - cache.Execute(func, new Context(OperationKey), tokenSource.Token).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + policy.Execute(func, new Context(OperationKey), tokenSource.Token).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); tokenSource.Cancel(); - cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(func, new Context(OperationKey), tokenSource.Token)); } - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); } [Fact] @@ -756,8 +755,8 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + var stubCacheProvider = new StubCacheProvider(); + CachePolicy policy = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); using (var tokenSource = new CancellationTokenSource()) { @@ -768,13 +767,12 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ return ValueToReturn; }; - cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(func, new Context(OperationKey), tokenSource.Token)); } (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); } #endregion @@ -785,7 +783,7 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ public void Should_call_onError_delegate_if_cache_get_errors() { Exception ex = new Exception(); - ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); + var stubCacheProvider = new StubErroringCacheProvider(getException: ex, putException: null); Exception? exceptionFromCacheProvider = null; @@ -807,18 +805,18 @@ public void Should_call_onError_delegate_if_cache_get_errors() delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromExecution); - delegateExecuted.Should().BeTrue(); + .ShouldBe(ValueToReturnFromExecution); + delegateExecuted.ShouldBeTrue(); // And error should be captured by onError delegate. - exceptionFromCacheProvider.Should().Be(ex); + exceptionFromCacheProvider.ShouldBe(ex); } [Fact] public void Should_call_onError_delegate_if_cache_put_errors() { Exception ex = new Exception(); - ISyncCacheProvider stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); + var stubCacheProvider = new StubErroringCacheProvider(getException: null, putException: ex); Exception? exceptionFromCacheProvider = null; @@ -830,18 +828,18 @@ public void Should_call_onError_delegate_if_cache_put_errors() CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); // error should be captured by onError delegate. - exceptionFromCacheProvider.Should().Be(ex); + exceptionFromCacheProvider.ShouldBe(ex); // failed to put it in the cache (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } @@ -861,7 +859,7 @@ public void Should_execute_oncacheget_after_got_from_cache() Action emptyDelegate = (_, _) => { }; Action onCacheAction = (ctx, key) => { contextPassedToDelegate = ctx; keyPassedToDelegate = key; }; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, onCacheAction, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -871,11 +869,11 @@ public void Should_execute_oncacheget_after_got_from_cache() delegateExecuted = true; return ValueToReturnFromExecution; }, contextToExecute) - .Should().Be(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + .ShouldBe(ValueToReturnFromCache); + delegateExecuted.ShouldBeFalse(); - contextPassedToDelegate.Should().BeSameAs(contextToExecute); - keyPassedToDelegate.Should().Be(OperationKey); + contextPassedToDelegate.ShouldBeSameAs(contextToExecute); + keyPassedToDelegate.ShouldBe(OperationKey); } [Fact] @@ -896,24 +894,24 @@ public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_val Action onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; }; Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, contextToExecute).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, contextToExecute).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); - contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute); - keyPassedToOnCacheMiss.Should().Be(OperationKey); + contextPassedToOnCacheMiss.ShouldBeSameAs(contextToExecute); + keyPassedToOnCacheMiss.ShouldBe(OperationKey); - contextPassedToOnCachePut.Should().BeSameAs(contextToExecute); - keyPassedToOnCachePut.Should().Be(OperationKey); + contextPassedToOnCachePut.ShouldBeSameAs(contextToExecute); + keyPassedToOnCachePut.ShouldBe(OperationKey); } [Fact] @@ -934,20 +932,20 @@ public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold Action onCacheMiss = (ctx, key) => { contextPassedToOnCacheMiss = ctx; keyPassedToOnCacheMiss = key; }; Action onCachePut = (ctx, key) => { contextPassedToOnCachePut = ctx; keyPassedToOnCachePut = key; }; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, new RelativeTtl(TimeSpan.Zero), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, onCachePut, noErrorHandling, noErrorHandling); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, contextToExecute).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, contextToExecute).ShouldBe(ValueToReturn); - contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute); - keyPassedToOnCacheMiss.Should().Be(OperationKey); + contextPassedToOnCacheMiss.ShouldBeSameAs(contextToExecute); + keyPassedToOnCacheMiss.ShouldBe(OperationKey); - contextPassedToOnCachePut.Should().BeNull(); - keyPassedToOnCachePut.Should().BeNull(); + contextPassedToOnCachePut.ShouldBeNull(); + keyPassedToOnCachePut.ShouldBeNull(); } [Fact] @@ -963,9 +961,9 @@ public void Should_not_execute_oncachemiss_if_dont_query_cache_because_cache_key CachePolicy cache = Policy.Cache(new StubCacheProvider(), new RelativeTtl(TimeSpan.MaxValue), DefaultCacheKeyStrategy.Instance, emptyDelegate, onCacheMiss, emptyDelegate, noErrorHandling, noErrorHandling); - cache.Execute(() => valueToReturn /*, no operation key */).Should().Be(valueToReturn); + cache.Execute(() => valueToReturn /*, no operation key */).ShouldBe(valueToReturn); - onCacheMissExecuted.Should().BeFalse(); + onCacheMissExecuted.ShouldBeFalse(); } #endregion diff --git a/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs b/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs index 2588fa3b97..9b1d093761 100644 --- a/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs @@ -43,10 +43,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -54,7 +54,7 @@ public void Should_throw_when_cache_provider_is_null() { IAsyncCacheProvider cacheProvider = null!; Action action = () => Policy.CacheAsync(cacheProvider, TimeSpan.MaxValue); - action.Should().Throw().And.ParamName.Should().Be("cacheProvider"); + Should.Throw(action).ParamName.ShouldBe("cacheProvider"); } [Fact] @@ -63,15 +63,15 @@ public void Should_throw_when_ttl_strategy_is_null() IAsyncCacheProvider cacheProvider = new StubCacheProvider(); ITtlStrategy ttlStrategy = null!; Action action = () => Policy.CacheAsync(cacheProvider, ttlStrategy); - action.Should().Throw().And.ParamName.Should().Be("ttlStrategy"); + Should.Throw(action).ParamName.ShouldBe("ttlStrategy"); } [Fact] public void Should_throw_when_cache_key_strategy_is_null() { - IAsyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); var ttl = TimeSpan.MaxValue; - ITtlStrategy ttlStrategy = new ContextualTtl(); + var ttlStrategy = new ContextualTtl(); ICacheKeyStrategy cacheKeyStrategy = null!; Func cacheKeyStrategyFunc = null!; Action onCacheGet = (_, _) => { }; @@ -82,42 +82,42 @@ public void Should_throw_when_cache_key_strategy_is_null() const string CacheKeyStrategyExpected = "cacheKeyStrategy"; Action action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategy, onCacheGetError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGetError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.CacheAsync(cacheProvider, ttl, cacheKeyStrategyFunc); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync(cacheProvider.AsyncFor(), ttl, cacheKeyStrategy); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.CacheAsync(cacheProvider.AsyncFor(), ttl, cacheKeyStrategy); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync(cacheProvider.AsyncFor(), ttlStrategy, cacheKeyStrategy); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.CacheAsync(cacheProvider.AsyncFor(), ttlStrategy, cacheKeyStrategy); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttlStrategy.For(), cacheKeyStrategy, onCacheGetError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttl, cacheKeyStrategy, onCacheGetError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttl, cacheKeyStrategy, onCacheGetError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttl, cacheKeyStrategy, @@ -126,9 +126,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCachePut, onCacheGetError, onCachePutError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttlStrategy, cacheKeyStrategy, @@ -137,9 +137,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCachePut, onCacheGetError, onCachePutError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.CacheAsync( + action = () => Policy.CacheAsync( cacheProvider.AsyncFor(), ttlStrategy.For(), cacheKeyStrategy, @@ -148,7 +148,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCachePut, onCacheGetError, onCachePutError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); } #endregion @@ -161,7 +161,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); @@ -173,9 +173,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -184,18 +184,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } [Fact] @@ -204,13 +204,13 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); TimeSpan ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); int delegateInvocations = 0; Func> func = async _ => @@ -224,25 +224,25 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); // Second execution (before cache expires) should get it from the cache - no further delegate execution. // (Manipulate time so just prior cache expiry). SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); // Manipulate time to force cache expiry. SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1); // Third execution (cache expired) should not get it from the cache - should cause further delegate execution. - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(2); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -251,18 +251,18 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).Should().Be(ValueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, new Context(OperationKey))).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } [Fact] @@ -281,20 +281,20 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func, new Context(OperationKey))).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); } [Fact] public async Task Should_allow_custom_FuncCacheKeyStrategy() { - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); object person1 = new ResultClass(ResultPrimitive.Good, "person1"); @@ -305,11 +305,11 @@ public async Task Should_allow_custom_FuncCacheKeyStrategy() bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } [Fact] @@ -318,8 +318,8 @@ public async Task Should_allow_custom_ICacheKeyStrategy() Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); + var stubCacheProvider = new StubCacheProvider(); + var cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); var cache = Policy.CacheAsync(stubCacheProvider.AsyncFor(), new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); @@ -331,11 +331,11 @@ public async Task Should_allow_custom_ICacheKeyStrategy() bool funcExecuted = false; Func> func = async _ => { funcExecuted = true; await TaskHelper.EmptyTask; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "1")))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + (await cache.ExecuteAsync(func, new Context("person", CreateDictionary("id", "2")))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } #endregion @@ -348,18 +348,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n ResultClass? valueToReturn = null; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -369,7 +369,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -381,9 +381,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return valueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -392,18 +392,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_n ResultPrimitive valueToReturn = default; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, new Context(OperationKey))).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -411,10 +411,10 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { ResultPrimitive valueToReturnFromCache = default; ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; - valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); + valueToReturnFromExecution.ShouldNotBe(valueToReturnFromCache); const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken, false); @@ -426,9 +426,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return valueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -442,7 +442,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = cache.WrapAsync(noop); @@ -457,9 +457,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -469,7 +469,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = noop.WrapAsync(cache); @@ -484,9 +484,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -496,7 +496,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache, noop); @@ -511,9 +511,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac await TaskHelper.EmptyTask; return ValueToReturnFromExecution; }, new Context(OperationKey))) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -535,11 +535,11 @@ public async Task Should_always_execute_delegate_if_execution_key_not_set() return valueToReturn; }; - (await cache.ExecuteAsync(func /*, no operation key */)).Should().Be(valueToReturn); - delegateInvocations.Should().Be(1); + (await cache.ExecuteAsync(func /*, no operation key */)).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(1); - (await cache.ExecuteAsync(func /*, no operation key */)).Should().Be(valueToReturn); - delegateInvocations.Should().Be(2); + (await cache.ExecuteAsync(func /*, no operation key */)).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(2); } #endregion @@ -552,7 +552,7 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); + var policy = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); int delegateInvocations = 0; @@ -566,16 +566,15 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + (await policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); tokenSource.Cancel(); - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)); } - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); } [Fact] @@ -584,8 +583,8 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); - var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); + var stubCacheProvider = new StubCacheProvider(); + var policy = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); using (var tokenSource = new CancellationTokenSource()) { @@ -597,13 +596,12 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p return ValueToReturn; }; - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)); } (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken, false); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); } #endregion diff --git a/test/Polly.Specs/Caching/CacheTResultSpecs.cs b/test/Polly.Specs/Caching/CacheTResultSpecs.cs index ae7cced1ae..09bb4b1f1f 100644 --- a/test/Polly.Specs/Caching/CacheTResultSpecs.cs +++ b/test/Polly.Specs/Caching/CacheTResultSpecs.cs @@ -38,10 +38,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -50,31 +50,31 @@ public void Should_throw_when_cache_provider_is_null() ISyncCacheProvider cacheProvider = null!; ISyncCacheProvider cacheProviderGeneric = null!; var ttl = TimeSpan.MaxValue; - ITtlStrategy ttlStrategy = new ContextualTtl(); - ITtlStrategy ttlStrategyGeneric = new ContextualTtl().For(); - ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); + var ttlStrategy = new ContextualTtl(); + var ttlStrategyGeneric = new ContextualTtl().For(); + var cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); Func cacheKeyStrategyFunc = (_) => string.Empty; Action onCache = (_, _) => { }; Action? onCacheError = null; const string CacheProviderExpected = "cacheProvider"; Action action = () => Policy.Cache(cacheProvider, ttl, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -84,7 +84,7 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -94,7 +94,7 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -105,7 +105,7 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -116,7 +116,7 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -127,7 +127,7 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); action = () => Policy.Cache( cacheProvider, @@ -138,36 +138,36 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttl, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttl, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, onCache, @@ -175,9 +175,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, onCache, @@ -185,9 +185,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, onCache, @@ -195,9 +195,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategy, @@ -206,9 +206,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -217,9 +217,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -228,9 +228,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategyFunc, @@ -239,9 +239,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -250,9 +250,9 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -261,13 +261,13 @@ public void Should_throw_when_cache_provider_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheProviderExpected); + Should.Throw(action).ParamName.ShouldBe(CacheProviderExpected); } [Fact] public void Should_throw_when_ttl_strategy_is_null() { - ISyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ISyncCacheProvider cacheProviderGeneric = new StubCacheProvider().For(); ITtlStrategy ttlStrategy = null!; ITtlStrategy ttlStrategyGeneric = null!; @@ -278,16 +278,16 @@ public void Should_throw_when_ttl_strategy_is_null() const string TtlStrategyExpected = "ttlStrategy"; Action action = () => Policy.Cache(cacheProvider, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -297,7 +297,7 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -308,7 +308,7 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -319,39 +319,39 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, onCache, onCache, onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, onCache, @@ -359,9 +359,9 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -370,9 +370,9 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -381,9 +381,9 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -392,9 +392,9 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -403,13 +403,13 @@ public void Should_throw_when_ttl_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(TtlStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(TtlStrategyExpected); } [Fact] public void Should_throw_when_cache_key_strategy_is_null() { - ISyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ISyncCacheProvider cacheProviderGeneric = new StubCacheProvider().For(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); @@ -421,16 +421,16 @@ public void Should_throw_when_cache_key_strategy_is_null() const string CacheKeyStrategyExpected = "cacheKeyStrategy"; Action action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -441,7 +441,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -452,7 +452,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache(cacheProvider, ttl, @@ -462,7 +462,7 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); action = () => Policy.Cache( cacheProvider, @@ -473,27 +473,27 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttl, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + action = () => Policy.Cache(cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, onCacheError); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategy, @@ -502,9 +502,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -513,9 +513,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -524,9 +524,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategyFunc, @@ -535,9 +535,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -546,9 +546,9 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -557,13 +557,13 @@ public void Should_throw_when_cache_key_strategy_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(CacheKeyStrategyExpected); + Should.Throw(action).ParamName.ShouldBe(CacheKeyStrategyExpected); } [Fact] public void Should_throw_when_on_cache_get_is_null() { - ISyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ISyncCacheProvider cacheProviderGeneric = new StubCacheProvider().For(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); @@ -583,7 +583,7 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache( cacheProvider, @@ -593,7 +593,7 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache( cacheProvider, @@ -604,7 +604,7 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache( cacheProvider, @@ -615,7 +615,7 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache( cacheProvider, @@ -626,7 +626,7 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); action = () => Policy.Cache( cacheProvider, @@ -637,9 +637,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, onCacheGet, @@ -647,9 +647,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, onCacheGet, @@ -657,9 +657,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, onCacheGet, @@ -667,9 +667,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategy, @@ -678,9 +678,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -689,9 +689,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -700,9 +700,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategyFunc, @@ -711,9 +711,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -722,9 +722,9 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -733,13 +733,13 @@ public void Should_throw_when_on_cache_get_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheGetExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheGetExpected); } [Fact] public void Should_throw_when_on_cache_miss_is_null() { - ISyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ISyncCacheProvider cacheProviderGeneric = new StubCacheProvider().For(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); @@ -759,7 +759,7 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache( cacheProvider, @@ -769,7 +769,7 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache( cacheProvider, @@ -780,7 +780,7 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache( cacheProvider, @@ -791,7 +791,7 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache( cacheProvider, @@ -802,7 +802,7 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); action = () => Policy.Cache( cacheProvider, @@ -813,9 +813,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, onCache, @@ -823,9 +823,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, onCache, @@ -833,9 +833,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, onCache, @@ -843,9 +843,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategy, @@ -854,9 +854,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -865,9 +865,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -876,9 +876,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategyFunc, @@ -887,9 +887,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -898,9 +898,9 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -909,13 +909,13 @@ public void Should_throw_when_on_cache_miss_is_null() onCache, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCacheMissExpected); + Should.Throw(action).ParamName.ShouldBe(OnCacheMissExpected); } [Fact] public void Should_throw_when_on_cache_put_is_null() { - ISyncCacheProvider cacheProvider = new StubCacheProvider(); + var cacheProvider = new StubCacheProvider(); ISyncCacheProvider cacheProviderGeneric = new StubCacheProvider().For(); var ttl = TimeSpan.MaxValue; ITtlStrategy ttlStrategy = new ContextualTtl(); @@ -935,7 +935,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache( cacheProvider, @@ -945,7 +945,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache( cacheProvider, @@ -956,7 +956,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache( cacheProvider, @@ -967,7 +967,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache( cacheProvider, @@ -978,7 +978,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); action = () => Policy.Cache( cacheProvider, @@ -989,9 +989,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, onCache, @@ -999,9 +999,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, onCache, @@ -1009,9 +1009,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, onCache, @@ -1019,9 +1019,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategy, @@ -1030,9 +1030,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategy, @@ -1041,9 +1041,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategy, @@ -1052,9 +1052,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttl, cacheKeyStrategyFunc, @@ -1063,9 +1063,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategy, cacheKeyStrategyFunc, @@ -1074,9 +1074,9 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); - action = () => Policy.Cache( + action = () => Policy.Cache( cacheProviderGeneric, ttlStrategyGeneric, cacheKeyStrategyFunc, @@ -1085,7 +1085,7 @@ public void Should_throw_when_on_cache_put_is_null() onCachePut, onCacheError, onCacheError); - action.Should().Throw().And.ParamName.Should().Be(OnCachePutExpected); + Should.Throw(action).ParamName.ShouldBe(OnCachePutExpected); } #endregion @@ -1099,7 +1099,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -1110,9 +1110,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -1121,18 +1121,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } [Fact] @@ -1141,13 +1141,13 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - TimeSpan ttl = TimeSpan.FromMinutes(30); + var stubCacheProvider = new StubCacheProvider(); + var ttl = TimeSpan.FromMinutes(30); CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); int delegateInvocations = 0; Func func = _ => @@ -1160,25 +1160,25 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); // Second execution (before cache expires) should get it from the cache - no further delegate execution. // (Manipulate time so just prior cache expiry). SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(-1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); // Manipulate time to force cache expiry. SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(ttl).AddSeconds(1); // Third execution (cache expired) should not get it from the cache - should cause further delegate execution. - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(2); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(2); } [Fact] @@ -1187,18 +1187,18 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeFalse(); - fromCache2.Should().BeNull(); + cacheHit2.ShouldBeFalse(); + fromCache2.ShouldBeNull(); } [Fact] @@ -1216,20 +1216,20 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe return ValueToReturn; }; - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func, new Context(OperationKey)).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); } [Fact] public void Should_allow_custom_FuncICacheKeyStrategy() { - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, context => context.OperationKey + context["id"]); object person1 = new ResultClass(ResultPrimitive.Good, "person1"); @@ -1240,11 +1240,11 @@ public void Should_allow_custom_FuncICacheKeyStrategy() bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; - cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } [Fact] @@ -1253,9 +1253,9 @@ public void Should_allow_custom_ICacheKeyStrategy() Action noErrorHandling = (_, _, _) => { }; Action emptyDelegate = (_, _) => { }; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); ICacheKeyStrategy cacheKeyStrategy = new StubCacheKeyStrategy(context => context.OperationKey + context["id"]); - CachePolicy cache = Policy.Cache(stubCacheProvider.For(), new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); + CachePolicy cache = Policy.Cache(stubCacheProvider.For(), new RelativeTtl(TimeSpan.MaxValue), cacheKeyStrategy, emptyDelegate, emptyDelegate, emptyDelegate, noErrorHandling, noErrorHandling); object person1 = new ResultClass(ResultPrimitive.Good, "person1"); stubCacheProvider.Put("person1", person1, new Ttl(TimeSpan.MaxValue)); @@ -1265,11 +1265,11 @@ public void Should_allow_custom_ICacheKeyStrategy() bool funcExecuted = false; Func func = _ => { funcExecuted = true; return new ResultClass(ResultPrimitive.Fault, "should never return this one"); }; - cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).Should().BeSameAs(person1); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "1"))).ShouldBeSameAs(person1); + funcExecuted.ShouldBeFalse(); - cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).Should().BeSameAs(person2); - funcExecuted.Should().BeFalse(); + cache.Execute(func, new Context("person", CreateDictionary("id", "2"))).ShouldBeSameAs(person2); + funcExecuted.ShouldBeFalse(); } #endregion @@ -1282,18 +1282,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol ResultClass? valueToReturn = null; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -1303,7 +1303,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -1314,9 +1314,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return valueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -1325,18 +1325,18 @@ public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hol ResultPrimitive valueToReturn = default; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).ShouldBe(valueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(valueToReturn); } [Fact] @@ -1344,10 +1344,10 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { ResultPrimitive valueToReturnFromCache = default; ResultPrimitive valueToReturnFromExecution = ResultPrimitive.Good; - valueToReturnFromExecution.Should().NotBe(valueToReturnFromCache); + valueToReturnFromExecution.ShouldNotBe(valueToReturnFromCache); const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); @@ -1358,9 +1358,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return valueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(valueToReturnFromCache); + .ShouldBe(valueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -1374,7 +1374,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = cache.Wrap(noop); @@ -1388,9 +1388,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -1400,7 +1400,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = noop.Wrap(cache); @@ -1414,9 +1414,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } [Fact] @@ -1426,7 +1426,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol const string ValueToReturnFromExecution = "valueToReturnFromExecution"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); + var stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache, noop); @@ -1440,9 +1440,9 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol delegateExecuted = true; return ValueToReturnFromExecution; }, new Context(OperationKey)) - .Should().Be(ValueToReturnFromCache); + .ShouldBe(ValueToReturnFromCache); - delegateExecuted.Should().BeFalse(); + delegateExecuted.ShouldBeFalse(); } #endregion @@ -1463,11 +1463,11 @@ public void Should_always_execute_delegate_if_execution_key_not_set() return valueToReturn; }; - cache.Execute(func /*, no operation key */).Should().Be(valueToReturn); - delegateInvocations.Should().Be(1); + cache.Execute(func /*, no operation key */).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(1); - cache.Execute(func /*, no operation key */).Should().Be(valueToReturn); - delegateInvocations.Should().Be(2); + cache.Execute(func /*, no operation key */).ShouldBe(valueToReturn); + delegateInvocations.ShouldBe(2); } #endregion @@ -1480,7 +1480,7 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); + CachePolicy policy = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); int delegateInvocations = 0; @@ -1493,16 +1493,15 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() return ValueToReturn; }; - cache.Execute(func, new Context(OperationKey), tokenSource.Token).Should().Be(ValueToReturn); - delegateInvocations.Should().Be(1); + policy.Execute(func, new Context(OperationKey), tokenSource.Token).ShouldBe(ValueToReturn); + delegateInvocations.ShouldBe(1); tokenSource.Cancel(); - cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(func, new Context(OperationKey), tokenSource.Token)); } - delegateInvocations.Should().Be(1); + delegateInvocations.ShouldBe(1); } [Fact] @@ -1511,8 +1510,8 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ const string ValueToReturn = "valueToReturn"; const string OperationKey = "SomeOperationKey"; - ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); - CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); + var stubCacheProvider = new StubCacheProvider(); + CachePolicy policy = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); using (var tokenSource = new CancellationTokenSource()) { @@ -1523,13 +1522,12 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ return ValueToReturn; }; - cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(func, new Context(OperationKey), tokenSource.Token)); } (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); } #endregion diff --git a/test/Polly.Specs/Caching/ContextualTtlSpecs.cs b/test/Polly.Specs/Caching/ContextualTtlSpecs.cs index 0cd272bb19..b00be44bb6 100644 --- a/test/Polly.Specs/Caching/ContextualTtlSpecs.cs +++ b/test/Polly.Specs/Caching/ContextualTtlSpecs.cs @@ -7,12 +7,12 @@ public void Should_throw_when_context_is_null() { Context context = null!; Action action = () => new ContextualTtl().GetTtl(context, null); - action.Should().Throw().And.ParamName.Should().Be("context"); + Should.Throw(action).ParamName.ShouldBe("context"); } [Fact] public void Should_return_zero_if_no_value_set_on_context() => - new ContextualTtl().GetTtl(new Context("someOperationKey"), null).Timespan.Should().Be(TimeSpan.Zero); + new ContextualTtl().GetTtl(new Context("someOperationKey"), null).Timespan.ShouldBe(TimeSpan.Zero); [Fact] public void Should_return_zero_if_invalid_value_set_on_context() @@ -23,7 +23,7 @@ public void Should_return_zero_if_invalid_value_set_on_context() }; Context context = new Context(string.Empty, contextData); - new ContextualTtl().GetTtl(context, null).Timespan.Should().Be(TimeSpan.Zero); + new ContextualTtl().GetTtl(context, null).Timespan.ShouldBe(TimeSpan.Zero); } [Fact] @@ -37,8 +37,8 @@ public void Should_return_value_set_on_context() Context context = new Context(string.Empty, contextData); Ttl gotTtl = new ContextualTtl().GetTtl(context, null); - gotTtl.Timespan.Should().Be(ttl); - gotTtl.SlidingExpiration.Should().BeFalse(); + gotTtl.Timespan.ShouldBe(ttl); + gotTtl.SlidingExpiration.ShouldBeFalse(); } [Fact] @@ -52,8 +52,8 @@ public void Should_return_negative_value_set_on_context() Context context = new Context(string.Empty, contextData); Ttl gotTtl = new ContextualTtl().GetTtl(context, null); - gotTtl.Timespan.Should().Be(ttl); - gotTtl.SlidingExpiration.Should().BeFalse(); + gotTtl.Timespan.ShouldBe(ttl); + gotTtl.SlidingExpiration.ShouldBeFalse(); } [Fact] @@ -65,7 +65,7 @@ public void Should_return_zero_if_non_timespan_value_set_on_context() }; Context context = new Context(string.Empty, contextData); - new ContextualTtl().GetTtl(context, null).Timespan.Should().Be(TimeSpan.Zero); + new ContextualTtl().GetTtl(context, null).Timespan.ShouldBe(TimeSpan.Zero); } [Fact] @@ -80,8 +80,8 @@ public void Should_return_sliding_expiration_if_set_on_context() var context = new Context(string.Empty, contextData); var gotTtl = new ContextualTtl().GetTtl(context, null); - gotTtl.Timespan.Should().Be(ttl); - gotTtl.SlidingExpiration.Should().BeTrue(); + gotTtl.Timespan.ShouldBe(ttl); + gotTtl.SlidingExpiration.ShouldBeTrue(); } [Fact] @@ -96,8 +96,8 @@ public void Should_return_no_sliding_expiration_if_set_to_false_on_context() var context = new Context(string.Empty, contextData); var gotTtl = new ContextualTtl().GetTtl(context, null); - gotTtl.Timespan.Should().Be(ttl); - gotTtl.SlidingExpiration.Should().BeFalse(); + gotTtl.Timespan.ShouldBe(ttl); + gotTtl.SlidingExpiration.ShouldBeFalse(); } [Fact] @@ -112,7 +112,7 @@ public void Should_return_no_sliding_expiration_if_non_boolean_value_set_on_cont var context = new Context(string.Empty, contextData); var gotTtl = new ContextualTtl().GetTtl(context, null); - gotTtl.Timespan.Should().Be(ttl); - gotTtl.SlidingExpiration.Should().BeFalse(); + gotTtl.Timespan.ShouldBe(ttl); + gotTtl.SlidingExpiration.ShouldBeFalse(); } } diff --git a/test/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs b/test/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs index 0158dc06a2..f42079cc0d 100644 --- a/test/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs +++ b/test/Polly.Specs/Caching/DefaultCacheKeyStrategySpecs.cs @@ -7,7 +7,7 @@ public void Should_throw_when_context_is_null() { Context context = null!; Action action = () => DefaultCacheKeyStrategy.Instance.GetCacheKey(context); - action.Should().Throw().And.ParamName.Should().Be("context"); + Should.Throw(action).ParamName.ShouldBe("context"); } [Fact] @@ -18,6 +18,6 @@ public void Should_return_Context_OperationKey_as_cache_key() Context context = new Context(operationKey); DefaultCacheKeyStrategy.Instance.GetCacheKey(context) - .Should().Be(operationKey); + .ShouldBe(operationKey); } } diff --git a/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs b/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs index c6fc3b8952..0dee9d9985 100644 --- a/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs @@ -15,8 +15,8 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); ResultPrimitive result = await cache.ExecuteAsync(async _ => { @@ -24,7 +24,7 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache return ResultPrimitive.Substitute; }, new Context(OperationKey)); - onErrorCalled.Should().BeFalse(); + onErrorCalled.ShouldBeFalse(); } [Fact] @@ -38,18 +38,18 @@ public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullabl var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, cancellationToken, false); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ResultPrimitive.Substitute; - }, new Context(OperationKey))).Should().Be(ValueToReturn); + }, new Context(OperationKey))).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, cancellationToken, false); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } public void Dispose() => diff --git a/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs b/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs index 8c0d2cbe92..42c5a505b7 100644 --- a/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs +++ b/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs @@ -15,12 +15,12 @@ public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_ CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); - cacheHit.Should().BeFalse(); - fromCache.Should().BeNull(); + cacheHit.ShouldBeFalse(); + fromCache.ShouldBeNull(); ResultPrimitive result = cache.Execute(_ => ResultPrimitive.Substitute, new Context(OperationKey)); - onErrorCalled.Should().BeFalse(); + onErrorCalled.ShouldBeFalse(); } [Fact] @@ -34,15 +34,15 @@ public void Should_execute_delegate_and_put_value_in_cache_for_non_nullable_type (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); - cacheHit1.Should().BeFalse(); - fromCache1.Should().BeNull(); + cacheHit1.ShouldBeFalse(); + fromCache1.ShouldBeNull(); - cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).ShouldBe(ValueToReturn); (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); - cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(ValueToReturn); + cacheHit2.ShouldBeTrue(); + fromCache2.ShouldBe(ValueToReturn); } public void Dispose() => diff --git a/test/Polly.Specs/Caching/RelativeTtlSpecs.cs b/test/Polly.Specs/Caching/RelativeTtlSpecs.cs index 3f992f7b43..7d56e7d7b5 100644 --- a/test/Polly.Specs/Caching/RelativeTtlSpecs.cs +++ b/test/Polly.Specs/Caching/RelativeTtlSpecs.cs @@ -7,7 +7,7 @@ public void Should_throw_when_timespan_is_less_than_zero() { Action configure = () => _ = new RelativeTtl(TimeSpan.FromMilliseconds(-1)); - configure.Should().Throw().And.ParamName.Should().Be("ttl"); + Should.Throw(configure).ParamName.ShouldBe("ttl"); } [Fact] @@ -15,7 +15,7 @@ public void Should_not_throw_when_timespan_is_zero() { Action configure = () => _ = new RelativeTtl(TimeSpan.Zero); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -23,7 +23,7 @@ public void Should_allow_timespan_max_value() { Action configure = () => _ = new RelativeTtl(TimeSpan.MaxValue); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -34,8 +34,8 @@ public void Should_return_configured_timespan() RelativeTtl ttlStrategy = new RelativeTtl(ttl); Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); - retrieved.Timespan.Should().BeCloseTo(ttl, TimeSpan.Zero); - retrieved.SlidingExpiration.Should().BeFalse(); + retrieved.Timespan.ShouldBe(ttl); + retrieved.SlidingExpiration.ShouldBeFalse(); } [Fact] @@ -50,7 +50,7 @@ public void Should_return_configured_timespan_from_time_requested() SystemClock.DateTimeOffsetUtcNow = () => fixedTime.Add(delay); Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); - retrieved.Timespan.Should().BeCloseTo(ttl, TimeSpan.Zero); - retrieved.SlidingExpiration.Should().BeFalse(); + retrieved.Timespan.ShouldBe(ttl); + retrieved.SlidingExpiration.ShouldBeFalse(); } } diff --git a/test/Polly.Specs/Caching/ResultTtlSpecs.cs b/test/Polly.Specs/Caching/ResultTtlSpecs.cs index 20263362f1..bcb763ccc1 100644 --- a/test/Polly.Specs/Caching/ResultTtlSpecs.cs +++ b/test/Polly.Specs/Caching/ResultTtlSpecs.cs @@ -7,7 +7,7 @@ public void Should_throw_when_func_is_null() { Action configure = () => _ = new ResultTtl((Func)null!); - configure.Should().Throw().And.ParamName.Should().Be("ttlFunc"); + Should.Throw(configure).ParamName.ShouldBe("ttlFunc"); } [Fact] @@ -15,7 +15,7 @@ public void Should_throw_when_func_is_null_using_context() { Action configure = () => _ = new ResultTtl((Func)null!); - configure.Should().Throw().And.ParamName.Should().Be("ttlFunc"); + Should.Throw(configure).ParamName.ShouldBe("ttlFunc"); } [Fact] @@ -23,7 +23,7 @@ public void Should_not_throw_when_func_is_set() { Action configure = () => _ = new ResultTtl(_ => default); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -31,7 +31,7 @@ public void Should_not_throw_when_func_is_set_using_context() { Action configure = () => _ = new ResultTtl((_, _) => default); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -43,8 +43,8 @@ public void Should_return_func_result() ResultTtl ttlStrategy = new ResultTtl(func); Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }); - retrieved.Timespan.Should().Be(ttl); - retrieved.SlidingExpiration.Should().BeFalse(); + retrieved.Timespan.ShouldBe(ttl); + retrieved.SlidingExpiration.ShouldBeFalse(); } [Fact] @@ -57,7 +57,7 @@ public void Should_return_func_result_using_context() ResultTtl ttlStrategy = new ResultTtl(func); - ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }).Timespan.Should().Be(ttl); - ttlStrategy.GetTtl(new Context(SpecialKey), new { Ttl = ttl }).Timespan.Should().Be(TimeSpan.Zero); + ttlStrategy.GetTtl(new Context("someOperationKey"), new { Ttl = ttl }).Timespan.ShouldBe(ttl); + ttlStrategy.GetTtl(new Context(SpecialKey), new { Ttl = ttl }).Timespan.ShouldBe(TimeSpan.Zero); } } diff --git a/test/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs b/test/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs index 847acf9795..227d7a70c6 100644 --- a/test/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs +++ b/test/Polly.Specs/Caching/SerializingCacheProviderSpecs.cs @@ -13,8 +13,8 @@ public void Single_generic_constructor_should_throw_on_no_wrapped_cache_provider Action configure = () => _ = new SerializingCacheProvider(null!, stubObjectSerializer); - configure.Should().Throw() - .And.ParamName.Should().Be("wrappedCacheProvider"); + Should.Throw(configure) + .ParamName.ShouldBe("wrappedCacheProvider"); } [Fact] @@ -22,8 +22,8 @@ public void Single_generic_constructor_should_throw_on_no_serializer() { Action configure = () => _ = new SerializingCacheProvider(new StubCacheProvider().For(), null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -31,8 +31,8 @@ public void Single_generic_extension_syntax_should_throw_on_no_serializer() { Action configure = () => new StubCacheProvider().For().WithSerializer(null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -49,13 +49,13 @@ public void Single_generic_SerializingCacheProvider_should_serialize_on_put() SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -72,13 +72,13 @@ public void Single_generic_SerializingCacheProvider_should_serialize_on_put_for_ SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -98,9 +98,9 @@ public void Single_generic_SerializingCacheProvider_should_deserialize_on_get() SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); (bool cacheHit, object? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -113,14 +113,14 @@ public void Single_generic_SerializingCacheProvider_should_not_deserialize_on_ge var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); SerializingCacheProvider serializingCacheProvider = new SerializingCacheProvider(stubCacheProvider.For(), stubSerializer); (bool cacheHit, object? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(default); } [Fact] @@ -137,13 +137,13 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -160,13 +160,13 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType() + .Original.ShouldBe(objectToCache); } [Fact] @@ -185,9 +185,9 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); (bool cacheHit, object? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -200,14 +200,14 @@ public void Single_generic_SerializingCacheProvider_from_extension_syntax_should var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); SerializingCacheProvider serializingCacheProvider = stubCacheProvider.For().WithSerializer(stubSerializer); (bool cacheHit, object? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(default); } #endregion @@ -223,8 +223,8 @@ public void Double_generic_constructor_should_throw_on_no_wrapped_cache_provider Action configure = () => _ = new SerializingCacheProvider>(null!, stubTResultSerializer); - configure.Should().Throw() - .And.ParamName.Should().Be("wrappedCacheProvider"); + Should.Throw(configure) + .ParamName.ShouldBe("wrappedCacheProvider"); } [Fact] @@ -232,8 +232,8 @@ public void Double_generic_constructor_should_throw_on_no_serializer() { Action configure = () => _ = new SerializingCacheProvider(new StubCacheProvider().For(), null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -241,8 +241,8 @@ public void Double_generic_extension_syntax_should_throw_on_no_serializer() { Action configure = () => new StubCacheProvider().For().WithSerializer(null!); - configure.Should().Throw() - .And.ParamName.Should().Be("serializer"); + Should.Throw(configure) + .ParamName.ShouldBe("serializer"); } [Fact] @@ -259,13 +259,13 @@ public void Double_generic_SerializingCacheProvider_should_serialize_on_put() SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -282,13 +282,13 @@ public void Double_generic_SerializingCacheProvider_should_serialize_on_put_for_ SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -307,9 +307,9 @@ public void Double_generic_SerializingCacheProvider_should_deserialize_on_get() stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); (bool cacheHit, object fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -322,14 +322,14 @@ public void Double_generic_SerializingCacheProvider_should_not_deserialize_on_ge var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item1.Should().BeFalse(); + stubCacheProvider.TryGet(key).Item1.ShouldBeFalse(); SerializingCacheProvider> serializingCacheProvider = new SerializingCacheProvider>(stubCacheProvider.For>(), stubTResultSerializer); (bool cacheHit, ResultPrimitive fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(default); } [Fact] @@ -347,13 +347,13 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should stubCacheProvider.For>().WithSerializer(stubTResultSerializer); serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -372,13 +372,13 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should serializingCacheProvider.Put(key, objectToCache, new Ttl(TimeSpan.FromMinutes(1))); - serializeInvoked.Should().BeTrue(); + serializeInvoked.ShouldBeTrue(); (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - fromCache.Should().BeOfType>() - .Which.Original.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + fromCache.ShouldBeOfType>() + .Original.ShouldBe(objectToCache); } [Fact] @@ -398,9 +398,9 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should stubCacheProvider.Put(key, new StubSerialized(objectToCache), new Ttl(TimeSpan.FromMinutes(1))); (bool cacheHit, ResultPrimitive? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeTrue(); - deserializeInvoked.Should().BeTrue(); - fromCache.Should().Be(objectToCache); + cacheHit.ShouldBeTrue(); + deserializeInvoked.ShouldBeTrue(); + fromCache.ShouldBe(objectToCache); } [Fact] @@ -413,15 +413,15 @@ public void Double_generic_SerializingCacheProvider_from_extension_syntax_should var stubCacheProvider = new StubCacheProvider(); string key = "some key"; - stubCacheProvider.TryGet(key).Item2.Should().BeNull(); + stubCacheProvider.TryGet(key).Item2.ShouldBeNull(); SerializingCacheProvider> serializingCacheProvider = stubCacheProvider.For>().WithSerializer(stubTResultSerializer); (bool cacheHit, ResultPrimitive? fromCache) = serializingCacheProvider.TryGet(key); - cacheHit.Should().BeFalse(); - deserializeInvoked.Should().BeFalse(); - fromCache.Should().Be(default); + cacheHit.ShouldBeFalse(); + deserializeInvoked.ShouldBeFalse(); + fromCache.ShouldBe(ResultPrimitive.Undefined); } #endregion diff --git a/test/Polly.Specs/Caching/SlidingTtlSpecs.cs b/test/Polly.Specs/Caching/SlidingTtlSpecs.cs index 4ee172443c..95f3bc7c8e 100644 --- a/test/Polly.Specs/Caching/SlidingTtlSpecs.cs +++ b/test/Polly.Specs/Caching/SlidingTtlSpecs.cs @@ -7,7 +7,7 @@ public void Should_throw_when_timespan_is_less_than_zero() { Action configure = () => _ = new SlidingTtl(TimeSpan.FromMilliseconds(-1)); - configure.Should().Throw().And.ParamName.Should().Be("slidingTtl"); + Should.Throw(configure).ParamName.ShouldBe("slidingTtl"); } [Fact] @@ -15,7 +15,7 @@ public void Should_not_throw_when_timespan_is_zero() { Action configure = () => _ = new SlidingTtl(TimeSpan.Zero); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -23,7 +23,7 @@ public void Should_allow_timespan_max_value() { Action configure = () => _ = new SlidingTtl(TimeSpan.MaxValue); - configure.Should().NotThrow(); + Should.NotThrow(configure); } [Fact] @@ -34,7 +34,7 @@ public void Should_return_configured_timespan() SlidingTtl ttlStrategy = new SlidingTtl(ttl); Ttl retrieved = ttlStrategy.GetTtl(new Context("someOperationKey"), null); - retrieved.Timespan.Should().Be(ttl); - retrieved.SlidingExpiration.Should().BeTrue(); + retrieved.Timespan.ShouldBe(ttl); + retrieved.SlidingExpiration.ShouldBeTrue(); } } diff --git a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs index 52b46b76a3..2211312b27 100644 --- a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs @@ -14,8 +14,7 @@ public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.MaxValue); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] @@ -25,9 +24,8 @@ public void Should_throw_if_failure_threshold_is_zero() .Handle() .AdvancedCircuitBreakerAsync(0, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -37,9 +35,8 @@ public void Should_throw_if_failure_threshold_is_less_than_zero() .Handle() .AdvancedCircuitBreakerAsync(-0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -49,7 +46,7 @@ public void Should_be_able_to_handle_a_failure_threshold_of_one() .Handle() .AdvancedCircuitBreakerAsync(1.0, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -59,9 +56,8 @@ public void Should_throw_if_failure_threshold_is_greater_than_one() .Handle() .AdvancedCircuitBreakerAsync(1.01, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -75,9 +71,8 @@ public void Should_throw_if_timeslice_duration_is_less_than_resolution_of_circui 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("samplingDuration"); + Should.Throw(action) + .ParamName.ShouldBe("samplingDuration"); } [Fact] @@ -87,7 +82,7 @@ public void Should_not_throw_if_timeslice_duration_is_resolution_of_circuit() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromMilliseconds(20), 4, TimeSpan.FromSeconds(30)); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -97,9 +92,8 @@ public void Should_throw_if_minimum_throughput_is_one() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 1, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("minimumThroughput"); + Should.Throw(action) + .ParamName.ShouldBe("minimumThroughput"); } [Fact] @@ -109,9 +103,8 @@ public void Should_throw_if_minimum_throughput_is_less_than_one() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 0, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("minimumThroughput"); + Should.Throw(action) + .ParamName.ShouldBe("minimumThroughput"); } [Fact] @@ -121,9 +114,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -133,7 +125,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -143,7 +135,7 @@ public void Should_initialise_to_closed_state() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -161,7 +153,7 @@ public void Should_initialise_to_closed_state() [Fact] public async Task Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_is_equalled_but_last_call_is_success() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -173,24 +165,20 @@ public async Task Should_not_open_circuit_if_failure_threshold_and_minimum_thres durationOfBreak: TimeSpan.FromSeconds(30)); // Three of three actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Failure threshold exceeded, but throughput threshold not yet. // Throughput threshold will be exceeded by the below successful call, but we never break on a successful call; hence don't break on this. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice } @@ -198,7 +186,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) [Fact] public async Task Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_specified_exceptions() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -211,21 +199,11 @@ public async Task Should_not_open_circuit_if_exceptions_raised_are_not_one_of_th durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw unhandled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + for (int i = 0; i < 4; i++) + { + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + } } #endregion @@ -241,7 +219,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) [Fact] public async Task Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -253,38 +231,31 @@ public async Task Should_open_circuit_blocking_executions_and_noting_the_last_ra durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); bool delegateExecutedWhenBroken = false; - var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); - + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -298,39 +269,33 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice. SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -342,36 +307,29 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -385,39 +343,33 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -429,36 +381,29 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -472,39 +417,33 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -518,31 +457,26 @@ public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_thro durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -556,31 +490,26 @@ public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_thro durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_error_occurring_just_at_the_end_of_the_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -596,34 +525,29 @@ public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_thro // Four of four actions in this test throw handled failures; but only the first three within the original timeslice. // Two actions at the start of the original timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Creates a new window right at the end of the original timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. If timeslice/window rollover is precisely defined, this should cause first two actions to be forgotten from statistics (rolled out of the window of relevance), and thus the circuit not to break. SystemClock.UtcNow = () => time.Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -637,37 +561,31 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -679,25 +597,20 @@ public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throu durationOfBreak: TimeSpan.FromSeconds(30)); // One of three actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -709,29 +622,23 @@ public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throu durationOfBreak: TimeSpan.FromSeconds(30)); // One of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -746,26 +653,22 @@ public async Task Should_open_circuit_if_failures_at_end_of_last_timeslice_below // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); @@ -773,15 +676,14 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // This failure opens the circuit, because it is the second failure of four calls // equalling the failure threshold. The minimum threshold within the defined // sampling duration is met, when using rolling windows. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_failures_in_beginning_of_new_timeslice_when_below_minimum_throughput_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -796,22 +698,19 @@ public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_a // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Two of three actions in this test occur within the first timeslice. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); @@ -819,15 +718,14 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // A third failure occurs just at the beginning of the new timeslice making // the number of failures above the failure threshold. However, the throughput is // below the minimum threshold as to open the circuit. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_open_circuit_if_failures_in_second_window_of_last_timeslice_and_failures_in_first_window_in_next_timeslice_exceeds_failure_threshold_and_minimum_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -843,32 +741,27 @@ public async Task Should_open_circuit_if_failures_in_second_window_of_last_times // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to the second window in the rolling metrics SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / (double)numberOfWindowsDefinedInCircuitBreaker); // Three actions occur in the second window of the first timeslice - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } #endregion @@ -884,7 +777,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -896,36 +789,29 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -937,36 +823,29 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -978,36 +857,29 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1021,31 +893,26 @@ public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_thro durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first within the timeslice. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1059,31 +926,26 @@ public async Task Should_not_open_circuit_if_failure_threshold_exceeded_but_thro durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures; but only the first within the timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1097,37 +959,31 @@ public async Task Should_open_circuit_with_the_last_raised_exception_if_failure_ durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -1139,25 +995,20 @@ public async Task Should_not_open_circuit_if_failure_threshold_not_met_and_throu durationOfBreak: TimeSpan.FromSeconds(30)); // One of three actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -1169,29 +1020,23 @@ public async Task Should_not_open_circuit_if_failure_threshold_not_met_but_throu durationOfBreak: TimeSpan.FromSeconds(30)); // One of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1206,35 +1051,30 @@ public async Task Should_not_open_circuit_if_failures_at_end_of_last_timeslice_b // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); // This failure does not open the circuit, because a new duration should have // started and with such low sampling duration, windows should not be used. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -1246,7 +1086,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) [Fact] public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1260,35 +1100,29 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1303,17 +1137,14 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. @@ -1321,28 +1152,25 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) var anotherWindowDuration = (samplingDuration.Seconds / 2d) + 1; SystemClock.UtcNow = () => time.AddSeconds(anotherWindowDuration); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Since the call that opened the circuit occurred in a later window, then the // break duration must be simulated as from that call. SystemClock.UtcNow = () => time.Add(durationOfBreak).AddSeconds(anotherWindowDuration); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] public async Task Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1356,41 +1184,33 @@ public async Task Should_open_circuit_again_after_the_specified_duration_has_pas durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] public async Task Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_raise_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1404,37 +1224,32 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1446,31 +1261,29 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ minimumThroughput: 2, durationOfBreak: durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. (tho still in half-open condition). - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1482,39 +1295,37 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s minimumThroughput: 2, durationOfBreak: durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. (tho still in half-open condition). - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1526,17 +1337,15 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ minimumThroughput: 2, durationOfBreak: durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exceptions raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -1553,7 +1362,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1566,7 +1375,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -1575,8 +1384,8 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -1600,7 +1409,11 @@ await breaker.ExecuteAsync(async () => // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -1611,22 +1424,25 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1638,17 +1454,15 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s minimumThroughput: 2, durationOfBreak: durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -1666,7 +1480,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1678,7 +1492,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -1687,8 +1501,8 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -1715,7 +1529,11 @@ await breaker.ExecuteAsync(async () => // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -1726,15 +1544,18 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -1747,72 +1568,68 @@ public async Task Should_open_circuit_and_block_calls_if_manual_override_open() var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); var breaker = Policy .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } [Fact] public async Task Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1826,28 +1643,23 @@ public async Task Should_be_able_to_reset_automatically_opened_circuit_without_s durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } #endregion @@ -1866,7 +1678,7 @@ public void Should_not_call_onreset_on_initialise() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -1876,7 +1688,7 @@ public async Task Should_call_onbreak_when_breaking_circuit_automatically() Action onBreak = (_, _) => { onBreakCalled = true; }; Action onReset = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -1890,32 +1702,27 @@ public async Task Should_call_onbreak_when_breaking_circuit_automatically() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { bool onBreakCalled = false; - Action onBreak = (_, _) => { onBreakCalled = true; }; + Action onBreak = (_, _) => onBreakCalled = true; Action onReset = () => { }; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1923,21 +1730,21 @@ public void Should_call_onbreak_when_breaking_circuit_manually() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { int onBreakCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -1951,35 +1758,27 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -2006,9 +1805,10 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(async () => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(async () => + // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + await Should.ThrowAsync(() => breaker.ExecuteAsync(async () => { await TaskHelper.EmptyTask; @@ -2018,44 +1818,44 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); throw new DivideByZeroException(); - })).Should().ThrowAsync(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })); }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method if (longRunningExecution.IsFaulted) { throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -2066,7 +1866,7 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not Action onBreak = (_, _) => { onBreakCalled++; }; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2082,38 +1882,33 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -2128,15 +1923,15 @@ public async Task Should_not_call_onreset_on_successive_successful_calls() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -2145,11 +1940,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2166,39 +1961,33 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - onHalfOpenCalled.Should().Be(1); // called as action was placed for execution - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); // called after action succeeded + onHalfOpenCalled.ShouldBe(1); // called as action was placed for execution + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); // called after action succeeded } [Fact] @@ -2207,11 +1996,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2228,35 +2017,30 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -2264,10 +2048,10 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() { int onBreakCalled = 0; int onResetCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2275,21 +2059,19 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } #region Tests of supplied parameters to onBreak delegate @@ -2313,25 +2095,20 @@ public async Task Should_call_onbreak_with_the_last_raised_exception() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - passedException?.Should().BeOfType(); + passedException?.ShouldBeOfType(); } [Fact] @@ -2339,7 +2116,7 @@ public async Task Should_call_onbreak_with_a_state_of_closed() { CircuitState? transitionedState = null; - Action onBreak = (_, state, _, _) => { transitionedState = state; }; + Action onBreak = (_, state, _, _) => transitionedState = state; Action onReset = _ => { }; Action onHalfOpen = () => { }; @@ -2354,25 +2131,20 @@ public async Task Should_call_onbreak_with_a_state_of_closed() onReset: onReset, onHalfOpen: onHalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - transitionedState?.Should().Be(CircuitState.Closed); + transitionedState?.ShouldBe(CircuitState.Closed); } [Fact] @@ -2384,7 +2156,7 @@ public async Task Should_call_onbreak_with_a_state_of_half_open() Action onReset = _ => { }; Action onHalfOpen = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2401,37 +2173,31 @@ public async Task Should_call_onbreak_with_a_state_of_half_open() onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - transitionedStates[0].Should().Be(CircuitState.Closed); - transitionedStates[1].Should().Be(CircuitState.HalfOpen); + transitionedStates[0].ShouldBe(CircuitState.Closed); + transitionedStates[1].ShouldBe(CircuitState.HalfOpen); } [Fact] @@ -2439,7 +2205,7 @@ public async Task Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; - Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -2455,35 +2221,30 @@ public async Task Should_call_onbreak_with_the_correct_timespan() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() { TimeSpan? passedBreakTimespan = null; - Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -2495,22 +2256,22 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() durationOfBreak: TimeSpan.FromMinutes(1), onBreak: onBreak, onReset: onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } [Fact] public void Should_throw_when_failureThreshold_is_less_or_equals_than_zero() { - Action onBreak = (_, timespan, _) => { _ = timespan; }; + Action onBreak = (_, timespan, _) => _ = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2523,7 +2284,7 @@ public void Should_throw_when_failureThreshold_is_less_or_equals_than_zero() onBreak: onBreak, onReset: onReset); - action.Should().Throw().And.ParamName.Should().Be("failureThreshold"); + Should.Throw(action).ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -2532,7 +2293,7 @@ public void Should_throw_when_failureThreshold_is_more_than_one() Action onBreak = (_, timespan, _) => { _ = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2545,7 +2306,7 @@ public void Should_throw_when_failureThreshold_is_more_than_one() onBreak: onBreak, onReset: onReset); - action.Should().Throw().And.ParamName.Should().Be("failureThreshold"); + Should.Throw(action).ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -2554,7 +2315,7 @@ public void Should_throw_when_samplingDuration_is_less_than_resolutionOfCircuit( Action onBreak = (_, timespan, _) => { _ = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2567,7 +2328,7 @@ public void Should_throw_when_samplingDuration_is_less_than_resolutionOfCircuit( onBreak: onBreak, onReset: onReset); - action.Should().Throw().And.ParamName.Should().Be("samplingDuration"); + Should.Throw(action).ParamName.ShouldBe("samplingDuration"); } [Fact] @@ -2576,7 +2337,7 @@ public void Should_throw_when_minimumThroughput_is_less_or_equals_than_one() Action onBreak = (_, timespan, _) => { _ = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2589,7 +2350,7 @@ public void Should_throw_when_minimumThroughput_is_less_or_equals_than_one() onBreak: onBreak, onReset: onReset); - action.Should().Throw().And.ParamName.Should().Be("minimumThroughput"); + Should.Throw(action).ParamName.ShouldBe("minimumThroughput"); } [Fact] @@ -2598,7 +2359,7 @@ public void Should_throw_when_durationOfBreak_is_negative_timespan() Action onBreak = (_, timespan, _) => { _ = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2611,7 +2372,7 @@ public void Should_throw_when_durationOfBreak_is_negative_timespan() onBreak: onBreak, onReset: onReset); - action.Should().Throw().And.ParamName.Should().Be("durationOfBreak"); + Should.Throw(action).ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -2619,7 +2380,7 @@ public void Should_throw_when_onReset_is_null() { Action onBreak = (_, timespan, _) => { _ = timespan; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2632,7 +2393,7 @@ public void Should_throw_when_onReset_is_null() onBreak: onBreak, onReset: null); - action.Should().Throw().And.ParamName.Should().Be("onReset"); + Should.Throw(action).ParamName.ShouldBe("onReset"); } [Fact] @@ -2641,7 +2402,7 @@ public void Should_throw_when_onHalfOpen_is_null() Action onBreak = (_, timespan, _) => { _ = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; Action action = () => Policy @@ -2655,7 +2416,7 @@ public void Should_throw_when_onHalfOpen_is_null() onReset: onReset, onHalfOpen: null); - action.Should().Throw().And.ParamName.Should().Be("onHalfOpen"); + Should.Throw(action).ParamName.ShouldBe("onHalfOpen"); } #endregion @@ -2670,7 +2431,7 @@ public async Task Should_call_onbreak_with_the_passed_context() Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -2684,25 +2445,24 @@ public async Task Should_call_onbreak_with_the_passed_context() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync( - CreateDictionary("key1", "value1", "key2", "value2"))).Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync( + () => + breaker.RaiseExceptionAsync( + CreateDictionary("key1", "value1", "key2", "value2"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -2713,7 +2473,7 @@ public async Task Should_call_onreset_with_the_passed_context() Action onBreak = (_, _, _) => { }; Action onReset = context => { contextData = context; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2729,33 +2489,28 @@ public async Task Should_call_onreset_with_the_passed_context() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context await breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, CreateDictionary("key1", "value1", "key2", "value2")); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -2766,7 +2521,7 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context Action onBreak = (_, _, context) => { contextData = context; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy @@ -2780,24 +2535,19 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -2810,7 +2560,7 @@ public async Task Should_create_new_context_for_each_call_to_execute() Action onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2826,35 +2576,31 @@ public async Task Should_create_new_context_for_each_call_to_execute() onReset: onReset); // Four of four actions in this test throw handled failures. - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync(CreateDictionary("key", "original_value"))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync(CreateDictionary("key", "original_value"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -2874,7 +2620,7 @@ public void Should_initialise_LastException_to_null_on_creation() minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -2888,11 +2634,10 @@ public async Task Should_set_LastException_on_handling_exception_even_when_not_b minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -2906,15 +2651,13 @@ public async Task Should_set_LastException_to_last_raised_exception_when_breakin minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -2928,19 +2671,17 @@ public async Task Should_set_LastException_to_null_on_circuit_reset() minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); breaker.Reset(); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } #endregion @@ -2966,11 +2707,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ using (var cancellationTokenSource = new CancellationTokenSource()) { - await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -2995,12 +2735,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -3025,12 +2764,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3055,12 +2793,11 @@ public async Task Should_report_cancellation_during_faulting_action_execution_wh { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3083,11 +2820,10 @@ public async Task Should_report_faulting_from_faulting_action_execution_when_use using (var cancellationTokenSource = new CancellationTokenSource()) { - await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3098,16 +2834,12 @@ public async Task Should_report_cancellation_when_both_open_circuit_and_cancella .Handle() .AdvancedCircuitBreakerAsync(0.5, TimeSpan.FromSeconds(10), 2, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); // Circuit is now broken. @@ -3126,19 +2858,18 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex2 = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex2.And.CancellationToken.Should().Be(cancellationToken); + var ex2 = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex2.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] public async Task Should_honour_different_cancellationToken_captured_implicitly_by_action() { - // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish TaskCanceledExceptions thrown with different CancellationTokens. - + // Before CancellationToken support was built in to Polly, users of the library may have implicitly captured a CancellationToken and used it to cancel actions. + // For backwards compatibility, Polly should not confuse these with its own CancellationToken; it should distinguish TaskCanceledExceptions thrown with different CancellationTokens. var durationOfBreak = TimeSpan.FromMinutes(1); var breaker = Policy .Handle() @@ -3154,18 +2885,17 @@ public async Task Should_honour_different_cancellationToken_captured_implicitly_ implicitlyCapturedActionCancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(async _ => { attemptsInvoked++; await TaskHelper.EmptyTask; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) - .Should().ThrowAsync(); + }, policyCancellationToken)); - ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + ex.CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3191,14 +2921,13 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await breaker.Awaiting(action) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(async () => result = await breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true)); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3225,15 +2954,13 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await breaker.Awaiting(action) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(async () => result = await breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true)); + ex.CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs index 30609cb9c4..cb4f4ea034 100644 --- a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs @@ -14,8 +14,7 @@ public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.MaxValue); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); } [Fact] @@ -25,9 +24,8 @@ public void Should_throw_if_failure_threshold_is_zero() .Handle() .AdvancedCircuitBreaker(0, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -37,9 +35,8 @@ public void Should_throw_if_failure_threshold_is_less_than_zero() .Handle() .AdvancedCircuitBreaker(-0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -49,7 +46,7 @@ public void Should_be_able_to_handle_a_failure_threshold_of_one() .Handle() .AdvancedCircuitBreaker(1.0, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -59,9 +56,8 @@ public void Should_throw_if_failure_threshold_is_greater_than_one() .Handle() .AdvancedCircuitBreaker(1.01, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("failureThreshold"); + Should.Throw(action) + .ParamName.ShouldBe("failureThreshold"); } [Fact] @@ -75,9 +71,8 @@ public void Should_throw_if_timeslice_duration_is_less_than_resolution_of_circui 4, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("samplingDuration"); + Should.Throw(action) + .ParamName.ShouldBe("samplingDuration"); } [Fact] @@ -87,7 +82,7 @@ public void Should_not_throw_if_timeslice_duration_is_resolution_of_circuit() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromMilliseconds(20), 4, TimeSpan.FromSeconds(30)); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -97,9 +92,8 @@ public void Should_throw_if_minimum_throughput_is_one() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 1, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("minimumThroughput"); + Should.Throw(action) + .ParamName.ShouldBe("minimumThroughput"); } [Fact] @@ -109,9 +103,8 @@ public void Should_throw_if_minimum_throughput_is_less_than_one() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 0, TimeSpan.FromSeconds(30)); - action.Should().Throw() - .And.ParamName.Should() - .Be("minimumThroughput"); + Should.Throw(action) + .ParamName.ShouldBe("minimumThroughput"); } [Fact] @@ -121,9 +114,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -133,7 +125,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -143,7 +135,7 @@ public void Should_initialise_to_closed_state() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -161,7 +153,7 @@ public void Should_initialise_to_closed_state() [Fact] public void Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_is_equalled_but_last_call_is_success() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -173,32 +165,26 @@ public void Should_not_open_circuit_if_failure_threshold_and_minimum_threshold_i durationOfBreak: TimeSpan.FromSeconds(30)); // Three of three actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Failure threshold exceeded, but throughput threshold not yet. // Throughput threshold will be exceeded by the below successful call, but we never break on a successful call; hence don't break on this. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_specified_exceptions() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -211,21 +197,17 @@ public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_spec durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw unhandled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -241,7 +223,7 @@ public void Should_not_open_circuit_if_exceptions_raised_are_not_one_of_the_spec [Fact] public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -253,38 +235,31 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); - + var ex = Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -298,39 +273,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice. SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -342,36 +311,29 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -385,39 +347,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -429,36 +385,29 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -472,39 +421,33 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. // They are still placed within same timeslice SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -518,31 +461,26 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -556,31 +494,26 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first three within the timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_error_occurring_just_at_the_end_of_the_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -596,34 +529,29 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput // Four of four actions in this test throw handled failures; but only the first three within the original timeslice. // Two actions at the start of the original timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Creates a new window right at the end of the original timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. If timeslice/window rollover is precisely defined, this should cause first two actions to be forgotten from statistics (rolled out of the window of relevance), and thus the circuit not to break. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -637,37 +565,31 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -679,25 +601,20 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ durationOfBreak: TimeSpan.FromSeconds(30)); // One of three actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -709,29 +626,23 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ durationOfBreak: TimeSpan.FromSeconds(30)); // One of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -746,26 +657,22 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); @@ -773,15 +680,14 @@ public void Should_open_circuit_if_failures_at_end_of_last_timeslice_below_failu // This failure opens the circuit, because it is the second failure of four calls // equalling the failure threshold. The minimum threshold within the defined // sampling duration is met, when using rolling windows. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_failures_in_beginning_of_new_timeslice_when_below_minimum_throughput_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -796,22 +702,19 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Two of three actions in this test occur within the first timeslice. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); @@ -819,15 +722,14 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_and_fai // A third failure occurs just at the beginning of the new timeslice making // the number of failures above the failure threshold. However, the throughput is // below the minimum threshold as to open the circuit. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_and_failures_in_first_window_in_next_timeslice_exceeds_failure_threshold_and_minimum_threshold() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromSeconds(10); @@ -843,32 +745,27 @@ public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_a // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to the second window in the rolling metrics SystemClock.UtcNow = () => time.AddSeconds(samplingDuration.Seconds / (double)numberOfWindowsDefinedInCircuitBreaker); // Three actions occur in the second window of the first timeslice - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } #endregion @@ -884,7 +781,7 @@ public void Should_open_circuit_if_failures_in_second_window_of_last_timeslice_a [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -896,36 +793,29 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_exceeded_though_not_all_are_failures_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -937,36 +827,29 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Three of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -978,36 +861,29 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1021,31 +897,26 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures; but only the first within the timeslice. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (clearly) expires; fourth exception thrown in next-recorded timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration).Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput_threshold_not_met_before_timeslice_expires_even_if_timeslice_expires_only_exactly_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1059,31 +930,26 @@ public void Should_not_open_circuit_if_failure_threshold_exceeded_but_throughput durationOfBreak: TimeSpan.FromSeconds(30)); // Two of four actions in this test throw handled failures; but only the first within the timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice (just) expires; fourth exception thrown in following timeslice. SystemClock.UtcNow = () => time.Add(samplingDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_open_circuit_with_the_last_raised_exception_if_failure_threshold_equalled_and_throughput_threshold_equalled_even_if_only_just_within_timeslice_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1097,37 +963,31 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh durationOfBreak: TimeSpan.FromSeconds(30)); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Adjust SystemClock so that timeslice doesn't quite expire; fourth exception thrown in same timeslice. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_threshold_not_met_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -1139,25 +999,20 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_and_throughput_ durationOfBreak: TimeSpan.FromSeconds(30)); // One of three actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_threshold_met_before_timeslice_expires_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -1169,29 +1024,23 @@ public void Should_not_open_circuit_if_failure_threshold_not_met_but_throughput_ durationOfBreak: TimeSpan.FromSeconds(30)); // One of four actions in this test throw handled failures. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - // No adjustment to SystemClock.UtcNow, so all exceptions were raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_failure_threshold_and_failures_in_beginning_of_new_timeslice_where_total_equals_failure_threshold_low_sampling_duration() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var samplingDuration = TimeSpan.FromMilliseconds(199); @@ -1206,35 +1055,30 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f // Executing a single invocation to ensure timeslice is created // This invocation is not be counted against the threshold - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // The time is set to just at the end of the sampling duration ensuring // the invocations are within the timeslice, but only barely. SystemClock.UtcNow = () => time.AddTicks(samplingDuration.Ticks - 1); // Three of four actions in this test occur within the first timeslice. - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })) - .Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Setting the time to just barely into the new timeslice SystemClock.UtcNow = () => time.Add(samplingDuration); // This failure does not open the circuit, because a new duration should have // started and with such low sampling duration, windows should not be used. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -1246,7 +1090,7 @@ public void Should_not_open_circuit_if_failures_at_end_of_last_timeslice_below_f [Fact] public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_same_window() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1260,35 +1104,29 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + Should.Throw(() => breaker.RaiseException()); } [Fact] public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with_failures_in_different_windows() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1303,17 +1141,14 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // Placing the rest of the invocations ('samplingDuration' / 2) + 1 seconds later // ensures that even if there are only two windows, then the invocations are placed in the second. @@ -1321,28 +1156,25 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with var anotherWindowDuration = (samplingDuration.Seconds / 2d) + 1; SystemClock.UtcNow = () => time.AddSeconds(anotherWindowDuration); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // Since the call that opened the circuit occurred in a later window, then the // break duration must be simulated as from that call. SystemClock.UtcNow = () => time.Add(durationOfBreak).AddSeconds(anotherWindowDuration); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + Should.Throw(() => breaker.RaiseException()); } [Fact] public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1356,39 +1188,32 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_raise_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1402,37 +1227,32 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1445,31 +1265,29 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ minimumThroughput: 2, durationOfBreak: durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1482,39 +1300,37 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ minimumThroughput: 2, durationOfBreak: durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1527,17 +1343,15 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ minimumThroughput: 2, durationOfBreak: durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); // exceptions raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -1554,7 +1368,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1566,7 +1380,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); firstExecutionActive = false; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -1575,8 +1389,8 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -1601,7 +1415,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ permitFirstExecutionEnd.Set(); #pragma warning disable xUnit1031 // Do not use blocking task operations in test method - Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).Should().BeTrue(); + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); #pragma warning restore xUnit1031 // Do not use blocking task operations in test method if (firstExecution.IsFaulted) @@ -1614,22 +1428,25 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1642,17 +1459,15 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ minimumThroughput: 2, durationOfBreak: durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -1670,7 +1485,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -1682,7 +1497,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); firstExecutionActive = false; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -1691,8 +1506,8 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -1719,7 +1534,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ permitFirstExecutionEnd.Set(); #pragma warning disable xUnit1031 // Do not use blocking task operations in test method - Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).Should().BeTrue(); + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); #pragma warning restore xUnit1031 // Do not use blocking task operations in test method if (firstExecution.IsFaulted) @@ -1732,15 +1547,18 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in half-open state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -1753,71 +1571,68 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, TimeSpan.FromSeconds(30)); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => { })) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => { })); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } [Fact] public void Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1831,27 +1646,23 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi durationOfBreak: durationOfBreak); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } #endregion @@ -1863,24 +1674,24 @@ public void Should_not_call_onreset_on_initialise() { Action onBreak = (_, _) => { }; bool onResetCalled = false; - Action onReset = () => { onResetCalled = true; }; + Action onReset = () => onResetCalled = true; var durationOfBreak = TimeSpan.FromSeconds(30); Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] public void Should_call_onbreak_when_breaking_circuit_automatically() { bool onBreakCalled = false; - Action onBreak = (_, _) => { onBreakCalled = true; }; + Action onBreak = (_, _) => onBreakCalled = true; Action onReset = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -1894,32 +1705,27 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { bool onBreakCalled = false; - Action onBreak = (_, _) => { onBreakCalled = true; }; + Action onBreak = (_, _) => onBreakCalled = true; Action onReset = () => { }; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -1927,21 +1733,21 @@ public void Should_call_onbreak_when_breaking_circuit_manually() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { int onBreakCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -1955,42 +1761,36 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { int onBreakCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; CircuitBreakerPolicy breaker = Policy @@ -2009,9 +1809,10 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(() => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => + // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + Should.Throw(() => breaker.Execute(() => { permitMainThreadToOpenCircuit.Set(); @@ -2019,23 +1820,21 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); throw new DivideByZeroException(); - })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })); }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); @@ -2043,9 +1842,9 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #pragma warning disable xUnit1031 // Do not use blocking task operations in test method #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif #pragma warning restore xUnit1031 // Do not use blocking task operations in test method @@ -2054,11 +1853,11 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -2066,10 +1865,10 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ { int onBreakCalled = 0; int onResetCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2085,38 +1884,33 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -2124,22 +1918,22 @@ public void Should_not_call_onreset_on_successive_successful_calls() { Action onBreak = (_, _) => { }; bool onResetCalled = false; - Action onReset = () => { onResetCalled = true; }; + Action onReset = () => onResetCalled = true; var durationOfBreak = TimeSpan.FromSeconds(30); CircuitBreakerPolicy breaker = Policy .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -2148,11 +1942,11 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2169,39 +1963,34 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - onHalfOpenCalled.Should().Be(1); // called as action was placed for execution - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); // called after action succeeded + onHalfOpenCalled.ShouldBe(1); // called as action was placed for execution + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); // called after action succeeded } [Fact] @@ -2210,11 +1999,11 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2231,35 +2020,30 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); // No adjustment to SystemClock.UtcNow, so all exceptions raised within same timeslice + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -2267,10 +2051,10 @@ public void Should_call_onreset_when_manually_resetting_circuit() { int onBreakCalled = 0; int onResetCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2278,20 +2062,19 @@ public void Should_call_onreset_when_manually_resetting_circuit() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 4, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => { })) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => { })); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } #region Tests of supplied parameters to onBreak delegate @@ -2301,7 +2084,7 @@ public void Should_call_onbreak_with_the_last_raised_exception() { Exception? passedException = null; - Action onBreak = (exception, _, _) => { passedException = exception; }; + Action onBreak = (exception, _, _) => passedException = exception; Action onReset = _ => { }; CircuitBreakerPolicy breaker = Policy @@ -2314,23 +2097,19 @@ public void Should_call_onbreak_with_the_last_raised_exception() onBreak: onBreak, onReset: onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedException?.Should().BeOfType(); + passedException?.ShouldBeOfType(); } [Fact] @@ -2338,7 +2117,7 @@ public void Should_call_onbreak_with_a_state_of_closed() { CircuitState? transitionedState = null; - Action onBreak = (_, state, _, _) => { transitionedState = state; }; + Action onBreak = (_, state, _, _) => transitionedState = state; Action onReset = _ => { }; Action onHalfOpen = () => { }; @@ -2353,23 +2132,19 @@ public void Should_call_onbreak_with_a_state_of_closed() onReset: onReset, onHalfOpen: onHalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - transitionedState?.Should().Be(CircuitState.Closed); + transitionedState?.ShouldBe(CircuitState.Closed); } [Fact] @@ -2381,7 +2156,7 @@ public void Should_call_onbreak_with_a_state_of_half_open() Action onReset = _ => { }; Action onHalfOpen = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2398,35 +2173,29 @@ public void Should_call_onbreak_with_a_state_of_half_open() onHalfOpen: onHalfOpen); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should open again - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - transitionedStates[0].Should().Be(CircuitState.Closed); - transitionedStates[1].Should().Be(CircuitState.HalfOpen); + transitionedStates[0].ShouldBe(CircuitState.Closed); + transitionedStates[1].ShouldBe(CircuitState.HalfOpen); } [Fact] @@ -2434,7 +2203,7 @@ public void Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; - Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromSeconds(30); @@ -2449,33 +2218,29 @@ public void Should_call_onbreak_with_the_correct_timespan() onBreak: onBreak, onReset: onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() { TimeSpan? passedBreakTimespan = null; - Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -2487,13 +2252,13 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() durationOfBreak: TimeSpan.FromSeconds(30), onBreak: onBreak, onReset: onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } #endregion @@ -2505,10 +2270,10 @@ public void Should_call_onbreak_with_the_passed_context() { IDictionary? contextData = null; - Action onBreak = (_, _, context) => { contextData = context; }; + Action onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -2522,25 +2287,24 @@ public void Should_call_onbreak_with_the_passed_context() onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException( - CreateDictionary("key1", "value1", "key2", "value2"))).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw( + () => + breaker.RaiseException( + CreateDictionary("key1", "value1", "key2", "value2"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -2549,9 +2313,9 @@ public void Should_call_onreset_with_the_passed_context() IDictionary? contextData = null; Action onBreak = (_, _, _) => { }; - Action onReset = context => { contextData = context; }; + Action onReset = context => contextData = context; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2567,33 +2331,28 @@ public void Should_call_onreset_with_the_passed_context() onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context breaker.Execute(_ => { }, CreateDictionary("key1", "value1", "key2", "value2")); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -2601,10 +2360,10 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( { IDictionary contextData = CreateDictionary("key1", "value1", "key2", "value2"); - Action onBreak = (_, _, context) => { contextData = context; }; + Action onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; CircuitBreakerPolicy breaker = Policy @@ -2618,24 +2377,19 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -2648,7 +2402,7 @@ public void Should_create_new_context_for_each_call_to_execute() Action onReset = context => { contextValue = context.ContainsKey("key") ? context["key"].ToString() : null; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromSeconds(30); @@ -2664,34 +2418,30 @@ public void Should_create_new_context_for_each_call_to_execute() onReset: onReset); // Four of four actions in this test throw handled failures. - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException(CreateDictionary("key", "original_value"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + Should.Throw(() => breaker.RaiseException(CreateDictionary("key", "original_value"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset breaker.Execute(_ => { }, CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -2711,7 +2461,7 @@ public void Should_initialise_LastException_to_null_on_creation() minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -2725,11 +2475,10 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -2743,15 +2492,13 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -2765,19 +2512,17 @@ public void Should_set_LastException_to_null_on_circuit_reset() minimumThroughput: 2, durationOfBreak: TimeSpan.FromSeconds(30)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); breaker.Reset(); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } #endregion @@ -2803,11 +2548,10 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca using (var cancellationTokenSource = new CancellationTokenSource()) { - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -2832,12 +2576,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -2862,12 +2605,11 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -2892,12 +2634,11 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -2920,11 +2661,10 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele using (var cancellationTokenSource = new CancellationTokenSource()) { - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -2935,19 +2675,14 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .Handle() .AdvancedCircuitBreaker(0.5, TimeSpan.FromSeconds(10), 2, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); // Circuit is now broken. - int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -2963,12 +2698,11 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -2991,16 +2725,15 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act implicitlyCapturedActionCancellationTokenSource.Cancel(); - breaker.Invoking(x => x.Execute(_ => + Should.Throw(() => breaker.Execute(_ => { attemptsInvoked++; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + .CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3025,13 +2758,13 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().NotThrow(); + Should.NotThrow(() => result = breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -3058,13 +2791,13 @@ public void Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => result = breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) + .CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs b/test/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs index d40eeb63dc..63782a205e 100644 --- a/test/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/CircuitBreakerAsyncSpecs.cs @@ -14,8 +14,7 @@ public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .Handle() .CircuitBreakerAsync(1, TimeSpan.MaxValue); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] @@ -25,9 +24,8 @@ public void Should_throw_if_exceptions_allowed_before_breaking_is_less_than_one( .Handle() .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); - action.Should().Throw() - .And.ParamName.Should() - .Be("exceptionsAllowedBeforeBreaking"); + Should.Throw(action) + .ParamName.ShouldBe("exceptionsAllowedBeforeBreaking"); } [Fact] @@ -37,9 +35,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .Handle() .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -48,7 +45,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() Action action = () => Policy .Handle() .CircuitBreakerAsync(1, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -60,7 +57,7 @@ public void Should_initialise_to_closed_state() .Handle() .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -74,16 +71,14 @@ public async Task Should_not_open_circuit_if_specified_number_of_specified_excep .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(b => b.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -93,22 +88,18 @@ public async Task Should_open_circuit_blocking_executions_and_noting_the_last_ra .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); bool delegateExecutedWhenBroken = false; - var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); - + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] @@ -119,22 +110,19 @@ public async Task Should_open_circuit_blocking_executions_and_noting_the_last_ra .Or() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open bool delegateExecutedWhenBroken = false; - var ex = await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] @@ -144,17 +132,14 @@ public async Task Should_not_open_circuit_if_exception_raised_is_not_the_specifi .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -165,17 +150,14 @@ public async Task Should_not_open_circuit_if_exception_raised_is_not_one_of_the_ .Or() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -185,7 +167,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) [Fact] public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -194,31 +176,27 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe .Handle() .CircuitBreakerAsync(2, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] public async Task Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -227,36 +205,31 @@ public async Task Should_open_circuit_again_after_the_specified_duration_has_pas .Handle() .CircuitBreakerAsync(2, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); } [Fact] public async Task Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_raise_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -265,46 +238,40 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i .Handle() .CircuitBreakerAsync(2, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // circuit has been reset so should once again allow 2 exceptions to be raised before breaking - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -312,29 +279,28 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .Handle() .CircuitBreakerAsync(1, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -342,37 +308,36 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .Handle() .CircuitBreakerAsync(1, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -380,15 +345,14 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .Handle() .CircuitBreakerAsync(1, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -405,7 +369,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -417,8 +381,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); await TaskHelper.EmptyTask; firstExecutionActive = false; - - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -427,8 +390,8 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -452,7 +415,11 @@ await breaker.ExecuteAsync(async () => // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -463,22 +430,25 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -486,15 +456,14 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .Handle() .CircuitBreakerAsync(1, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -512,7 +481,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -524,7 +493,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); await TaskHelper.EmptyTask; firstExecutionActive = false; - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -533,8 +502,8 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -561,7 +530,11 @@ await breaker.ExecuteAsync(async () => // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -572,15 +545,18 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -590,7 +566,7 @@ await breaker.ExecuteAsync(async () => [Fact] public async Task Should_open_circuit_and_block_calls_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -598,26 +574,25 @@ public async Task Should_open_circuit_and_block_calls_if_manual_override_open() var breaker = Policy .Handle() .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -625,23 +600,22 @@ public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_overri var breaker = Policy .Handle() .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })) - .Should().ThrowAsync(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return TaskHelper.EmptyTask; })); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -649,22 +623,21 @@ public async Task Should_close_circuit_again_on_reset_after_manual_override() var breaker = Policy .Handle() .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } [Fact] public async Task Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -673,24 +646,21 @@ public async Task Should_be_able_to_reset_automatically_opened_circuit_without_s .Handle() .CircuitBreakerAsync(2, durationOfBreak); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } #endregion @@ -708,7 +678,7 @@ public void Should_not_call_onreset_on_initialise() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -722,17 +692,15 @@ public async Task Should_call_onbreak_when_breaking_circuit_automatically() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBeFalse(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().BeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBeTrue(); } [Fact] @@ -745,42 +713,39 @@ public void Should_call_onbreak_when_breaking_circuit_manually() var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { int onBreakCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -800,9 +765,10 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(async () => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(async () => + // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + await Should.ThrowAsync(() => breaker.ExecuteAsync(async () => { await TaskHelper.EmptyTask; @@ -812,42 +778,43 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); throw new DivideByZeroException(); - })).Should().ThrowAsync(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })); }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method if (longRunningExecution.IsFaulted) { throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -855,10 +822,10 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not { int onBreakCalled = 0; int onResetCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -867,34 +834,31 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -908,15 +872,15 @@ public async Task Should_not_call_onreset_on_successive_successful_calls() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -925,11 +889,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; Action onHalfOpen = () => { onHalfOpenCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -938,32 +902,29 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(() => TaskHelper.EmptyTask); - onHalfOpenCalled.Should().Be(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + onHalfOpenCalled.ShouldBe(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -972,11 +933,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -985,28 +946,25 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(0); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(0); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -1014,10 +972,10 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() { int onBreakCalled = 0; int onResetCalled = 0; - Action onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1026,20 +984,19 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => TaskHelper.EmptyTask)).Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => TaskHelper.EmptyTask)); } #region Tests of supplied parameters to onBreak delegate @@ -1049,22 +1006,20 @@ public async Task Should_call_onbreak_with_the_last_raised_exception() { Exception? passedException = null; - Action onBreak = (exception, _, _) => { passedException = exception; }; + Action onBreak = (exception, _, _) => passedException = exception; Action onReset = _ => { }; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedException?.Should().BeOfType(); + passedException?.ShouldBeOfType(); } [Fact] @@ -1072,7 +1027,7 @@ public async Task Should_call_onbreak_with_a_state_of_closed() { CircuitState? transitionedState = null; - Action onBreak = (_, state, _, _) => { transitionedState = state; }; + Action onBreak = (_, state, _, _) => transitionedState = state; Action onReset = _ => { }; Action onHalfOpen = () => { }; @@ -1080,15 +1035,13 @@ public async Task Should_call_onbreak_with_a_state_of_closed() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - transitionedState?.Should().Be(CircuitState.Closed); + transitionedState?.ShouldBe(CircuitState.Closed); } [Fact] @@ -1096,11 +1049,11 @@ public async Task Should_call_onbreak_with_a_state_of_half_open() { List transitionedStates = []; - Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; + Action onBreak = (_, state, _, _) => transitionedStates.Add(state); Action onReset = _ => { }; Action onHalfOpen = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1109,33 +1062,28 @@ public async Task Should_call_onbreak_with_a_state_of_half_open() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - transitionedStates[0].Should().Be(CircuitState.Closed); - transitionedStates[1].Should().Be(CircuitState.HalfOpen); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + + transitionedStates[0].ShouldBe(CircuitState.Closed); + transitionedStates[1].ShouldBe(CircuitState.HalfOpen); } [Fact] @@ -1143,7 +1091,7 @@ public async Task Should_rethrow_and_call_onbreak_with_the_last_raised_exception { Exception? passedException = null; - Action onBreak = (exception, _, _) => { passedException = exception; }; + Action onBreak = (exception, _, _) => passedException = exception; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -1156,16 +1104,14 @@ public async Task Should_rethrow_and_call_onbreak_with_the_last_raised_exception Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) - .Should().ThrowAsync(); - ex.Which.Should().BeSameAs(toRaiseAsInner); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync(withInner)); + ex.ShouldBeSameAs(toRaiseAsInner); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedException?.Should().BeSameAs(toRaiseAsInner); + passedException?.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -1182,37 +1128,35 @@ public async Task Should_call_onbreak_with_the_correct_timespan() .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() { TimeSpan? passedBreakTimespan = null; - Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } #endregion @@ -1224,24 +1168,23 @@ public async Task Should_call_onbreak_with_the_passed_context() { IDictionary? contextData = null; - Action onBreak = (_, _, context) => { contextData = context; }; + Action onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - await breaker.Awaiting(x => x.RaiseExceptionAsync( - CreateDictionary("key1", "value1", "key2", "value2"))).Should().ThrowAsync(); + await Should.ThrowAsync( + () => breaker.RaiseExceptionAsync(CreateDictionary("key1", "value1", "key2", "value2"))); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1250,9 +1193,9 @@ public async Task Should_call_onreset_with_the_passed_context() IDictionary? contextData = null; Action onBreak = (_, _, _) => { }; - Action onReset = context => { contextData = context; }; + Action onReset = context => contextData = context; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1261,21 +1204,19 @@ public async Task Should_call_onreset_with_the_passed_context() .Handle() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context await breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1283,22 +1224,19 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context { IDictionary contextData = CreateDictionary("key1", "value1", "key2", "value2"); - Action onBreak = (_, _, context) => { contextData = context; }; + Action onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; var breaker = Policy .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -1313,31 +1251,29 @@ public async Task Should_create_new_context_for_each_call_to_execute() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); // 2 exception raised, circuit is now open - await breaker.Awaiting(x => x.RaiseExceptionAsync(CreateDictionary("key", "original_value"))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync(CreateDictionary("key", "original_value"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(_ => TaskHelper.EmptyTask, CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -1353,7 +1289,7 @@ public void Should_initialise_LastException_to_null_on_creation() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1363,12 +1299,11 @@ public async Task Should_set_LastException_on_handling_exception_even_when_not_b .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -1381,13 +1316,12 @@ public async Task Should_set_LastException_on_handling_inner_exception_even_when Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync(withInner)) - .Should().ThrowAsync(); - ex.Which.Should().BeSameAs(toRaiseAsInner); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync(withInner)); + ex.ShouldBeSameAs(toRaiseAsInner); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeSameAs(toRaiseAsInner); + breaker.LastException.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -1397,15 +1331,12 @@ public async Task Should_set_LastException_to_last_raised_exception_when_breakin .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.CircuitState.Should().Be(CircuitState.Open); - - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -1415,19 +1346,16 @@ public async Task Should_set_LastException_to_null_on_circuit_reset() .Handle() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); - - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); breaker.Reset(); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } #endregion @@ -1453,11 +1381,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ using (var cancellationTokenSource = new CancellationTokenSource()) { - await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1482,12 +1409,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1512,12 +1438,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1542,12 +1467,11 @@ public async Task Should_report_cancellation_during_faulting_action_execution_wh { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1570,11 +1494,10 @@ public async Task Should_report_faulting_from_faulting_action_execution_when_use using (var cancellationTokenSource = new CancellationTokenSource()) { - await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1584,13 +1507,11 @@ public async Task Should_report_cancellation_when_both_open_circuit_and_cancella .Handle() .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1)); - await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); - var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); - ex.WithInnerException(); + var ex = await Should.ThrowAsync(() => breaker.RaiseExceptionAsync()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); // Circuit is now broken. @@ -1609,12 +1530,11 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex2 = await breaker.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex2.And.CancellationToken.Should().Be(cancellationToken); + var ex2 = await Should.ThrowAsync(() => breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex2.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1637,17 +1557,16 @@ public async Task Should_honour_different_cancellationToken_captured_implicitly_ implicitlyCapturedActionCancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(async _ => { attemptsInvoked++; await TaskHelper.EmptyTask; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); - }, policyCancellationToken)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + }, policyCancellationToken)); + ex.CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1672,14 +1591,14 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await breaker.Awaiting(action) - .Should().NotThrowAsync(); + Func action = async () => result = await breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + await Should.NotThrowAsync(action); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1705,15 +1624,14 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await breaker.Awaiting(action) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + Func action = async () => result = await breaker.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + var ex = await Should.ThrowAsync(action); + ex.CancellationToken.ShouldBe(cancellationToken); - result.Should().Be(null); + result.ShouldBeNull(); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs b/test/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs index 9636acf5ca..40c1b4efd1 100644 --- a/test/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/CircuitBreakerSpecs.cs @@ -12,8 +12,7 @@ public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .Handle() .CircuitBreaker(1, TimeSpan.MaxValue); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); } [Fact] @@ -23,9 +22,8 @@ public void Should_throw_if_exceptions_allowed_before_breaking_is_less_than_one( .Handle() .CircuitBreaker(0, TimeSpan.FromSeconds(10)); - action.Should().Throw() - .And.ParamName.Should() - .Be("exceptionsAllowedBeforeBreaking"); + Should.Throw(action) + .ParamName.ShouldBe("exceptionsAllowedBeforeBreaking"); } [Fact] @@ -35,9 +33,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .Handle() .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -46,7 +43,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() Action action = () => Policy .Handle() .CircuitBreaker(1, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -58,7 +55,7 @@ public void Should_initialise_to_closed_state() .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -72,16 +69,14 @@ public void Should_not_open_circuit_if_specified_number_of_specified_exception_a .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.Execute(() => { })).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -91,21 +86,18 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); + var ex = Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] @@ -116,22 +108,19 @@ public void Should_open_circuit_blocking_executions_and_noting_the_last_raised_e .Or() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); - breaker.CircuitState.Should().Be(CircuitState.Open); - delegateExecutedWhenBroken.Should().BeFalse(); + var ex = Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] @@ -141,17 +130,14 @@ public void Should_not_open_circuit_if_exception_raised_is_not_the_specified_exc .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -162,17 +148,14 @@ public void Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specif .Or() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -182,7 +165,7 @@ public void Should_not_open_circuit_if_exception_raised_is_not_one_of_the_specif [Fact] public void Should_halfopen_circuit_after_the_specified_duration_has_passed() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -191,31 +174,27 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + Should.Throw(() => breaker.RaiseException()); } [Fact] public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -224,37 +203,31 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); } [Fact] public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_raise_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -263,46 +236,40 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // circuit has been reset so should once again allow 2 exceptions to be raised before breaking - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -310,29 +277,28 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ .Handle() .CircuitBreaker(1, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -340,37 +306,36 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ .Handle() .CircuitBreaker(1, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution in the same time window. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -378,15 +343,14 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ .Handle() .CircuitBreaker(1, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -403,7 +367,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -415,7 +379,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); firstExecutionActive = false; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -424,8 +388,8 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -448,7 +412,11 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -459,22 +427,25 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -482,15 +453,14 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ .Handle() .CircuitBreaker(1, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -508,7 +478,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -520,7 +490,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); firstExecutionActive = false; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -529,8 +499,8 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -555,7 +525,11 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -566,15 +540,18 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -584,7 +561,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ [Fact] public void Should_open_circuit_and_block_calls_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -592,25 +569,24 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-exception-throwing executions should not reset circuit bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => delegateExecutedWhenBroken = true)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => delegateExecutedWhenBroken = true)); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -618,23 +594,22 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })) - .Should().Throw(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -642,22 +617,21 @@ public void Should_close_circuit_again_on_reset_after_manual_override() CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => { })) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => { })); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } [Fact] public void Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -666,24 +640,21 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi .Handle() .CircuitBreaker(2, durationOfBreak); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } #endregion @@ -701,7 +672,7 @@ public void Should_not_call_onreset_on_initialise() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -715,17 +686,15 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBeFalse(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().BeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBeTrue(); } [Fact] @@ -738,11 +707,11 @@ public void Should_call_onbreak_when_breaking_circuit_manually() CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] @@ -756,24 +725,21 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -793,9 +759,10 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(() => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => + // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + Should.Throw(() => breaker.Execute(() => { permitMainThreadToOpenCircuit.Set(); @@ -803,41 +770,43 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); throw new DivideByZeroException(); - })).Should().Throw(); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original exception will still be thrown. + })); }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (longRunningExecution.IsFaulted) { throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -848,7 +817,7 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ Action onBreak = (_, _) => { onBreakCalled++; }; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -857,34 +826,31 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -898,15 +864,15 @@ public void Should_not_call_onreset_on_successive_successful_calls() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => { }); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -919,7 +885,7 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ Action onReset = () => { onResetCalled++; }; Action onHalfOpen = () => { onHalfOpenCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -928,32 +894,29 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset breaker.Execute(() => { }); - onHalfOpenCalled.Should().Be(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + onHalfOpenCalled.ShouldBe(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -966,7 +929,7 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ Action onReset = () => { onResetCalled++; }; Action onHalfOpen = () => { onHalfOpenCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -975,28 +938,25 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(0); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(0); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -1007,7 +967,7 @@ public void Should_call_onreset_when_manually_resetting_circuit() Action onBreak = (_, _) => { onBreakCalled++; }; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1016,20 +976,19 @@ public void Should_call_onreset_when_manually_resetting_circuit() .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => { })) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => { })); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => { })).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => { })); } #region Tests of supplied parameters to onBreak delegate @@ -1048,15 +1007,12 @@ public void Should_call_onbreak_with_the_last_raised_exception() .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedException?.Should().BeOfType(); + passedException?.ShouldBeOfType(); } [Fact] @@ -1072,15 +1028,12 @@ public void Should_call_onbreak_with_a_state_of_closed() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.CircuitState.Should().Be(CircuitState.Open); - - transitionedState?.Should().Be(CircuitState.Closed); + transitionedState?.ShouldBe(CircuitState.Closed); } [Fact] @@ -1088,11 +1041,11 @@ public void Should_call_onbreak_with_a_state_of_half_open() { List transitionedStates = []; - Action onBreak = (_, state, _, _) => { transitionedStates.Add(state); }; + Action onBreak = (_, state, _, _) => transitionedStates.Add(state); Action onReset = _ => { }; Action onHalfOpen = () => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1101,33 +1054,28 @@ public void Should_call_onbreak_with_a_state_of_half_open() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset, onHalfOpen); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration raises an exception, so circuit should break again - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - transitionedStates[0].Should().Be(CircuitState.Closed); - transitionedStates[1].Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + + transitionedStates[0].ShouldBe(CircuitState.Closed); + transitionedStates[1].ShouldBe(CircuitState.HalfOpen); } [Fact] @@ -1148,15 +1096,14 @@ public void Should_rethrow_and_call_onbreak_with_the_last_raised_exception_unwra Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException(withInner)) - .Should().Throw().Which.Should().BeSameAs(toRaiseAsInner); + Should.Throw(() => breaker.RaiseException(withInner)) + .ShouldBeSameAs(toRaiseAsInner); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedException?.Should().BeSameAs(toRaiseAsInner); + passedException?.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -1173,15 +1120,12 @@ public void Should_call_onbreak_with_the_correct_timespan() .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] @@ -1191,7 +1135,7 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() Action onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1199,13 +1143,13 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() CircuitBreakerPolicy breaker = Policy .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } #endregion @@ -1224,17 +1168,15 @@ public void Should_call_onbreak_with_the_passed_context() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException( - CreateDictionary("key1", "value1", "key2", "value2"))).Should().Throw(); + Should.Throw(() => breaker.RaiseException(CreateDictionary("key1", "value1", "key2", "value2"))); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1245,7 +1187,7 @@ public void Should_call_onreset_with_the_passed_context() Action onBreak = (_, _, _) => { }; Action onReset = context => { contextData = context; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1254,21 +1196,19 @@ public void Should_call_onreset_with_the_passed_context() .Handle() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context breaker.Execute(_ => { }, CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1283,15 +1223,12 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.CircuitState.Should().Be(CircuitState.Open); - - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -1306,31 +1243,29 @@ public void Should_create_new_context_for_each_call_to_execute() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.RaiseException(CreateDictionary("key", "original_value"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + Should.Throw(() => breaker.RaiseException(CreateDictionary("key", "original_value"))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset breaker.Execute(_ => { }, CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -1346,7 +1281,7 @@ public void Should_initialise_LastException_to_null_on_creation() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1356,12 +1291,11 @@ public void Should_set_LastException_on_handling_exception_even_when_not_breakin .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -1374,12 +1308,12 @@ public void Should_set_LastException_on_handling_inner_exception_even_when_not_b Exception toRaiseAsInner = new DivideByZeroException(); Exception withInner = new AggregateException(toRaiseAsInner); - breaker.Invoking(x => x.RaiseException(withInner)) - .Should().Throw().Which.Should().BeSameAs(toRaiseAsInner); + Should.Throw(() => breaker.RaiseException(withInner)) + .ShouldBeSameAs(toRaiseAsInner); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastException.Should().BeSameAs(toRaiseAsInner); + breaker.LastException.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -1389,15 +1323,12 @@ public void Should_set_LastException_to_last_raised_exception_when_breaking() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -1407,19 +1338,16 @@ public void Should_set_LastException_to_null_on_circuit_reset() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); - - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); + Should.Throw(() => breaker.RaiseException()); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastException.Should().BeOfType(); + breaker.LastException.ShouldBeOfType(); breaker.Reset(); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } #endregion @@ -1438,8 +1366,8 @@ public void Should_set_PolicyResult_on_handling_inner_exception() PolicyResult policyResult = breaker.ExecuteAndCapture(() => throw withInner); - policyResult.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); - policyResult.FinalException.Should().BeSameAs(toRaiseAsInner); + policyResult.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); + policyResult.FinalException.ShouldBeSameAs(toRaiseAsInner); } #endregion @@ -1465,11 +1393,10 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca using (var cancellationTokenSource = new CancellationTokenSource()) { - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1494,12 +1421,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1524,12 +1450,11 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1554,12 +1479,11 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1582,11 +1506,10 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele using (var cancellationTokenSource = new CancellationTokenSource()) { - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1596,13 +1519,11 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .Handle() .CircuitBreaker(1, TimeSpan.FromMinutes(1)); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => breaker.RaiseException()); - breaker.Invoking(x => x.RaiseException()) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var ex = Should.Throw(() => breaker.RaiseException()); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.InnerException.ShouldBeOfType(); // Circuit is now broken. @@ -1621,12 +1542,11 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1649,16 +1569,15 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act implicitlyCapturedActionCancellationTokenSource.Cancel(); - breaker.Invoking(x => x.Execute(_ => + Should.Throw(() => breaker.Execute(_ => { attemptsInvoked++; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + .CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1684,13 +1603,13 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().NotThrow(); + Should.NotThrow(() => result = breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1715,13 +1634,13 @@ public void Should_honour_and_report_cancellation_during_func_execution() using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => result = breaker.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) + .CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs index 6f99f0f457..386dfd9b31 100644 --- a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultAsyncSpecs.cs @@ -38,10 +38,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -52,7 +52,7 @@ public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .CircuitBreakerAsync(1, TimeSpan.MaxValue); var result = await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault); - result.Should().Be(ResultPrimitive.Fault); + result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -62,9 +62,8 @@ public void Should_throw_if_faults_allowed_before_breaking_is_less_than_one() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(0, TimeSpan.FromSeconds(10)); - action.Should().Throw() - .And.ParamName.Should() - .Be("handledEventsAllowedBeforeBreaking"); + Should.Throw(action) + .ParamName.ShouldBe("handledEventsAllowedBeforeBreaking"); } [Fact] @@ -74,9 +73,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(1, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -85,7 +83,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() Action action = () => Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(1, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -97,7 +95,7 @@ public void Should_initialise_to_closed_state() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -112,16 +110,16 @@ public async Task Should_not_open_circuit_if_specified_number_of_specified_handl .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Good); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -132,19 +130,18 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.Fault); + var ex = await Should.ThrowAsync>(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.Result.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -156,19 +153,18 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + var ex = await Should.ThrowAsync>(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.Result.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -179,19 +175,18 @@ public async Task Should_open_circuit_with_the_last_handled_result_after_specifi .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault))) - .ResultCode.Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault))) - .ResultCode.Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ResultCode.ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Good))) - .Should().ThrowAsync>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result.ResultCode == ResultPrimitive.Fault); + var ex = await Should.ThrowAsync>(() => breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Good))); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); + ex.Result.ResultCode.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -202,16 +197,16 @@ public async Task Should_not_open_circuit_if_result_returned_is_not_the_handled_ .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -223,16 +218,16 @@ public async Task Should_not_open_circuit_if_result_returned_is_not_one_of_the_h .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -243,16 +238,16 @@ public async Task Should_not_open_circuit_if_result_returned_does_not_match_resu .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -264,16 +259,16 @@ public async Task Should_not_open_circuit_if_result_returned_does_not_match_any_ .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain))) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -283,7 +278,7 @@ public async Task Should_not_open_circuit_if_result_returned_does_not_match_any_ [Fact] public async Task Should_halfopen_circuit_after_the_specified_duration_has_passed() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -293,30 +288,29 @@ public async Task Should_halfopen_circuit_after_the_specified_duration_has_passe .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); } [Fact] public async Task Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_a_fault() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -326,35 +320,33 @@ public async Task Should_open_circuit_again_after_the_specified_duration_has_pas .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration returns a fault, so circuit should break again (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync(); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); } [Fact] public async Task Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_return_a_fault() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -364,46 +356,44 @@ public async Task Should_reset_circuit_after_the_specified_duration_has_passed_i .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Good); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // circuit has been reset so should once again allow 2 faults to be raised before breaking (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - await breaker.Awaiting(b => b.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -412,28 +402,28 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -442,36 +432,36 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public async Task Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -480,14 +470,14 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -504,7 +494,7 @@ public async Task Should_only_allow_single_execution_on_first_entering_halfopen_ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -513,22 +503,22 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => permitSecondExecutionAttempt.Set(); // Hold first execution open until second indicates it is no longer needed, or time out. - permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); await TaskHelper.EmptyTask; firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. - permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitSecondExecutionAttempt.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -557,7 +547,7 @@ await breaker.ExecuteAsync(async () => permitFirstExecutionEnd.Set(); #pragma warning disable xUnit1031 - Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).Should().BeTrue(); + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); #pragma warning restore xUnit1031 if (firstExecution.IsFaulted) @@ -570,22 +560,25 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public async Task Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -594,14 +587,14 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s .CircuitBreakerAsync(1, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -619,7 +612,7 @@ public async Task Should_allow_single_execution_per_break_duration_in_halfopen_s // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(async () => { - await breaker.Awaiting(x => x.ExecuteAsync(async () => + await Should.NotThrowAsync(() => breaker.ExecuteAsync(async () => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -633,7 +626,7 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrowAsync(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -642,8 +635,8 @@ await breaker.Awaiting(x => x.ExecuteAsync(async () => Task secondExecution = Task.Factory.StartNew(async () => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -674,7 +667,7 @@ await breaker.ExecuteAsync(async () => permitFirstExecutionEnd.Set(); #pragma warning disable xUnit1031 - Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).Should().BeTrue(); + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); #pragma warning restore xUnit1031 if (firstExecution.IsFaulted) @@ -687,15 +680,18 @@ await breaker.ExecuteAsync(async () => throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -705,7 +701,7 @@ await breaker.ExecuteAsync(async () => [Fact] public async Task Should_open_circuit_and_block_calls_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -713,26 +709,25 @@ public async Task Should_open_circuit_and_block_calls_if_manual_override_open() var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-fault-returning executions should not reset circuit bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(b => b.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -740,24 +735,23 @@ public async Task Should_hold_circuit_open_despite_elapsed_time_if_manual_overri var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - await breaker.Awaiting(x => x.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })) - .Should().ThrowAsync(); - delegateExecutedWhenBroken.Should().BeFalse(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => { delegateExecutedWhenBroken = true; return Task.FromResult(ResultPrimitive.Good); })); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public async Task Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -765,22 +759,21 @@ public async Task Should_close_circuit_again_on_reset_after_manual_override() var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); } [Fact] public async Task Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -790,23 +783,22 @@ public async Task Should_be_able_to_reset_automatically_opened_circuit_without_s .CircuitBreakerAsync(2, durationOfBreak); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); } #endregion @@ -818,20 +810,20 @@ public void Should_not_call_onreset_on_initialise() { Action, TimeSpan> onBreak = (_, _) => { }; bool onResetCalled = false; - Action onReset = () => { onResetCalled = true; }; + Action onReset = () => onResetCalled = true; Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] public async Task Should_call_onbreak_when_breaking_circuit_automatically() { bool onBreakCalled = false; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled = true; Action onReset = () => { }; var breaker = Policy @@ -839,40 +831,40 @@ public async Task Should_call_onbreak_when_breaking_circuit_automatically() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBeFalse(); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().BeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBeTrue(); } [Fact] public void Should_call_onbreak_when_breaking_circuit_manually() { bool onBreakCalled = false; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled = true; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled = true; Action onReset = () => { }; var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_calls_placed_through_open_circuit() { int onBreakCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; var breaker = Policy @@ -880,30 +872,29 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_subsequent_call_failure_which_arrives_on_open_state_though_started_on_closed_state() { int onBreakCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; Action onReset = () => { }; var breaker = Policy @@ -916,7 +907,7 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(async () => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); (await breaker.ExecuteAsync(async () => { @@ -928,21 +919,21 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); return ResultPrimitive.Fault; - })).Should().Be(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. + })).ShouldBe(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); @@ -950,9 +941,9 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f #pragma warning disable xUnit1031 // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif #pragma warning restore xUnit1031 @@ -961,11 +952,11 @@ public async Task Should_call_onbreak_when_breaking_circuit_first_time_but_not_f throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -973,10 +964,10 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not { int onBreakCalled = 0; int onResetCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -985,34 +976,33 @@ public async Task Should_call_onreset_when_automatically_closing_circuit_but_not .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -1026,15 +1016,15 @@ public async Task Should_not_call_onreset_on_successive_successful_calls() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))).Should().NotThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -1043,11 +1033,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1056,33 +1046,31 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().NotThrowAsync(); - onHalfOpenCalled.Should().Be(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + onHalfOpenCalled.ShouldBe(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -1091,11 +1079,11 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1104,28 +1092,27 @@ public async Task Should_call_onhalfopen_when_automatically_transitioning_to_hal .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception or fault raised, circuit is now open - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -1133,10 +1120,10 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() { int onBreakCalled = 0; int onResetCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1145,21 +1132,19 @@ public async Task Should_call_onreset_when_manually_resetting_circuit() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().ThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + await Should.ThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - await breaker.Awaiting(x => x.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))) - .Should().NotThrowAsync(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + await Should.NotThrowAsync(() => breaker.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good))); } #region Tests of supplied parameters to onBreak delegate @@ -1169,7 +1154,7 @@ public async Task Should_call_onbreak_with_the_last_handled_result() { ResultPrimitive? handledResult = null; - Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; + Action, TimeSpan, Context> onBreak = (outcome, _, _) => handledResult = outcome.Result; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -1179,14 +1164,14 @@ public async Task Should_call_onbreak_with_the_last_handled_result() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - handledResult?.Should().Be(ResultPrimitive.Fault); + handledResult?.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -1194,7 +1179,7 @@ public async Task Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; - Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action, TimeSpan, Context> onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -1204,24 +1189,24 @@ public async Task Should_call_onbreak_with_the_correct_timespan() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() { TimeSpan? passedBreakTimespan = null; - Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action, TimeSpan, Context> onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1229,13 +1214,13 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() var breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } #endregion @@ -1247,7 +1232,7 @@ public async Task Should_call_onbreak_with_the_passed_context() { IDictionary? contextData = null; - Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; + Action, TimeSpan, Context> onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; var breaker = Policy @@ -1255,17 +1240,17 @@ public async Task Should_call_onbreak_with_the_passed_context() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1274,9 +1259,9 @@ public async Task Should_call_onreset_with_the_passed_context() IDictionary? contextData = null; Action, TimeSpan, Context> onBreak = (_, _, _) => { }; - Action onReset = context => { contextData = context; }; + Action onReset = context => contextData = context; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1286,20 +1271,20 @@ public async Task Should_call_onreset_with_the_passed_context() .CircuitBreakerAsync(2, durationOfBreak, onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context await breaker.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1307,7 +1292,7 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context { IDictionary contextData = CreateDictionary("key1", "value1", "key2", "value2"); - Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; + Action, TimeSpan, Context> onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; var breaker = Policy @@ -1315,14 +1300,14 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -1337,31 +1322,31 @@ public async Task Should_create_new_context_for_each_call_to_execute() .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1), onBreak, onReset); - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // 2 exception or fault raised, circuit is now open (await breaker.RaiseResultSequenceAsync(CreateDictionary("key", "original_value"), ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset await breaker.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -1377,8 +1362,8 @@ public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_cre .HandleResult(ResultPrimitive.Fault) .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1389,12 +1374,12 @@ public async Task Should_set_LastHandledResult_on_handling_result_even_when_not_ .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1405,15 +1390,15 @@ public async Task Should_set_LastHandledResult_to_last_handled_result_when_break .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1424,20 +1409,20 @@ public async Task Should_set_LastHandledResult_to_default_on_circuit_reset() .CircuitBreakerAsync(2, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); breaker.Reset(); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } #endregion @@ -1465,10 +1450,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ CancellationToken cancellationToken = cancellationTokenSource.Token; (await breaker.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1492,15 +1477,18 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => breaker.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1524,14 +1512,17 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => breaker.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1555,14 +1546,17 @@ public async Task Should_report_cancellation_during_faulting_action_execution_wh { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => breaker.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1587,10 +1581,10 @@ public async Task Should_report_faulting_from_faulting_action_execution_when_use CancellationToken cancellationToken = cancellationTokenSource.Token; (await breaker.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1601,11 +1595,10 @@ public async Task Should_report_cancellation_when_both_open_circuit_and_cancella .CircuitBreakerAsync(1, TimeSpan.FromMinutes(1)); (await breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - var ex = await breaker.Awaiting(x => x.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().ThrowAsync() - .WithMessage("The circuit is now open and is not allowing calls."); + var ex = await Should.ThrowAsync(() => breaker.RaiseResultSequenceAsync(ResultPrimitive.Fault)); + ex.Message.ShouldBe("The circuit is now open and is not allowing calls."); // Circuit is now broken. @@ -1623,14 +1616,13 @@ public async Task Should_report_cancellation_when_both_open_circuit_and_cancella CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex2 = await breaker.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, + var ex2 = await Should.ThrowAsync(() => breaker.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex2.And.CancellationToken.Should().Be(cancellationToken); + ResultPrimitive.Good)); + ex2.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1653,18 +1645,17 @@ public async Task Should_honour_different_cancellationToken_captured_implicitly_ implicitlyCapturedActionCancellationTokenSource.Cancel(); - var ex = await breaker.Awaiting(x => x.ExecuteAsync(async _ => + var ex = await Should.ThrowAsync(() => breaker.ExecuteAsync(async _ => { attemptsInvoked++; await TaskHelper.EmptyTask; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); return ResultPrimitive.Good; - }, policyCancellationToken)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + }, policyCancellationToken)); + ex.CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs index 1686046dc4..4e238687c9 100644 --- a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultMixedResultExceptionSpecs.cs @@ -12,20 +12,17 @@ public void Should_open_circuit_with_exception_after_specified_number_of_specifi .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var exception = Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.InnerException.ShouldBeOfType(); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -37,20 +34,18 @@ public void Should_open_circuit_with_the_last_exception_after_specified_number_o .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var exception = Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.InnerException.ShouldBeOfType(); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -61,21 +56,19 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .Or() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.Fault); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -87,20 +80,18 @@ public void Should_open_circuit_with_the_last_exception_after_specified_number_o .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var exception = Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.InnerException.ShouldBeOfType(); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -111,21 +102,19 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.Fault); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -136,21 +125,19 @@ public void Should_open_circuit_if_results_and_exceptions_returned_match_combina .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "key"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "key"))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault)) - .ResultCode.Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ResultCode.ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(new ResultClass(ResultPrimitive.Good))) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result.ResultCode == ResultPrimitive.Fault); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Good))); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ResultCode.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -162,16 +149,16 @@ public void Should_not_open_circuit_if_result_returned_is_not_one_of_the_configu .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -182,17 +169,14 @@ public void Should_not_open_circuit_if_exception_thrown_is_not_one_of_the_config .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -205,29 +189,26 @@ public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the // non-matched result predicate breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // non-matched exception predicate - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "value"))); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -240,29 +221,24 @@ public void Should_open_circuit_with_the_last_exception_after_specified_number_o .OrResult(ResultPrimitive.FaultAgain) .CircuitBreaker(4, TimeSpan.FromMinutes(1)); - breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.RaiseResultSequence(ResultPrimitive.Fault).ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.RaiseResultSequence(ResultPrimitive.FaultAgain).ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 4 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls.") - .WithInnerException(); + var exception = Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.InnerException.ShouldBeOfType(); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -275,29 +251,26 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .OrResult(ResultPrimitive.FaultAgain) .CircuitBreaker(4, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 4 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Good)) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.FaultAgain); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(ResultPrimitive.Good)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ShouldBe(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -309,20 +282,18 @@ public void Should_not_open_circuit_if_result_raised_or_exception_thrown_is_not_ .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new ArgumentException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new ArgumentException())); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -332,7 +303,7 @@ public void Should_not_open_circuit_if_result_raised_or_exception_thrown_is_not_ [Fact] public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_a_fault() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -343,36 +314,32 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration returns a fault, so circuit should break again breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); } [Fact] public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_an_exception() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -383,29 +350,25 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration returns a fault, so circuit should break again - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); + breaker.CircuitState.ShouldBe(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); } @@ -420,7 +383,7 @@ public void Should_call_onbreak_with_the_last_handled_result() { ResultPrimitive? handledResult = null; - Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; + Action, TimeSpan, Context> onBreak = (outcome, _, _) => handledResult = outcome.Result; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -430,15 +393,14 @@ public void Should_call_onbreak_with_the_last_handled_result() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - handledResult?.Should().Be(ResultPrimitive.Fault); + handledResult?.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -446,7 +408,7 @@ public void Should_call_onbreak_with_the_last_raised_exception() { Exception? lastException = null; - Action, TimeSpan, Context> onBreak = (outcome, _, _) => { lastException = outcome.Exception; }; + Action, TimeSpan, Context> onBreak = (outcome, _, _) => lastException = outcome.Exception; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -457,14 +419,13 @@ public void Should_call_onbreak_with_the_last_raised_exception() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - lastException.Should().BeOfType(); + lastException.ShouldBeOfType(); } #endregion @@ -481,8 +442,8 @@ public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_cre .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -494,12 +455,12 @@ public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaki .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -510,13 +471,12 @@ public void Should_set_LastException_on_exception_even_when_not_breaking() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeOfType(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -527,16 +487,15 @@ public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -548,15 +507,14 @@ public void Should_set_LastException_to_last_exception_when_breaking() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeOfType(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeOfType(); } [Fact] @@ -567,21 +525,20 @@ public void Should_set_LastHandledResult_and_LastException_to_default_on_circuit .OrResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.Invoking(b => b.RaiseResultAndOrExceptionSequence(new DivideByZeroException())) - .Should().Throw(); + Should.Throw(() => breaker.RaiseResultAndOrExceptionSequence(new DivideByZeroException())); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); breaker.Reset(); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs index ce2e45bda7..8b81387544 100644 --- a/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/CircuitBreakerTResultSpecs.cs @@ -38,10 +38,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -52,7 +52,7 @@ public void Should_be_able_to_handle_a_duration_of_timespan_maxvalue() .CircuitBreaker(1, TimeSpan.MaxValue); var result = breaker.RaiseResultSequence(ResultPrimitive.Fault); - result.Should().Be(ResultPrimitive.Fault); + result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -62,9 +62,8 @@ public void Should_throw_if_faults_allowed_before_breaking_is_less_than_one() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(0, TimeSpan.FromSeconds(10)); - action.Should().Throw() - .And.ParamName.Should() - .Be("handledEventsAllowedBeforeBreaking"); + Should.Throw(action) + .ParamName.ShouldBe("handledEventsAllowedBeforeBreaking"); } [Fact] @@ -74,9 +73,8 @@ public void Should_throw_if_duration_of_break_is_less_than_zero() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, -TimeSpan.FromSeconds(1)); - action.Should().Throw() - .And.ParamName.Should() - .Be("durationOfBreak"); + Should.Throw(action) + .ParamName.ShouldBe("durationOfBreak"); } [Fact] @@ -85,7 +83,7 @@ public void Should_be_able_to_handle_a_duration_of_break_of_zero() Action action = () => Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(1, TimeSpan.Zero); - action.Should().NotThrow(); + Should.NotThrow(action); } [Fact] @@ -97,7 +95,7 @@ public void Should_initialise_to_closed_state() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -112,16 +110,16 @@ public void Should_not_open_circuit_if_specified_number_of_specified_handled_res .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Good); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -132,19 +130,18 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.Fault); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -156,19 +153,18 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result == ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Open); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -179,19 +175,18 @@ public void Should_open_circuit_with_the_last_handled_result_after_specified_num .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault)) - .ResultCode.Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault)) - .ResultCode.Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ResultCode.ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(new ResultClass(ResultPrimitive.Good))) - .Should().Throw>() - .WithMessage("The circuit is now open and is not allowing calls.") - .Where(e => e.Result.ResultCode == ResultPrimitive.Fault); + var exception = Should.Throw>(() => breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.Good))); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); + exception.Result.ResultCode.ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] @@ -202,16 +197,16 @@ public void Should_not_open_circuit_if_result_returned_is_not_the_handled_result .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -223,16 +218,16 @@ public void Should_not_open_circuit_if_result_returned_is_not_one_of_the_handled .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -243,16 +238,16 @@ public void Should_not_open_circuit_if_result_returned_does_not_match_result_pre .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -264,16 +259,16 @@ public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain)) - .ResultCode.Should().Be(ResultPrimitive.FaultAgain); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ResultCode.ShouldBe(ResultPrimitive.FaultAgain); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -283,7 +278,7 @@ public void Should_not_open_circuit_if_result_returned_does_not_match_any_of_the [Fact] public void Should_halfopen_circuit_after_the_specified_duration_has_passed() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -293,30 +288,29 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed() .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); } [Fact] public void Should_open_circuit_again_after_the_specified_duration_has_passed_if_the_next_call_raises_a_fault() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -326,36 +320,33 @@ public void Should_open_circuit_again_after_the_specified_duration_has_passed_if .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration returns a fault, so circuit should break again breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); } [Fact] public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_next_call_does_not_return_a_fault() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -365,45 +356,43 @@ public void Should_reset_circuit_after_the_specified_duration_has_passed_if_the_ .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration is successful, so circuit should reset breaker.Execute(() => ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // circuit has been reset so should once again allow 2 faults to be raised before breaking breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.Invoking(b => b.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + breaker.CircuitState.ShouldBe(CircuitState.Open); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -412,28 +401,28 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__test_execution_permit_directly() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -442,36 +431,36 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should permit first execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should reject a second execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.Throw(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Allow another time window to pass (breaker should still be HalfOpen). SystemClock.UtcNow = () => time.Add(durationOfBreak).Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // OnActionPreExecute() should now permit another trial execution. - breaker.BreakerController.Invoking(c => c.OnActionPreExecute()).Should().NotThrow(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + Should.NotThrow(() => breaker.BreakerController.OnActionPreExecute()); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); } [Fact] public void Should_only_allow_single_execution_on_first_entering_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -480,14 +469,14 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state, and request a second execution before the first has completed (ie still during the HalfOpen state). // The second execution should be rejected due to the halfopen state. @@ -504,7 +493,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -517,7 +506,7 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap: we should be able to verify it doesn't execute, and is rejected by a breaker in a HalfOpen state. @@ -526,8 +515,8 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -552,7 +541,11 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -563,22 +556,25 @@ public void Should_only_allow_single_execution_on_first_entering_halfopen_state_ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should not have been permitted. // - Second execution attempt should have been rejected with HalfOpen state as cause. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeFalse(); - secondDelegateRejectedInHalfOpenState.Should().BeTrue(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeFalse(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeTrue(); } [Fact] public void Should_allow_single_execution_per_break_duration_in_halfopen_state__integration_test() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -587,14 +583,14 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ .CircuitBreaker(1, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // exception raised, circuit is now open. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); // break duration passes, circuit now half open SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // Start one execution during the HalfOpen state. // Request a second execution while the first is still in flight (not completed), while still during the HalfOpen state, but after one breakDuration later. @@ -612,7 +608,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // First execution in HalfOpen state: we should be able to verify state is HalfOpen as it executes. Task firstExecution = Task.Factory.StartNew(() => { - breaker.Invoking(x => x.Execute(() => + Should.NotThrow(() => breaker.Execute(() => { firstDelegateExecutedInHalfOpenState = breaker.CircuitState == CircuitState.HalfOpen; // For readability of test results, we assert on this at test end rather than nested in Task and breaker here. @@ -625,7 +621,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ firstExecutionActive = false; return ResultPrimitive.Good; - })).Should().NotThrow(); + })); }, TaskCreationOptions.LongRunning); // Attempt a second execution, signalled by the first execution to ensure they overlap; start it one breakDuration later. We should be able to verify it does execute, though the breaker is still in a HalfOpen state. @@ -634,8 +630,8 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ Task secondExecution = Task.Factory.StartNew(() => { // Validation of correct sequencing and overlapping of tasks in test (guard against erroneous test refactorings/operation). - firstExecutionActive.Should().BeTrue(); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + firstExecutionActive.ShouldBeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); try { @@ -662,7 +658,11 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ // Graceful cleanup: allow executions time to end naturally; signal them to end if not; timeout any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. permitFirstExecutionEnd.WaitOne(testTimeoutToExposeDeadlocks); permitFirstExecutionEnd.Set(); - Task.WaitAll(new[] { firstExecution, secondExecution }, testTimeoutToExposeDeadlocks).Should().BeTrue(); + +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method + Task.WaitAll([firstExecution, secondExecution], testTimeoutToExposeDeadlocks).ShouldBeTrue(); +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method + if (firstExecution.IsFaulted) { throw firstExecution!.Exception!; @@ -673,15 +673,18 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ throw secondExecution!.Exception!; } - firstExecution.Status.Should().Be(TaskStatus.RanToCompletion); - secondExecution.Status.Should().Be(TaskStatus.RanToCompletion); + firstExecution.Status.ShouldBe(TaskStatus.RanToCompletion); + secondExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // Assert: // - First execution should have been permitted and executed under a HalfOpen state // - Second overlapping execution in halfopen state should have been permitted, one breakDuration later. - firstDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateExecutedInHalfOpenState.Should().BeTrue(); - secondDelegateRejectedInHalfOpenState.Should().BeFalse(); + firstDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + firstDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateExecutedInHalfOpenState.ShouldNotBeNull(); + secondDelegateExecutedInHalfOpenState.Value.ShouldBeTrue(); + secondDelegateRejectedInHalfOpenState.ShouldNotBeNull(); + secondDelegateRejectedInHalfOpenState.Value.ShouldBeFalse(); } #endregion @@ -691,7 +694,7 @@ public void Should_allow_single_execution_per_break_duration_in_halfopen_state__ [Fact] public void Should_open_circuit_and_block_calls_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -699,26 +702,25 @@ public void Should_open_circuit_and_block_calls_if_manual_override_open() CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); // circuit manually broken: execution should be blocked; even non-fault-returning executions should not reset circuit bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.LastException.Should().BeOfType(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + breaker.LastException.ShouldBeOfType(); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_open() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -726,24 +728,23 @@ public void Should_hold_circuit_open_despite_elapsed_time_if_manual_override_ope CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); bool delegateExecutedWhenBroken = false; - breaker.Invoking(x => x.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })) - .Should().Throw(); - delegateExecutedWhenBroken.Should().BeFalse(); + Should.Throw(() => breaker.Execute(() => { delegateExecutedWhenBroken = true; return ResultPrimitive.Good; })); + delegateExecutedWhenBroken.ShouldBeFalse(); } [Fact] public void Should_close_circuit_again_on_reset_after_manual_override() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -751,22 +752,21 @@ public void Should_close_circuit_again_on_reset_after_manual_override() CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => ResultPrimitive.Good)); } [Fact] public void Should_be_able_to_reset_automatically_opened_circuit_without_specified_duration_passing() { - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -776,23 +776,22 @@ public void Should_be_able_to_reset_automatically_opened_circuit_without_specifi .CircuitBreaker(2, durationOfBreak); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); + breaker.CircuitState.ShouldBe(CircuitState.Open); // reset circuit, with no time having passed breaker.Reset(); - SystemClock.UtcNow().Should().Be(time); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)).Should().NotThrow(); + SystemClock.UtcNow().ShouldBe(time); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => ResultPrimitive.Good)); } #endregion @@ -804,13 +803,13 @@ public void Should_not_call_onreset_on_initialise() { Action, TimeSpan> onBreak = (_, _) => { }; bool onResetCalled = false; - Action onReset = () => { onResetCalled = true; }; + Action onReset = () => onResetCalled = true; Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -825,16 +824,16 @@ public void Should_call_onbreak_when_breaking_circuit_automatically() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBeFalse(); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().BeTrue(); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBeTrue(); } [Fact] @@ -847,11 +846,11 @@ public void Should_call_onbreak_when_breaking_circuit_manually() CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onBreakCalled.Should().BeFalse(); + onBreakCalled.ShouldBeFalse(); breaker.Isolate(); - onBreakCalled.Should().BeTrue(); + onBreakCalled.ShouldBeTrue(); } [Fact] @@ -866,23 +865,22 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // call through circuit when already broken - should not retrigger onBreak - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -902,7 +900,7 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub using ManualResetEvent permitMainThreadToOpenCircuit = new ManualResetEvent(false); Task longRunningExecution = Task.Factory.StartNew(() => { - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); breaker.Execute(() => { @@ -912,42 +910,44 @@ public void Should_call_onbreak_when_breaking_circuit_first_time_but_not_for_sub permitLongRunningExecutionToReturnItsFailure.WaitOne(testTimeoutToExposeDeadlocks); // Throw a further failure when rest of test has already broken the circuit. - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); return ResultPrimitive.Fault; - }).Should().Be(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. + }).ShouldBe(ResultPrimitive.Fault); // However, since execution started when circuit was closed, BrokenCircuitException will not have been thrown on entry; the original fault should still be returned. }, TaskCreationOptions.LongRunning); - permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).Should().BeTrue(); + permitMainThreadToOpenCircuit.WaitOne(testTimeoutToExposeDeadlocks).ShouldBeTrue(); // Break circuit in the normal manner: onBreak() should be called once. - breaker.CircuitState.Should().Be(CircuitState.Closed); - onBreakCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); // Permit the second (long-running) execution to hit the open circuit with its failure. permitLongRunningExecutionToReturnItsFailure.Set(); +#pragma warning disable xUnit1031 // Do not use blocking task operations in test method // Graceful cleanup: allow executions time to end naturally; timeout if any deadlocks; expose any execution faults. This validates the test ran as expected (and background delegates are complete) before we assert on outcomes. #if NET - longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks, CancellationToken.None).ShouldBeTrue(); #else - longRunningExecution.Wait(testTimeoutToExposeDeadlocks).Should().BeTrue(); + longRunningExecution.Wait(testTimeoutToExposeDeadlocks).ShouldBeTrue(); #endif +#pragma warning restore xUnit1031 // Do not use blocking task operations in test method if (longRunningExecution.IsFaulted) { throw longRunningExecution!.Exception!; } - longRunningExecution.Status.Should().Be(TaskStatus.RanToCompletion); + longRunningExecution.Status.ShouldBe(TaskStatus.RanToCompletion); // onBreak() should still only have been called once. - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); } [Fact] @@ -958,7 +958,7 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -967,34 +967,33 @@ public void Should_call_onreset_when_automatically_closing_circuit_but_not_when_ .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); // first call after duration is successful, so circuit should reset breaker.Execute(() => ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -1002,21 +1001,21 @@ public void Should_not_call_onreset_on_successive_successful_calls() { Action, TimeSpan> onBreak = (_, _) => { }; bool onResetCalled = false; - Action onReset = () => { onResetCalled = true; }; + Action onReset = () => onResetCalled = true; CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - onResetCalled.Should().BeFalse(); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); breaker.Execute(() => ResultPrimitive.Good); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().BeFalse(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBeFalse(); } [Fact] @@ -1025,11 +1024,11 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ int onBreakCalled = 0; int onResetCalled = 0; int onHalfOpenCalled = 0; - Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; - Action onReset = () => { onResetCalled++; }; - Action onHalfOpen = () => { onHalfOpenCalled++; }; + Action, TimeSpan> onBreak = (_, _) => onBreakCalled++; + Action onReset = () => onResetCalled++; + Action onHalfOpen = () => onHalfOpenCalled++; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1038,32 +1037,31 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - onHalfOpenCalled.Should().Be(0); // not yet transitioned to half-open, because we have not queried state + onHalfOpenCalled.ShouldBe(0); // not yet transitioned to half-open, because we have not queried state // first call after duration is successful, so circuit should reset breaker.Execute(() => ResultPrimitive.Good); - onHalfOpenCalled.Should().Be(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - onResetCalled.Should().Be(1); + onHalfOpenCalled.ShouldBe(1); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + onResetCalled.ShouldBe(1); } [Fact] @@ -1076,7 +1074,7 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ Action onReset = () => { onResetCalled++; }; Action onHalfOpen = () => { onHalfOpenCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1085,28 +1083,27 @@ public void Should_call_onhalfopen_when_automatically_transitioning_to_halfopen_ .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset, onHalfOpen); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(0); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(0); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - onBreakCalled.Should().Be(1); + .ShouldBe(ResultPrimitive.Fault); + onBreakCalled.ShouldBe(1); // 2 exception raised, circuit is now open - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); - onBreakCalled.Should().Be(1); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); + breaker.CircuitState.ShouldBe(CircuitState.Open); + onBreakCalled.ShouldBe(1); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); - onHalfOpenCalled.Should().Be(1); - onResetCalled.Should().Be(0); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); + onHalfOpenCalled.ShouldBe(1); + onResetCalled.ShouldBe(0); } [Fact] @@ -1117,7 +1114,7 @@ public void Should_call_onreset_when_manually_resetting_circuit() Action, TimeSpan> onBreak = (_, _) => { onBreakCalled++; }; Action onReset = () => { onResetCalled++; }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1126,20 +1123,19 @@ public void Should_call_onreset_when_manually_resetting_circuit() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - onBreakCalled.Should().Be(0); + onBreakCalled.ShouldBe(0); breaker.Isolate(); - onBreakCalled.Should().Be(1); + onBreakCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Isolated); - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)) - .Should().Throw(); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); + Should.Throw(() => breaker.Execute(() => ResultPrimitive.Good)); - onResetCalled.Should().Be(0); + onResetCalled.ShouldBe(0); breaker.Reset(); - onResetCalled.Should().Be(1); + onResetCalled.ShouldBe(1); - breaker.CircuitState.Should().Be(CircuitState.Closed); - breaker.Invoking(x => x.Execute(() => ResultPrimitive.Good)).Should().NotThrow(); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + Should.NotThrow(() => breaker.Execute(() => ResultPrimitive.Good)); } #region Tests of supplied parameters to onBreak delegate @@ -1149,7 +1145,7 @@ public void Should_call_onbreak_with_the_last_handled_result() { ResultPrimitive? handledResult = null; - Action, TimeSpan, Context> onBreak = (outcome, _, _) => { handledResult = outcome.Result; }; + Action, TimeSpan, Context> onBreak = (outcome, _, _) => handledResult = outcome.Result; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -1159,14 +1155,14 @@ public void Should_call_onbreak_with_the_last_handled_result() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - handledResult?.Should().Be(ResultPrimitive.Fault); + handledResult?.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -1174,7 +1170,7 @@ public void Should_call_onbreak_with_the_correct_timespan() { TimeSpan? passedBreakTimespan = null; - Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action, TimeSpan, Context> onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; TimeSpan durationOfBreak = TimeSpan.FromMinutes(1); @@ -1184,24 +1180,24 @@ public void Should_call_onbreak_with_the_correct_timespan() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - passedBreakTimespan.Should().Be(durationOfBreak); + passedBreakTimespan.ShouldBe(durationOfBreak); } [Fact] public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() { TimeSpan? passedBreakTimespan = null; - Action, TimeSpan, Context> onBreak = (_, timespan, _) => { passedBreakTimespan = timespan; }; + Action, TimeSpan, Context> onBreak = (_, timespan, _) => passedBreakTimespan = timespan; Action onReset = _ => { }; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1209,13 +1205,13 @@ public void Should_open_circuit_with_timespan_maxvalue_if_manual_override_open() CircuitBreakerPolicy breaker = Policy .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, durationOfBreak, onBreak, onReset); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); // manually break circuit breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); - passedBreakTimespan.Should().Be(TimeSpan.MaxValue); + passedBreakTimespan.ShouldBe(TimeSpan.MaxValue); } #endregion @@ -1227,7 +1223,7 @@ public void Should_call_onbreak_with_the_passed_context() { IDictionary? contextData = null; - Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; + Action, TimeSpan, Context> onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; CircuitBreakerPolicy breaker = Policy @@ -1235,17 +1231,17 @@ public void Should_call_onbreak_with_the_passed_context() .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1254,9 +1250,9 @@ public void Should_call_onreset_with_the_passed_context() IDictionary? contextData = null; Action, TimeSpan, Context> onBreak = (_, _, _) => { }; - Action onReset = context => { contextData = context; }; + Action onReset = context => contextData = context; - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); @@ -1266,20 +1262,20 @@ public void Should_call_onreset_with_the_passed_context() .CircuitBreaker(2, durationOfBreak, onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); SystemClock.UtcNow = () => time.Add(durationOfBreak); - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // first call after duration should invoke onReset, with context breaker.Execute(_ => ResultPrimitive.Good, CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -1287,7 +1283,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( { IDictionary contextData = CreateDictionary("key1", "value1", "key2", "value2"); - Action, TimeSpan, Context> onBreak = (_, _, context) => { contextData = context; }; + Action, TimeSpan, Context> onBreak = (_, _, context) => contextData = context; Action onReset = _ => { }; CircuitBreakerPolicy breaker = Policy @@ -1295,14 +1291,14 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - contextData.Should().BeEmpty(); + contextData.ShouldBeEmpty(); } [Fact] @@ -1317,31 +1313,31 @@ public void Should_create_new_context_for_each_call_to_execute() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1), onBreak, onReset); - var time = 1.January(2000); + var time = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); SystemClock.UtcNow = () => time; var durationOfBreak = TimeSpan.FromMinutes(1); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); // 2 exception raised, circuit is now open breaker.RaiseResultSequence(CreateDictionary("key", "original_value"), ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); - contextValue.Should().Be("original_value"); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); + contextValue.ShouldBe("original_value"); SystemClock.UtcNow = () => time.Add(durationOfBreak); // duration has passed, circuit now half open - breaker.CircuitState.Should().Be(CircuitState.HalfOpen); + breaker.CircuitState.ShouldBe(CircuitState.HalfOpen); // but not yet reset // first call after duration is successful, so circuit should reset breaker.Execute(_ => ResultPrimitive.Good, CreateDictionary("key", "new_value")); - breaker.CircuitState.Should().Be(CircuitState.Closed); - contextValue.Should().Be("new_value"); + breaker.CircuitState.ShouldBe(CircuitState.Closed); + contextValue.ShouldBe("new_value"); } #endregion @@ -1357,8 +1353,8 @@ public void Should_initialise_LastHandledResult_and_LastResult_to_default_on_cre .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1369,12 +1365,12 @@ public void Should_set_LastHandledResult_on_handling_result_even_when_not_breaki .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1385,15 +1381,15 @@ public void Should_set_LastHandledResult_to_last_handled_result_when_breaking() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); } [Fact] @@ -1404,20 +1400,20 @@ public void Should_set_LastHandledResult_to_default_on_circuit_reset() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + breaker.CircuitState.ShouldBe(CircuitState.Open); - breaker.LastHandledResult.Should().Be(ResultPrimitive.Fault); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(ResultPrimitive.Fault); + breaker.LastException.ShouldBeNull(); breaker.Reset(); - breaker.LastHandledResult.Should().Be(default); - breaker.LastException.Should().BeNull(); + breaker.LastHandledResult.ShouldBe(default); + breaker.LastException.ShouldBeNull(); } #endregion @@ -1444,10 +1440,10 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca { breaker.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1471,15 +1467,18 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => breaker.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1502,14 +1501,17 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => breaker.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1532,14 +1534,17 @@ public void Should_report_cancellation_during_faulting_action_execution_when_use using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => breaker.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1562,10 +1567,10 @@ public void Should_report_faulting_from_faulting_action_execution_when_user_dele using (var cancellationTokenSource = new CancellationTokenSource()) { breaker.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1576,11 +1581,10 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() .CircuitBreaker(1, TimeSpan.FromMinutes(1)); breaker.RaiseResultSequence(ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - breaker.Invoking(x => x.RaiseResultSequence(ResultPrimitive.Fault)) - .Should().Throw() - .WithMessage("The circuit is now open and is not allowing calls."); + var exception = Should.Throw(() => breaker.RaiseResultSequence(ResultPrimitive.Fault)); + exception.Message.ShouldBe("The circuit is now open and is not allowing calls."); // Circuit is now broken. int attemptsInvoked = 0; @@ -1597,14 +1601,17 @@ public void Should_report_cancellation_when_both_open_circuit_and_cancellation() CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - breaker.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => breaker.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -1627,17 +1634,16 @@ public void Should_honour_different_cancellationToken_captured_implicitly_by_act implicitlyCapturedActionCancellationTokenSource.Cancel(); - breaker.Invoking(x => x.Execute(_ => + Should.Throw(() => breaker.Execute(_ => { attemptsInvoked++; implicitlyCapturedActionCancellationToken.ThrowIfCancellationRequested(); return ResultPrimitive.Good; }, policyCancellationToken)) - .Should().Throw() - .And.CancellationToken.Should().Be(implicitlyCapturedActionCancellationToken); + .CancellationToken.ShouldBe(implicitlyCapturedActionCancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs b/test/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs index ce4e3a3188..b0bb310f2a 100644 --- a/test/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/ICircuitBreakerPolicySpecs.cs @@ -9,7 +9,7 @@ public void Should_be_able_to_use_CircuitState_via_interface() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } @@ -21,7 +21,7 @@ public void Should_be_able_to_use_Isolate_via_interface() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); } [Fact] @@ -32,10 +32,10 @@ public void Should_be_able_to_use_Reset_via_interface() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); breaker.Isolate(); - breaker.CircuitState.Should().Be(CircuitState.Isolated); + breaker.CircuitState.ShouldBe(CircuitState.Isolated); breaker.Reset(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -45,6 +45,6 @@ public void Should_be_able_to_use_LastException_via_interface() .Handle() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.LastException.Should().BeNull(); + breaker.LastException.ShouldBeNull(); } } diff --git a/test/Polly.Specs/CircuitBreaker/ICircuitBreakerTResultPolicySpecs.cs b/test/Polly.Specs/CircuitBreaker/ICircuitBreakerTResultPolicySpecs.cs index c9d8b345a0..b2b9fdd161 100644 --- a/test/Polly.Specs/CircuitBreaker/ICircuitBreakerTResultPolicySpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/ICircuitBreakerTResultPolicySpecs.cs @@ -9,6 +9,6 @@ public void Should_be_able_to_use_LastHandledResult_via_interface() .HandleResult(ResultPrimitive.Fault) .CircuitBreaker(2, TimeSpan.FromMinutes(1)); - breaker.LastHandledResult.Should().Be(default); + breaker.LastHandledResult.ShouldBe(default); } } diff --git a/test/Polly.Specs/ContextSpecs.cs b/test/Polly.Specs/ContextSpecs.cs index d9cb105c94..f7b8528b01 100644 --- a/test/Polly.Specs/ContextSpecs.cs +++ b/test/Polly.Specs/ContextSpecs.cs @@ -7,9 +7,9 @@ public void Should_assign_OperationKey_from_constructor() { Context context = new Context("SomeKey"); - context.OperationKey.Should().Be("SomeKey"); + context.OperationKey.ShouldBe("SomeKey"); - context.Keys.Count.Should().Be(0); + context.Keys.Count.ShouldBe(0); } [Fact] @@ -17,9 +17,9 @@ public void Should_assign_OperationKey_and_context_data_from_constructor() { Context context = new Context("SomeKey", CreateDictionary("key1", "value1", "key2", "value2")); - context.OperationKey.Should().Be("SomeKey"); - context["key1"].Should().Be("value1"); - context["key2"].Should().Be("value2"); + context.OperationKey.ShouldBe("SomeKey"); + context["key1"].ShouldBe("value1"); + context["key2"].ShouldBe("value2"); } [Fact] @@ -27,7 +27,7 @@ public void NoArgsCtor_should_assign_no_OperationKey() { Context context = []; - context.OperationKey.Should().BeNull(); + context.OperationKey.ShouldBeNull(); } [Fact] @@ -35,7 +35,7 @@ public void Should_assign_CorrelationId_when_accessed() { Context context = new Context("SomeKey"); - context.CorrelationId.Should().NotBeEmpty(); + context.OperationKey.ShouldBe("SomeKey"); } [Fact] @@ -46,6 +46,6 @@ public void Should_return_consistent_CorrelationId() Guid retrieved1 = context.CorrelationId; Guid retrieved2 = context.CorrelationId; - retrieved1.Should().Be(retrieved2); + retrieved1.ShouldBe(retrieved2); } } diff --git a/test/Polly.Specs/Custom/CustomAsyncSpecs.cs b/test/Polly.Specs/Custom/CustomAsyncSpecs.cs index e98c27c47e..ce3937b30e 100644 --- a/test/Polly.Specs/Custom/CustomAsyncSpecs.cs +++ b/test/Polly.Specs/Custom/CustomAsyncSpecs.cs @@ -9,13 +9,12 @@ public void Should_be_able_to_construct_active_policy() { AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(async () => { - // Placeholder for more substantive async work. Console.WriteLine("Do something"); await Task.CompletedTask; }); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -26,11 +25,10 @@ public async Task Active_policy_should_execute() bool executed = false; - await policy.Awaiting(x => x.ExecuteAsync(() => { executed = true; return Task.CompletedTask; })) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.ExecuteAsync(() => { executed = true; return Task.CompletedTask; })); - executed.Should().BeTrue(); - preExecuted.Should().BeTrue(); + executed.ShouldBeTrue(); + preExecuted.ShouldBeTrue(); } [Fact] @@ -40,13 +38,12 @@ public void Should_be_able_to_construct_reactive_policy() { AsyncAddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviourAsync(async ex => { - // Placeholder for more substantive async work. Console.WriteLine("Handling " + ex.Message); await Task.CompletedTask; }); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -58,16 +55,15 @@ public async Task Reactive_policy_should_handle_exception() Exception toThrow = new InvalidOperationException(); bool executed = false; - var ex = await policy.Awaiting(x => x.ExecuteAsync(() => + var ex = await Should.ThrowAsync(() => policy.ExecuteAsync(() => { executed = true; throw toThrow; - })) - .Should().ThrowAsync(); - ex.Which.Should().Be(toThrow); + })); + ex.ShouldBe(toThrow); - executed.Should().BeTrue(); - handled.Should().Be(toThrow); + executed.ShouldBeTrue(); + handled.ShouldBe(toThrow); } [Fact] @@ -79,15 +75,14 @@ public async Task Reactive_policy_should_be_able_to_ignore_unhandled_exception() Exception toThrow = new NotImplementedException(); bool executed = false; - var ex = await policy.Awaiting(x => x.ExecuteAsync(() => - { - executed = true; - throw toThrow; - })) - .Should().ThrowAsync(); - ex.Which.Should().Be(toThrow); - - executed.Should().BeTrue(); - handled.Should().Be(null); + var ex = await Should.ThrowAsync(() => policy.ExecuteAsync(() => + { + executed = true; + throw toThrow; + })); + ex.ShouldBe(toThrow); + + executed.ShouldBeTrue(); + handled.ShouldBe(null); } } diff --git a/test/Polly.Specs/Custom/CustomSpecs.cs b/test/Polly.Specs/Custom/CustomSpecs.cs index 65a981be81..18db7adbed 100644 --- a/test/Polly.Specs/Custom/CustomSpecs.cs +++ b/test/Polly.Specs/Custom/CustomSpecs.cs @@ -10,7 +10,7 @@ public void Should_be_able_to_construct_active_policy() PreExecutePolicy policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -21,11 +21,10 @@ public void Active_policy_should_execute() bool executed = false; - policy.Invoking(x => x.Execute(() => { executed = true; })) - .Should().NotThrow(); + Should.NotThrow(() => policy.Execute(() => executed = true)); - executed.Should().BeTrue(); - preExecuted.Should().BeTrue(); + executed.ShouldBeTrue(); + preExecuted.ShouldBeTrue(); } [Fact] @@ -36,7 +35,7 @@ public void Should_be_able_to_construct_reactive_policy() AddBehaviourIfHandlePolicy policy = Policy.Handle().WithBehaviour(ex => Console.WriteLine("Handling " + ex.Message)); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -48,15 +47,14 @@ public void Reactive_policy_should_handle_exception() Exception toThrow = new InvalidOperationException(); bool executed = false; - policy.Invoking(x => x.Execute(() => + Should.Throw(() => policy.Execute(() => { executed = true; throw toThrow; - })) - .Should().Throw().Which.Should().Be(toThrow); + })).ShouldBe(toThrow); - executed.Should().BeTrue(); - handled.Should().Be(toThrow); + executed.ShouldBeTrue(); + handled.ShouldBe(toThrow); } [Fact] @@ -68,14 +66,13 @@ public void Reactive_policy_should_be_able_to_ignore_unhandled_exception() Exception toThrow = new NotImplementedException(); bool executed = false; - policy.Invoking(x => x.Execute(() => + Should.Throw(() => policy.Execute(() => { executed = true; throw toThrow; - })) - .Should().Throw().Which.Should().Be(toThrow); + })).ShouldBe(toThrow); - executed.Should().BeTrue(); - handled.Should().Be(null); + executed.ShouldBeTrue(); + handled.ShouldBeNull(); } } diff --git a/test/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs b/test/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs index 7eb82ea357..c76b9309b0 100644 --- a/test/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Custom/CustomTResultAsyncSpecs.cs @@ -15,7 +15,7 @@ public void Should_be_able_to_construct_active_policy() }); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -25,11 +25,10 @@ public async Task Active_policy_should_execute() AsyncPreExecutePolicy policy = AsyncPreExecutePolicy.CreateAsync(() => { preExecuted = true; return Task.CompletedTask; }); bool executed = false; - await policy.Awaiting(x => x.ExecuteAsync(async () => { executed = true; await Task.CompletedTask; return ResultPrimitive.Undefined; })) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.ExecuteAsync(async () => { executed = true; await Task.CompletedTask; return ResultPrimitive.Undefined; })); - executed.Should().BeTrue(); - preExecuted.Should().BeTrue(); + executed.ShouldBeTrue(); + preExecuted.ShouldBeTrue(); } [Fact] @@ -45,7 +44,7 @@ public void Should_be_able_to_construct_reactive_policy() }); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -65,10 +64,10 @@ public async Task Reactive_policy_should_handle_result() await Task.CompletedTask; return toReturn; })) - .Should().Be(toReturn); + .ShouldBe(toReturn); - executed.Should().BeTrue(); - handled.Should().Be(toReturn); + executed.ShouldBeTrue(); + handled.ShouldBe(toReturn); } [Fact] @@ -88,9 +87,9 @@ public async Task Reactive_policy_should_be_able_to_ignore_unhandled_result() await Task.CompletedTask; return toReturn; })) - .Should().Be(toReturn); + .ShouldBe(toReturn); - executed.Should().BeTrue(); - handled.Should().Be(null); + executed.ShouldBeTrue(); + handled.ShouldBe(null); } } diff --git a/test/Polly.Specs/Custom/CustomTResultSpecs.cs b/test/Polly.Specs/Custom/CustomTResultSpecs.cs index acf63fcd76..4df2d232fe 100644 --- a/test/Polly.Specs/Custom/CustomTResultSpecs.cs +++ b/test/Polly.Specs/Custom/CustomTResultSpecs.cs @@ -10,7 +10,7 @@ public void Should_be_able_to_construct_active_policy() PreExecutePolicy policy = PreExecutePolicy.Create(() => Console.WriteLine("Do something")); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -21,15 +21,14 @@ public void Active_policy_should_execute() bool executed = false; - policy.Invoking(x => x.Execute(() => + Should.NotThrow(() => policy.Execute(() => { executed = true; return ResultPrimitive.Undefined; - })) - .Should().NotThrow(); + })); - executed.Should().BeTrue(); - preExecuted.Should().BeTrue(); + executed.ShouldBeTrue(); + preExecuted.ShouldBeTrue(); } [Fact] @@ -40,7 +39,7 @@ public void Should_be_able_to_construct_reactive_policy() AddBehaviourIfHandlePolicy policy = Policy.HandleResult(ResultPrimitive.Fault).WithBehaviour(outcome => Console.WriteLine("Handling " + outcome.Result)); }; - construct.Should().NotThrow(); + Should.NotThrow(construct); } [Fact] @@ -57,10 +56,10 @@ public void Reactive_policy_should_handle_result() executed = true; return toReturn; }) - .Should().Be(toReturn); + .ShouldBe(toReturn); - executed.Should().BeTrue(); - handled.Should().Be(toReturn); + executed.ShouldBeTrue(); + handled.ShouldBe(toReturn); } [Fact] @@ -77,9 +76,9 @@ public void Reactive_policy_should_be_able_to_ignore_unhandled_result() executed = true; return toReturn; }) - .Should().Be(toReturn); + .ShouldBe(toReturn); - executed.Should().BeTrue(); - handled.Should().Be(null); + executed.ShouldBeTrue(); + handled.ShouldBe(null); } } diff --git a/test/Polly.Specs/Fallback/FallbackAsyncSpecs.cs b/test/Polly.Specs/Fallback/FallbackAsyncSpecs.cs index 23796ffd6c..ab80fcde70 100644 --- a/test/Polly.Specs/Fallback/FallbackAsyncSpecs.cs +++ b/test/Polly.Specs/Fallback/FallbackAsyncSpecs.cs @@ -15,8 +15,8 @@ public void Should_throw_when_fallback_func_is_null() .Handle() .FallbackAsync(fallbackActionAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -29,8 +29,8 @@ public void Should_throw_when_fallback_func_is_null_with_onFallback() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -43,8 +43,8 @@ public void Should_throw_when_fallback_func_is_null_with_onFallback_with_context .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -57,8 +57,8 @@ public void Should_throw_when_onFallback_delegate_is_null() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallbackAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallbackAsync"); } [Fact] @@ -71,8 +71,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallbackAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallbackAsync"); } #endregion @@ -91,7 +91,7 @@ public async Task Should_not_execute_fallback_when_executed_delegate_does_not_th await fallbackPolicy.ExecuteAsync(() => TaskHelper.EmptyTask); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -104,9 +104,9 @@ public async Task Should_not_execute_fallback_when_executed_delegate_throws_exce .Handle() .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -119,9 +119,9 @@ public async Task Should_execute_fallback_when_executed_delegate_throws_exceptio .Handle() .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -135,9 +135,9 @@ public async Task Should_execute_fallback_when_executed_delegate_throws_one_of_e .Or() .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -151,9 +151,9 @@ public async Task Should_not_execute_fallback_when_executed_delegate_throws_exce .Or() .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -166,9 +166,9 @@ public async Task Should_not_execute_fallback_when_exception_thrown_does_not_mat .Handle(_ => false) .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -182,9 +182,9 @@ public async Task Should_not_execute_fallback_when_exception_thrown_does_not_mat .Or(_ => false) .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -197,9 +197,9 @@ public async Task Should_execute_fallback_when_exception_thrown_matches_handling .Handle(_ => true) .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -213,9 +213,9 @@ public async Task Should_execute_fallback_when_exception_thrown_matches_one_of_h .Or() .FallbackAsync(fallbackActionAsync); - await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -232,11 +232,10 @@ public async Task Should_not_handle_exception_thrown_by_fallback_delegate_even_i .Handle() .FallbackAsync(fallbackActionAsync); - var ex = await fallbackPolicy.Awaiting(x => x.RaiseExceptionAsync((e, _) => e.HelpLink = "FromExecuteDelegate")) - .Should().ThrowAsync(); - ex.And.HelpLink.Should().Be("FromFallbackAction"); + var ex = await Should.ThrowAsync(() => fallbackPolicy.RaiseExceptionAsync((e, _) => e.HelpLink = "FromExecuteDelegate")); + ex.HelpLink.ShouldBe("FromFallbackAction"); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -246,7 +245,7 @@ public async Task Should_throw_for_generic_method_execution_on_non_generic_polic .Handle() .FallbackAsync(_ => TaskHelper.EmptyTask); - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => Task.FromResult(0))).Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.ExecuteAsync(() => Task.FromResult(0))); } #endregion @@ -269,9 +268,9 @@ public async Task Should_call_onFallback_passing_exception_triggering_fallback() Exception instanceToThrow = new ArgumentNullException("myParam"); await fallbackPolicy.RaiseExceptionAsync(instanceToThrow); - fallbackActionExecuted.Should().BeTrue(); - exceptionPassedToOnFallback.Should().BeOfType(); - exceptionPassedToOnFallback.Should().Be(instanceToThrow); + fallbackActionExecuted.ShouldBeTrue(); + exceptionPassedToOnFallback.ShouldBeOfType(); + exceptionPassedToOnFallback.ShouldBe(instanceToThrow); } [Fact] @@ -288,7 +287,7 @@ public async Task Should_not_call_onFallback_when_executed_delegate_does_not_thr await fallbackPolicy.ExecuteAsync(() => TaskHelper.EmptyTask); - onFallbackExecuted.Should().BeFalse(); + onFallbackExecuted.ShouldBeFalse(); } #endregion @@ -308,13 +307,15 @@ public async Task Should_call_onFallback_with_the_passed_context() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + fallbackPolicy.ExecuteAsync( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -330,13 +331,15 @@ public async Task Should_call_onFallback_with_the_passed_context_when_execute_an .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + fallbackPolicy.ExecuteAndCaptureAsync( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -344,7 +347,7 @@ public async Task Should_call_onFallback_with_independent_context_for_independen { Func fallbackActionAsync = (_, _) => TaskHelper.EmptyTask; - IDictionary contextData = new Dictionary(); + var contextData = new Dictionary(); Func onFallbackAsync = (ex, ctx) => { contextData[ex.GetType()] = ctx["key"]; return TaskHelper.EmptyTask; }; @@ -353,18 +356,13 @@ public async Task Should_call_onFallback_with_independent_context_for_independen .Or() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), CreateDictionary("key", "value1"))) - .Should().NotThrowAsync(); - - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new DivideByZeroException(), CreateDictionary("key", "value2"))) - .Should().NotThrowAsync(); - - contextData.Count.Should().Be(2); - contextData.Keys.Should().Contain(typeof(ArgumentNullException)); - contextData.Keys.Should().Contain(typeof(DivideByZeroException)); - contextData[typeof(ArgumentNullException)].Should().Be("value1"); - contextData[typeof(DivideByZeroException)].Should().Be("value2"); + await Should.NotThrowAsync(() => fallbackPolicy.ExecuteAsync(_ => throw new ArgumentNullException(), CreateDictionary("key", "value1"))); + await Should.NotThrowAsync(() => fallbackPolicy.ExecuteAsync(_ => throw new DivideByZeroException(), CreateDictionary("key", "value2"))); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue(typeof(ArgumentNullException), "value1"); + contextData.ShouldContainKeyAndValue(typeof(DivideByZeroException), "value2"); + contextData.Count.ShouldBe(2); } [Fact] @@ -383,8 +381,8 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context await fallbackPolicy.RaiseExceptionAsync(); - onFallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + onFallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -400,13 +398,15 @@ public async Task Should_call_fallbackAction_with_the_passed_context() .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + fallbackPolicy.ExecuteAsync( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -422,13 +422,15 @@ public async Task Should_call_fallbackAction_with_the_passed_context_when_execut .Handle() .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + fallbackPolicy.ExecuteAndCaptureAsync( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -448,8 +450,8 @@ public async Task Context_should_be_empty_at_fallbackAction_if_execute_not_calle await fallbackPolicy.RaiseExceptionAsync(); - fallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + fallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } #endregion @@ -470,10 +472,9 @@ public async Task Should_call_fallbackAction_with_the_exception() .FallbackAsync(fallbackFunc, onFallback); Exception instanceToThrow = new ArgumentNullException("myParam"); - await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync(instanceToThrow)); - fallbackException.Should().Be(instanceToThrow); + fallbackException.ShouldBe(instanceToThrow); } [Fact] @@ -489,11 +490,10 @@ public async Task Should_call_fallbackAction_with_the_exception_when_execute_and .Handle() .FallbackAsync(fallbackFunc, onFallback); - await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(() => throw new ArgumentNullException())) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.ExecuteAndCaptureAsync(() => throw new ArgumentNullException())); - fallbackException.Should().NotBeNull() - .And.BeOfType(); + fallbackException.ShouldNotBeNull() + .ShouldBeOfType(); } [Fact] @@ -511,10 +511,9 @@ public async Task Should_call_fallbackAction_with_the_matched_inner_exception_un Exception instanceToCapture = new ArgumentNullException("myParam"); Exception instanceToThrow = new Exception(string.Empty, instanceToCapture); - await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync(instanceToThrow)); - fallbackException.Should().Be(instanceToCapture); + fallbackException.ShouldBe(instanceToCapture); } [Fact] @@ -532,10 +531,9 @@ public async Task Should_call_fallbackAction_with_the_matched_inner_of_aggregate Exception instanceToCapture = new ArgumentNullException("myParam"); Exception instanceToThrow = new AggregateException(instanceToCapture); - await fallbackPolicy.Awaiting(p => p.RaiseExceptionAsync(instanceToThrow)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => fallbackPolicy.RaiseExceptionAsync(instanceToThrow)); - fallbackException.Should().Be(instanceToCapture); + fallbackException.ShouldBe(instanceToCapture); } [Fact] @@ -551,10 +549,9 @@ public async Task Should_not_call_fallbackAction_with_the_exception_if_exception .Handle() .FallbackAsync(fallbackFunc, onFallback); - await fallbackPolicy.Awaiting(p => p.ExecuteAsync(() => throw new ArgumentNullException())) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => fallbackPolicy.ExecuteAsync(() => throw new ArgumentNullException())); - fallbackException.Should().BeNull(); + fallbackException.ShouldBeNull(); } #endregion @@ -567,9 +564,8 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -583,13 +579,12 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -598,9 +593,8 @@ public async Task Should_execute_fallback_when_faulting_and_cancellationToken_no bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -614,13 +608,12 @@ public async Task Should_execute_fallback_when_faulting_and_cancellationToken_no using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -629,9 +622,8 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -647,14 +639,13 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -663,9 +654,8 @@ public async Task Should_report_cancellation_and_not_execute_fallback_during_oth bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -681,14 +671,13 @@ public async Task Should_report_cancellation_and_not_execute_fallback_during_oth { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -697,10 +686,9 @@ public async Task Should_handle_cancellation_and_execute_fallback_during_otherwi bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .Or() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .Or() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -716,13 +704,12 @@ public async Task Should_handle_cancellation_and_execute_fallback_during_otherwi { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -731,9 +718,8 @@ public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -749,13 +735,12 @@ public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -764,9 +749,8 @@ public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_acti bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -782,13 +766,12 @@ public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_acti { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -797,9 +780,8 @@ public async Task Should_handle_handled_fault_and_execute_fallback_following_fau bool fallbackActionExecuted = false; Func fallbackActionAsync = _ => { fallbackActionExecuted = true; return TaskHelper.EmptyTask; }; - var policy = Policy - .Handle() - .FallbackAsync(fallbackActionAsync); + var policy = Policy.Handle() + .FallbackAsync(fallbackActionAsync); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -815,13 +797,12 @@ public async Task Should_handle_handled_fault_and_execute_fallback_following_fau { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } #endregion diff --git a/test/Polly.Specs/Fallback/FallbackSpecs.cs b/test/Polly.Specs/Fallback/FallbackSpecs.cs index 428af9c28f..23daf1707e 100644 --- a/test/Polly.Specs/Fallback/FallbackSpecs.cs +++ b/test/Polly.Specs/Fallback/FallbackSpecs.cs @@ -12,11 +12,11 @@ public void Should_throw_when_fallback_action_is_null() Action fallbackAction = null!; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -28,8 +28,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null() .Handle() .Fallback(fallbackAction); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -39,11 +39,11 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() Action onFallback = _ => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -56,8 +56,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF .Handle() .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -67,11 +67,11 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte Action onFallback = (_, _) => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -81,11 +81,11 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF Action onFallback = (_, _) => { }; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -95,11 +95,11 @@ public void Should_throw_when_onFallback_delegate_is_null() Action onFallback = null!; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -112,8 +112,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_action_with_cance .Handle() .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -123,11 +123,11 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Action onFallback = null!; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -137,11 +137,11 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti Action onFallback = null!; Action policy = () => Policy - .Handle() - .Fallback(fallbackAction, onFallback); + .Handle() + .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } #endregion @@ -152,139 +152,139 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti public void Should_not_execute_fallback_when_executed_delegate_does_not_throw() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); fallbackPolicy.Execute(() => { }); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); + Should.Throw(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_exception_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_exceptions_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_exception_not_one_of_exceptions_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .Handle() - .Or() - .Fallback(fallbackAction); + .Handle() + .Or() + .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); + Should.Throw(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_not_execute_fallback_when_exception_thrown_does_not_match_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .Handle(_ => false) - .Fallback(fallbackAction); + .Handle(_ => false) + .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); + Should.Throw(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_not_execute_fallback_when_exception_thrown_does_not_match_any_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .Handle(_ => false) - .Or(_ => false) - .Fallback(fallbackAction); + .Handle(_ => false) + .Or(_ => false) + .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().Throw(); + Should.Throw(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_exception_thrown_matches_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle(_ => true) .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_exception_thrown_matches_one_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle(_ => true) .Or() .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException()).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException()); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -301,10 +301,10 @@ public void Should_not_handle_exception_thrown_by_fallback_delegate_even_if_is_e .Handle() .Fallback(fallbackAction); - fallbackPolicy.Invoking(x => x.RaiseException((e, _) => e.HelpLink = "FromExecuteDelegate")) - .Should().Throw().And.HelpLink.Should().Be("FromFallbackAction"); + Should.Throw(() => fallbackPolicy.RaiseException((e, _) => e.HelpLink = "FromExecuteDelegate")) + .HelpLink.ShouldBe("FromFallbackAction"); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -314,7 +314,7 @@ public void Should_throw_for_generic_method_execution_on_non_generic_policy() .Handle() .Fallback(() => { }); - fallbackPolicy.Invoking(p => p.Execute(() => 0)).Should().Throw(); + Should.Throw(() => fallbackPolicy.Execute(() => 0)); } #endregion @@ -325,7 +325,7 @@ public void Should_throw_for_generic_method_execution_on_non_generic_policy() public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exception_where_policy_doesnt_handle_inner() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -333,16 +333,16 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exce Exception withInner = new Exception(string.Empty, new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerException.ShouldBeOfType(); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_policy_handles_inner_and_executed_delegate_throws_as_non_inner() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -350,16 +350,16 @@ public void Should_execute_fallback_when_policy_handles_inner_and_executed_deleg Exception nonInner = new DivideByZeroException(); - fallbackPolicy.Invoking(x => x.RaiseException(nonInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(nonInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_inner_exception_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -367,16 +367,16 @@ public void Should_execute_fallback_when_executed_delegate_throws_inner_exceptio Exception withInner = new Exception(string.Empty, new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_exceptions_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -385,16 +385,16 @@ public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_e Exception withInner = new Exception(string.Empty, new ArgumentException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_exception_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -402,33 +402,33 @@ public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_e Exception withInner = new Exception(string.Empty, new Exception(string.Empty, new Exception(string.Empty, new DivideByZeroException()))); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_exception_not_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner() - .Fallback(fallbackAction); + .HandleInner() + .Fallback(fallbackAction); Exception withInner = new Exception(string.Empty, new ArgumentException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerException.ShouldBeOfType(); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_inner_exception_thrown_matches_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -436,16 +436,16 @@ public void Should_execute_fallback_when_inner_exception_thrown_matches_handling Exception withInner = new Exception(string.Empty, new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_inner_nested_exception_thrown_matches_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -453,16 +453,16 @@ public void Should_execute_fallback_when_inner_nested_exception_thrown_matches_h Exception withInner = new Exception(string.Empty, new Exception(string.Empty, new Exception(string.Empty, new DivideByZeroException()))); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_inner_exception_thrown_matches_one_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -471,44 +471,44 @@ public void Should_execute_fallback_when_inner_exception_thrown_matches_one_of_h Exception withInner = new Exception(string.Empty, new ArgumentNullException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_match_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner(_ => false) - .Fallback(fallbackAction); + .HandleInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new Exception(string.Empty, new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerException.ShouldBeOfType(); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_match_any_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner(_ => false) - .OrInner(_ => false) - .Fallback(fallbackAction); + .HandleInner(_ => false) + .OrInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new Exception(string.Empty, new ArgumentNullException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerException.Should().BeOfType(); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerException.ShouldBeOfType(); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } #endregion @@ -519,7 +519,7 @@ public void Should_not_execute_fallback_when_inner_exception_thrown_does_not_mat public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_where_policy_doesnt_handle_inner() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -527,16 +527,16 @@ public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_a Exception withInner = new AggregateException(new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerExceptions.Should().ContainSingle(e => e is DivideByZeroException); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerExceptions.Count(e => e is DivideByZeroException).ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -544,16 +544,16 @@ public void Should_execute_fallback_when_executed_delegate_throws_inner_of_aggre Exception withInner = new AggregateException(new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_of_aggregate_exceptions_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -562,16 +562,16 @@ public void Should_execute_fallback_when_executed_delegate_throws_one_of_inner_o Exception withInner = new AggregateException(new ArgumentException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_aggregate_exception_with_inner_handled_by_policy_amongst_other_inners() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -579,16 +579,16 @@ public void Should_execute_fallback_when_executed_delegate_throws_aggregate_exce Exception withInner = new AggregateException(new ArgumentException(), new DivideByZeroException(), new ArgumentNullException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_of_aggregate_exception_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner() @@ -596,33 +596,35 @@ public void Should_execute_fallback_when_executed_delegate_throws_nested_inner_o Exception withInner = new AggregateException(new AggregateException(new DivideByZeroException())); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_execute_fallback_when_executed_delegate_throws_inner_of_aggregate_exception_not_handled_by_policy() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner() - .Fallback(fallbackAction); + .HandleInner() + .Fallback(fallbackAction); Exception withInner = new AggregateException(new ArgumentException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerExceptions.Should().ContainSingle(e => e is ArgumentException); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerExceptions + .Count(e => e is ArgumentException) + .ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_matches_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -630,16 +632,16 @@ public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_mat Exception withInner = new AggregateException(new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_inner_of_aggregate_nested_exception_thrown_matches_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -647,16 +649,16 @@ public void Should_execute_fallback_when_inner_of_aggregate_nested_exception_thr Exception withInner = new AggregateException(new AggregateException(new DivideByZeroException())); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_matches_one_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy .HandleInner(_ => true) @@ -665,44 +667,44 @@ public void Should_execute_fallback_when_inner_of_aggregate_exception_thrown_mat Exception withInner = new AggregateException(new ArgumentNullException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(withInner)); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown_does_not_match_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner(_ => false) - .Fallback(fallbackAction); + .HandleInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new AggregateException(new DivideByZeroException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerExceptions.Should().ContainSingle(e => e is DivideByZeroException); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerExceptions.Count(e => e is DivideByZeroException).ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown_does_not_match_any_of_handling_predicates() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy fallbackPolicy = Policy - .HandleInner(_ => false) - .OrInner(_ => false) - .Fallback(fallbackAction); + .HandleInner(_ => false) + .OrInner(_ => false) + .Fallback(fallbackAction); Exception withInner = new AggregateException(new ArgumentNullException()); - fallbackPolicy.Invoking(x => x.RaiseException(withInner)).Should().Throw().And.InnerExceptions.Should().ContainSingle(e => e is ArgumentNullException); + Should.Throw(() => fallbackPolicy.RaiseException(withInner)).InnerExceptions.Count(e => e is ArgumentNullException).ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } #endregion @@ -713,10 +715,10 @@ public void Should_not_execute_fallback_when_inner_of_aggregate_exception_thrown public void Should_call_onFallback_passing_exception_triggering_fallback() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; Exception? exceptionPassedToOnFallback = null; - Action onFallback = ex => { exceptionPassedToOnFallback = ex; }; + Action onFallback = ex => exceptionPassedToOnFallback = ex; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -725,9 +727,9 @@ public void Should_call_onFallback_passing_exception_triggering_fallback() Exception instanceToThrow = new ArgumentNullException("myParam"); fallbackPolicy.RaiseException(instanceToThrow); - fallbackActionExecuted.Should().BeTrue(); - exceptionPassedToOnFallback.Should().BeOfType(); - exceptionPassedToOnFallback.Should().Be(instanceToThrow); + fallbackActionExecuted.ShouldBeTrue(); + exceptionPassedToOnFallback.ShouldBeOfType(); + exceptionPassedToOnFallback.ShouldBe(instanceToThrow); } [Fact] @@ -736,7 +738,7 @@ public void Should_not_call_onFallback_when_executed_delegate_does_not_throw() Action fallbackAction = () => { }; bool onFallbackExecuted = false; - Action onFallback = _ => { onFallbackExecuted = true; }; + Action onFallback = _ => onFallbackExecuted = true; FallbackPolicy fallbackPolicy = Policy .Handle() @@ -744,7 +746,7 @@ public void Should_not_call_onFallback_when_executed_delegate_does_not_throw() fallbackPolicy.Execute(() => { }); - onFallbackExecuted.Should().BeFalse(); + onFallbackExecuted.ShouldBeFalse(); } #endregion @@ -758,19 +760,21 @@ public void Should_call_onFallback_with_the_passed_context() IDictionary? contextData = null; - Action onFallback = (_, ctx) => { contextData = ctx; }; + Action onFallback = (_, ctx) => contextData = ctx; FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.Execute(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrow(); + Should.NotThrow( + () => + fallbackPolicy.Execute( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -780,19 +784,21 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt IDictionary? contextData = null; - Action onFallback = (_, ctx) => { contextData = ctx; }; + Action onFallback = (_, ctx) => contextData = ctx; FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.ExecuteAndCapture(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrow(); + Should.NotThrow( + () => + fallbackPolicy.ExecuteAndCapture( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -802,26 +808,21 @@ public void Should_call_onFallback_with_independent_context_for_independent_call IDictionary contextData = new Dictionary(); - Action onFallback = (ex, ctx) => { contextData[ex.GetType()] = ctx["key"]; }; + Action onFallback = (ex, ctx) => contextData[ex.GetType()] = ctx["key"]; FallbackPolicy fallbackPolicy = Policy .Handle() .Or() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking( - p => p.Execute(_ => throw new ArgumentNullException(), CreateDictionary("key", "value1"))) - .Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.Execute(_ => throw new ArgumentNullException(), CreateDictionary("key", "value1"))); + Should.NotThrow(() => fallbackPolicy.Execute(_ => throw new DivideByZeroException(), CreateDictionary("key", "value2"))); - fallbackPolicy.Invoking( - p => p.Execute(_ => throw new DivideByZeroException(), CreateDictionary("key", "value2"))) - .Should().NotThrow(); - - contextData.Count.Should().Be(2); - contextData.Keys.Should().Contain(typeof(ArgumentNullException)); - contextData.Keys.Should().Contain(typeof(DivideByZeroException)); - contextData[typeof(ArgumentNullException)].Should().Be("value1"); - contextData[typeof(DivideByZeroException)].Should().Be("value2"); + contextData.Count.ShouldBe(2); + contextData.Keys.ShouldContain(typeof(ArgumentNullException)); + contextData.Keys.ShouldContain(typeof(DivideByZeroException)); + contextData[typeof(ArgumentNullException)].ShouldBe("value1"); + contextData[typeof(DivideByZeroException)].ShouldBe("value2"); } @@ -841,8 +842,8 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( fallbackPolicy.RaiseException(); - onFallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + onFallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -850,7 +851,7 @@ public void Should_call_fallbackAction_with_the_passed_context() { IDictionary? contextData = null; - Action fallbackAction = (ctx, _) => { contextData = ctx; }; + Action fallbackAction = (ctx, _) => contextData = ctx; Action onFallback = (_, _) => { }; @@ -858,13 +859,15 @@ public void Should_call_fallbackAction_with_the_passed_context() .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.Execute(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrow(); + Should.NotThrow( + () => + fallbackPolicy.Execute( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -872,7 +875,7 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ { IDictionary? contextData = null; - Action fallbackAction = (ctx, _) => { contextData = ctx; }; + Action fallbackAction = (ctx, _) => contextData = ctx; Action onFallback = (_, _) => { }; @@ -880,13 +883,15 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.ExecuteAndCapture(_ => throw new ArgumentNullException(), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrow(); + Should.NotThrow( + () => + fallbackPolicy.ExecuteAndCapture( + _ => throw new ArgumentNullException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -905,8 +910,8 @@ public void Context_should_be_empty_at_fallbackAction_if_execute_not_called_with fallbackPolicy.RaiseException(); - fallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + fallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } #endregion @@ -918,7 +923,7 @@ public void Should_call_fallbackAction_with_the_exception() { Exception? fallbackException = null; - Action fallbackAction = (ex, _, _) => { fallbackException = ex; }; + Action fallbackAction = (ex, _, _) => fallbackException = ex; Action onFallback = (_, _) => { }; @@ -927,10 +932,9 @@ public void Should_call_fallbackAction_with_the_exception() .Fallback(fallbackAction, onFallback); Exception instanceToThrow = new ArgumentNullException("myParam"); - fallbackPolicy.Invoking(p => p.RaiseException(instanceToThrow)) - .Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(instanceToThrow)); - fallbackException.Should().Be(instanceToThrow); + fallbackException.ShouldBe(instanceToThrow); } [Fact] @@ -938,18 +942,18 @@ public void Should_call_fallbackAction_with_the_exception_when_execute_and_captu { Exception? fallbackException = null; - Action fallbackAction = (ex, _, _) => { fallbackException = ex; }; + Action fallbackAction = (ex, _, _) => fallbackException = ex; Action onFallback = (_, _) => { }; FallbackPolicy fallbackPolicy = Policy .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.ExecuteAndCapture(() => throw new ArgumentNullException())) - .Should().NotThrow(); - fallbackException.Should().NotBeNull() - .And.BeOfType(); + Should.NotThrow(() => fallbackPolicy.ExecuteAndCapture(() => throw new ArgumentNullException())); + + fallbackException.ShouldNotBeNull() + .ShouldBeOfType(); } [Fact] @@ -957,7 +961,7 @@ public void Should_call_fallbackAction_with_the_matched_inner_exception_unwrappe { Exception? fallbackException = null; - Action fallbackAction = (ex, _, _) => { fallbackException = ex; }; + Action fallbackAction = (ex, _, _) => fallbackException = ex; Action onFallback = (_, _) => { }; @@ -967,10 +971,9 @@ public void Should_call_fallbackAction_with_the_matched_inner_exception_unwrappe Exception instanceToCapture = new ArgumentNullException("myParam"); Exception instanceToThrow = new Exception(string.Empty, instanceToCapture); - fallbackPolicy.Invoking(p => p.RaiseException(instanceToThrow)) - .Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(instanceToThrow)); - fallbackException.Should().Be(instanceToCapture); + fallbackException.ShouldBe(instanceToCapture); } [Fact] @@ -978,7 +981,7 @@ public void Should_call_fallbackAction_with_the_matched_inner_of_aggregate_excep { Exception? fallbackException = null; - Action fallbackAction = (ex, _, _) => { fallbackException = ex; }; + Action fallbackAction = (ex, _, _) => fallbackException = ex; Action onFallback = (_, _) => { }; @@ -988,10 +991,9 @@ public void Should_call_fallbackAction_with_the_matched_inner_of_aggregate_excep Exception instanceToCapture = new ArgumentNullException("myParam"); Exception instanceToThrow = new AggregateException(instanceToCapture); - fallbackPolicy.Invoking(p => p.RaiseException(instanceToThrow)) - .Should().NotThrow(); + Should.NotThrow(() => fallbackPolicy.RaiseException(instanceToThrow)); - fallbackException.Should().Be(instanceToCapture); + fallbackException.ShouldBe(instanceToCapture); } [Fact] @@ -1010,10 +1012,9 @@ public void Should_not_call_fallbackAction_with_the_exception_if_exception_unhan .Handle() .Fallback(fallbackAction, onFallback); - fallbackPolicy.Invoking(p => p.Execute(() => throw new ArgumentNullException())) - .Should().Throw(); + Should.Throw(() => fallbackPolicy.Execute(() => throw new ArgumentNullException())); - fallbackException.Should().BeNull(); + fallbackException.ShouldBeNull(); } #endregion @@ -1027,8 +1028,8 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca Action fallbackAction = () => { fallbackActionExecuted = true; }; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1041,13 +1042,12 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -1057,8 +1057,8 @@ public void Should_execute_fallback_when_faulting_and_cancellationToken_not_canc Action fallbackAction = () => { fallbackActionExecuted = true; }; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1071,13 +1071,12 @@ public void Should_execute_fallback_when_faulting_and_cancellationToken_not_canc using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -1087,8 +1086,8 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex Action fallbackAction = () => { fallbackActionExecuted = true; }; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1105,14 +1104,13 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex cancellationTokenSource.Cancel(); - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } @@ -1120,11 +1118,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex public void Should_report_cancellation_and_not_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_does_not_handle_cancellations() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1139,26 +1137,25 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non_faulting_action_execution_when_user_delegate_observes_cancellationToken_and_fallback_handles_cancellations() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy policy = Policy - .Handle() - .Or() - .Fallback(fallbackAction); + .Handle() + .Or() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1172,24 +1169,23 @@ public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] public void Should_not_report_cancellation_and_not_execute_fallback_if_non_faulting_action_execution_completes_and_user_delegate_does_not_observe_the_set_cancellationToken() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1203,23 +1199,22 @@ public void Should_not_report_cancellation_and_not_execute_fallback_if_non_fault using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); - fallbackActionExecuted.Should().BeFalse(); + attemptsInvoked.ShouldBe(1); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_execution_raises_unhandled_fault_and_user_delegate_does_not_observe_the_set_cancellationToken() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1233,24 +1228,23 @@ public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_exe using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public void Should_handle_handled_fault_and_execute_fallback_following_faulting_action_execution_when_user_delegate_does_not_observe_cancellationToken() { bool fallbackActionExecuted = false; - Action fallbackAction = () => { fallbackActionExecuted = true; }; + Action fallbackAction = () => fallbackActionExecuted = true; FallbackPolicy policy = Policy - .Handle() - .Fallback(fallbackAction); + .Handle() + .Fallback(fallbackAction); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1264,13 +1258,12 @@ public void Should_handle_handled_fault_and_execute_fallback_following_faulting_ using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } #endregion diff --git a/test/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs b/test/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs index a06431b0e9..139cf1501b 100644 --- a/test/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Fallback/FallbackTResultAsyncSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -39,11 +39,11 @@ public void Should_throw_when_fallback_action_is_null() Func> fallbackAction = null!; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -53,11 +53,11 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() Func, Task> onFallbackAsync = _ => TaskHelper.EmptyTask; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -67,11 +67,11 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte Func, Context, Task> onFallbackAsync = (_, _) => TaskHelper.EmptyTask; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -81,11 +81,11 @@ public void Should_throw_when_onFallback_delegate_is_null() Func, Task> onFallbackAsync = null!; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallbackAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallbackAsync"); } [Fact] @@ -95,11 +95,11 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() Func, Context, Task> onFallbackAsync = null!; Action policy = () => Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction, onFallbackAsync); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction, onFallbackAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallbackAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallbackAsync"); } #endregion @@ -113,12 +113,12 @@ public async Task Should_not_execute_fallback_when_executed_delegate_does_not_ra Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -128,24 +128,24 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.FaultAgain); + .ShouldBe(ResultPrimitive.FaultAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] public async Task Should_return_fallback_value_when_executed_delegate_raises_fault_handled_by_policy() { var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(ResultPrimitive.Substitute); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(ResultPrimitive.Substitute); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } [Fact] @@ -155,13 +155,13 @@ public async Task Should_execute_fallback_when_executed_delegate_raises_fault_ha Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -171,14 +171,14 @@ public async Task Should_execute_fallback_when_executed_delegate_raises_one_of_r Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -188,14 +188,14 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(ResultPrimitive.Fault) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(ResultPrimitive.Fault) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain)) - .Should().Be(ResultPrimitive.FaultYetAgain); + .ShouldBe(ResultPrimitive.FaultYetAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -205,13 +205,13 @@ public async Task Should_not_execute_fallback_when_result_raised_does_not_match_ Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => false) - .FallbackAsync(fallbackAction); + .HandleResult(_ => false) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -221,14 +221,14 @@ public async Task Should_not_execute_fallback_when_executed_delegate_raises_faul Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(r => r == ResultPrimitive.Fault) - .OrResult(r => r == ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(r => r == ResultPrimitive.Fault) + .OrResult(r => r == ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain)) - .Should().Be(ResultPrimitive.FaultYetAgain); + .ShouldBe(ResultPrimitive.FaultYetAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -238,13 +238,13 @@ public async Task Should_execute_fallback_when_result_raised_matches_handling_pr Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => true) - .FallbackAsync(fallbackAction); + .HandleResult(_ => true) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Undefined)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -254,14 +254,14 @@ public async Task Should_execute_fallback_when_result_raised_matches_one_of_hand Func> fallbackAction = _ => { fallbackActionExecuted = true; return Task.FromResult(ResultPrimitive.Substitute); }; var fallbackPolicy = Policy - .HandleResult(_ => true) - .OrResult(ResultPrimitive.FaultAgain) - .FallbackAsync(fallbackAction); + .HandleResult(_ => true) + .OrResult(ResultPrimitive.FaultAgain) + .FallbackAsync(fallbackAction); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Undefined)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -278,10 +278,11 @@ public async Task Should_not_handle_result_raised_by_fallback_delegate_even_if_i .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .FallbackAsync(fallbackAction); - (await fallbackPolicy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault, "FromExecuteDelegate"))) - .Should().Match(r => r.ResultCode == ResultPrimitive.Fault && r.SomeString == "FromFallbackAction"); + var result = await fallbackPolicy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault, "FromExecuteDelegate")); + result.ResultCode.ShouldBe(ResultPrimitive.Fault); + result.SomeString.ShouldBe("FromFallbackAction"); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } #endregion @@ -304,9 +305,9 @@ public async Task Should_call_onFallback_passing_result_triggering_fallback() ResultClass resultFromDelegate = new ResultClass(ResultPrimitive.Fault); await fallbackPolicy.ExecuteAsync(() => Task.FromResult(resultFromDelegate)); - fallbackActionExecuted.Should().BeTrue(); - resultPassedToOnFallback.Should().NotBeNull(); - resultPassedToOnFallback.Should().Be(resultFromDelegate); + fallbackActionExecuted.ShouldBeTrue(); + resultPassedToOnFallback.ShouldNotBeNull(); + resultPassedToOnFallback.ShouldBe(resultFromDelegate); } [Fact] @@ -323,7 +324,7 @@ public async Task Should_not_call_onFallback_when_executed_delegate_does_not_rai await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); - onFallbackExecuted.Should().BeFalse(); + onFallbackExecuted.ShouldBeFalse(); } #endregion @@ -331,7 +332,7 @@ public async Task Should_not_call_onFallback_when_executed_delegate_does_not_rai #region Context passing tests [Fact] - public void Should_call_onFallback_with_the_passed_context() + public async Task Should_call_onFallback_with_the_passed_context() { Func> fallbackAction = (_, _) => Task.FromResult(ResultPrimitive.Substitute); @@ -343,14 +344,11 @@ public void Should_call_onFallback_with_the_passed_context() .HandleResult(ResultPrimitive.Fault) .FallbackAsync(fallbackAction, onFallbackAsync); - fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), - CreateDictionary("key1", "value1", "key2", "value2")) - .Result - .Should().Be(ResultPrimitive.Substitute); + (await fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), CreateDictionary("key1", "value1", "key2", "value2"))).ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -366,21 +364,20 @@ public async Task Should_call_onFallback_with_the_passed_context_when_execute_an .HandleResult(ResultPrimitive.Fault) .FallbackAsync(fallbackAction, onFallbackAsync); - (await fallbackPolicy.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Result.Should().Be(ResultPrimitive.Substitute); + (await fallbackPolicy.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), CreateDictionary("key1", "value1", "key2", "value2"))) + .Result.ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] - public void Should_call_onFallback_with_independent_context_for_independent_calls() + public async Task Should_call_onFallback_with_independent_context_for_independent_calls() { Func> fallbackAction = (_, _) => Task.FromResult(ResultPrimitive.Substitute); - IDictionary contextData = new Dictionary(); + var contextData = new Dictionary(); Func, Context, Task> onFallbackAsync = (dr, ctx) => { contextData[dr.Result] = ctx["key"]; return TaskHelper.EmptyTask; }; @@ -389,19 +386,16 @@ public void Should_call_onFallback_with_independent_context_for_independent_call .OrResult(ResultPrimitive.FaultAgain) .FallbackAsync(fallbackAction, onFallbackAsync); - fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), CreateDictionary("key", "value1")) - .Result - .Should().Be(ResultPrimitive.Substitute); + (await fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), CreateDictionary("key", "value1"))) + .ShouldBe(ResultPrimitive.Substitute); - fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.FaultAgain), CreateDictionary("key", "value2")) - .Result - .Should().Be(ResultPrimitive.Substitute); + (await fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.FaultAgain), CreateDictionary("key", "value2"))) + .ShouldBe(ResultPrimitive.Substitute); - contextData.Count.Should().Be(2); - contextData.Keys.Should().Contain(ResultPrimitive.Fault); - contextData.Keys.Should().Contain(ResultPrimitive.FaultAgain); - contextData[ResultPrimitive.Fault].Should().Be("value1"); - contextData[ResultPrimitive.FaultAgain].Should().Be("value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue(ResultPrimitive.Fault, "value1"); + contextData.ShouldContainKeyAndValue(ResultPrimitive.FaultAgain, "value2"); + contextData.Count.ShouldBe(2); } [Fact] @@ -419,14 +413,14 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context .FallbackAsync(fallbackAction, onFallbackAsync); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - onFallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + onFallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } [Fact] - public void Should_call_fallbackAction_with_the_passed_context() + public async Task Should_call_fallbackAction_with_the_passed_context() { IDictionary? contextData = null; @@ -438,14 +432,12 @@ public void Should_call_fallbackAction_with_the_passed_context() .HandleResult(ResultPrimitive.Fault) .FallbackAsync(fallbackActionAsync, onFallbackAsync); - fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), - CreateDictionary("key1", "value1", "key2", "value2")) - .Result - .Should().Be(ResultPrimitive.Substitute); + (await fallbackPolicy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Fault), CreateDictionary("key1", "value1", "key2", "value2"))) + .ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -461,13 +453,15 @@ public async Task Should_call_fallbackAction_with_the_passed_context_when_execut .HandleResult(ResultPrimitive.Fault) .FallbackAsync(fallbackActionAsync, onFallbackAsync); - await fallbackPolicy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Fault), - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + fallbackPolicy.ExecuteAndCaptureAsync( + _ => Task.FromResult(ResultPrimitive.Fault), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -490,10 +484,10 @@ public async Task Context_should_be_empty_at_fallbackAction_if_execute_not_calle .FallbackAsync(fallbackActionAsync, onFallbackAsync); (await fallbackPolicy.RaiseResultSequenceAsync(ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + fallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } #endregion @@ -514,11 +508,11 @@ public async Task Should_call_fallbackAction_with_the_fault() .FallbackAsync(fallbackAction, onFallback); var result = await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Fault)); - result.Should().Be(ResultPrimitive.Substitute); + result.ShouldBe(ResultPrimitive.Substitute); - fallbackOutcome!.Should().NotBeNull(); - fallbackOutcome!.Exception.Should().BeNull(); - fallbackOutcome!.Result.Should().Be(ResultPrimitive.Fault); + fallbackOutcome!.ShouldNotBeNull(); + fallbackOutcome!.Exception.ShouldBeNull(); + fallbackOutcome!.Result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -536,12 +530,12 @@ public async Task Should_call_fallbackAction_with_the_fault_when_execute_and_cap .FallbackAsync(fallbackAction, onFallback); var result = await fallbackPolicy.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Fault)); - result.Should().NotBeNull(); - result.Result.Should().Be(ResultPrimitive.Substitute); + result.ShouldNotBeNull(); + result.Result.ShouldBe(ResultPrimitive.Substitute); - fallbackOutcome!.Should().NotBeNull(); - fallbackOutcome!.Exception.Should().BeNull(); - fallbackOutcome!.Result.Should().Be(ResultPrimitive.Fault); + fallbackOutcome!.ShouldNotBeNull(); + fallbackOutcome!.Exception.ShouldBeNull(); + fallbackOutcome!.Result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -559,9 +553,9 @@ public async Task Should_not_call_fallbackAction_with_the_fault_if_fault_unhandl .FallbackAsync(fallbackAction, onFallback); var result = await fallbackPolicy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.FaultAgain)); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); - fallbackOutcome.Should().BeNull(); + fallbackOutcome.ShouldBeNull(); } #endregion @@ -592,12 +586,12 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -624,12 +618,12 @@ public async Task Should_execute_fallback_when_faulting_and_cancellationToken_no CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -656,15 +650,14 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } @@ -692,14 +685,13 @@ public async Task Should_report_cancellation_and_not_execute_fallback_during_oth { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -728,12 +720,12 @@ public async Task Should_handle_cancellation_and_execute_fallback_during_otherwi CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -761,12 +753,12 @@ public async Task Should_not_report_cancellation_and_not_execute_fallback_if_non CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -794,12 +786,12 @@ public async Task Should_report_unhandled_fault_and_not_execute_fallback_if_acti CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.FaultYetAgain)) - .Should().Be(ResultPrimitive.FaultYetAgain); + .ShouldBe(ResultPrimitive.FaultYetAgain); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -827,12 +819,12 @@ public async Task Should_handle_handled_fault_and_execute_fallback_following_fau CancellationToken cancellationToken = cancellationTokenSource.Token; (await policy.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } #endregion diff --git a/test/Polly.Specs/Fallback/FallbackTResultSpecs.cs b/test/Polly.Specs/Fallback/FallbackTResultSpecs.cs index 6f51dd02bc..fcc4c8f381 100644 --- a/test/Polly.Specs/Fallback/FallbackTResultSpecs.cs +++ b/test/Polly.Specs/Fallback/FallbackTResultSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -42,8 +42,8 @@ public void Should_throw_when_fallback_action_is_null() .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -55,8 +55,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null() .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -69,8 +69,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback() .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -83,8 +83,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -97,8 +97,8 @@ public void Should_throw_when_fallback_action_is_null_with_onFallback_with_conte .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -111,8 +111,8 @@ public void Should_throw_when_fallback_action_with_cancellation_is_null_with_onF .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("fallbackAction"); + Should.Throw(policy) + .ParamName.ShouldBe("fallbackAction"); } [Fact] @@ -125,8 +125,8 @@ public void Should_throw_when_onFallback_delegate_is_null() .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -139,8 +139,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_action_with_cance .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -153,8 +153,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context() .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } [Fact] @@ -167,8 +167,8 @@ public void Should_throw_when_onFallback_delegate_is_null_with_context_with_acti .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); - policy.Should().Throw() - .And.ParamName.Should().Be("onFallback"); + Should.Throw(policy) + .ParamName.ShouldBe("onFallback"); } #endregion @@ -187,7 +187,7 @@ public void Should_not_execute_fallback_when_executed_delegate_does_not_raise_fa fallbackPolicy.Execute(() => ResultPrimitive.Good); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -200,9 +200,9 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).Should().Be(ResultPrimitive.FaultAgain); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).ShouldBe(ResultPrimitive.FaultAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -212,7 +212,7 @@ public void Should_return_fallback_value_when_executed_delegate_raises_fault_han .HandleResult(ResultPrimitive.Fault) .Fallback(ResultPrimitive.Substitute); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Substitute); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).ShouldBe(ResultPrimitive.Substitute); } [Fact] @@ -225,9 +225,9 @@ public void Should_execute_fallback_when_executed_delegate_raises_fault_handled_ .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Substitute); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -241,9 +241,9 @@ public void Should_execute_fallback_when_executed_delegate_raises_one_of_results .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).Should().Be(ResultPrimitive.Substitute); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultAgain).ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -257,9 +257,9 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).Should().Be(ResultPrimitive.FaultYetAgain); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).ShouldBe(ResultPrimitive.FaultYetAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -272,9 +272,9 @@ public void Should_not_execute_fallback_when_result_raised_does_not_match_handli .HandleResult(_ => false) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).Should().Be(ResultPrimitive.Fault); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault).ShouldBe(ResultPrimitive.Fault); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -288,9 +288,9 @@ public void Should_not_execute_fallback_when_executed_delegate_raises_fault_not_ .OrResult(r => r == ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).Should().Be(ResultPrimitive.FaultYetAgain); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.FaultYetAgain).ShouldBe(ResultPrimitive.FaultYetAgain); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -303,9 +303,9 @@ public void Should_execute_fallback_when_result_raised_matches_handling_predicat .HandleResult(_ => true) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).Should().Be(ResultPrimitive.Substitute); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -319,9 +319,9 @@ public void Should_execute_fallback_when_result_raised_matches_one_of_handling_p .OrResult(ResultPrimitive.FaultAgain) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).Should().Be(ResultPrimitive.Substitute); + fallbackPolicy.RaiseResultSequence(ResultPrimitive.Undefined).ShouldBe(ResultPrimitive.Substitute); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -338,10 +338,12 @@ public void Should_not_handle_result_raised_by_fallback_delegate_even_if_is_resu .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Fallback(fallbackAction); - fallbackPolicy.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault, "FromExecuteDelegate")) - .Should().Match(r => r.ResultCode == ResultPrimitive.Fault && r.SomeString == "FromFallbackAction"); + var result = fallbackPolicy.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault, "FromExecuteDelegate")); - fallbackActionExecuted.Should().BeTrue(); + result.ShouldNotBeNull(); + result.ResultCode.ShouldBe(ResultPrimitive.Fault); + result.SomeString.ShouldBe("FromFallbackAction"); + fallbackActionExecuted.ShouldBeTrue(); } #endregion @@ -364,9 +366,9 @@ public void Should_call_onFallback_passing_result_triggering_fallback() ResultClass resultFromDelegate = new ResultClass(ResultPrimitive.Fault); fallbackPolicy.Execute(() => resultFromDelegate); - fallbackActionExecuted.Should().BeTrue(); - resultPassedToOnFallback.Should().NotBeNull(); - resultPassedToOnFallback.Should().Be(resultFromDelegate); + fallbackActionExecuted.ShouldBeTrue(); + resultPassedToOnFallback.ShouldNotBeNull(); + resultPassedToOnFallback.ShouldBe(resultFromDelegate); } [Fact] @@ -383,7 +385,7 @@ public void Should_not_call_onFallback_when_executed_delegate_does_not_raise_fau fallbackPolicy.Execute(() => ResultPrimitive.Good); - onFallbackExecuted.Should().BeFalse(); + onFallbackExecuted.ShouldBeFalse(); } #endregion @@ -405,11 +407,11 @@ public void Should_call_onFallback_with_the_passed_context() fallbackPolicy.Execute(_ => ResultPrimitive.Fault, CreateDictionary("key1", "value1", "key2", "value2")) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -427,11 +429,11 @@ public void Should_call_onFallback_with_the_passed_context_when_execute_and_capt fallbackPolicy.ExecuteAndCapture(_ => ResultPrimitive.Fault, CreateDictionary("key1", "value1", "key2", "value2")) - .Result.Should().Be(ResultPrimitive.Substitute); + .Result.ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -449,16 +451,16 @@ public void Should_call_onFallback_with_independent_context_for_independent_call .Fallback(fallbackAction, onFallback); fallbackPolicy.Execute(_ => ResultPrimitive.Fault, CreateDictionary("key", "value1")) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); fallbackPolicy.Execute(_ => ResultPrimitive.FaultAgain, CreateDictionary("key", "value2")) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - contextData.Count.Should().Be(2); - contextData.Keys.Should().Contain(ResultPrimitive.Fault); - contextData.Keys.Should().Contain(ResultPrimitive.FaultAgain); - contextData[ResultPrimitive.Fault].Should().Be("value1"); - contextData[ResultPrimitive.FaultAgain].Should().Be("value2"); + contextData.Count.ShouldBe(2); + contextData.Keys.ShouldContain(ResultPrimitive.Fault); + contextData.Keys.ShouldContain(ResultPrimitive.FaultAgain); + contextData[ResultPrimitive.Fault].ShouldBe("value1"); + contextData[ResultPrimitive.FaultAgain].ShouldBe("value2"); } [Fact] @@ -477,8 +479,8 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault); - onFallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + onFallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -496,11 +498,11 @@ public void Should_call_fallbackAction_with_the_passed_context() fallbackPolicy.Execute(_ => ResultPrimitive.Fault, CreateDictionary("key1", "value1", "key2", "value2")) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -518,11 +520,11 @@ public void Should_call_fallbackAction_with_the_passed_context_when_execute_and_ fallbackPolicy.ExecuteAndCapture(_ => ResultPrimitive.Fault, CreateDictionary("key1", "value1", "key2", "value2")) - .Result.Should().Be(ResultPrimitive.Substitute); + .Result.ShouldBe(ResultPrimitive.Substitute); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -542,8 +544,8 @@ public void Context_should_be_empty_at_fallbackAction_if_execute_not_called_with fallbackPolicy.RaiseResultSequence(ResultPrimitive.Fault); - fallbackExecuted.Should().BeTrue(); - capturedContext.Should().BeEmpty(); + fallbackExecuted.ShouldBeTrue(); + capturedContext.ShouldBeEmpty(); } #endregion @@ -564,11 +566,11 @@ public void Should_call_fallbackAction_with_the_fault() .Fallback(fallbackAction, onFallback); fallbackPolicy.Execute(() => ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); - fallbackOutcome!.Should().NotBeNull(); - fallbackOutcome!.Exception.Should().BeNull(); - fallbackOutcome!.Result.Should().Be(ResultPrimitive.Fault); + fallbackOutcome!.ShouldNotBeNull(); + fallbackOutcome!.Exception.ShouldBeNull(); + fallbackOutcome!.Result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -586,12 +588,12 @@ public void Should_call_fallbackAction_with_the_fault_when_execute_and_capture() .Fallback(fallbackAction, onFallback); var result = fallbackPolicy.ExecuteAndCapture(() => ResultPrimitive.Fault); - result.Should().NotBeNull(); - result.Result.Should().Be(ResultPrimitive.Substitute); + result.ShouldNotBeNull(); + result.Result.ShouldBe(ResultPrimitive.Substitute); - fallbackOutcome!.Should().NotBeNull(); - fallbackOutcome!.Exception.Should().BeNull(); - fallbackOutcome!.Result.Should().Be(ResultPrimitive.Fault); + fallbackOutcome!.ShouldNotBeNull(); + fallbackOutcome!.Exception.ShouldBeNull(); + fallbackOutcome!.Result.ShouldBe(ResultPrimitive.Fault); } [Fact] @@ -609,9 +611,9 @@ public void Should_not_call_fallbackAction_with_the_fault_if_fault_unhandled() .Fallback(fallbackAction, onFallback); fallbackPolicy.Execute(() => ResultPrimitive.FaultAgain) - .Should().Be(ResultPrimitive.FaultAgain); + .ShouldBe(ResultPrimitive.FaultAgain); - fallbackOutcome.Should().BeNull(); + fallbackOutcome.ShouldBeNull(); } #endregion @@ -640,12 +642,12 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca using (var cancellationTokenSource = new CancellationTokenSource()) { policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -670,12 +672,12 @@ public void Should_execute_fallback_when_faulting_and_cancellationToken_not_canc using (var cancellationTokenSource = new CancellationTokenSource()) { policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -702,14 +704,13 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } @@ -737,14 +738,13 @@ public void Should_report_cancellation_and_not_execute_fallback_during_otherwise { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -772,12 +772,12 @@ public void Should_handle_cancellation_and_execute_fallback_during_otherwise_non { CancellationToken cancellationToken = cancellationTokenSource.Token; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } [Fact] @@ -805,12 +805,12 @@ public void Should_not_report_cancellation_and_not_execute_fallback_if_non_fault CancellationToken cancellationToken = cancellationTokenSource.Token; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -837,12 +837,12 @@ public void Should_report_unhandled_fault_and_not_execute_fallback_if_action_exe { CancellationToken cancellationToken = cancellationTokenSource.Token; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.FaultYetAgain) - .Should().Be(ResultPrimitive.FaultYetAgain); + .ShouldBe(ResultPrimitive.FaultYetAgain); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeFalse(); + fallbackActionExecuted.ShouldBeFalse(); } [Fact] @@ -870,12 +870,12 @@ public void Should_handle_handled_fault_and_execute_fallback_following_faulting_ CancellationToken cancellationToken = cancellationTokenSource.Token; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Substitute); + .ShouldBe(ResultPrimitive.Substitute); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - fallbackActionExecuted.Should().BeTrue(); + fallbackActionExecuted.ShouldBeTrue(); } #endregion diff --git a/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs b/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs index cae57bb82a..12450b80f1 100644 --- a/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs +++ b/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs @@ -6,8 +6,8 @@ public static void ShouldPermitAnExecution(this IRateLimiter rateLimiter) { (bool PermitExecution, TimeSpan RetryAfter) canExecute = rateLimiter.PermitExecution(); - canExecute.PermitExecution.Should().BeTrue(); - canExecute.RetryAfter.Should().Be(TimeSpan.Zero); + canExecute.PermitExecution.ShouldBeTrue(); + canExecute.RetryAfter.ShouldBe(TimeSpan.Zero); } public static void ShouldPermitNExecutions(this IRateLimiter rateLimiter, long numberOfExecutions) @@ -22,14 +22,14 @@ public static void ShouldNotPermitAnExecution(this IRateLimiter rateLimiter, Tim { (bool PermitExecution, TimeSpan RetryAfter) canExecute = rateLimiter.PermitExecution(); - canExecute.PermitExecution.Should().BeFalse(); + canExecute.PermitExecution.ShouldBeFalse(); if (retryAfter == null) { - canExecute.RetryAfter.Should().BeGreaterThan(TimeSpan.Zero); + canExecute.RetryAfter.ShouldBeGreaterThan(TimeSpan.Zero); } else { - canExecute.RetryAfter.Should().Be(retryAfter.Value); + canExecute.RetryAfter.ShouldBe(retryAfter.Value); } } } diff --git a/test/Polly.Specs/IAsyncPolicyExtensionsSpecs.cs b/test/Polly.Specs/IAsyncPolicyExtensionsSpecs.cs index 443db1dfd0..2c151d4529 100644 --- a/test/Polly.Specs/IAsyncPolicyExtensionsSpecs.cs +++ b/test/Polly.Specs/IAsyncPolicyExtensionsSpecs.cs @@ -8,7 +8,7 @@ public void Converting_a_nongeneric_IAsyncPolicy_to_generic_should_return_a_gene IAsyncPolicy nonGenericPolicy = Policy.TimeoutAsync(10); var genericPolicy = nonGenericPolicy.AsAsyncPolicy(); - genericPolicy.Should().BeAssignableTo>(); + genericPolicy.ShouldBeAssignableTo>(); } [Fact] @@ -21,9 +21,9 @@ public async Task Converting_a_nongeneric_IAsyncPolicy_to_generic_should_return_ var genericPolicy = nonGenericPolicy.AsAsyncPolicy(); Func> deleg = () => Task.FromResult(ResultPrimitive.Good); - (await genericPolicy.ExecuteAsync(deleg)).Should().Be(ResultPrimitive.Good); + (await genericPolicy.ExecuteAsync(deleg)).ShouldBe(ResultPrimitive.Good); breaker.Isolate(); - await genericPolicy.Awaiting(p => p.ExecuteAsync(deleg)).Should().ThrowAsync(); + await Should.ThrowAsync(() => genericPolicy.ExecuteAsync(deleg)); } } diff --git a/test/Polly.Specs/ISyncPolicyExtensionsSpecs.cs b/test/Polly.Specs/ISyncPolicyExtensionsSpecs.cs index 2759117c2f..72427b6a81 100644 --- a/test/Polly.Specs/ISyncPolicyExtensionsSpecs.cs +++ b/test/Polly.Specs/ISyncPolicyExtensionsSpecs.cs @@ -8,7 +8,7 @@ public void Converting_a_nongeneric_ISyncPolicy_to_generic_should_return_a_gener ISyncPolicy nonGenericPolicy = Policy.Timeout(10); var genericPolicy = nonGenericPolicy.AsPolicy(); - genericPolicy.Should().BeAssignableTo>(); + genericPolicy.ShouldBeAssignableTo>(); } [Fact] @@ -21,9 +21,9 @@ public void Converting_a_nongeneric_ISyncPolicy_to_generic_should_return_an_ISyn var genericPolicy = nonGenericPolicy.AsPolicy(); Func deleg = () => ResultPrimitive.Good; - genericPolicy.Execute(deleg).Should().Be(ResultPrimitive.Good); + genericPolicy.Execute(deleg).ShouldBe(ResultPrimitive.Good); breaker.Isolate(); - genericPolicy.Invoking(p => p.Execute(deleg)).Should().Throw(); + Should.Throw(() => genericPolicy.Execute(deleg)); } } diff --git a/test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs b/test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs index b89b21bb1f..aebad9d3ec 100644 --- a/test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs +++ b/test/Polly.Specs/NoOp/NoOpAsyncSpecs.cs @@ -16,9 +16,9 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.WithInnerException("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType().ParamName.ShouldBe("action"); } [Fact] @@ -27,10 +27,9 @@ public async Task Should_execute_user_delegate() var policy = Policy.NoOpAsync(); bool executed = false; - await policy.Awaiting(p => p.ExecuteAsync(() => { executed = true; return TaskHelper.EmptyTask; })) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.ExecuteAsync(() => { executed = true; return TaskHelper.EmptyTask; })); - executed.Should().BeTrue(); + executed.ShouldBeTrue(); } [Fact] @@ -44,11 +43,10 @@ public async Task Should_execute_user_delegate_without_adding_extra_cancellation { cts.Cancel(); - await policy.Awaiting(p => p.ExecuteAsync( - _ => { executed = true; return TaskHelper.EmptyTask; }, cts.Token)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.ExecuteAsync( + _ => { executed = true; return TaskHelper.EmptyTask; }, cts.Token)); } - executed.Should().BeTrue(); + executed.ShouldBeTrue(); } } diff --git a/test/Polly.Specs/NoOp/NoOpSpecs.cs b/test/Polly.Specs/NoOp/NoOpSpecs.cs index 1bc37b87b5..f4436a8508 100644 --- a/test/Polly.Specs/NoOp/NoOpSpecs.cs +++ b/test/Polly.Specs/NoOp/NoOpSpecs.cs @@ -16,10 +16,10 @@ public void Should_throw_when_action_is_null() var generic = methodInfo.MakeGenericMethod(typeof(EmptyStruct)); var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -28,10 +28,9 @@ public void Should_execute_user_delegate() NoOpPolicy policy = Policy.NoOp(); bool executed = false; - policy.Invoking(x => x.Execute(() => { executed = true; })) - .Should().NotThrow(); + Should.NotThrow(() => policy.Execute(() => executed = true)); - executed.Should().BeTrue(); + executed.ShouldBeTrue(); } [Fact] @@ -44,10 +43,9 @@ public void Should_execute_user_delegate_without_adding_extra_cancellation_behav { cts.Cancel(); - policy.Invoking(p => p.Execute(_ => { executed = true; }, cts.Token)) - .Should().NotThrow(); + Should.NotThrow(() => policy.Execute(_ => executed = true, cts.Token)); } - executed.Should().BeTrue(); + executed.ShouldBeTrue(); } } diff --git a/test/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs b/test/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs index 3121fd9ae8..d5edce728f 100644 --- a/test/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs +++ b/test/Polly.Specs/NoOp/NoOpTResultAsyncSpecs.cs @@ -15,10 +15,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -27,12 +27,10 @@ public async Task Should_execute_user_delegate() var policy = Policy.NoOpAsync(); int? result = null; - Func, Task> action = async p => result = await p.ExecuteAsync(() => Task.FromResult((int?)10)); - await policy.Awaiting(action) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(async () => result = await policy.ExecuteAsync(() => Task.FromResult((int?)10))); - result.HasValue.Should().BeTrue(); - result.Should().Be(10); + result.HasValue.ShouldBeTrue(); + result.ShouldBe(10); } [Fact] @@ -45,12 +43,10 @@ public async Task Should_execute_user_delegate_without_adding_extra_cancellation { cts.Cancel(); - Func, Task> action = async p => result = await p.ExecuteAsync(_ => Task.FromResult((int?)10), cts.Token); - await policy.Awaiting(action) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(async () => result = await policy.ExecuteAsync(_ => Task.FromResult((int?)10), cts.Token)); } - result.HasValue.Should().BeTrue(); - result.Should().Be(10); + result.HasValue.ShouldBeTrue(); + result.ShouldBe(10); } } diff --git a/test/Polly.Specs/NoOp/NoOpTResultSpecs.cs b/test/Polly.Specs/NoOp/NoOpTResultSpecs.cs index 1a961f5183..b8ecc74c24 100644 --- a/test/Polly.Specs/NoOp/NoOpTResultSpecs.cs +++ b/test/Polly.Specs/NoOp/NoOpTResultSpecs.cs @@ -14,9 +14,9 @@ public void Should_throw_when_action_is_null() var methodInfo = methods.First(method => method is { Name: "Implementation", ReturnType.Name: "EmptyStruct" }); var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.WithInnerException("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType().ParamName.ShouldBe("action"); } [Fact] @@ -25,11 +25,10 @@ public void Should_execute_user_delegate() NoOpPolicy policy = Policy.NoOp(); int? result = null; - policy.Invoking(x => result = x.Execute(() => 10)) - .Should().NotThrow(); + Should.NotThrow(() => result = policy.Execute(() => 10)); - result.HasValue.Should().BeTrue(); - result.Should().Be(10); + result.HasValue.ShouldBeTrue(); + result.ShouldBe(10); } [Fact] @@ -42,11 +41,10 @@ public void Should_execute_user_delegate_without_adding_extra_cancellation_behav { cts.Cancel(); - policy.Invoking(p => result = p.Execute(_ => 10, cts.Token)) - .Should().NotThrow(); + Should.NotThrow(() => result = policy.Execute(_ => 10, cts.Token)); } - result.HasValue.Should().BeTrue(); - result.Should().Be(10); + result.HasValue.ShouldBeTrue(); + result.ShouldBe(10); } } diff --git a/test/Polly.Specs/PolicyAsyncSpecs.cs b/test/Polly.Specs/PolicyAsyncSpecs.cs index 100a174a85..d058f29383 100644 --- a/test/Polly.Specs/PolicyAsyncSpecs.cs +++ b/test/Polly.Specs/PolicyAsyncSpecs.cs @@ -19,8 +19,7 @@ await policy.ExecuteAsync(() => return TaskHelper.EmptyTask; }); - executed.Should() - .BeTrue(); + executed.ShouldBeTrue(); } [Fact] @@ -32,8 +31,7 @@ public async Task Executing_the_policy_function_should_execute_the_specified_asy int result = await policy.ExecuteAsync(() => Task.FromResult(2)); - result.Should() - .Be(2); + result.ShouldBe(2); } #endregion @@ -48,12 +46,10 @@ public async Task Executing_the_policy_action_successfully_should_return_success .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => TaskHelper.EmptyTask); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); } [Fact] @@ -66,12 +62,10 @@ public async Task Executing_the_policy_action_and_failing_with_a_handled_excepti .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => throw handledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = handledException, - ExceptionType = ExceptionType.HandledByThisPolicy, - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBe(handledException); + result.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); } [Fact] @@ -84,12 +78,10 @@ public async Task Executing_the_policy_action_and_failing_with_an_unhandled_exce .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => throw unhandledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = unhandledException, - ExceptionType = ExceptionType.Unhandled - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBe(unhandledException); + result.ExceptionType.ShouldBe(ExceptionType.Unhandled); } [Fact] @@ -100,15 +92,13 @@ public async Task Executing_the_policy_function_successfully_should_return_succe .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => Task.FromResult(int.MaxValue)); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = (FaultType?)null, - FinalHandledResult = default(int), - Result = int.MaxValue - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBeNull(); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(int.MaxValue); } [Fact] @@ -121,15 +111,13 @@ public async Task Executing_the_policy_function_and_failing_with_a_handled_excep .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => throw handledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = handledException, - ExceptionType = ExceptionType.HandledByThisPolicy, - FaultType = FaultType.ExceptionHandledByThisPolicy, - FinalHandledResult = default(int), - Result = default(int) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBe(handledException); + result.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); + result.FaultType.ShouldBe(FaultType.ExceptionHandledByThisPolicy); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(default); } [Fact] @@ -142,15 +130,13 @@ public async Task Executing_the_policy_function_and_failing_with_an_unhandled_ex .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => throw unhandledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = unhandledException, - ExceptionType = ExceptionType.Unhandled, - FaultType = FaultType.UnhandledException, - FinalHandledResult = default(int), - Result = default(int) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBe(unhandledException); + result.ExceptionType.ShouldBe(ExceptionType.Unhandled); + result.FaultType.ShouldBe(FaultType.UnhandledException); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(default); } #endregion @@ -164,8 +150,7 @@ public async Task Executing_the_policy_action_should_throw_when_context_data_is_ .Handle() .RetryAsync((_, _, _) => { }); - await policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, (IDictionary)null!)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(_ => TaskHelper.EmptyTask, (IDictionary)null!)); } [Fact] @@ -175,9 +160,8 @@ public async Task Executing_the_policy_action_should_throw_when_context_is_null( .Handle() .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => TaskHelper.EmptyTask, null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAsync(_ => TaskHelper.EmptyTask, null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -187,8 +171,7 @@ public async Task Executing_the_policy_function_should_throw_when_context_data_i .Handle() .RetryAsync((_, _, _) => { }); - await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), (IDictionary)null!)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(_ => Task.FromResult(2), (IDictionary)null!)); } [Fact] @@ -198,9 +181,8 @@ public async Task Executing_the_policy_function_should_throw_when_context_is_nul .Handle() .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(2), null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAsync(_ => Task.FromResult(2), null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -214,7 +196,7 @@ public async Task Executing_the_policy_function_should_pass_context_to_executed_ await policy.ExecuteAsync(context => { capturedContext = context; return TaskHelper.EmptyTask; }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -224,8 +206,7 @@ public async Task Execute_and_capturing_the_policy_action_should_throw_when_cont .Handle() .RetryAsync((_, _, _) => { }); - await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (IDictionary)null!)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, (IDictionary)null!)); } [Fact] @@ -235,9 +216,8 @@ public async Task Execute_and_capturing_the_policy_action_should_throw_when_cont .Handle() .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -247,8 +227,7 @@ public async Task Execute_and_capturing_the_policy_function_should_throw_when_co .Handle() .RetryAsync((_, _, _) => { }); - await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (IDictionary)null!)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAndCaptureAsync(_ => Task.FromResult(2), (IDictionary)null!)); } [Fact] @@ -258,9 +237,8 @@ public async Task Execute_and_capturing_the_policy_function_should_throw_when_co .Handle() .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(2), null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAndCaptureAsync(_ => Task.FromResult(2), null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -274,7 +252,7 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ await policy.ExecuteAndCaptureAsync(context => { capturedContext = context; return TaskHelper.EmptyTask; }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -286,7 +264,7 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ var policy = Policy.NoOpAsync(); (await policy.ExecuteAndCaptureAsync(_ => TaskHelper.EmptyTask, executionContext)) - .Context.Should().BeSameAs(executionContext); + .Context.ShouldBeSameAs(executionContext); } #endregion diff --git a/test/Polly.Specs/PolicyKeyAsyncSpecs.cs b/test/Polly.Specs/PolicyKeyAsyncSpecs.cs index 697875429c..8b017a5d5b 100644 --- a/test/Polly.Specs/PolicyKeyAsyncSpecs.cs +++ b/test/Polly.Specs/PolicyKeyAsyncSpecs.cs @@ -9,7 +9,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key() { var policy = Policy.Handle().RetryAsync().WithPolicyKey(Guid.NewGuid().ToString()); - policy.Should().BeAssignableTo(); + policy.ShouldBeAssignableTo(); } [Fact] @@ -18,7 +18,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() IAsyncPolicy policyAsInterface = Policy.Handle().RetryAsync(); var policyAsInterfaceAfterWithPolicyKey = policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - policyAsInterfaceAfterWithPolicyKey.Should().BeAssignableTo(); + policyAsInterfaceAfterWithPolicyKey.ShouldBeAssignableTo(); } [Fact] @@ -28,7 +28,7 @@ public void PolicyKey_property_should_be_the_fluently_configured_policy_key() var policy = Policy.Handle().RetryAsync().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(Key); + policy.PolicyKey.ShouldBe(Key); } [Fact] @@ -38,9 +38,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -50,9 +50,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ Action configure = () => policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -60,7 +60,7 @@ public void PolicyKey_property_should_be_non_null_or_empty_if_not_explicitly_con { var policy = Policy.Handle().RetryAsync(); - policy.PolicyKey.Should().NotBeNullOrEmpty(); + policy.PolicyKey.ShouldNotBeNullOrEmpty(); } [Fact] @@ -68,7 +68,7 @@ public void PolicyKey_property_should_start_with_policy_type_if_not_explicitly_c { var policy = Policy.Handle().RetryAsync(); - policy.PolicyKey.Should().StartWith("AsyncRetry"); + policy.PolicyKey.ShouldStartWith("AsyncRetry"); } [Fact] @@ -77,7 +77,7 @@ public void PolicyKey_property_should_be_unique_for_different_instances_if_not_e var policy1 = Policy.Handle().RetryAsync(); var policy2 = Policy.Handle().RetryAsync(); - policy1.PolicyKey.Should().NotBe(policy2.PolicyKey); + policy1.PolicyKey.ShouldNotBe(policy2.PolicyKey); } [Fact] @@ -88,7 +88,7 @@ public void PolicyKey_property_should_return_consistent_value_for_same_policy_in var keyRetrievedFirst = policy.PolicyKey; var keyRetrievedSecond = policy.PolicyKey; - keyRetrievedSecond.Should().Be(keyRetrievedFirst); + keyRetrievedSecond.ShouldBe(keyRetrievedFirst); } [Fact] @@ -100,7 +100,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -125,7 +125,7 @@ public async Task Should_pass_PolicyKey_to_execution_context() await retry.RaiseExceptionAsync(1); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -148,7 +148,7 @@ await retry.ExecuteAsync(async _ => } }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } [Fact] @@ -173,7 +173,7 @@ await retry.ExecuteAsync(async () => return 0; }); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -186,7 +186,7 @@ public async Task Should_pass_OperationKey_to_execution_context_in_generic_execu var retry = Policy.Handle().RetryAsync(1, onRetry); bool firstExecution = true; - await retry.ExecuteAsync(async _ => + await retry.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; if (firstExecution) @@ -198,7 +198,7 @@ await retry.ExecuteAsync(async _ => return 0; }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } #endregion } diff --git a/test/Polly.Specs/PolicyKeySpecs.cs b/test/Polly.Specs/PolicyKeySpecs.cs index a729d0ee30..617a72e39f 100644 --- a/test/Polly.Specs/PolicyKeySpecs.cs +++ b/test/Polly.Specs/PolicyKeySpecs.cs @@ -9,7 +9,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key() { var policy = Policy.Handle().Retry().WithPolicyKey(Guid.NewGuid().ToString()); - policy.Should().BeAssignableTo(); + policy.ShouldBeAssignableTo(); } [Fact] @@ -18,7 +18,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() ISyncPolicy policyAsInterface = Policy.Handle().Retry(); var policyAsInterfaceAfterWithPolicyKey = policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - policyAsInterfaceAfterWithPolicyKey.Should().BeAssignableTo(); + policyAsInterfaceAfterWithPolicyKey.ShouldBeAssignableTo(); } [Fact] @@ -28,7 +28,7 @@ public void PolicyKey_property_should_be_the_fluently_configured_policy_key() var policy = Policy.Handle().Retry().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(Key); + policy.PolicyKey.ShouldBe(Key); } [Fact] @@ -38,9 +38,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -48,7 +48,7 @@ public void PolicyKey_property_should_be_non_null_or_empty_if_not_explicitly_con { var policy = Policy.Handle().Retry(); - policy.PolicyKey.Should().NotBeNullOrEmpty(); + policy.PolicyKey.ShouldNotBeNullOrEmpty(); } [Fact] @@ -56,7 +56,7 @@ public void PolicyKey_property_should_start_with_policy_type_if_not_explicitly_c { var policy = Policy.Handle().Retry(); - policy.PolicyKey.Should().StartWith("Retry"); + policy.PolicyKey.ShouldStartWith("Retry"); } [Fact] @@ -65,7 +65,7 @@ public void PolicyKey_property_should_be_unique_for_different_instances_if_not_e var policy1 = Policy.Handle().Retry(); var policy2 = Policy.Handle().Retry(); - policy1.PolicyKey.Should().NotBe(policy2.PolicyKey); + policy1.PolicyKey.ShouldNotBe(policy2.PolicyKey); } [Fact] @@ -76,7 +76,7 @@ public void PolicyKey_property_should_return_consistent_value_for_same_policy_in var keyRetrievedFirst = policy.PolicyKey; var keyRetrievedSecond = policy.PolicyKey; - keyRetrievedSecond.Should().Be(keyRetrievedFirst); + keyRetrievedSecond.ShouldBe(keyRetrievedFirst); } [Fact] @@ -88,7 +88,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } #endregion @@ -106,7 +106,7 @@ public void Should_pass_PolicyKey_to_execution_context() retry.RaiseException(1); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -128,7 +128,7 @@ public void Should_pass_OperationKey_to_execution_context() } }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } [Fact] @@ -152,7 +152,7 @@ public void Should_pass_PolicyKey_to_execution_context_in_generic_execution_on_n return 0; }); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -176,7 +176,7 @@ public void Should_pass_OperationKey_to_execution_context_in_generic_execution_o return 0; }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } #endregion } diff --git a/test/Polly.Specs/PolicySpecs.cs b/test/Polly.Specs/PolicySpecs.cs index 782e99b220..fb5aacb0cb 100644 --- a/test/Polly.Specs/PolicySpecs.cs +++ b/test/Polly.Specs/PolicySpecs.cs @@ -15,8 +15,7 @@ public void Executing_the_policy_action_should_execute_the_specified_action() policy.Execute(() => executed = true); - executed.Should() - .BeTrue(); + executed.ShouldBeTrue(); } [Fact] @@ -28,8 +27,7 @@ public void Executing_the_policy_function_should_execute_the_specified_function_ var result = policy.Execute(() => 2); - result.Should() - .Be(2); + result.ShouldBe(2); } #endregion @@ -44,12 +42,10 @@ public void Executing_the_policy_action_successfully_should_return_success_resul .Retry((_, _) => { }) .ExecuteAndCapture(() => { }); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); } [Fact] @@ -62,12 +58,10 @@ public void Executing_the_policy_action_and_failing_with_a_handled_exception_typ .Retry((_, _) => { }) .ExecuteAndCapture(() => throw handledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = handledException, - ExceptionType = ExceptionType.HandledByThisPolicy - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeSameAs(handledException); + result.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); } [Fact] @@ -80,12 +74,10 @@ public void Executing_the_policy_action_and_failing_with_an_unhandled_exception_ .Retry((_, _) => { }) .ExecuteAndCapture(() => throw unhandledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = unhandledException, - ExceptionType = ExceptionType.Unhandled - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeSameAs(unhandledException); + result.ExceptionType.ShouldBe(ExceptionType.Unhandled); } [Fact] @@ -96,15 +88,13 @@ public void Executing_the_policy_function_successfully_should_return_success_res .Retry((_, _) => { }) .ExecuteAndCapture(() => int.MaxValue); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = (FaultType?)null, - FinalHandledResult = default(int), - Result = int.MaxValue - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBeNull(); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(int.MaxValue); } [Fact] @@ -117,15 +107,13 @@ public void Executing_the_policy_function_and_failing_with_a_handled_exception_t .Retry((_, _) => { }) .ExecuteAndCapture(() => throw handledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = handledException, - ExceptionType = ExceptionType.HandledByThisPolicy, - FaultType = FaultType.ExceptionHandledByThisPolicy, - FinalHandledResult = default(int), - Result = default(int) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeSameAs(handledException); + result.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); + result.FaultType.ShouldBe(FaultType.ExceptionHandledByThisPolicy); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(default); } [Fact] @@ -138,15 +126,13 @@ public void Executing_the_policy_function_and_failing_with_an_unhandled_exceptio .Retry((_, _) => { }) .ExecuteAndCapture(() => throw unhandledException); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = unhandledException, - ExceptionType = ExceptionType.Unhandled, - FaultType = FaultType.UnhandledException, - FinalHandledResult = default(int), - Result = default(int) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeSameAs(unhandledException); + result.ExceptionType.ShouldBe(ExceptionType.Unhandled); + result.FaultType.ShouldBe(FaultType.UnhandledException); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(default); } #endregion @@ -160,8 +146,7 @@ public void Executing_the_policy_action_should_throw_when_context_data_is_null() .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => { }, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => { }, (IDictionary)null!)); } [Fact] @@ -171,9 +156,8 @@ public void Executing_the_policy_action_should_throw_when_context_is_null() .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => { }, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.Execute(_ => { }, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -183,8 +167,7 @@ public void Executing_the_policy_function_should_throw_when_context_data_is_null .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => 2, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => 2, (IDictionary)null!)); } [Fact] @@ -194,9 +177,8 @@ public void Executing_the_policy_function_should_throw_when_context_is_null() .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => 2, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.Execute(_ => 2, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -208,9 +190,9 @@ public void Executing_the_policy_function_should_pass_context_to_executed_delega Policy policy = Policy.NoOp(); - policy.Execute(context => { capturedContext = context; }, executionContext); + policy.Execute(context => capturedContext = context, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -220,8 +202,7 @@ public void Execute_and_capturing_the_policy_action_should_throw_when_context_da .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => { }, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.ExecuteAndCapture(_ => { }, (IDictionary)null!)); } [Fact] @@ -231,9 +212,8 @@ public void Execute_and_capturing_the_policy_action_should_throw_when_context_is .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => { }, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.ExecuteAndCapture(_ => { }, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -243,8 +223,7 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => 2, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.ExecuteAndCapture(_ => 2, (IDictionary)null!)); } [Fact] @@ -254,9 +233,8 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .Handle() .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => 2, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.ExecuteAndCapture(_ => 2, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -270,7 +248,7 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_exe policy.ExecuteAndCapture(context => { capturedContext = context; }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -282,7 +260,7 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_Pol Policy policy = Policy.NoOp(); policy.ExecuteAndCapture(_ => { }, executionContext) - .Context.Should().BeSameAs(executionContext); + .Context.ShouldBeSameAs(executionContext); } #endregion diff --git a/test/Polly.Specs/PolicyTResultAsyncSpecs.cs b/test/Polly.Specs/PolicyTResultAsyncSpecs.cs index 18957deb20..fe947069b3 100644 --- a/test/Polly.Specs/PolicyTResultAsyncSpecs.cs +++ b/test/Polly.Specs/PolicyTResultAsyncSpecs.cs @@ -13,8 +13,7 @@ public async Task Executing_the_policy_function_should_execute_the_specified_fun var result = await policy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); - result.Should() - .Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } #endregion @@ -29,15 +28,13 @@ public async Task Executing_the_policy_function_successfully_should_return_succe .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Good)); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - Result = ResultPrimitive.Good, - FinalHandledResult = default(ResultPrimitive), - FaultType = (FaultType?)null - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.Result.ShouldBe(ResultPrimitive.Good); + result.FinalHandledResult.ShouldBe(default); + result.FaultType.ShouldBeNull(); } [Fact] @@ -50,15 +47,13 @@ public async Task Executing_the_policy_function_and_failing_with_a_handled_resul .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => Task.FromResult(handledResult)); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = FaultType.ResultHandledByThisPolicy, - FinalHandledResult = handledResult, - Result = default(ResultPrimitive) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBe(FaultType.ResultHandledByThisPolicy); + result.FinalHandledResult.ShouldBe(handledResult); + result.Result.ShouldBe(default); } [Fact] @@ -72,15 +67,13 @@ public async Task Executing_the_policy_function_and_returning_an_unhandled_resul .RetryAsync((_, _) => { }) .ExecuteAndCaptureAsync(() => Task.FromResult(unhandledResult)); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - Result = unhandledResult, - FinalHandledResult = default(ResultPrimitive), - FaultType = (FaultType?)null - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.Result.ShouldBe(unhandledResult); + result.FaultType.ShouldBeNull(); + result.FinalHandledResult.ShouldBe(default); } #endregion @@ -94,8 +87,7 @@ public async Task Executing_the_policy_function_should_throw_when_context_data_i .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (IDictionary)null!)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), (IDictionary)null!)); } [Fact] @@ -105,9 +97,8 @@ public async Task Executing_the_policy_function_should_throw_when_context_is_nul .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -121,7 +112,7 @@ public async Task Executing_the_policy_function_should_pass_context_to_executed_ await policy.ExecuteAsync(context => { capturedContext = context; return Task.FromResult(ResultPrimitive.Good); }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -131,9 +122,8 @@ public async Task Execute_and_capturing_the_policy_function_should_throw_when_co .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, _, _) => { }); - var ex = await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), null!)) - .Should().ThrowAsync(); - ex.And.ParamName.Should().Be("context"); + var ex = await Should.ThrowAsync(() => policy.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), null!)); + ex.ParamName.ShouldBe("context"); } [Fact] @@ -147,7 +137,7 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ await policy.ExecuteAndCaptureAsync(context => { capturedContext = context; return Task.FromResult(ResultPrimitive.Good); }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -159,7 +149,7 @@ public async Task Execute_and_capturing_the_policy_function_should_pass_context_ var policy = Policy.NoOpAsync(); (await policy.ExecuteAndCaptureAsync(_ => Task.FromResult(ResultPrimitive.Good), executionContext)) - .Context.Should().BeSameAs(executionContext); + .Context.ShouldBeSameAs(executionContext); } #endregion diff --git a/test/Polly.Specs/PolicyTResultKeyAsyncSpecs.cs b/test/Polly.Specs/PolicyTResultKeyAsyncSpecs.cs index fee237aee5..4b6b3bb1e7 100644 --- a/test/Polly.Specs/PolicyTResultKeyAsyncSpecs.cs +++ b/test/Polly.Specs/PolicyTResultKeyAsyncSpecs.cs @@ -9,7 +9,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key() { var policy = Policy.HandleResult(0).RetryAsync().WithPolicyKey(Guid.NewGuid().ToString()); - policy.Should().BeAssignableTo>(); + policy.ShouldBeAssignableTo>(); } [Fact] @@ -18,7 +18,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() IAsyncPolicy policyAsInterface = Policy.HandleResult(0).RetryAsync(); var policyAsInterfaceAfterWithPolicyKey = policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - policyAsInterfaceAfterWithPolicyKey.Should().BeAssignableTo>(); + policyAsInterfaceAfterWithPolicyKey.ShouldBeAssignableTo>(); } [Fact] @@ -28,7 +28,7 @@ public void PolicyKey_property_should_be_the_fluently_configured_policy_key() var policy = Policy.HandleResult(0).RetryAsync().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(Key); + policy.PolicyKey.ShouldBe(Key); } [Fact] @@ -38,9 +38,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -49,9 +49,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ IAsyncPolicy policyAsInterface = Policy.HandleResult(0).RetryAsync(); Action configure = () => policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -59,7 +59,7 @@ public void PolicyKey_property_should_be_non_null_or_empty_if_not_explicitly_con { var policy = Policy.HandleResult(0).RetryAsync(); - policy.PolicyKey.Should().NotBeNullOrEmpty(); + policy.PolicyKey.ShouldNotBeNullOrEmpty(); } [Fact] @@ -67,7 +67,7 @@ public void PolicyKey_property_should_start_with_policy_type_if_not_explicitly_c { var policy = Policy.HandleResult(0).RetryAsync(); - policy.PolicyKey.Should().StartWith("AsyncRetry"); + policy.PolicyKey.ShouldStartWith("AsyncRetry"); } [Fact] @@ -76,7 +76,7 @@ public void PolicyKey_property_should_be_unique_for_different_instances_if_not_e var policy1 = Policy.HandleResult(0).RetryAsync(); var policy2 = Policy.HandleResult(0).RetryAsync(); - policy1.PolicyKey.Should().NotBe(policy2.PolicyKey); + policy1.PolicyKey.ShouldNotBe(policy2.PolicyKey); } [Fact] @@ -87,7 +87,7 @@ public void PolicyKey_property_should_return_consistent_value_for_same_policy_in var keyRetrievedFirst = policy.PolicyKey; var keyRetrievedSecond = policy.PolicyKey; - keyRetrievedSecond.Should().Be(keyRetrievedFirst); + keyRetrievedSecond.ShouldBe(keyRetrievedFirst); } [Fact] @@ -99,7 +99,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } #endregion @@ -117,7 +117,7 @@ public async Task Should_pass_PolicyKey_to_execution_context() await retry.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -142,7 +142,7 @@ await retry.ExecuteAsync(async _ => return ResultPrimitive.Good; }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } #endregion diff --git a/test/Polly.Specs/PolicyTResultKeySpecs.cs b/test/Polly.Specs/PolicyTResultKeySpecs.cs index 6f464bc42a..149e073891 100644 --- a/test/Polly.Specs/PolicyTResultKeySpecs.cs +++ b/test/Polly.Specs/PolicyTResultKeySpecs.cs @@ -9,7 +9,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key() { var policy = Policy.HandleResult(0).Retry().WithPolicyKey(Guid.NewGuid().ToString()); - policy.Should().BeAssignableTo>(); + policy.ShouldBeAssignableTo>(); } [Fact] @@ -18,7 +18,7 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() ISyncPolicy policyAsInterface = Policy.HandleResult(0).Retry(); var policyAsInterfaceAfterWithPolicyKey = policyAsInterface.WithPolicyKey(Guid.NewGuid().ToString()); - policyAsInterfaceAfterWithPolicyKey.Should().BeAssignableTo>(); + policyAsInterfaceAfterWithPolicyKey.ShouldBeAssignableTo>(); } [Fact] @@ -28,7 +28,7 @@ public void PolicyKey_property_should_be_the_fluently_configured_policy_key() var policy = Policy.HandleResult(0).Retry().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(Key); + policy.PolicyKey.ShouldBe(Key); } [Fact] @@ -38,9 +38,9 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_more_than_ Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().NotThrow(); + Should.NotThrow(configure); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } [Fact] @@ -48,7 +48,7 @@ public void PolicyKey_property_should_be_non_null_or_empty_if_not_explicitly_con { var policy = Policy.HandleResult(0).Retry(); - policy.PolicyKey.Should().NotBeNullOrEmpty(); + policy.PolicyKey.ShouldNotBeNullOrEmpty(); } [Fact] @@ -56,7 +56,7 @@ public void PolicyKey_property_should_start_with_policy_type_if_not_explicitly_c { var policy = Policy.HandleResult(0).Retry(); - policy.PolicyKey.Should().StartWith("Retry"); + policy.PolicyKey.ShouldStartWith("Retry"); } [Fact] @@ -65,7 +65,7 @@ public void PolicyKey_property_should_be_unique_for_different_instances_if_not_e var policy1 = Policy.HandleResult(0).Retry(); var policy2 = Policy.HandleResult(0).Retry(); - policy1.PolicyKey.Should().NotBe(policy2.PolicyKey); + policy1.PolicyKey.ShouldNotBe(policy2.PolicyKey); } [Fact] @@ -76,7 +76,7 @@ public void PolicyKey_property_should_return_consistent_value_for_same_policy_in var keyRetrievedFirst = policy.PolicyKey; var keyRetrievedSecond = policy.PolicyKey; - keyRetrievedSecond.Should().Be(keyRetrievedFirst); + keyRetrievedSecond.ShouldBe(keyRetrievedFirst); } [Fact] @@ -88,7 +88,7 @@ public void Should_not_be_able_to_configure_the_policy_key_explicitly_after_retr Action configure = () => policy.WithPolicyKey(Guid.NewGuid().ToString()); - configure.Should().Throw().And.ParamName.Should().Be("policyKey"); + Should.Throw(configure).ParamName.ShouldBe("policyKey"); } #endregion @@ -106,7 +106,7 @@ public void Should_pass_PolicyKey_to_execution_context() retry.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - policyKeySetOnExecutionContext.Should().Be(policyKey); + policyKeySetOnExecutionContext.ShouldBe(policyKey); } [Fact] @@ -130,7 +130,7 @@ public void Should_pass_OperationKey_to_execution_context() return ResultPrimitive.Good; }, new Context(operationKey)); - operationKeySetOnContext.Should().Be(operationKey); + operationKeySetOnContext.ShouldBe(operationKey); } #endregion diff --git a/test/Polly.Specs/PolicyTResultSpecs.cs b/test/Polly.Specs/PolicyTResultSpecs.cs index 7edc83e011..b0812c2bb0 100644 --- a/test/Polly.Specs/PolicyTResultSpecs.cs +++ b/test/Polly.Specs/PolicyTResultSpecs.cs @@ -13,8 +13,7 @@ public void Executing_the_policy_function_should_execute_the_specified_function_ var result = policy.Execute(() => ResultPrimitive.Good); - result.Should() - .Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } #endregion @@ -29,15 +28,13 @@ public void Executing_the_policy_function_successfully_should_return_success_res .Retry((_, _) => { }) .ExecuteAndCapture(() => ResultPrimitive.Good); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - Result = ResultPrimitive.Good, - FinalHandledResult = default(ResultPrimitive), - FaultType = (FaultType?)null - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.Result.ShouldBe(ResultPrimitive.Good); + result.FinalHandledResult.ShouldBe(default); + result.FaultType.ShouldBeNull(); } [Fact] @@ -50,15 +47,13 @@ public void Executing_the_policy_function_and_failing_with_a_handled_result_shou .Retry((_, _) => { }) .ExecuteAndCapture(() => handledResult); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Failure, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = FaultType.ResultHandledByThisPolicy, - FinalHandledResult = handledResult, - Result = default(ResultPrimitive) - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Failure); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBe(FaultType.ResultHandledByThisPolicy); + result.FinalHandledResult.ShouldBe(handledResult); + result.Result.ShouldBe(default); } [Fact] @@ -72,15 +67,13 @@ public void Executing_the_policy_function_and_returning_an_unhandled_result_shou .Retry((_, _) => { }) .ExecuteAndCapture(() => unhandledResult); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - Result = unhandledResult, - FinalHandledResult = default(ResultPrimitive), - FaultType = (FaultType?)null - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.Result.ShouldBe(unhandledResult); + result.FinalHandledResult.ShouldBe(default); + result.FaultType.ShouldBeNull(); } #endregion @@ -94,8 +87,7 @@ public void Executing_the_policy_function_should_throw_when_context_data_is_null .HandleResult(ResultPrimitive.Fault) .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => ResultPrimitive.Good, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => ResultPrimitive.Good, (IDictionary)null!)); } [Fact] @@ -105,9 +97,8 @@ public void Executing_the_policy_function_should_throw_when_context_is_null() .HandleResult(ResultPrimitive.Fault) .Retry((_, _, _) => { }); - policy.Invoking(p => p.Execute(_ => ResultPrimitive.Good, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.Execute(_ => ResultPrimitive.Good, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -121,7 +112,8 @@ public void Executing_the_policy_function_should_pass_context_to_executed_delega policy.Execute(context => { capturedContext = context; return ResultPrimitive.Good; }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldNotBeNull(); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -131,8 +123,7 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .HandleResult(ResultPrimitive.Fault) .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => ResultPrimitive.Good, (IDictionary)null!)) - .Should().Throw(); + Should.Throw(() => policy.ExecuteAndCapture(_ => ResultPrimitive.Good, (IDictionary)null!)); } [Fact] @@ -142,9 +133,8 @@ public void Execute_and_capturing_the_policy_function_should_throw_when_context_ .HandleResult(ResultPrimitive.Fault) .Retry((_, _, _) => { }); - policy.Invoking(p => p.ExecuteAndCapture(_ => ResultPrimitive.Good, null!)) - .Should().Throw().And - .ParamName.Should().Be("context"); + Should.Throw(() => policy.ExecuteAndCapture(_ => ResultPrimitive.Good, null!)) + .ParamName.ShouldBe("context"); } [Fact] @@ -158,7 +148,8 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_exe policy.ExecuteAndCapture(context => { capturedContext = context; return ResultPrimitive.Good; }, executionContext); - capturedContext.Should().BeSameAs(executionContext); + capturedContext.ShouldNotBeNull(); + capturedContext.ShouldBeSameAs(executionContext); } [Fact] @@ -170,7 +161,7 @@ public void Execute_and_capturing_the_policy_function_should_pass_context_to_Pol Policy policy = Policy.NoOp(); policy.ExecuteAndCapture(_ => ResultPrimitive.Good, executionContext) - .Context.Should().BeSameAs(executionContext); + .Context.ShouldBeSameAs(executionContext); } #endregion diff --git a/test/Polly.Specs/Polly.Specs.csproj b/test/Polly.Specs/Polly.Specs.csproj index 85b8c518fd..f87665d32b 100644 --- a/test/Polly.Specs/Polly.Specs.csproj +++ b/test/Polly.Specs/Polly.Specs.csproj @@ -14,9 +14,6 @@ - - - @@ -33,6 +30,5 @@ - diff --git a/test/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs b/test/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs index 1f4f6f80a0..3470ed7792 100644 --- a/test/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs +++ b/test/Polly.Specs/RateLimit/AsyncRateLimitPolicySpecs.cs @@ -52,9 +52,9 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } } diff --git a/test/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs b/test/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs index 65fa2ddbfe..8e5d4a6cb3 100644 --- a/test/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs +++ b/test/Polly.Specs/RateLimit/AsyncRateLimitPolicyTResultSpecs.cs @@ -68,9 +68,9 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs b/test/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs index 63ee1dbf58..0aefac0a73 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicySpecs.cs @@ -52,9 +52,9 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs index 2c25b4beff..4828fa5f1b 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs @@ -19,8 +19,8 @@ protected void ShouldPermitAnExecution(IRateLimitPolicy policy) { (bool permitExecution, TimeSpan retryAfter) = TryExecuteThroughPolicy(policy); - permitExecution.Should().BeTrue(); - retryAfter.Should().Be(TimeSpan.Zero); + permitExecution.ShouldBeTrue(); + retryAfter.ShouldBe(TimeSpan.Zero); } protected void ShouldPermitNExecutions(IRateLimitPolicy policy, long numberOfExecutions) @@ -35,14 +35,14 @@ protected void ShouldNotPermitAnExecution(IRateLimitPolicy policy, TimeSpan? ret { (bool PermitExecution, TimeSpan RetryAfter) canExecute = TryExecuteThroughPolicy(policy); - canExecute.PermitExecution.Should().BeFalse(); + canExecute.PermitExecution.ShouldBeFalse(); if (retryAfter == null) { - canExecute.RetryAfter.Should().BeGreaterThan(TimeSpan.Zero); + canExecute.RetryAfter.ShouldBeGreaterThan(TimeSpan.Zero); } else { - canExecute.RetryAfter.Should().Be(retryAfter.Value); + canExecute.RetryAfter.ShouldBe(retryAfter.Value); } } @@ -51,7 +51,7 @@ public void Syntax_should_throw_for_perTimeSpan_zero() { Action invalidSyntax = () => GetPolicyViaSyntax(1, TimeSpan.Zero); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("perTimeSpan"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("perTimeSpan"); } [Fact] @@ -59,7 +59,7 @@ public void Syntax_should_throw_for_perTimeSpan_infinite() { Action invalidSyntax = () => GetPolicyViaSyntax(1, System.Threading.Timeout.InfiniteTimeSpan); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("perTimeSpan"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("perTimeSpan"); } [Fact] @@ -67,8 +67,8 @@ public void Syntax_should_throw_for_perTimeSpan_too_small() { Action invalidSyntax = () => GetPolicyViaSyntax(int.MaxValue, TimeSpan.FromSeconds(1)); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("perTimeSpan"); - invalidSyntax.Should().Throw().And.Message.Should().StartWith("The number of executions per timespan must be positive."); + Should.Throw(invalidSyntax).ParamName.ShouldBe("perTimeSpan"); + Should.Throw(invalidSyntax).Message.ShouldStartWith("The number of executions per timespan must be positive."); } [Fact] @@ -76,7 +76,7 @@ public void Syntax_should_throw_for_numberOfExecutions_negative() { Action invalidSyntax = () => GetPolicyViaSyntax(-1, TimeSpan.FromSeconds(1)); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("numberOfExecutions"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("numberOfExecutions"); } [Fact] @@ -84,7 +84,7 @@ public void Syntax_should_throw_for_numberOfExecutions_zero() { Action invalidSyntax = () => GetPolicyViaSyntax(0, TimeSpan.FromSeconds(1)); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("numberOfExecutions"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("numberOfExecutions"); } [Fact] @@ -92,7 +92,7 @@ public void Syntax_should_throw_for_perTimeSpan_negative() { Action invalidSyntax = () => GetPolicyViaSyntax(1, TimeSpan.FromTicks(-1)); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("perTimeSpan"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("perTimeSpan"); } [Fact] @@ -100,7 +100,7 @@ public void Syntax_should_throw_for_maxBurst_negative() { Action invalidSyntax = () => GetPolicyViaSyntax(1, TimeSpan.FromSeconds(1), -1); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("maxBurst"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("maxBurst"); } [Fact] @@ -108,7 +108,7 @@ public void Syntax_should_throw_for_maxBurst_zero() { Action invalidSyntax = () => GetPolicyViaSyntax(1, TimeSpan.FromSeconds(1), 0); - invalidSyntax.Should().Throw().And.ParamName.Should().Be("maxBurst"); + Should.Throw(invalidSyntax).ParamName.ShouldBe("maxBurst"); } [Theory] @@ -223,7 +223,7 @@ public void Given_any_bucket_capacity_rate_limiter_permits_full_bucket_burst_aft [InlineData(100)] public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burst_after_half_required_refill_time_elapsed(int bucketCapacity) { - (bucketCapacity % 2).Should().Be(0); + (bucketCapacity % 2).ShouldBe(0); FixClock(); @@ -249,7 +249,7 @@ public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burs [InlineData(100, 5)] public void Given_any_bucket_capacity_rate_limiter_permits_only_full_bucket_burst_even_if_multiple_required_refill_time_elapsed(int bucketCapacity, int multipleRefillTimePassed) { - multipleRefillTimePassed.Should().BeGreaterThan(1); + multipleRefillTimePassed.ShouldBeGreaterThan(1); FixClock(); @@ -302,7 +302,7 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o // Assert - one should have permitted execution, n-1 not. var results = tasks.Select(t => t.Result).ToList(); - results.Count(r => r.PermitExecution).Should().Be(1); - results.Count(r => !r.PermitExecution).Should().Be(parallelContention - 1); + results.Count(r => r.PermitExecution).ShouldBe(1); + results.Count(r => !r.PermitExecution).ShouldBe(parallelContention - 1); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs b/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs index 99fc2a224c..4d75dad4a2 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecs.cs @@ -68,9 +68,9 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecsBase.cs index 44bd8acbba..cc45b807e6 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicyTResultSpecsBase.cs @@ -39,13 +39,13 @@ public void Ratelimiter_specifies_correct_wait_until_next_execution_by_custom_fa var resultExpectedBlocked = TryExecuteThroughPolicy(rateLimiter, contextToPassIn, new ResultClassWithRetryAfter(ResultPrimitive.Good)); // Assert - should be blocked - time not advanced. - resultExpectedBlocked.ResultCode.Should().NotBe(ResultPrimitive.Good); + resultExpectedBlocked.ResultCode.ShouldNotBe(ResultPrimitive.Good); // Result should be expressed per the retryAfterFactory. - resultExpectedBlocked.RetryAfter.Should().Be(onePer); + resultExpectedBlocked.RetryAfter.ShouldBe(onePer); // Context should have been passed to the retryAfterFactory. - contextPassedToRetryAfter.Should().NotBeNull(); - contextPassedToRetryAfter.Should().BeSameAs(contextToPassIn); + contextPassedToRetryAfter.ShouldNotBeNull(); + contextPassedToRetryAfter.ShouldBeSameAs(contextToPassIn); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitRejectedExceptionTests.cs b/test/Polly.Specs/RateLimit/RateLimitRejectedExceptionTests.cs index febc177c38..5d327e15b6 100644 --- a/test/Polly.Specs/RateLimit/RateLimitRejectedExceptionTests.cs +++ b/test/Polly.Specs/RateLimit/RateLimitRejectedExceptionTests.cs @@ -9,27 +9,27 @@ public void Ctor_Ok() var exception = new InvalidOperationException(); var retryAfter = TimeSpan.FromSeconds(4); - new RateLimitRejectedException().Message.Should().Be("The operation could not be executed because it was rejected by the rate limit."); - new RateLimitRejectedException(Dummy).Message.Should().Be(Dummy); + new RateLimitRejectedException().Message.ShouldBe("The operation could not be executed because it was rejected by the rate limit."); + new RateLimitRejectedException(Dummy).Message.ShouldBe(Dummy); var rate = new RateLimitRejectedException(Dummy, exception); - rate.Message.Should().Be(Dummy); - rate.InnerException.Should().Be(exception); + rate.Message.ShouldBe(Dummy); + rate.InnerException.ShouldBe(exception); - new RateLimitRejectedException(retryAfter).RetryAfter.Should().Be(retryAfter); - new RateLimitRejectedException(retryAfter).Message.Should().Be($"The operation has been rate-limited and should be retried after {retryAfter}"); + new RateLimitRejectedException(retryAfter).RetryAfter.ShouldBe(retryAfter); + new RateLimitRejectedException(retryAfter).Message.ShouldBe($"The operation has been rate-limited and should be retried after {retryAfter}"); rate = new RateLimitRejectedException(retryAfter, exception); - rate.RetryAfter.Should().Be(retryAfter); - rate.InnerException.Should().Be(exception); + rate.RetryAfter.ShouldBe(retryAfter); + rate.InnerException.ShouldBe(exception); rate = new RateLimitRejectedException(retryAfter, Dummy); - rate.RetryAfter.Should().Be(retryAfter); - rate.Message.Should().Be(Dummy); + rate.RetryAfter.ShouldBe(retryAfter); + rate.Message.ShouldBe(Dummy); rate = new RateLimitRejectedException(retryAfter, Dummy, exception); - rate.RetryAfter.Should().Be(retryAfter); - rate.Message.Should().Be(Dummy); - rate.InnerException.Should().Be(exception); + rate.RetryAfter.ShouldBe(retryAfter); + rate.Message.ShouldBe(Dummy); + rate.InnerException.ShouldBe(exception); } } diff --git a/test/Polly.Specs/RateLimit/RateLimitSpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitSpecsBase.cs index 51a9b79516..7bc409a35e 100644 --- a/test/Polly.Specs/RateLimit/RateLimitSpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitSpecsBase.cs @@ -23,7 +23,7 @@ protected static void Within(TimeSpan timeSpan, Action actionContainingAssertion } catch (Exception e) { - if (e is not AssertionFailedException and not IAssertionException) + if (e is not IAssertionException) { throw; } diff --git a/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs b/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs index 08a9b1d8e2..f07601b7d6 100644 --- a/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs +++ b/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs @@ -120,7 +120,7 @@ public void Given_any_bucket_capacity_rate_limiter_permits_full_bucket_burst_aft [InlineData(100)] public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burst_after_half_required_refill_time_elapsed(int bucketCapacity) { - (bucketCapacity % 2).Should().Be(0); + (bucketCapacity % 2).ShouldBe(0); FixClock(); @@ -146,7 +146,7 @@ public void Given_any_bucket_capacity_rate_limiter_permits_half_full_bucket_burs [InlineData(100, 5)] public void Given_any_bucket_capacity_rate_limiter_permits_only_full_bucket_burst_even_if_multiple_required_refill_time_elapsed(int bucketCapacity, int multipleRefillTimePassed) { - multipleRefillTimePassed.Should().BeGreaterThan(1); + multipleRefillTimePassed.ShouldBeGreaterThan(1); FixClock(); @@ -200,7 +200,7 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o // Assert - one should have permitted execution, n-1 not. var results = tasks.Select(t => t.Result).ToList(); - results.Count(r => r.PermitExecution).Should().Be(1); - results.Count(r => !r.PermitExecution).Should().Be(parallelContention - 1); + results.Count(r => r.PermitExecution).ShouldBe(1); + results.Count(r => !r.PermitExecution).ShouldBe(parallelContention - 1); } } diff --git a/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs b/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs index 51b0694d6c..b4ff1e05ff 100644 --- a/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs +++ b/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs @@ -14,15 +14,15 @@ public void Should_be_able_to_add_Policy_using_TryAdd() string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); - _registry.Count.Should().Be(1); - insert.Should().Be(true); + _registry.Count.ShouldBe(1); + insert.ShouldBe(true); Policy policy2 = Policy.NoOp(); string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); - _registry.Count.Should().Be(2); - insert2.Should().Be(true); + _registry.Count.ShouldBe(2); + insert2.ShouldBe(true); } [Fact] @@ -32,15 +32,15 @@ public void Should_be_able_to_add_PolicyTResult_using_TryAdd() string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); - _registry.Count.Should().Be(1); - insert.Should().Be(true); + _registry.Count.ShouldBe(1); + insert.ShouldBe(true); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); - _registry.Count.Should().Be(2); - insert2.Should().Be(true); + _registry.Count.ShouldBe(2); + insert2.ShouldBe(true); } [Fact] @@ -50,15 +50,15 @@ public void Should_be_able_to_add_Policy_by_interface_using_TryAdd() string key = Guid.NewGuid().ToString(); var insert = _registry.TryAdd(key, policy); - _registry.Count.Should().Be(1); - insert.Should().Be(true); + _registry.Count.ShouldBe(1); + insert.ShouldBe(true); ISyncPolicy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); string key2 = Guid.NewGuid().ToString(); var insert2 = _registry.TryAdd(key2, policy2); - _registry.Count.Should().Be(2); - insert2.Should().Be(true); + _registry.Count.ShouldBe(2); + insert2.ShouldBe(true); } [Fact] @@ -68,12 +68,12 @@ public void Should_be_able_to_remove_policy_with_TryRemove() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); bool removed = _registry.TryRemove(key, out IsPolicy removedPolicy); - _registry.Count.Should().Be(0); - removedPolicy.Should().BeSameAs(policy); - removed.Should().BeTrue(); + _registry.Count.ShouldBe(0); + removedPolicy.ShouldBeSameAs(policy); + removed.ShouldBeTrue(); } [Fact] @@ -82,7 +82,7 @@ public void Should_report_false_from_TryRemove_if_no_Policy() string key = Guid.NewGuid().ToString(); bool removed = _registry.TryRemove(key, out IsPolicy removedPolicy); - removed.Should().BeFalse(); + removed.ShouldBeFalse(); } [Fact] @@ -96,8 +96,8 @@ public void Should_be_able_to_update_policy_with_TryUpdate() bool updated = _registry.TryUpdate(key, newPolicy, existingPolicy); - updated.Should().BeTrue(); - _registry[key].Should().BeSameAs(newPolicy); + updated.ShouldBeTrue(); + _registry[key].ShouldBeSameAs(newPolicy); } [Fact] @@ -112,8 +112,8 @@ public void Should_not_update_policy_with_TryUpdate_when_existingPolicy_mismatch bool updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); - updated.Should().BeFalse(); - _registry[key].Should().BeSameAs(existingPolicy); + updated.ShouldBeFalse(); + _registry[key].ShouldBeSameAs(existingPolicy); } [Fact] @@ -126,8 +126,8 @@ public void Should_not_update_policy_with_TryUpdate_when_no_existing_value() bool updated = _registry.TryUpdate(key, newPolicy, someOtherPolicy); - updated.Should().BeFalse(); - _registry.ContainsKey(key).Should().BeFalse(); + updated.ShouldBeFalse(); + _registry.ContainsKey(key).ShouldBeFalse(); } [Fact] @@ -138,7 +138,7 @@ public void Should_add_with_GetOrAdd_with_value_when_no_existing_policy() var returnedPolicy = _registry.GetOrAdd(key, newPolicy); - returnedPolicy.Should().BeSameAs(newPolicy); + returnedPolicy.ShouldBeSameAs(newPolicy); } [Fact] @@ -149,7 +149,7 @@ public void Should_add_with_GetOrAdd_with_factory_when_no_existing_policy() var returnedPolicy = _registry.GetOrAdd(key, _ => newPolicy); - returnedPolicy.Should().BeSameAs(newPolicy); + returnedPolicy.ShouldBeSameAs(newPolicy); } [Fact] @@ -163,7 +163,7 @@ public void Should_return_existing_with_GetOrAdd_with_value_when_existing_policy var returnedPolicy = _registry.GetOrAdd(key, newPolicy); - returnedPolicy.Should().BeSameAs(existingPolicy); + returnedPolicy.ShouldBeSameAs(existingPolicy); } [Fact] @@ -177,7 +177,7 @@ public void Should_return_existing_with_GetOrAdd_with_factory_when_existing_poli var returnedPolicy = _registry.GetOrAdd(key, _ => newPolicy); - returnedPolicy.Should().BeSameAs(existingPolicy); + returnedPolicy.ShouldBeSameAs(existingPolicy); } [Fact] @@ -191,7 +191,7 @@ public void Should_add_with_AddOrUpdate_with_value_when_no_existing_policy() newPolicy, (_, _) => throw new InvalidOperationException("Update factory should not be called in this test.")); - returnedPolicy.Should().BeSameAs(newPolicy); + returnedPolicy.ShouldBeSameAs(newPolicy); } [Fact] @@ -205,7 +205,7 @@ public void Should_add_with_AddOrUpdate_with_addfactory_when_no_existing_policy( _ => newPolicy, (_, _) => throw new InvalidOperationException("Update factory should not be called in this test.")); - returnedPolicy.Should().BeSameAs(newPolicy); + returnedPolicy.ShouldBeSameAs(newPolicy); } [Fact] @@ -224,9 +224,9 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addvalue_ otherPolicyNotExpectingToAdd, (_, _) => existingPolicy.WithPolicyKey(PolicyKeyToDecorate)); - returnedPolicy.Should().NotBeSameAs(otherPolicyNotExpectingToAdd); - returnedPolicy.Should().BeSameAs(existingPolicy); - returnedPolicy.PolicyKey.Should().Be(PolicyKeyToDecorate); + returnedPolicy.ShouldNotBeSameAs(otherPolicyNotExpectingToAdd); + returnedPolicy.ShouldBeSameAs(existingPolicy); + returnedPolicy.PolicyKey.ShouldBe(PolicyKeyToDecorate); } [Fact] @@ -245,8 +245,8 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addfactor _ => otherPolicyNotExpectingToAdd, (_, _) => existingPolicy.WithPolicyKey(PolicyKeyToDecorate)); - returnedPolicy.Should().NotBeSameAs(otherPolicyNotExpectingToAdd); - returnedPolicy.Should().BeSameAs(existingPolicy); - returnedPolicy.PolicyKey.Should().Be(PolicyKeyToDecorate); + returnedPolicy.ShouldNotBeSameAs(otherPolicyNotExpectingToAdd); + returnedPolicy.ShouldBeSameAs(existingPolicy); + returnedPolicy.PolicyKey.ShouldBe(PolicyKeyToDecorate); } } diff --git a/test/Polly.Specs/Registry/PolicyRegistrySpecs.cs b/test/Polly.Specs/Registry/PolicyRegistrySpecs.cs index 1fd8f1fed0..e7d6b7ffe9 100644 --- a/test/Polly.Specs/Registry/PolicyRegistrySpecs.cs +++ b/test/Polly.Specs/Registry/PolicyRegistrySpecs.cs @@ -2,10 +2,7 @@ public class PolicyRegistrySpecs { - private readonly IPolicyRegistry _registry; - - public PolicyRegistrySpecs() => - _registry = new PolicyRegistry(); + private readonly PolicyRegistry _registry = []; #region Tests for adding Policy @@ -16,13 +13,13 @@ public void Should_be_able_to_add_Policy_using_Add() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); Policy policy2 = Policy.NoOp(); string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); } [Fact] @@ -32,13 +29,13 @@ public void Should_be_able_to_add_PolicyTResult_using_Add() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); } [Fact] @@ -48,13 +45,13 @@ public void Should_be_able_to_add_Policy_by_interface_using_Add() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); ISyncPolicy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); string key2 = Guid.NewGuid().ToString(); _registry.Add>(key2, policy2); - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); } [Fact] @@ -64,13 +61,13 @@ public void Should_be_able_to_add_Policy_using_Indexer() string key = Guid.NewGuid().ToString(); _registry[key] = policy; - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); Policy policy2 = Policy.NoOp(); string key2 = Guid.NewGuid().ToString(); _registry[key2] = policy2; - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); } [Fact] @@ -80,13 +77,13 @@ public void Should_be_able_to_add_PolicyTResult_using_Indexer() string key = Guid.NewGuid().ToString(); _registry[key] = policy; - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); Policy policy2 = Policy.HandleResult(ResultPrimitive.Fault).Retry(); string key2 = Guid.NewGuid().ToString(); _registry[key2] = policy2; - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); } [Fact] @@ -95,13 +92,11 @@ public void Should_not_be_able_to_add_Policy_with_duplicate_key_using_Add() Policy policy = Policy.NoOp(); string key = Guid.NewGuid().ToString(); - _registry.Invoking(r => r.Add(key, policy)) - .Should().NotThrow(); + Should.NotThrow(() => _registry.Add(key, policy)); - _registry.Invoking(r => r.Add(key, policy)) - .Should().Throw(); + Should.Throw(() => _registry.Add(key, policy)); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); } [Fact] @@ -114,9 +109,9 @@ public void Should_be_able_to_overwrite_existing_Policy_if_key_exists_when_inser Policy policy_new = Policy.NoOp(); _registry[key] = policy_new; - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); - _registry.Get(key).Should().BeSameAs(policy_new); + _registry.Get(key).ShouldBeSameAs(policy_new); } [Fact] @@ -129,9 +124,9 @@ public void Should_be_able_to_overwrite_existing_PolicyTResult_if_key_exists_whe Policy policy_new = Policy.HandleResult(ResultPrimitive.Fault).Retry(); _registry[key] = policy_new; - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); - _registry.Get>(key).Should().BeSameAs(policy_new); + _registry.Get>(key).ShouldBeSameAs(policy_new); } [Fact] @@ -139,8 +134,7 @@ public void Should_throw_when_adding_Policy_using_Add_when_key_is_null() { string key = null!; Policy policy = Policy.NoOp(); - _registry.Invoking(r => r.Add(key, policy)) - .Should().Throw(); + Should.Throw(() => _registry.Add(key, policy)); } [Fact] @@ -148,8 +142,7 @@ public void Should_throw_when_adding_Policy_using_Indexer_when_key_is_null() { string key = null!; Policy policy = Policy.NoOp(); - _registry.Invoking(r => r[key] = policy) - .Should().Throw(); + Should.Throw(() => _registry[key] = policy); } #endregion @@ -163,8 +156,8 @@ public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.TryGet(key, out Policy? outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + _registry.TryGet(key, out Policy? outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -174,8 +167,8 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.TryGet(key, out Policy outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + _registry.TryGet(key, out Policy outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -185,8 +178,8 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.TryGet(key, out ISyncPolicy outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + _registry.TryGet(key, out ISyncPolicy outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -196,7 +189,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Get(key).Should().BeSameAs(policy); + _registry.Get(key).ShouldBeSameAs(policy); } [Fact] @@ -206,7 +199,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Get>(key).Should().BeSameAs(policy); + _registry.Get>(key).ShouldBeSameAs(policy); } [Fact] @@ -216,7 +209,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Get>(key).Should().BeSameAs(policy); + _registry.Get>(key).ShouldBeSameAs(policy); } [Fact] @@ -226,7 +219,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry[key].Should().BeSameAs(policy); + _registry[key].ShouldBeSameAs(policy); } [Fact] @@ -236,7 +229,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry[key].Should().BeSameAs(policy); + _registry[key].ShouldBeSameAs(policy); } [Fact] @@ -246,7 +239,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer( string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry[key].Should().BeSameAs(policy); + _registry[key].ShouldBeSameAs(policy); } [Fact] @@ -256,11 +249,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG Policy? policy = null; bool result = false; - _registry.Invoking(r => result = r.TryGet(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = _registry.TryGet(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -270,11 +262,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG Policy? policy = null; bool result = false; - _registry.Invoking(r => result = r.TryGet(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = _registry.TryGet(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -284,11 +275,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG ISyncPolicy? policy = null; bool result = false; - _registry.Invoking(r => result = r.TryGet>(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = _registry.TryGet>(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -296,9 +286,8 @@ public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() { string key = Guid.NewGuid().ToString(); Policy? policy = null; - _registry.Invoking(r => policy = r.Get(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get(key)); + policy.ShouldBeNull(); } [Fact] @@ -306,9 +295,8 @@ public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exi { string key = Guid.NewGuid().ToString(); Policy? policy = null; - _registry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -316,9 +304,8 @@ public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_n { string key = Guid.NewGuid().ToString(); ISyncPolicy? policy = null; - _registry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -326,9 +313,8 @@ public void Should_throw_while_retrieving_when_key_does_not_exist_using_Indexer( { string key = Guid.NewGuid().ToString(); IsPolicy? policy = null; - _registry.Invoking(r => policy = r[key]) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry[key]); + policy.ShouldBeNull(); } [Fact] @@ -336,9 +322,8 @@ public void Should_throw_when_retrieving_using_Get_when_key_is_null() { string key = null!; Policy? policy = null; - _registry.Invoking(r => policy = r.Get(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get(key)); + policy.ShouldBeNull(); } [Fact] @@ -346,9 +331,8 @@ public void Should_throw_when_retrieving_using_GetTResult_when_key_is_null() { string key = null!; Policy? policy = null; - _registry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -356,9 +340,8 @@ public void Should_throw_when_retrieving_using_Get_by_interface_when_key_is_null { string key = null!; ISyncPolicy? policy = null; - _registry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -366,9 +349,8 @@ public void Should_throw_when_retrieving_using_Indexer_when_key_is_null() { string key = null!; IsPolicy? policy = null; - _registry.Invoking(r => policy = r[key]) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = _registry[key]); + policy.ShouldBeNull(); } #endregion @@ -380,16 +362,16 @@ public void Should_be_able_to_clear_registry() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); Policy policy2 = Policy.NoOp(); string key2 = Guid.NewGuid().ToString(); _registry.Add(key2, policy2); - _registry.Count.Should().Be(2); + _registry.Count.ShouldBe(2); _registry.Clear(); - _registry.Count.Should().Be(0); + _registry.Count.ShouldBe(0); } [Fact] @@ -399,18 +381,17 @@ public void Should_be_able_to_remove_policy() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.Count.Should().Be(1); + _registry.Count.ShouldBe(1); _registry.Remove(key); - _registry.Count.Should().Be(0); + _registry.Count.ShouldBe(0); } [Fact] public void Should_throw_when_removing_Policy_when_key_is_null() { string key = null!; - _registry.Invoking(r => r.Remove(key)) - .Should().Throw(); + Should.Throw(() => _registry.Remove(key)); } #endregion @@ -423,18 +404,17 @@ public void Should_be_able_to_check_if_key_exists() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - _registry.ContainsKey(key).Should().BeTrue(); + _registry.ContainsKey(key).ShouldBeTrue(); string key2 = Guid.NewGuid().ToString(); - _registry.ContainsKey(key2).Should().BeFalse(); + _registry.ContainsKey(key2).ShouldBeFalse(); } [Fact] public void Should_throw_when_checking_if_key_exists_when_key_is_null() { string key = null!; - _registry.Invoking(r => r.ContainsKey(key)) - .Should().Throw(); + Should.Throw(() => _registry.ContainsKey(key)); } #endregion @@ -448,7 +428,7 @@ public void Constructor_Called_With_A_Registry_Parameter_Should_Assign_The_Passe // Generally, using reflection is a bad practice, but we are accepting it given we own the implementation. var registryField = typeof(PolicyRegistry).GetField("_registry", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance)!; var registryFieldValue = registryField.GetValue(testRegistry); - registryFieldValue.Should().Be(testDictionary); + registryFieldValue.ShouldBe(testDictionary); } [Fact] @@ -460,7 +440,7 @@ public void Constructor_Called_With_Default_Parameters_Assigns_A_ConcurrentDicti // Generally, using reflection is a bad practice, but we are accepting it given we own the implementation. var registryField = typeof(PolicyRegistry).GetField("_registry", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance)!; var registryFieldValue = registryField.GetValue(testRegistry); - registryFieldValue.Should().BeOfType(expectedDictionaryType); + registryFieldValue.ShouldBeOfType(expectedDictionaryType); } #endregion diff --git a/test/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs b/test/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs index 09a09496f7..a2b506913e 100644 --- a/test/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs +++ b/test/Polly.Specs/Registry/ReadOnlyPolicyRegistrySpecs.cs @@ -18,8 +18,8 @@ public void Should_be_able_to_retrieve_stored_Policy_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.TryGet(key, out Policy? outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + ReadOnlyRegistry.TryGet(key, out Policy? outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -29,8 +29,8 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.TryGet(key, out Policy? outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + ReadOnlyRegistry.TryGet(key, out Policy? outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -40,8 +40,8 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_TryGet() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.TryGet(key, out ISyncPolicy? outPolicy).Should().BeTrue(); - outPolicy.Should().BeSameAs(policy); + ReadOnlyRegistry.TryGet(key, out ISyncPolicy? outPolicy).ShouldBeTrue(); + outPolicy.ShouldBeSameAs(policy); } [Fact] @@ -51,7 +51,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.Get(key).Should().BeSameAs(policy); + ReadOnlyRegistry.Get(key).ShouldBeSameAs(policy); } [Fact] @@ -61,7 +61,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.Get>(key).Should().BeSameAs(policy); + ReadOnlyRegistry.Get>(key).ShouldBeSameAs(policy); } [Fact] @@ -71,7 +71,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Get() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.Get>(key).Should().BeSameAs(policy); + ReadOnlyRegistry.Get>(key).ShouldBeSameAs(policy); } [Fact] @@ -81,7 +81,7 @@ public void Should_be_able_to_retrieve_stored_Policy_using_Indexer() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry[key].Should().BeSameAs(policy); + ReadOnlyRegistry[key].ShouldBeSameAs(policy); } [Fact] @@ -91,7 +91,7 @@ public void Should_be_able_to_retrieve_stored_PolicyTResult_using_Indexer() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry[key].Should().BeSameAs(policy); + ReadOnlyRegistry[key].ShouldBeSameAs(policy); } [Fact] @@ -101,7 +101,7 @@ public void Should_be_able_to_retrieve_stored_Policy_by_interface_using_Indexer( string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry[key].Should().BeSameAs(policy); + ReadOnlyRegistry[key].ShouldBeSameAs(policy); } [Fact] @@ -111,11 +111,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG Policy? policy = null; bool result = false; - ReadOnlyRegistry.Invoking(r => result = r.TryGet(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = ReadOnlyRegistry.TryGet(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -125,11 +124,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG Policy? policy = null; bool result = false; - ReadOnlyRegistry.Invoking(r => result = r.TryGet(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = ReadOnlyRegistry.TryGet(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -139,11 +137,10 @@ public void Should_not_throw_while_retrieving_when_key_does_not_exist_using_TryG ISyncPolicy? policy = null; bool result = false; - ReadOnlyRegistry.Invoking(r => result = r.TryGet>(key, out policy)) - .Should().NotThrow(); + Should.NotThrow(() => result = ReadOnlyRegistry.TryGet>(key, out policy)); - result.Should().BeFalse(); - policy.Should().BeNull(); + result.ShouldBeFalse(); + policy.ShouldBeNull(); } [Fact] @@ -151,9 +148,8 @@ public void Should_throw_while_retrieving_using_Get_when_key_does_not_exist() { string key = Guid.NewGuid().ToString(); Policy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get(key)); + policy.ShouldBeNull(); } [Fact] @@ -161,9 +157,8 @@ public void Should_throw_while_retrieving_using_GetTResult_when_key_does_not_exi { string key = Guid.NewGuid().ToString(); Policy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -171,9 +166,8 @@ public void Should_throw_while_retrieving_using_Get_by_interface_when_key_does_n { string key = Guid.NewGuid().ToString(); ISyncPolicy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -181,9 +175,8 @@ public void Should_throw_while_retrieving_when_key_does_not_exist_using_Indexer( { string key = Guid.NewGuid().ToString(); IsPolicy? outPolicy = null; - ReadOnlyRegistry.Invoking(r => outPolicy = r[key]) - .Should().Throw(); - outPolicy.Should().BeNull(); + Should.Throw(() => outPolicy = ReadOnlyRegistry[key]); + outPolicy.ShouldBeNull(); } [Fact] @@ -191,9 +184,8 @@ public void Should_throw_when_retrieving_using_Get_when_key_is_null() { string key = null!; Policy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get(key)); + policy.ShouldBeNull(); } [Fact] @@ -201,9 +193,8 @@ public void Should_throw_when_retrieving_using_GetTResult_when_key_is_null() { string key = null!; Policy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -211,9 +202,8 @@ public void Should_throw_when_retrieving_using_Get_by_interface_when_key_is_null { string key = null!; ISyncPolicy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r.Get>(key)) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry.Get>(key)); + policy.ShouldBeNull(); } [Fact] @@ -221,9 +211,8 @@ public void Should_throw_when_retrieving_using_Indexer_when_key_is_null() { string key = null!; IsPolicy? policy = null; - ReadOnlyRegistry.Invoking(r => policy = r[key]) - .Should().Throw(); - policy.Should().BeNull(); + Should.Throw(() => policy = ReadOnlyRegistry[key]); + policy.ShouldBeNull(); } #endregion @@ -236,18 +225,17 @@ public void Should_be_able_to_check_if_key_exists() string key = Guid.NewGuid().ToString(); _registry.Add(key, policy); - ReadOnlyRegistry.ContainsKey(key).Should().BeTrue(); + ReadOnlyRegistry.ContainsKey(key).ShouldBeTrue(); string key2 = Guid.NewGuid().ToString(); - ReadOnlyRegistry.ContainsKey(key2).Should().BeFalse(); + ReadOnlyRegistry.ContainsKey(key2).ShouldBeFalse(); } [Fact] public void Should_throw_when_checking_if_key_exists_when_key_is_null() { string key = null!; - ReadOnlyRegistry.Invoking(r => r.ContainsKey(key)) - .Should().Throw(); + Should.Throw(() => ReadOnlyRegistry.ContainsKey(key)); } #endregion @@ -276,12 +264,12 @@ public void Policies_Should_Be_Added_To_The_Registry_When_Using_Collection_Initi var testRegistry = new PolicyRegistry { - {key, policy} + [key] = policy }; - testRegistry.Should().Equal(new Dictionary + testRegistry.ShouldBe(new Dictionary { - {key, policy} + [key] = policy }); } #endregion diff --git a/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs b/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs index f213e1f614..37aebab3dc 100644 --- a/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs +++ b/test/Polly.Specs/ResiliencePipelineConversionExtensionsTests.cs @@ -22,11 +22,11 @@ public ResiliencePipelineConversionExtensionsTests() { Before = (context, _) => { - context.GetType().GetProperty("IsVoid", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).Should().Be(_isVoid); - context.GetType().GetProperty("IsSynchronous", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).Should().Be(_isSynchronous); + context.GetType().GetProperty("IsVoid", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).ShouldBe(_isVoid); + context.GetType().GetProperty("IsSynchronous", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(context).ShouldBe(_isSynchronous); context.Properties.Set(Outgoing, "outgoing-value"); - context.Properties.GetValue(Incoming, string.Empty).Should().Be("incoming-value"); - context.OperationKey.Should().Be("op-key"); + context.Properties.GetValue(Incoming, string.Empty).ShouldBe("incoming-value"); + context.OperationKey.ShouldBe("op-key"); } }; @@ -66,7 +66,7 @@ public void AsSyncPolicy_Generic_Ok() var result = _genericStrategy.AsSyncPolicy().Execute(_ => { context[Executing.Key] = "executing-value"; return "dummy"; }, context); AssertContext(context); - result.Should().Be("dummy"); + result.ShouldBe("dummy"); } [Fact] @@ -82,7 +82,7 @@ public void AsSyncPolicy_Result_Ok() var result = _strategy.AsPipeline().AsSyncPolicy().Execute(_ => { context[Executing.Key] = "executing-value"; return "dummy"; }, context); AssertContext(context); - result.Should().Be("dummy"); + result.ShouldBe("dummy"); } [Fact] @@ -122,7 +122,7 @@ public async Task AsAsyncPolicy_Generic_Ok() }, context); AssertContext(context); - result.Should().Be("dummy"); + result.ShouldBe("dummy"); } [Fact] @@ -143,7 +143,7 @@ public async Task AsAsyncPolicy_Result_Ok() context); AssertContext(context); - result.Should().Be("dummy"); + result.ShouldBe("dummy"); } [Fact] @@ -172,15 +172,14 @@ public void RetryStrategy_AsSyncPolicy_Ok() return "dummy"; }, context) - .Should() - .Be("dummy"); + .ShouldBe("dummy"); - context["retry"].Should().Be(6); + context["retry"].ShouldBe(6); } private static void AssertContext(Context context) { - context[Outgoing.Key].Should().Be("outgoing-value"); - context[Executing.Key].Should().Be("executing-value"); + context[Outgoing.Key].ShouldBe("outgoing-value"); + context[Executing.Key].ShouldBe("executing-value"); } } diff --git a/test/Polly.Specs/Retry/RetryAsyncSpecs.cs b/test/Polly.Specs/Retry/RetryAsyncSpecs.cs index 4cca60d4e3..d3802b3f50 100644 --- a/test/Polly.Specs/Retry/RetryAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/RetryAsyncSpecs.cs @@ -28,10 +28,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -43,8 +43,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() .Handle() .RetryAsync(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -54,8 +54,7 @@ public async Task Should_not_throw_when_specified_exception_thrown_same_number_o .Handle() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -66,8 +65,7 @@ public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_s .Or() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -77,8 +75,7 @@ public async Task Should_not_throw_when_specified_exception_thrown_less_number_o .Handle() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -89,8 +86,7 @@ public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_l .Or() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -100,8 +96,7 @@ public async Task Should_throw_when_specified_exception_thrown_more_times_then_r .Handle() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync(3 + 1)); } [Fact] @@ -112,8 +107,7 @@ public async Task Should_throw_when_one_of_the_specified_exceptions_are_thrown_m .Or() .RetryAsync(3); - await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync(3 + 1)); } [Fact] @@ -123,8 +117,7 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except .Handle() .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -135,8 +128,7 @@ public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified .Or() .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -146,8 +138,7 @@ public async Task Should_throw_when_specified_exception_predicate_is_not_satisfi .Handle(_ => false) .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -158,8 +149,7 @@ public async Task Should_throw_when_none_of_the_specified_exception_predicates_a .Or(_ => false) .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -169,8 +159,7 @@ public async Task Should_not_throw_when_specified_exception_predicate_is_satisfi .Handle(_ => true) .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -181,8 +170,7 @@ public async Task Should_not_throw_when_one_of_the_specified_exception_predicate .Or(_ => true) .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -192,7 +180,7 @@ public void Should_throw_when_onRetry_is_null() .Handle() .RetryAsync(3, (Action)null!); - action.Should().Throw().And.ParamName.Should().Be("onRetry"); + Should.Throw(action).ParamName.ShouldBe("onRetry"); } [Fact] @@ -202,7 +190,7 @@ public void Should_throw_when_onRetryAsync_is_null() .Handle() .RetryAsync(3, (Func)null!); - action.Should().Throw().And.ParamName.Should().Be("onRetryAsync"); + Should.Throw(action).ParamName.ShouldBe("onRetryAsync"); } [Fact] @@ -217,8 +205,7 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count await policy.RaiseExceptionAsync(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -235,8 +222,7 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_exception() retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -253,7 +239,7 @@ public async Task Should_call_onretry_with_a_handled_innerexception() await policy.RaiseExceptionAsync(withInner); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -265,11 +251,9 @@ public async Task Should_not_call_onretry_when_no_retries_are_performed() .Handle() .RetryAsync((_, retryCount) => retryCounts.Add(retryCount)); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryCounts.Should() - .BeEmpty(); + retryCounts.ShouldBeEmpty(); } [Fact] @@ -279,11 +263,8 @@ public async Task Should_create_new_state_for_each_call_to_policy() .Handle() .RetryAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); - - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -298,9 +279,9 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseExceptionAsync( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -312,13 +293,15 @@ public async Task Should_call_onretry_with_the_passed_context_when_execute_and_c .Handle() .RetryAsync((_, _, context) => contextData = context); - await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => { throw new DivideByZeroException(); }, - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + policy.ExecuteAndCaptureAsync( + _ => { throw new DivideByZeroException(); }, + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -330,10 +313,10 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data() .Handle() .RetryAsync((_, _, context) => capturedContext = context); - await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); - capturedContext.Should() - .BeEmpty(); + capturedContext.ShouldNotBeNull(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -348,12 +331,12 @@ public void Should_create_new_context_for_each_call_to_execute() policy.RaiseExceptionAsync( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseExceptionAsync( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -365,17 +348,21 @@ public async Task Should_create_new_context_for_each_call_to_execute_and_capture .Handle() .RetryAsync((_, _, context) => contextValue = context["key"].ToString()); - await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), - CreateDictionary("key", "original_value"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + policy.ExecuteAndCaptureAsync( + _ => throw new DivideByZeroException(), + CreateDictionary("key", "original_value"))); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); - await policy.Awaiting(p => p.ExecuteAndCaptureAsync(_ => throw new DivideByZeroException(), - CreateDictionary("key", "new_value"))) - .Should().NotThrowAsync(); + await Should.NotThrowAsync( + () => + policy.ExecuteAndCaptureAsync( + _ => throw new DivideByZeroException(), + CreateDictionary("key", "new_value"))); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -389,10 +376,9 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero() .Handle() .RetryAsync(0, onRetry); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } #region Async and cancellation tests @@ -406,7 +392,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' of the retry policy would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); int executeDelegateInvocations = 0; int executeDelegateInvocationsWhenOnRetryExits = 0; @@ -419,20 +405,20 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; throw new DivideByZeroException(); - })).Should().ThrowAsync(); + })); while (executeDelegateInvocationsWhenOnRetryExits == 0) { // Wait for the onRetry delegate to complete. } - executeDelegateInvocationsWhenOnRetryExits.Should().Be(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. - executeDelegateInvocations.Should().Be(2); + executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. + executeDelegateInvocations.ShouldBe(2); } [Fact] @@ -455,11 +441,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -482,11 +467,10 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -510,12 +494,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -539,12 +522,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -568,12 +550,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -596,12 +577,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec using (var cancellationTokenSource = new CancellationTokenSource()) { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -625,12 +605,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -654,12 +633,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -683,12 +661,11 @@ public async Task Should_report_cancellation_during_faulting_last_retry_executio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -712,11 +689,10 @@ public async Task Should_report_faulting_from_faulting_last_retry_execution_when { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -743,12 +719,11 @@ public async Task Should_report_cancellation_after_faulting_action_execution_and cancellationTokenSource.Cancel(); }); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -773,14 +748,14 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await policy.Awaiting(action) - .Should().NotThrowAsync(); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + await Should.NotThrowAsync(action); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -806,14 +781,14 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await policy.Awaiting(action).Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + var ex = await Should.ThrowAsync(action); + ex.CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs b/test/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs index 7c45c04293..641dea6405 100644 --- a/test/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/RetryForeverAsyncSpecs.cs @@ -11,8 +11,7 @@ public async Task Should_not_throw_regardless_of_how_many_times_the_specified_ex .Handle() .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -23,8 +22,7 @@ public async Task Should_not_throw_regardless_of_how_many_times_one_of_the_speci .Or() .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -34,8 +32,7 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except .Handle() .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -46,8 +43,7 @@ public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified .Or() .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -57,8 +53,7 @@ public async Task Should_throw_when_specified_exception_predicate_is_not_satisfi .Handle(_ => false) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -69,8 +64,7 @@ public async Task Should_throw_when_none_of_the_specified_exception_predicates_a .Or(_ => false) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -80,8 +74,7 @@ public async Task Should_not_throw_when_specified_exception_predicate_is_satisfi .Handle(_ => true) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -92,8 +85,7 @@ public async Task Should_not_throw_when_one_of_the_specified_exception_predicate .Or(_ => true) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -148,8 +140,7 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_exception() retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -164,9 +155,9 @@ public void Should_call_onretry_on_each_retry_with_the_passed_context() policy.RaiseExceptionAsync( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -181,8 +172,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseExceptionAsync(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -194,10 +184,9 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data() .Handle() .RetryForeverAsync((_, context) => capturedContext = context); - await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); - capturedContext.Should() - .BeEmpty(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -212,12 +201,12 @@ public void Should_create_new_context_for_each_call_to_execute() policy.RaiseExceptionAsync( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseExceptionAsync( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -227,13 +216,11 @@ public async Task Should_not_call_onretry_when_no_retries_are_performed() var policy = Policy .Handle() - .RetryForeverAsync(exception => retryExceptions.Add(exception)); + .RetryForeverAsync(retryExceptions.Add); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryExceptions.Should() - .BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] @@ -245,7 +232,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); int executeDelegateInvocations = 0; int executeDelegateInvocationsWhenOnRetryExits = 0; @@ -258,7 +245,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.NotThrowAsync(() => policy.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; @@ -266,15 +253,15 @@ await policy.Awaiting(p => p.ExecuteAsync(async () => { throw new DivideByZeroException(); } - })).Should().NotThrowAsync(); + })); while (executeDelegateInvocationsWhenOnRetryExits == 0) { // Wait for the onRetry delegate to complete. } - executeDelegateInvocationsWhenOnRetryExits.Should().Be(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. - executeDelegateInvocations.Should().Be(2); + executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. + executeDelegateInvocations.ShouldBe(2); } [Fact] @@ -297,11 +284,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -325,12 +311,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -354,12 +339,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -383,12 +367,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -412,12 +395,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -441,12 +423,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -470,12 +451,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -503,12 +483,11 @@ public async Task Should_report_cancellation_after_faulting_action_execution_and cancellationTokenSource.Cancel(); }); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -533,14 +512,14 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await policy.Awaiting(action) - .Should().NotThrowAsync(); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + await Should.NotThrowAsync(action); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -566,13 +545,13 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await policy.Awaiting(action).Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + var ex = await Should.ThrowAsync(action); + ex.CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBe(null); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } } diff --git a/test/Polly.Specs/Retry/RetryForeverSpecs.cs b/test/Polly.Specs/Retry/RetryForeverSpecs.cs index 495bfe20d3..aa1b5dbe54 100644 --- a/test/Polly.Specs/Retry/RetryForeverSpecs.cs +++ b/test/Polly.Specs/Retry/RetryForeverSpecs.cs @@ -11,8 +11,8 @@ public void Should_throw_when_onretry_action_without_context_is_null() .Handle() .RetryForever(nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -24,8 +24,8 @@ public void Should_throw_when_onretry_action_with_context_is_null() .Handle() .RetryForever(nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -35,8 +35,7 @@ public void Should_not_throw_regardless_of_how_many_times_the_specified_exceptio .Handle() .RetryForever(); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -47,8 +46,7 @@ public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_e .Or() .RetryForever(); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -58,8 +56,7 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .Handle() .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -69,8 +66,7 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except .Handle() .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -81,8 +77,7 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .Or() .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -92,8 +87,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .Handle(_ => false) .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -104,8 +98,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .Or(_ => false) .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -115,8 +108,7 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .Handle(_ => true) .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -126,8 +118,7 @@ public async Task Should_not_throw_when_specified_exception_predicate_is_satisfi .Handle(_ => true) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -138,8 +129,7 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ .Or(_ => true) .RetryForever(); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -150,8 +140,7 @@ public async Task Should_not_throw_when_one_of_the_specified_exception_predicate .Or(_ => true) .RetryForeverAsync(); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -162,14 +151,13 @@ public void Should_call_onretry_on_each_retry_with_the_current_exception() var policy = Policy .Handle() - .RetryForever(exception => retryExceptions.Add(exception)); + .RetryForever(retryExceptions.Add); policy.RaiseException(3, (e, i) => e.HelpLink = "Exception #" + i); retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -184,9 +172,9 @@ public void Should_call_onretry_on_each_retry_with_the_passed_context() policy.RaiseException( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -201,8 +189,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseException(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -212,13 +199,11 @@ public void Should_not_call_onretry_when_no_retries_are_performed() var policy = Policy .Handle() - .RetryForever(exception => retryExceptions.Add(exception)); + .RetryForever(retryExceptions.Add); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryExceptions.Should() - .BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] @@ -233,11 +218,11 @@ public void Should_create_new_context_for_each_call_to_execute() policy.RaiseException( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseException( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } } diff --git a/test/Polly.Specs/Retry/RetrySpecs.cs b/test/Polly.Specs/Retry/RetrySpecs.cs index 352b40b2df..1b83df0fe6 100644 --- a/test/Polly.Specs/Retry/RetrySpecs.cs +++ b/test/Polly.Specs/Retry/RetrySpecs.cs @@ -26,10 +26,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -41,8 +41,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() .Handle() .Retry(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -54,8 +54,8 @@ public void Should_throw_when_onretry_action_without_context_is_null() .Handle() .Retry(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -67,8 +67,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() .Handle() .Retry(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -80,8 +80,8 @@ public void Should_throw_when_onretry_action_with_context_is_null() .Handle() .Retry(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -91,8 +91,7 @@ public void Should_not_throw_when_specified_exception_thrown_same_number_of_time .Handle() .Retry(3); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -103,8 +102,7 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_nu .Or() .Retry(3); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -114,8 +112,7 @@ public void Should_not_throw_when_specified_exception_thrown_less_number_of_time .Handle() .Retry(3); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -126,8 +123,7 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_nu .Or() .Retry(3); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -137,8 +133,7 @@ public void Should_throw_when_specified_exception_thrown_more_times_then_retry_c .Handle() .Retry(3); - policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + Should.Throw(() => policy.RaiseException(3 + 1)); } [Fact] @@ -149,8 +144,7 @@ public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_ti .Or() .Retry(3); - policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + Should.Throw(() => policy.RaiseException(3 + 1)); } [Fact] @@ -160,8 +154,7 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .Handle() .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -172,8 +165,7 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .Or() .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -183,8 +175,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .Handle(_ => false) .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -195,8 +186,7 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .Or(_ => false) .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -206,8 +196,7 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() .Handle(_ => true) .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -218,8 +207,7 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ .Or(_ => true) .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -234,8 +222,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseException(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -252,8 +239,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_exception() retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -270,7 +256,7 @@ public void Should_call_onretry_with_a_handled_innerexception() policy.RaiseException(withInner); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -291,7 +277,7 @@ public void Should_call_onretry_with_handled_exception_nested_in_aggregate_as_fi policy.RaiseException(aggregateException); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -312,7 +298,7 @@ public void Should_call_onretry_with_handled_exception_nested_in_aggregate_as_se policy.RaiseException(aggregateException); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -335,7 +321,7 @@ public void Should_call_onretry_with_handled_exception_nested_in_aggregate_insid policy.RaiseException(aggregateException); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -358,7 +344,7 @@ public void Should_call_onretry_with_handled_exception_nested_in_aggregate_insid policy.RaiseException(aggregateException); - passedToOnRetry.Should().BeSameAs(toRaiseAsInner); + passedToOnRetry.ShouldBeSameAs(toRaiseAsInner); } [Fact] @@ -370,11 +356,9 @@ public void Should_not_call_onretry_when_no_retries_are_performed() .Handle() .Retry((_, retryCount) => retryCounts.Add(retryCount)); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryCounts.Should() - .BeEmpty(); + retryCounts.ShouldBeEmpty(); } [Fact] @@ -389,9 +373,9 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseException( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -403,13 +387,12 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture .Handle() .Retry((_, _, context) => contextData = context); - policy.Invoking(p => p.ExecuteAndCapture(_ => { throw new DivideByZeroException(); }, - CreateDictionary("key1", "value1", "key2", "value2"))) - .Should().NotThrow(); + Should.NotThrow(() => policy.ExecuteAndCapture(_ => throw new DivideByZeroException(), + CreateDictionary("key1", "value1", "key2", "value2"))); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -423,8 +406,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( policy.RaiseException(); - capturedContext.Should() - .BeEmpty(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -439,12 +421,12 @@ public void Should_create_new_context_for_each_call_to_execute() policy.RaiseException( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseException( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -456,17 +438,13 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() .Handle() .Retry((_, _, context) => contextValue = context["key"].ToString()); - policy.Invoking(p => p.ExecuteAndCapture(_ => throw new DivideByZeroException(), - CreateDictionary("key", "original_value"))) - .Should().NotThrow(); + Should.NotThrow(() => policy.ExecuteAndCapture(_ => throw new DivideByZeroException(), CreateDictionary("key", "original_value"))); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); - policy.Invoking(p => p.ExecuteAndCapture(_ => throw new DivideByZeroException(), - CreateDictionary("key", "new_value"))) - .Should().NotThrow(); + Should.NotThrow(() => policy.ExecuteAndCapture(_ => throw new DivideByZeroException(), CreateDictionary("key", "new_value"))); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -476,11 +454,8 @@ public void Should_create_new_state_for_each_call_to_policy() .Handle() .Retry(); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); - - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -488,16 +463,15 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() { bool retryInvoked = false; - Action onRetry = (_, _) => { retryInvoked = true; }; + Action onRetry = (_, _) => retryInvoked = true; var policy = Policy .Handle() .Retry(0, onRetry); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -505,16 +479,15 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() { bool retryInvoked = false; - Action onRetry = (_, _, _) => { retryInvoked = true; }; + Action onRetry = (_, _, _) => retryInvoked = true; var policy = Policy .Handle() .Retry(0, onRetry); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } #region Sync cancellation tests @@ -539,11 +512,10 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -566,11 +538,10 @@ public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_can { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -594,12 +565,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -623,12 +593,11 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -652,12 +621,11 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -681,12 +649,11 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -710,12 +677,11 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -739,12 +705,11 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -768,12 +733,11 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -797,11 +761,10 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -828,12 +791,11 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance cancellationTokenSource.Cancel(); }); - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -858,13 +820,13 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().NotThrow(); + Should.NotThrow(() => result = policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -890,13 +852,13 @@ public void Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => result = policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) + .CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/Retry/RetryTResultAsyncSpecs.cs b/test/Polly.Specs/Retry/RetryTResultAsyncSpecs.cs index 863ea0b014..f32a5c6587 100644 --- a/test/Polly.Specs/Retry/RetryTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/RetryTResultAsyncSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -42,8 +42,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() .HandleResult(ResultPrimitive.Fault) .RetryAsync(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -55,8 +55,8 @@ public void Should_throw_when_onretry_action_without_context_is_null() .HandleResult(ResultPrimitive.Fault) .RetryAsync(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -68,8 +68,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() .HandleResult(ResultPrimitive.Fault) .RetryAsync(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -81,8 +81,8 @@ public void Should_throw_when_onretry_action_with_context_is_null() .HandleResult(ResultPrimitive.Fault) .RetryAsync(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -93,7 +93,7 @@ public async Task Should_not_return_handled_result_when_handled_result_raised_sa .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -105,7 +105,7 @@ public async Task Should_not_return_handled_result_when_one_of_the_handled_resul .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -116,7 +116,7 @@ public async Task Should_not_return_handled_result_when_handled_result_raised_le .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -128,7 +128,7 @@ public async Task Should_not_return_handled_result_when_all_of_the_handled_resul .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -139,7 +139,7 @@ public async Task Should_return_handled_result_when_handled_result_raised_more_t .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. + result.ShouldBe(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. } [Fact] @@ -151,7 +151,7 @@ public async Task Should_return_handled_result_when_one_of_the_handled_results_i .RetryAsync(3); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -162,7 +162,7 @@ public async Task Should_return_result_when_result_is_not_the_specified_handled_ .RetryAsync(); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -174,7 +174,7 @@ public async Task Should_return_result_when_result_is_not_one_of_the_specified_h .RetryAsync(); ResultPrimitive result = await policy.RaiseResultSequenceAsync(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultYetAgain); + result.ShouldBe(ResultPrimitive.FaultYetAgain); } [Fact] @@ -185,7 +185,7 @@ public async Task Should_return_result_when_specified_result_predicate_is_not_sa .RetryAsync(); ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); + result.ResultCode.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -197,7 +197,7 @@ public async Task Should_return_result_when_none_of_the_specified_result_predica .RetryAsync(); ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.FaultYetAgain); + result.ResultCode.ShouldBe(ResultPrimitive.FaultYetAgain); } [Fact] @@ -208,7 +208,7 @@ public async Task Should_not_return_handled_result_when_specified_result_predica .RetryAsync(); ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.Good); + result.ResultCode.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -220,7 +220,7 @@ public async Task Should_not_return_handled_result_when_one_of_the_specified_res .RetryAsync(); ResultClass result = await policy.RaiseResultSequenceAsync(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.Good); + result.ResultCode.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -234,10 +234,9 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count .RetryAsync(3, (_, retryCount) => retryCounts.Add(retryCount)); (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -250,15 +249,13 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_handled_res .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .RetryAsync(3, (outcome, _) => retryFaults.Add(outcome.Result.SomeString)); - IList resultsToRaise = expectedFaults.Select(s => new ResultClass(ResultPrimitive.Fault, s)).ToList(); + var resultsToRaise = expectedFaults.Select(s => new ResultClass(ResultPrimitive.Fault, s)).ToList(); resultsToRaise.Add(new ResultClass(ResultPrimitive.Fault)); (await policy.RaiseResultSequenceAsync(resultsToRaise)) - .ResultCode.Should().Be(ResultPrimitive.Fault); + .ResultCode.ShouldBe(ResultPrimitive.Fault); - retryFaults - .Should() - .ContainInOrder(expectedFaults); + retryFaults.ShouldBe(expectedFaults); } [Fact] @@ -271,10 +268,9 @@ public async Task Should_not_call_onretry_when_no_retries_are_performed() .RetryAsync((_, retryCount) => retryCounts.Add(retryCount)); (await policy.RaiseResultSequenceAsync(ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); - retryCounts.Should() - .BeEmpty(); + retryCounts.ShouldBeEmpty(); } [Fact] @@ -289,11 +285,11 @@ public async Task Should_call_onretry_with_the_passed_context() (await policy.RaiseResultSequenceAsync( CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -309,19 +305,17 @@ public async Task Should_call_onretry_with_the_passed_context_when_execute_and_c CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = (FaultType?)null, - FinalHandledResult = default(ResultPrimitive), - Result = ResultPrimitive.Good - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBeNull(); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(ResultPrimitive.Good); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -335,8 +329,8 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_context await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - capturedContext.Should() - .BeEmpty(); + capturedContext.ShouldNotBeNull(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -352,13 +346,13 @@ await policy.RaiseResultSequenceAsync( CreateDictionary("key", "original_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); await policy.RaiseResultSequenceAsync( CreateDictionary("key", "new_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -374,13 +368,13 @@ await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( CreateDictionary("key", "original_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( CreateDictionary("key", "new_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -390,9 +384,9 @@ public async Task Should_create_new_state_for_each_call_to_policy() .HandleResult(ResultPrimitive.Fault) .RetryAsync(1); - (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).Should().Be(ResultPrimitive.Good); + (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).ShouldBe(ResultPrimitive.Good); - (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).Should().Be(ResultPrimitive.Good); + (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).ShouldBe(ResultPrimitive.Good); } @@ -407,9 +401,9 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero_without_conte .HandleResult(ResultPrimitive.Fault) .RetryAsync(0, onRetry); - (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).Should().Be(ResultPrimitive.Fault); + (await policy.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good)).ShouldBe(ResultPrimitive.Fault); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -425,9 +419,9 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero_with_context( (await policy.RaiseResultSequenceAsync( CreateDictionary("key", "value"), - ResultPrimitive.Fault, ResultPrimitive.Good)).Should().Be(ResultPrimitive.Fault); + ResultPrimitive.Fault, ResultPrimitive.Good)).ShouldBe(ResultPrimitive.Fault); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } #region Async and cancellation tests @@ -441,7 +435,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); int executeDelegateInvocations = 0; int executeDelegateInvocationsWhenOnRetryExits = 0; @@ -459,15 +453,15 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocations++; await TaskHelper.EmptyTask; return ResultPrimitive.Fault; - })).Should().Be(ResultPrimitive.Fault); + })).ShouldBe(ResultPrimitive.Fault); while (executeDelegateInvocationsWhenOnRetryExits == 0) { // Wait for the onRetry delegate to complete. } - executeDelegateInvocationsWhenOnRetryExits.Should().Be(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. - executeDelegateInvocations.Should().Be(2); + executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. + executeDelegateInvocations.ShouldBe(2); } [Fact] @@ -494,10 +488,10 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -520,16 +514,19 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -552,16 +549,19 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -584,16 +584,19 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -616,16 +619,19 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -648,16 +654,19 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -680,16 +689,19 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -712,17 +724,20 @@ public async Task Should_report_cancellation_during_faulting_last_retry_executio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -751,10 +766,10 @@ public async Task Should_report_faulting_from_faulting_last_retry_execution_when ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good)) - .Should().Be(ResultPrimitive.Fault); + .ShouldBe(ResultPrimitive.Fault); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -780,16 +795,19 @@ public async Task Should_report_cancellation_after_faulting_action_execution_and cancellationTokenSource.Cancel(); }); - var ex = await policy.Awaiting(x => x.RaiseResultSequenceAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync( + () => policy.RaiseResultSequenceAndOrCancellationAsync( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs b/test/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs index c12c154865..a8f2fce043 100644 --- a/test/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs +++ b/test/Polly.Specs/Retry/RetryTResultMixedResultExceptionSpecs.cs @@ -9,7 +9,7 @@ public void Should_handle_exception_when_TResult_policy_handling_exceptions_only .Handle().Retry(1); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(new DivideByZeroException(), ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -18,8 +18,7 @@ public void Should_throw_unhandled_exception_when_TResult_policy_handling_except Policy policy = Policy .Handle().Retry(1); - policy.Invoking(p => p.RaiseResultAndOrExceptionSequence(new ArgumentException(), ResultPrimitive.Good)) - .Should().Throw(); + Should.Throw(() => policy.RaiseResultAndOrExceptionSequence(new ArgumentException(), ResultPrimitive.Good)); } [Fact] @@ -31,7 +30,7 @@ public void Should_handle_both_exception_and_specified_result_if_raised_same_num .Retry(2); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -43,7 +42,7 @@ public void Should_handle_both_exception_and_specified_result_if_raised_same_num .Retry(2); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -57,7 +56,7 @@ public void Should_handle_both_exceptions_and_specified_results_if_raised_same_n .Retry(4); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -71,7 +70,7 @@ public void Should_handle_both_exceptions_and_specified_results_if_raised_same_n .Retry(4); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -85,7 +84,7 @@ public void Should_return_handled_result_when_handled_result_returned_next_after .Retry(3); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -98,8 +97,7 @@ public void Should_throw_when_exception_thrown_next_after_retries_exhaust_handli .Or() .Retry(3); - policy.Invoking(p => p.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.FaultAgain, new ArgumentException(), ResultPrimitive.Good)) - .Should().Throw(); + Should.Throw(() => policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.FaultAgain, new ArgumentException(), ResultPrimitive.Good)); } [Fact] @@ -113,7 +111,7 @@ public void Should_return_handled_result_when_handled_result_returned_next_after .Retry(3); ResultPrimitive result = policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), new ArgumentException(), ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -126,8 +124,7 @@ public void Should_throw_when_exception_thrown_next_after_retries_exhaust_handli .OrResult(ResultPrimitive.FaultAgain) .Retry(3); - policy.Invoking(p => p.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.FaultAgain, new ArgumentException(), ResultPrimitive.Good)) - .Should().Throw(); + Should.Throw(() => policy.RaiseResultAndOrExceptionSequence(ResultPrimitive.Fault, new DivideByZeroException(), ResultPrimitive.FaultAgain, new ArgumentException(), ResultPrimitive.Good)); } [Fact] @@ -139,7 +136,7 @@ public void Should_return_unhandled_result_if_not_one_of_results_or_exceptions_s .Retry(2); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -150,8 +147,7 @@ public void Should_throw_if_not_one_of_results_or_exceptions_handled() .OrResult(ResultPrimitive.Fault) .Retry(2); - policy.Invoking(p => p.RaiseResultAndOrExceptionSequence(new ArgumentException(), ResultPrimitive.Good)) - .Should().Throw(); + Should.Throw(() => policy.RaiseResultAndOrExceptionSequence(new ArgumentException(), ResultPrimitive.Good)); } [Fact] @@ -163,7 +159,7 @@ public void Should_handle_both_exceptions_and_specified_results_with_predicates( .Retry(2); ResultClass result = policy.RaiseResultAndOrExceptionSequence(new ResultClass(ResultPrimitive.Fault), new ArgumentException("message", "key"), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.Good); + result.ResultCode.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -174,8 +170,7 @@ public void Should_throw_if_exception_predicate_not_matched() .OrResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(2); - policy.Invoking(p => p.RaiseResultAndOrExceptionSequence(new ResultClass(ResultPrimitive.Fault), new ArgumentException("message", "value"), new ResultClass(ResultPrimitive.Good))) - .Should().Throw(); + Should.Throw(() => policy.RaiseResultAndOrExceptionSequence(new ResultClass(ResultPrimitive.Fault), new ArgumentException("message", "value"), new ResultClass(ResultPrimitive.Good))); } [Fact] @@ -187,6 +182,6 @@ public void Should_return_unhandled_result_if_result_predicate_not_matched() .Retry(2); ResultClass result = policy.RaiseResultAndOrExceptionSequence(new ArgumentException("message", "key"), new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); + result.ResultCode.ShouldBe(ResultPrimitive.FaultAgain); } } diff --git a/test/Polly.Specs/Retry/RetryTResultSpecs.cs b/test/Polly.Specs/Retry/RetryTResultSpecs.cs index 1b9a1a99b5..8b3e5be557 100644 --- a/test/Polly.Specs/Retry/RetryTResultSpecs.cs +++ b/test/Polly.Specs/Retry/RetryTResultSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -42,8 +42,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() .HandleResult(ResultPrimitive.Fault) .Retry(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -55,8 +55,8 @@ public void Should_throw_when_onretry_action_without_context_is_null() .HandleResult(ResultPrimitive.Fault) .Retry(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -68,8 +68,8 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() .HandleResult(ResultPrimitive.Fault) .Retry(-1, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -81,8 +81,8 @@ public void Should_throw_when_onretry_action_with_context_is_null() .HandleResult(ResultPrimitive.Fault) .Retry(1, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -93,7 +93,7 @@ public void Should_not_return_handled_result_when_handled_result_raised_same_num .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -105,7 +105,7 @@ public void Should_not_return_handled_result_when_one_of_the_handled_results_rai .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -116,7 +116,7 @@ public void Should_not_return_handled_result_when_handled_result_raised_less_num .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -128,7 +128,7 @@ public void Should_not_return_handled_result_when_all_of_the_handled_results_rai .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Good); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -139,7 +139,7 @@ public void Should_return_handled_result_when_handled_result_raised_more_times_t .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. + result.ShouldBe(ResultPrimitive.Fault); // It should give up retrying after 3 retries and return the last failure, so should return Fault, not Good. } [Fact] @@ -151,7 +151,7 @@ public void Should_return_handled_result_when_one_of_the_handled_results_is_rais .Retry(3); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -162,7 +162,7 @@ public void Should_return_result_when_result_is_not_the_specified_handled_result .Retry(); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultAgain); + result.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -174,7 +174,7 @@ public void Should_return_result_when_result_is_not_one_of_the_specified_handled .Retry(); ResultPrimitive result = policy.RaiseResultSequence(ResultPrimitive.FaultYetAgain, ResultPrimitive.Good); - result.Should().Be(ResultPrimitive.FaultYetAgain); + result.ShouldBe(ResultPrimitive.FaultYetAgain); } [Fact] @@ -185,7 +185,7 @@ public void Should_return_result_when_specified_result_predicate_is_not_satisfie .Retry(); ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.FaultAgain); + result.ResultCode.ShouldBe(ResultPrimitive.FaultAgain); } [Fact] @@ -197,7 +197,7 @@ public void Should_return_result_when_none_of_the_specified_result_predicates_ar .Retry(); ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultYetAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.FaultYetAgain); + result.ResultCode.ShouldBe(ResultPrimitive.FaultYetAgain); } [Fact] @@ -208,7 +208,7 @@ public void Should_not_return_handled_result_when_specified_result_predicate_is_ .Retry(); ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.Fault), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.Good); + result.ResultCode.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -220,7 +220,7 @@ public void Should_not_return_handled_result_when_one_of_the_specified_result_pr .Retry(); ResultClass result = policy.RaiseResultSequence(new ResultClass(ResultPrimitive.FaultAgain), new ResultClass(ResultPrimitive.Good)); - result.ResultCode.Should().Be(ResultPrimitive.Good); + result.ResultCode.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -235,8 +235,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -249,14 +248,12 @@ public void Should_call_onretry_on_each_retry_with_the_current_handled_result() .HandleResult(r => r.ResultCode == ResultPrimitive.Fault) .Retry(3, (outcome, _) => retryFaults.Add(outcome.Result.SomeString)); - IList resultsToRaise = expectedFaults.Select(s => new ResultClass(ResultPrimitive.Fault, s)).ToList(); + var resultsToRaise = expectedFaults.Select(s => new ResultClass(ResultPrimitive.Fault, s)).ToList(); resultsToRaise.Add(new ResultClass(ResultPrimitive.Fault)); policy.RaiseResultSequence(resultsToRaise); - retryFaults - .Should() - .ContainInOrder(expectedFaults); + retryFaults.ShouldBe(expectedFaults); } [Fact] @@ -270,8 +267,7 @@ public void Should_not_call_onretry_when_no_retries_are_performed() policy.RaiseResultSequence(ResultPrimitive.Good); - retryCounts.Should() - .BeEmpty(); + retryCounts.ShouldBeEmpty(); } [Fact] @@ -286,11 +282,11 @@ public void Should_call_onretry_with_the_passed_context() policy.RaiseResultSequence( CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -306,19 +302,17 @@ public void Should_call_onretry_with_the_passed_context_when_execute_and_capture CreateDictionary("key1", "value1", "key2", "value2"), ResultPrimitive.Fault, ResultPrimitive.Good); - result.Should().BeEquivalentTo(new - { - Outcome = OutcomeType.Successful, - FinalException = (Exception?)null, - ExceptionType = (ExceptionType?)null, - FaultType = (FaultType?)null, - FinalHandledResult = default(ResultPrimitive), - Result = ResultPrimitive.Good - }); + result.ShouldNotBeNull(); + result.Outcome.ShouldBe(OutcomeType.Successful); + result.FinalException.ShouldBeNull(); + result.ExceptionType.ShouldBeNull(); + result.FaultType.ShouldBeNull(); + result.FinalHandledResult.ShouldBe(default); + result.Result.ShouldBe(ResultPrimitive.Good); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -332,8 +326,7 @@ public void Context_should_be_empty_if_execute_not_called_with_any_context_data( policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - capturedContext.Should() - .BeEmpty(); + capturedContext.ShouldBeEmpty(); } [Fact] @@ -349,13 +342,13 @@ public void Should_create_new_context_for_each_call_to_execute() CreateDictionary("key", "original_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseResultSequence( CreateDictionary("key", "new_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -371,13 +364,13 @@ public void Should_create_new_context_for_each_call_to_execute_and_capture() CreateDictionary("key", "original_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseResultSequenceOnExecuteAndCapture( CreateDictionary("key", "new_value"), ResultPrimitive.Fault, ResultPrimitive.Good); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -387,9 +380,9 @@ public void Should_create_new_state_for_each_call_to_policy() .HandleResult(ResultPrimitive.Fault) .Retry(1); - policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).Should().Be(ResultPrimitive.Good); + policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).ShouldBe(ResultPrimitive.Good); - policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).Should().Be(ResultPrimitive.Good); + policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).ShouldBe(ResultPrimitive.Good); } @@ -404,9 +397,9 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() .HandleResult(ResultPrimitive.Fault) .Retry(0, onRetry); - policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).Should().Be(ResultPrimitive.Fault); + policy.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good).ShouldBe(ResultPrimitive.Fault); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -422,9 +415,9 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() policy.RaiseResultSequence( CreateDictionary("key", "value"), - ResultPrimitive.Fault, ResultPrimitive.Good).Should().Be(ResultPrimitive.Fault); + ResultPrimitive.Fault, ResultPrimitive.Good).ShouldBe(ResultPrimitive.Fault); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } #region Sync cancellation tests @@ -449,10 +442,10 @@ public void Should_execute_action_when_non_faulting_and_cancellationToken_not_ca CancellationToken cancellationToken = cancellationTokenSource.Token; policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -479,10 +472,10 @@ public void Should_execute_all_tries_when_faulting_and_cancellationToken_not_can ResultPrimitive.Fault, ResultPrimitive.Fault, ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Good); + .ShouldBe(ResultPrimitive.Good); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -505,16 +498,20 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -537,16 +534,20 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -569,16 +570,20 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -601,16 +606,20 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -633,16 +642,20 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -665,16 +678,20 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -697,17 +714,21 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -730,16 +751,19 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good) - .Should().Be(ResultPrimitive.Fault); + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good) + .ShouldBe(ResultPrimitive.Fault); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -765,16 +789,20 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance cancellationTokenSource.Cancel(); }); - policy.Invoking(x => x.RaiseResultSequenceAndOrCancellation(scenario, cancellationTokenSource, onExecute, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Fault, - ResultPrimitive.Good)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw( + () => + policy.RaiseResultSequenceAndOrCancellation( + scenario, + cancellationTokenSource, + onExecute, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Fault, + ResultPrimitive.Good)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs index 863df54a03..00666252d4 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryAsyncSpecs.cs @@ -16,8 +16,8 @@ public void Should_throw_when_sleep_durations_is_null_without_context() .Handle() .WaitAndRetryAsync(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurations"); } [Fact] @@ -27,10 +27,10 @@ public void Should_throw_when_onretry_action_is_null_without_context() Action policy = () => Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty(), nullOnRetry); + .WaitAndRetryAsync([], nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -38,10 +38,10 @@ public void Should_throw_when_onretry_exception_timespan_context_is_null_with_sl { Action policy = () => Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty(), default(Action)); + .WaitAndRetryAsync([], default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -53,8 +53,8 @@ public void Should_throw_when_onretry_exception_timespan_int_context_is_null_wit .Handle() .WaitAndRetryAsync(3, provider, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -62,36 +62,36 @@ public void Should_throw_when_onretry_exception_timespan_int_context_is_null_wit { Action policy = () => Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty(), default(Action)); + .WaitAndRetryAsync([], default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] public void Should_throw_when_onretry_exception_timespan_context_is_null_with_sleep_duration_provider() { - Func provider = (_, _) => 1.Seconds(); + Func provider = (_, _) => TimeSpan.FromSeconds(1); Action policy = () => Policy .Handle() .WaitAndRetryAsync(3, provider, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] public void Should_throw_when_onretry_exception_timespan_int_context_is_null_with_sleep_duration_provider() { - Func provider = (_, _) => 1.Seconds(); + Func provider = (_, _) => TimeSpan.FromSeconds(1); Action policy = () => Policy .Handle() .WaitAndRetryAsync(3, provider, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -99,15 +99,14 @@ public async Task Should_not_throw_when_specified_exception_thrown_same_number_o { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -116,15 +115,14 @@ public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_s var policy = Policy .Handle() .Or() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -132,15 +130,14 @@ public async Task Should_not_throw_when_specified_exception_thrown_less_number_o { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().NotThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(2)); } [Fact] @@ -149,15 +146,14 @@ public async Task Should_not_throw_when_one_of_the_specified_exceptions_thrown_l var policy = Policy .Handle() .Or() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().NotThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(2)); } [Fact] @@ -165,15 +161,14 @@ public async Task Should_throw_when_specified_exception_thrown_more_times_than_t { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().ThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.ThrowAsync(() => policy.RaiseExceptionAsync(3 + 1)); } [Fact] @@ -182,15 +177,14 @@ public async Task Should_throw_when_one_of_the_specified_exceptions_are_thrown_m var policy = Policy .Handle() .Or() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().ThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + await Should.ThrowAsync(() => policy.RaiseExceptionAsync(3 + 1)); } [Fact] @@ -198,10 +192,9 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except { var policy = Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -210,10 +203,9 @@ public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified var policy = Policy .Handle() .Or() - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -221,10 +213,9 @@ public async Task Should_throw_when_specified_exception_predicate_is_not_satisfi { var policy = Policy .Handle(_ => false) - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -233,10 +224,9 @@ public async Task Should_throw_when_none_of_the_specified_exception_predicates_a var policy = Policy .Handle(_ => false) .Or(_ => false) - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -244,13 +234,12 @@ public async Task Should_not_throw_when_specified_exception_predicate_is_satisfi { var policy = Policy .Handle(_ => true) - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1) + ]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -259,13 +248,12 @@ public async Task Should_not_throw_when_one_of_the_specified_exception_predicate var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1) + ]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -275,12 +263,12 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.SleepAsync = (span, _) => { @@ -290,8 +278,7 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif await policy.RaiseExceptionAsync(3); - totalTimeSlept.Should() - .Be(1 + 2 + 3); + totalTimeSlept.ShouldBe(1 + 2 + 3); } [Fact] @@ -301,12 +288,12 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.SleepAsync = (span, _) => { @@ -314,11 +301,9 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif return TaskHelper.EmptyTask; }; - await policy.Awaiting(x => x.RaiseExceptionAsync(3 + 1)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync(3 + 1)); - totalTimeSlept.Should() - .Be(1 + 2 + 3); + totalTimeSlept.ShouldBe(1 + 2 + 3); } [Fact] @@ -328,12 +313,12 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.SleepAsync = (span, _) => { @@ -343,8 +328,7 @@ public async Task Should_sleep_for_the_specified_duration_each_retry_when_specif await policy.RaiseExceptionAsync(2); - totalTimeSlept.Should() - .Be(1 + 2); + totalTimeSlept.ShouldBe(1 + 2); } [Fact] @@ -354,7 +338,7 @@ public async Task Should_not_sleep_if_no_retries() var policy = Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); SystemClock.SleepAsync = (span, _) => { @@ -362,38 +346,35 @@ public async Task Should_not_sleep_if_no_retries() return TaskHelper.EmptyTask; }; - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - totalTimeSlept.Should() - .Be(0); + totalTimeSlept.ShouldBe(0); } [Fact] public async Task Should_call_onretry_on_each_retry_with_the_current_timespan() { var expectedRetryWaits = new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }; + { + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + }; var actualRetryWaits = new List(); var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, timeSpan) => actualRetryWaits.Add(timeSpan)); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, timeSpan) => actualRetryWaits.Add(timeSpan)); await policy.RaiseExceptionAsync(3); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBe(expectedRetryWaits); } [Fact] @@ -404,19 +385,18 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_exception() var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (exception, _) => retryExceptions.Add(exception)); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (exception, _) => retryExceptions.Add(exception)); await policy.RaiseExceptionAsync(3, (e, i) => e.HelpLink = "Exception #" + i); retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -427,17 +407,16 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_retry_count var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, _, retryCount, _) => retryCounts.Add(retryCount)); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, _, retryCount, _) => retryCounts.Add(retryCount)); await policy.RaiseExceptionAsync(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -447,12 +426,11 @@ public async Task Should_not_call_onretry_when_no_retries_are_performed() var policy = Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty(), (exception, _) => retryExceptions.Add(exception)); + .WaitAndRetryAsync([], (exception, _) => retryExceptions.Add(exception)); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryExceptions.Should().BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] @@ -460,16 +438,13 @@ public async Task Should_create_new_state_for_each_call_to_policy() { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }); - - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1) + ]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -479,19 +454,19 @@ public async Task Should_call_onretry_with_the_passed_context() var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, _, context) => contextData = context); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, _, context) => contextData = context); await policy.RaiseExceptionAsync( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -501,16 +476,15 @@ public async Task Context_should_be_empty_if_execute_not_called_with_any_data() var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, _, context) => capturedContext = context); - await policy.Awaiting(x => x.RaiseExceptionAsync()).Should().NotThrowAsync(); - - capturedContext.Should() - .BeEmpty(); + .WaitAndRetryAsync( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, _, context) => capturedContext = context); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); + + capturedContext.ShouldBeEmpty(); } [Fact] @@ -520,21 +494,18 @@ public async Task Should_create_new_context_for_each_call_to_execute() var policy = Policy .Handle() - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }, + .WaitAndRetryAsync([TimeSpan.FromSeconds(1)], (_, _, context) => contextValue = context["key"].ToString()); await policy.RaiseExceptionAsync( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); await policy.RaiseExceptionAsync( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -543,11 +514,11 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(-1, _ => TimeSpan.Zero, onRetry); + .Handle() + .WaitAndRetryAsync(-1, _ => TimeSpan.Zero, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -556,11 +527,11 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() Action onRetry = (_, _) => { }; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(1, null, onRetry); + .Handle() + .WaitAndRetryAsync(1, null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -569,24 +540,24 @@ public void Should_throw_when_onretry_action_is_null_without_context_when_using_ Action nullOnRetry = null!; Action policy = () => Policy - .Handle() - .WaitAndRetryAsync(1, _ => TimeSpan.Zero, nullOnRetry); + .Handle() + .WaitAndRetryAsync(1, _ => TimeSpan.Zero, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] public async Task Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(4), + TimeSpan.FromSeconds(8), + TimeSpan.FromSeconds(16), + TimeSpan.FromSeconds(32) + }; var actualRetryWaits = new List(); @@ -598,8 +569,7 @@ public async Task Should_calculate_retry_timespans_from_current_retry_attempt_an await policy.RaiseExceptionAsync(5); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBe(expectedRetryWaits); } [Fact] @@ -621,7 +591,7 @@ public async Task Should_be_able_to_pass_handled_exception_to_sleepdurationprovi await policy.RaiseExceptionAsync(exceptionInstance); - capturedExceptionInstance.Should().Be(exceptionInstance); + capturedExceptionInstance.ShouldBe(exceptionInstance); } [Fact] @@ -629,8 +599,8 @@ public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handl { Dictionary expectedRetryWaits = new Dictionary { - {new DivideByZeroException(), 2.Seconds()}, - {new ArgumentNullException(), 4.Seconds()}, + [new DivideByZeroException()] = TimeSpan.FromSeconds(2), + [new ArgumentNullException()] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -652,16 +622,16 @@ await policy.ExecuteAsync(() => enumerator.MoveNext() : TaskHelper.EmptyTask); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBe(expectedRetryWaits.Values); } [Fact] public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepDurationProvider_via_context() { - var expectedRetryDuration = 1.Seconds(); + var expectedRetryDuration = TimeSpan.FromSeconds(1); TimeSpan? actualRetryDuration = null; - TimeSpan defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = TimeSpan.FromSeconds(30); var policy = Policy .Handle() @@ -684,7 +654,7 @@ await policy.ExecuteAsync(async (context, _) => CreateDictionary("RetryAfter", defaultRetryAfter), // Can also set an initial value for RetryAfter, in the Context passed into the call. CancellationToken.None); - actualRetryDuration.Should().Be(expectedRetryDuration); + actualRetryDuration.ShouldBe(expectedRetryDuration); } [Fact] @@ -692,16 +662,15 @@ public async Task Should_not_call_onretry_when_retry_count_is_zero() { bool retryInvoked = false; - Action onRetry = (_, _) => { retryInvoked = true; }; + Action onRetry = (_, _) => retryInvoked = true; var policy = Policy .Handle() .WaitAndRetryAsync(0, _ => TimeSpan.FromSeconds(1), onRetry); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -712,8 +681,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // However, if it compiles to async void (assigning tp Action<...>), then the delegate, when run, will return at the first await, and execution continues without waiting for the Action to complete, as described by Stephen Toub: https://devblogs.microsoft.com/pfxteam/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/ // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); int executeDelegateInvocations = 0; int executeDelegateInvocationsWhenOnRetryExits = 0; @@ -728,20 +696,20 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; throw new DivideByZeroException(); - })).Should().ThrowAsync(); + })); while (executeDelegateInvocationsWhenOnRetryExits == 0) { // Wait for the onRetry delegate to complete. } - executeDelegateInvocationsWhenOnRetryExits.Should().Be(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. - executeDelegateInvocations.Should().Be(2); + executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. + executeDelegateInvocations.ShouldBe(2); } [Fact] @@ -749,7 +717,7 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -764,11 +732,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -776,7 +743,7 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -791,11 +758,10 @@ public async Task Should_execute_all_tries_when_faulting_and_cancellationToken_n { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -803,7 +769,7 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -819,12 +785,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -832,7 +797,7 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -848,12 +813,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -861,7 +825,7 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -877,12 +841,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -890,7 +853,7 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -906,12 +869,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -919,7 +881,7 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -935,12 +897,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -948,7 +909,7 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -964,12 +925,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -977,7 +937,7 @@ public async Task Should_report_cancellation_during_faulting_last_retry_executio { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -993,12 +953,11 @@ public async Task Should_report_cancellation_during_faulting_last_retry_executio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -1006,7 +965,7 @@ public async Task Should_report_faulting_from_faulting_last_retry_execution_when { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1022,11 +981,10 @@ public async Task Should_report_faulting_from_faulting_last_retry_execution_when { CancellationToken cancellationToken = cancellationTokenSource.Token; - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -1034,18 +992,17 @@ public async Task Should_honour_cancellation_immediately_during_wait_phase_of_wa { SystemClock.SleepAsync = Task.Delay; - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); TimeSpan retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { retryDelay }); + .WaitAndRetryAsync([retryDelay]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - Stopwatch watch = new Stopwatch(); - watch.Start(); + Stopwatch watch = Stopwatch.StartNew(); Scenario scenario = new Scenario { @@ -1060,17 +1017,16 @@ public async Task Should_honour_cancellation_immediately_during_wait_phase_of_wa cancellationTokenSource.CancelAfter(shimTimeSpan); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } watch.Stop(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - watch.Elapsed.Should().BeLessThan(retryDelay); - watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: TimeSpan.FromMilliseconds(shimTimeSpan.TotalMilliseconds / 2)); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. + watch.Elapsed.ShouldBeLessThan(retryDelay); + watch.Elapsed.ShouldBe(shimTimeSpan, TimeSpan.FromMilliseconds(shimTimeSpan.TotalMilliseconds / 2)); } [Fact] @@ -1092,18 +1048,17 @@ public async Task Should_report_cancellation_after_faulting_action_execution_and var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }, + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)], (_, _) => { cancellationTokenSource.Cancel(); }); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1111,7 +1066,7 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1128,14 +1083,14 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await policy.Awaiting(action) - .Should().NotThrowAsync(); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + await Should.NotThrowAsync(action); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1143,7 +1098,7 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy .Handle() - .WaitAndRetryAsync(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3)]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1161,14 +1116,14 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await policy.Awaiting(action).Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + var ex = await Should.ThrowAsync(action); + ex.CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs index e63fbf6287..fbb95e1998 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryForeverAsyncSpecs.cs @@ -16,8 +16,8 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() .Handle() .WaitAndRetryForeverAsync(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -29,8 +29,8 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() .Handle() .WaitAndRetryForeverAsync(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -40,8 +40,8 @@ public void Should_throw_when_sleep_duration_provider_int_timespan_is_null() .Handle() .WaitAndRetryForeverAsync(default(Func)); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -53,8 +53,8 @@ public void Should_throw_when_sleep_duration_provider_int_timespan_is_null_with_ .Handle() .WaitAndRetryForeverAsync(default, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -64,8 +64,8 @@ public void Should_throw_when_sleep_duration_provider_int_context_timespan_is_nu .Handle() .WaitAndRetryForeverAsync(default(Func)); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -77,8 +77,8 @@ public void Should_throw_when_onretry_exception_int_timespan_is_null_with_sleep_ .Handle() .WaitAndRetryForeverAsync(provider, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -88,21 +88,21 @@ public void Should_throw_when_sleep_duration_provider_int_context_timespan_is_nu .Handle() .WaitAndRetryForeverAsync(default, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] public void Should_throw_when_onretry_exception_int_timespan_context_is_null_with_sleep_duration_provider() { - Func provider = (_, _) => 1.Seconds(); + Func provider = (_, _) => TimeSpan.FromSeconds(1); Action policy = () => Policy .Handle() .WaitAndRetryForeverAsync(provider, default(Action)); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -115,8 +115,8 @@ public void Should_throw_when_onretry_action_is_null_without_context() .Handle() .WaitAndRetryForeverAsync(provider, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -129,8 +129,8 @@ public void Should_throw_when_onretry_action_is_null_with_context() .Handle() .WaitAndRetryForeverAsync(provider, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -140,8 +140,7 @@ public async Task Should_not_throw_regardless_of_how_many_times_the_specified_ex .Handle() .WaitAndRetryForeverAsync(_ => TimeSpan.Zero); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -152,8 +151,7 @@ public async Task Should_not_throw_regardless_of_how_many_times_one_of_the_speci .Or() .WaitAndRetryForeverAsync(_ => TimeSpan.Zero); - await policy.Awaiting(x => x.RaiseExceptionAsync(3)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync(3)); } [Fact] @@ -165,8 +163,7 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except .Handle() .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -179,8 +176,7 @@ public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified .Or() .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -192,8 +188,7 @@ public async Task Should_throw_when_specified_exception_predicate_is_not_satisfi .Handle(_ => false) .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -206,41 +201,38 @@ public async Task Should_throw_when_none_of_the_specified_exception_predicates_a .Or(_ => false) .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] public async Task Should_not_throw_when_specified_exception_predicate_is_satisfied() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var policy = Policy .Handle(_ => true) .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] public async Task Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var policy = Policy .Handle(_ => true) .Or(_ => true) .WaitAndRetryForeverAsync(provider); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] public async Task Should_not_sleep_if_no_retries() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var totalTimeSlept = 0; @@ -250,11 +242,9 @@ public async Task Should_not_sleep_if_no_retries() SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - totalTimeSlept.Should() - .Be(0); + totalTimeSlept.ShouldBe(0); } [Fact] @@ -272,8 +262,7 @@ public async Task Should_call_onretry_on_each_retry_with_the_current_exception() retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -289,30 +278,28 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseExceptionAsync(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] public async Task Should_not_call_onretry_when_no_retries_are_performed() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var retryExceptions = new List(); var policy = Policy .Handle() .WaitAndRetryForeverAsync(provider, (exception, _) => retryExceptions.Add(exception)); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); - retryExceptions.Should().BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] public void Should_create_new_context_for_each_call_to_policy() { - Func provider = (_, _) => 1.Seconds(); + Func provider = (_, _) => TimeSpan.FromSeconds(1); string? contextValue = null; @@ -325,25 +312,25 @@ public void Should_create_new_context_for_each_call_to_policy() policy.RaiseExceptionAsync( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseExceptionAsync( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] public async Task Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(4), + TimeSpan.FromSeconds(8), + TimeSpan.FromSeconds(16), + TimeSpan.FromSeconds(32) + }; var actualRetryWaits = new List(); @@ -355,8 +342,7 @@ public async Task Should_calculate_retry_timespans_from_current_retry_attempt_an await policy.RaiseExceptionAsync(5); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBe(expectedRetryWaits); } [Fact] @@ -364,8 +350,8 @@ public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handl { Dictionary expectedRetryWaits = new Dictionary { - {new DivideByZeroException(), 2.Seconds()}, - {new ArgumentNullException(), 4.Seconds()}, + [new DivideByZeroException()] = TimeSpan.FromSeconds(2), + [new ArgumentNullException()] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -393,16 +379,16 @@ await policy.ExecuteAsync(() => }); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBe(expectedRetryWaits.Values); } [Fact] public async Task Should_be_able_to_pass_retry_duration_from_execution_to_sleepDurationProvider_via_context() { - var expectedRetryDuration = 1.Seconds(); + var expectedRetryDuration = TimeSpan.FromSeconds(1); TimeSpan? actualRetryDuration = null; - TimeSpan defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = TimeSpan.FromSeconds(30); var policy = Policy .Handle() @@ -425,7 +411,7 @@ await policy.ExecuteAsync(async (context, _) => CreateDictionary("RetryAfter", defaultRetryAfter), // Can also set an initial value for RetryAfter, in the Context passed into the call. CancellationToken.None); - actualRetryDuration.Should().Be(expectedRetryDuration); + actualRetryDuration.ShouldBe(expectedRetryDuration); } [Fact] @@ -437,7 +423,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() // If Polly were to declare only an Action<...> delegate for onRetry - but users declared async () => { } onRetry delegates - the compiler would happily assign them to the Action<...>, but the next 'try' would/could occur before onRetry execution had completed. // This test ensures the relevant retry policy does have a Func<..., Task> form for onRetry, and that it is awaited before the next try commences. - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(0.2); int executeDelegateInvocations = 0; int executeDelegateInvocationsWhenOnRetryExits = 0; @@ -452,7 +438,7 @@ public async Task Should_wait_asynchronously_for_async_onretry_delegate() executeDelegateInvocationsWhenOnRetryExits = executeDelegateInvocations; }); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.NotThrowAsync(() => policy.ExecuteAsync(async () => { executeDelegateInvocations++; await TaskHelper.EmptyTask; @@ -460,15 +446,15 @@ await policy.Awaiting(p => p.ExecuteAsync(async () => { throw new DivideByZeroException(); } - })).Should().NotThrowAsync(); + })); while (executeDelegateInvocationsWhenOnRetryExits == 0) { // Wait for the onRetry delegate to complete. } - executeDelegateInvocationsWhenOnRetryExits.Should().Be(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. - executeDelegateInvocations.Should().Be(2); + executeDelegateInvocationsWhenOnRetryExits.ShouldBe(1); // If the async onRetry delegate is genuinely awaited, only one execution of the .Execute delegate should have occurred by the time onRetry completes. If the async onRetry delegate were instead assigned to an Action<...>, then onRetry will return, and the second action execution will commence, before await Task.Delay() completes, leaving executeDelegateInvocationsWhenOnRetryExits == 2. + executeDelegateInvocations.ShouldBe(2); } [Fact] @@ -491,11 +477,10 @@ public async Task Should_execute_action_when_non_faulting_and_cancellationToken_ using (var cancellationTokenSource = new CancellationTokenSource()) { - await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -521,12 +506,11 @@ public async Task Should_not_execute_action_when_cancellationToken_cancelled_bef CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -552,12 +536,11 @@ public async Task Should_report_cancellation_during_otherwise_non_faulting_actio { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -583,12 +566,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -614,12 +596,11 @@ public async Task Should_report_cancellation_during_faulting_initial_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -645,12 +626,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -676,12 +656,11 @@ public async Task Should_report_cancellation_during_faulting_retried_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -711,12 +690,11 @@ public async Task Should_report_cancellation_after_faulting_action_execution_and cancellationTokenSource.Cancel(); }); - var ex = await policy.Awaiting(x => x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)) - .Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + var ex = await Should.ThrowAsync(() => policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute)); + ex.CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -741,13 +719,14 @@ public async Task Should_execute_func_returning_value_when_cancellationToken_not using (var cancellationTokenSource = new CancellationTokenSource()) { - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - await policy.Awaiting(action).Should().NotThrowAsync(); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + await Should.NotThrowAsync(action); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -775,14 +754,14 @@ public async Task Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - Func action = async x => result = await x.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); - var ex = await policy.Awaiting(action).Should().ThrowAsync(); - ex.And.CancellationToken.Should().Be(cancellationToken); + Func action = async () => result = await policy.RaiseExceptionAndOrCancellationAsync(scenario, cancellationTokenSource, onExecute, true); + var ex = await Should.ThrowAsync(action); + ex.CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBeNull(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs index ae2a193c68..f2802a1c27 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryForeverSpecs.cs @@ -14,8 +14,8 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() .Handle() .WaitAndRetryForever(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -29,8 +29,8 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() .Handle() .WaitAndRetryForever(sleepDurationProvider, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -43,8 +43,8 @@ public void Should_throw_when_onretry_action_is_null_without_context() .Handle() .WaitAndRetryForever(provider, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -57,8 +57,8 @@ public void Should_throw_when_onretry_action_is_null_with_context() .Handle() .WaitAndRetryForever(provider, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -68,8 +68,7 @@ public void Should_not_throw_regardless_of_how_many_times_the_specified_exceptio .Handle() .WaitAndRetryForever(_ => default); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -80,8 +79,7 @@ public void Should_not_throw_regardless_of_how_many_times_one_of_the_specified_e .Or() .WaitAndRetryForever(_ => default); - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -93,8 +91,7 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty .Handle() .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -107,8 +104,7 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep .Or() .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -120,8 +116,7 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() .Handle(_ => false) .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -134,41 +129,38 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat .Or(_ => false) .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] public void Should_not_throw_when_specified_exception_predicate_is_satisfied() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var policy = Policy .Handle(_ => true) .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_satisfied() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var policy = Policy .Handle(_ => true) .Or(_ => true) .WaitAndRetryForever(provider); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] public void Should_not_sleep_if_no_retries() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var totalTimeSlept = 0; @@ -178,11 +170,9 @@ public void Should_not_sleep_if_no_retries() SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - totalTimeSlept.Should() - .Be(0); + totalTimeSlept.ShouldBe(0); } [Fact] @@ -200,8 +190,7 @@ public void Should_call_onretry_on_each_retry_with_the_current_exception() retryExceptions .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + .ShouldBe(expectedExceptions); } [Fact] @@ -217,30 +206,28 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() policy.RaiseException(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] public void Should_not_call_onretry_when_no_retries_are_performed() { - Func provider = _ => 1.Seconds(); + Func provider = _ => TimeSpan.FromSeconds(1); var retryExceptions = new List(); var policy = Policy .Handle() .WaitAndRetryForever(provider, (exception, _) => retryExceptions.Add(exception)); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryExceptions.Should().BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] public void Should_create_new_context_for_each_call_to_policy() { - Func provider = (_, _) => 1.Seconds(); + Func provider = (_, _) => TimeSpan.FromSeconds(1); string? contextValue = null; @@ -253,25 +240,25 @@ public void Should_create_new_context_for_each_call_to_policy() policy.RaiseException( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseException( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] public void Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(4), + TimeSpan.FromSeconds(8), + TimeSpan.FromSeconds(16), + TimeSpan.FromSeconds(32) + }; var actualRetryWaits = new List(); @@ -283,8 +270,7 @@ public void Should_calculate_retry_timespans_from_current_retry_attempt_and_time policy.RaiseException(5); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBe(expectedRetryWaits); } [Fact] @@ -292,8 +278,8 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau { Dictionary expectedRetryWaits = new Dictionary { - {new DivideByZeroException(), 2.Seconds()}, - {new ArgumentNullException(), 4.Seconds()}, + [new DivideByZeroException()] = TimeSpan.FromSeconds(2), + [new ArgumentNullException()] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -315,16 +301,16 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau }); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBe(expectedRetryWaits.Values); } [Fact] public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDurationProvider_via_context() { - var expectedRetryDuration = 1.Seconds(); + var expectedRetryDuration = TimeSpan.FromSeconds(1); TimeSpan? actualRetryDuration = null; - TimeSpan defaultRetryAfter = 30.Seconds(); + TimeSpan defaultRetryAfter = TimeSpan.FromSeconds(30); var policy = Policy .Handle() @@ -346,7 +332,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio }, CreateDictionary("RetryAfter", defaultRetryAfter)); // Can also set an initial value for RetryAfter, in the Context passed into the call. - actualRetryDuration.Should().Be(expectedRetryDuration); + actualRetryDuration.ShouldBe(expectedRetryDuration); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs index 6d087da58d..2c6785b2d2 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryForeverTResultAsyncSpecs.cs @@ -10,8 +10,8 @@ public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handl { Dictionary expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + [ResultPrimitive.Fault] = TimeSpan.FromSeconds(2), + [ResultPrimitive.FaultAgain] = TimeSpan.FromSeconds(4) }; var actualRetryWaits = new List(); @@ -38,7 +38,7 @@ await policy.ExecuteAsync(async () => }); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBe(expectedRetryWaits.Values); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs index 25a74e24f5..6776e9983c 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryForeverTResultSpecs.cs @@ -10,8 +10,8 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau { Dictionary expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + [ResultPrimitive.Fault] = TimeSpan.FromSeconds(2), + [ResultPrimitive.FaultAgain] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -30,7 +30,8 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau : ResultPrimitive.Undefined); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBeSubsetOf(expectedRetryWaits.Values); + actualRetryWaits.ShouldBeInOrder(); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs b/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs index f0140c529f..4a515f88e5 100644 --- a/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs @@ -10,12 +10,12 @@ public void Should_throw_when_sleep_durations_is_null_without_context() { Action onRetry = (_, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurations"); } [Fact] @@ -23,12 +23,12 @@ public void Should_throw_when_sleep_durations_is_null_with_context() { Action onRetry = (_, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurations"); } [Fact] @@ -36,12 +36,12 @@ public void Should_throw_when_sleep_durations_is_null_with_attempts_with_context { Action onRetry = (_, _, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(null, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurations"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurations"); } [Fact] @@ -49,12 +49,12 @@ public void Should_throw_when_onretry_action_is_null_without_context() { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry([], nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -62,12 +62,12 @@ public void Should_throw_when_onretry_action_is_null_with_context() { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry([], nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -75,12 +75,12 @@ public void Should_throw_when_onretry_action_is_null_with_attempts_with_context( { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(Enumerable.Empty(), nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry([], nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -88,15 +88,14 @@ public void Should_not_throw_when_specified_exception_thrown_same_number_of_time { var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -105,15 +104,14 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_same_nu var policy = Policy .Handle() .Or() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(3)) - .Should().NotThrow(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.NotThrow(() => policy.RaiseException(3)); } [Fact] @@ -121,15 +119,14 @@ public void Should_not_throw_when_specified_exception_thrown_less_number_of_time { var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(2)) - .Should().NotThrow(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.NotThrow(() => policy.RaiseException(2)); } [Fact] @@ -138,15 +135,14 @@ public void Should_not_throw_when_one_of_the_specified_exceptions_thrown_less_nu var policy = Policy .Handle() .Or() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(2)) - .Should().NotThrow(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.NotThrow(() => policy.RaiseException(2)); } [Fact] @@ -154,15 +150,14 @@ public void Should_throw_when_specified_exception_thrown_more_times_than_there_a { var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.Throw(() => policy.RaiseException(3 + 1)); } [Fact] @@ -171,15 +166,14 @@ public void Should_throw_when_one_of_the_specified_exceptions_are_thrown_more_ti var policy = Policy .Handle() .Or() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); - - policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); + + Should.Throw(() => policy.RaiseException(3 + 1)); } [Fact] @@ -187,10 +181,9 @@ public void Should_throw_when_exception_thrown_is_not_the_specified_exception_ty { var policy = Policy .Handle() - .WaitAndRetry(Enumerable.Empty()); + .WaitAndRetry([]); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -198,10 +191,9 @@ public async Task Should_throw_when_exception_thrown_is_not_the_specified_except { var policy = Policy .Handle() - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -210,10 +202,9 @@ public void Should_throw_when_exception_thrown_is_not_one_of_the_specified_excep var policy = Policy .Handle() .Or() - .WaitAndRetry(Enumerable.Empty()); + .WaitAndRetry([]); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -222,10 +213,9 @@ public async Task Should_throw_when_exception_thrown_is_not_one_of_the_specified var policy = Policy .Handle() .Or() - .WaitAndRetryAsync(Enumerable.Empty()); + .WaitAndRetryAsync([]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -233,10 +223,9 @@ public void Should_throw_when_specified_exception_predicate_is_not_satisfied() { var policy = Policy .Handle(_ => false) - .WaitAndRetry(Enumerable.Empty()); + .WaitAndRetry([]); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -245,10 +234,9 @@ public void Should_throw_when_none_of_the_specified_exception_predicates_are_sat var policy = Policy .Handle(_ => false) .Or(_ => false) - .WaitAndRetry(Enumerable.Empty()); + .WaitAndRetry([]); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); } [Fact] @@ -256,13 +244,9 @@ public void Should_not_throw_when_specified_exception_predicate_is_satisfied() { var policy = Policy .Handle(_ => true) - .WaitAndRetry(new[] - { - 1.Seconds() - }); + .WaitAndRetry([TimeSpan.FromSeconds(1)]); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -270,13 +254,9 @@ public async Task Should_not_throw_when_specified_exception_predicate_is_satisfi { var policy = Policy .Handle(_ => true) - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1)]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -285,13 +265,9 @@ public void Should_not_throw_when_one_of_the_specified_exception_predicates_are_ var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetry(new[] - { - 1.Seconds() - }); + .WaitAndRetry([TimeSpan.FromSeconds(1)]); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -300,13 +276,9 @@ public async Task Should_not_throw_when_one_of_the_specified_exception_predicate var policy = Policy .Handle(_ => true) .Or(_ => true) - .WaitAndRetryAsync(new[] - { - 1.Seconds() - }); + .WaitAndRetryAsync([TimeSpan.FromSeconds(1)]); - await policy.Awaiting(x => x.RaiseExceptionAsync()) - .Should().NotThrowAsync(); + await Should.NotThrowAsync(() => policy.RaiseExceptionAsync()); } [Fact] @@ -316,19 +288,18 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; policy.RaiseException(3); - totalTimeSlept.Should() - .Be(1 + 2 + 3); + totalTimeSlept.ShouldBe(1 + 2 + 3); } [Fact] @@ -338,20 +309,18 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; - policy.Invoking(x => x.RaiseException(3 + 1)) - .Should().Throw(); + Should.Throw(() => policy.RaiseException(3 + 1)); - totalTimeSlept.Should() - .Be(1 + 2 + 3); + totalTimeSlept.ShouldBe(1 + 2 + 3); } [Fact] @@ -361,19 +330,18 @@ public void Should_sleep_for_the_specified_duration_each_retry_when_specified_ex var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; policy.RaiseException(2); - totalTimeSlept.Should() - .Be(1 + 2); + totalTimeSlept.ShouldBe(1 + 2); } [Fact] @@ -383,42 +351,39 @@ public void Should_not_sleep_if_no_retries() var policy = Policy .Handle() - .WaitAndRetry(Enumerable.Empty()); + .WaitAndRetry([]); SystemClock.Sleep = (span, _) => totalTimeSlept += span.Seconds; - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - totalTimeSlept.Should() - .Be(0); + totalTimeSlept.ShouldBe(0); } [Fact] public void Should_call_onretry_on_each_retry_with_the_current_timespan() { var expectedRetryWaits = new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }; + { + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + }; var actualRetryWaits = new List(); var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, timeSpan) => actualRetryWaits.Add(timeSpan)); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, timeSpan) => actualRetryWaits.Add(timeSpan)); policy.RaiseException(3); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBeSubsetOf(expectedRetryWaits); } [Fact] @@ -429,19 +394,16 @@ public void Should_call_onretry_on_each_retry_with_the_current_exception() var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (exception, _) => retryExceptions.Add(exception)); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (exception, _) => retryExceptions.Add(exception)); policy.RaiseException(3, (e, i) => e.HelpLink = "Exception #" + i); - retryExceptions - .Select(x => x.HelpLink) - .Should() - .ContainInOrder(expectedExceptions); + retryExceptions.Select((p) => p.HelpLink).ShouldBe(expectedExceptions); } [Fact] @@ -452,17 +414,16 @@ public void Should_call_onretry_on_each_retry_with_the_current_retry_count() var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, _, retryCount, _) => retryCounts.Add(retryCount)); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, _, retryCount, _) => retryCounts.Add(retryCount)); policy.RaiseException(3); - retryCounts.Should() - .ContainInOrder(expectedRetryCounts); + retryCounts.ShouldBe(expectedRetryCounts); } [Fact] @@ -472,13 +433,11 @@ public void Should_not_call_onretry_when_no_retries_are_performed() var policy = Policy .Handle() - .WaitAndRetry(Enumerable.Empty(), (exception, _) => retryExceptions.Add(exception)); + .WaitAndRetry([], (exception, _) => retryExceptions.Add(exception)); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryExceptions.Should() - .BeEmpty(); + retryExceptions.ShouldBeEmpty(); } [Fact] @@ -486,16 +445,10 @@ public void Should_create_new_state_for_each_call_to_policy() { var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds() - }); + .WaitAndRetry([TimeSpan.FromSeconds(1)]); - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); - - policy.Invoking(x => x.RaiseException()) - .Should().NotThrow(); + Should.NotThrow(() => policy.RaiseException()); + Should.NotThrow(() => policy.RaiseException()); } [Fact] @@ -505,19 +458,19 @@ public void Should_call_onretry_with_the_passed_context() var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds(), - 2.Seconds(), - 3.Seconds() - }, (_, _, context) => contextData = context); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], (_, _, context) => contextData = context); policy.RaiseException( CreateDictionary("key1", "value1", "key2", "value2")); - contextData.Should() - .ContainKeys("key1", "key2").And - .ContainValues("value1", "value2"); + contextData.ShouldNotBeNull(); + contextData.ShouldContainKeyAndValue("key1", "value1"); + contextData.ShouldContainKeyAndValue("key2", "value2"); } [Fact] @@ -527,21 +480,18 @@ public void Should_create_new_context_for_each_call_to_execute() var policy = Policy .Handle() - .WaitAndRetry(new[] - { - 1.Seconds() - }, + .WaitAndRetry([TimeSpan.FromSeconds(1)], (_, _, context) => contextValue = context["key"].ToString()); policy.RaiseException( CreateDictionary("key", "original_value")); - contextValue.Should().Be("original_value"); + contextValue.ShouldBe("original_value"); policy.RaiseException( CreateDictionary("key", "new_value")); - contextValue.Should().Be("new_value"); + contextValue.ShouldBe("new_value"); } [Fact] @@ -549,12 +499,12 @@ public void Should_throw_when_retry_count_is_less_than_zero_without_context() { Action onRetry = (_, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => default, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(-1, _ => default, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -562,12 +512,12 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_context() { Action onRetry = (_, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => default, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(-1, _ => default, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -575,12 +525,12 @@ public void Should_throw_when_retry_count_is_less_than_zero_with_attempts_with_c { Action onRetry = (_, _, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(-1, _ => default, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(-1, _ => default, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("retryCount"); + Should.Throw(policy) + .ParamName.ShouldBe("retryCount"); } [Fact] @@ -588,12 +538,12 @@ public void Should_throw_when_sleep_duration_provider_is_null_without_context() { Action onRetry = (_, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, null, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, null, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -601,12 +551,12 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_context() { Action onRetry = (_, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, (Func)null!, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, (Func)null!, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -614,12 +564,12 @@ public void Should_throw_when_sleep_duration_provider_is_null_with_attempts_with { Action onRetry = (_, _, _, _) => { }; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, (Func)null!, onRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, (Func)null!, onRetry); - policy.Should().Throw().And - .ParamName.Should().Be("sleepDurationProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("sleepDurationProvider"); } [Fact] @@ -627,12 +577,12 @@ public void Should_throw_when_onretry_action_is_null_without_context_when_using_ { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => default, nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, _ => default, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -640,12 +590,12 @@ public void Should_throw_when_onretry_action_is_null_with_context_when_using_pro { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => default, nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, _ => default, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] @@ -653,25 +603,25 @@ public void Should_throw_when_onretry_action_is_null_with_attempts_with_context_ { Action nullOnRetry = null!; - Action policy = () => Policy - .Handle() - .WaitAndRetry(1, _ => default, nullOnRetry); + Action policy = () => + Policy.Handle() + .WaitAndRetry(1, _ => default, nullOnRetry); - policy.Should().Throw().And - .ParamName.Should().Be("onRetry"); + Should.Throw(policy) + .ParamName.ShouldBe("onRetry"); } [Fact] public void Should_calculate_retry_timespans_from_current_retry_attempt_and_timespan_provider() { var expectedRetryWaits = new[] - { - 2.Seconds(), - 4.Seconds(), - 8.Seconds(), - 16.Seconds(), - 32.Seconds() - }; + { + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(4), + TimeSpan.FromSeconds(8), + TimeSpan.FromSeconds(16), + TimeSpan.FromSeconds(32) + }; var actualRetryWaits = new List(); @@ -683,8 +633,7 @@ public void Should_calculate_retry_timespans_from_current_retry_attempt_and_time policy.RaiseException(5); - actualRetryWaits.Should() - .ContainInOrder(expectedRetryWaits); + actualRetryWaits.ShouldBe(expectedRetryWaits); } [Fact] @@ -702,13 +651,11 @@ public void Should_be_able_to_pass_handled_exception_to_sleepdurationprovider() capturedExceptionInstance = ex; return TimeSpan.FromMilliseconds(0); }, - onRetry: (_, _, _, _) => - { - }); + onRetry: (_, _, _, _) => { }); policy.RaiseException(exceptionInstance); - capturedExceptionInstance.Should().Be(exceptionInstance); + capturedExceptionInstance.ShouldBe(exceptionInstance); } [Fact] @@ -716,8 +663,8 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau { Dictionary expectedRetryWaits = new Dictionary { - {new DivideByZeroException(), 2.Seconds()}, - {new ArgumentNullException(), 4.Seconds()}, + [new DivideByZeroException()] = TimeSpan.FromSeconds(2), + [new ArgumentNullException()] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -739,16 +686,16 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau }); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBe(expectedRetryWaits.Values); } [Fact] public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDurationProvider_via_context() { - var expectedRetryDuration = 1.Seconds(); + var expectedRetryDuration = TimeSpan.FromSeconds(1); TimeSpan? actualRetryDuration = null; - TimeSpan defaultRetryAfter = 30.Seconds(); + var defaultRetryAfter = TimeSpan.FromSeconds(30); var policy = Policy .Handle() @@ -770,7 +717,7 @@ public void Should_be_able_to_pass_retry_duration_from_execution_to_sleepDuratio }, CreateDictionary("RetryAfter", defaultRetryAfter)); // Can also set an initial value for RetryAfter, in the Context passed into the call. - actualRetryDuration.Should().Be(expectedRetryDuration); + actualRetryDuration.ShouldBe(expectedRetryDuration); } [Fact] @@ -778,16 +725,15 @@ public void Should_not_call_onretry_when_retry_count_is_zero_without_context() { bool retryInvoked = false; - Action onRetry = (_, _) => { retryInvoked = true; }; + Action onRetry = (_, _) => retryInvoked = true; var policy = Policy .Handle() .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -795,16 +741,15 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_context() { bool retryInvoked = false; - Action onRetry = (_, _, _) => { retryInvoked = true; }; + Action onRetry = (_, _, _) => retryInvoked = true; Policy policy = Policy .Handle() .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } [Fact] @@ -812,16 +757,15 @@ public void Should_not_call_onretry_when_retry_count_is_zero_with_attempts_with_ { bool retryInvoked = false; - Action onRetry = (_, _, _, _) => { retryInvoked = true; }; + Action onRetry = (_, _, _, _) => retryInvoked = true; Policy policy = Policy .Handle() .WaitAndRetry(0, _ => TimeSpan.FromSeconds(1), onRetry); - policy.Invoking(x => x.RaiseException()) - .Should().Throw(); + Should.Throw(() => policy.RaiseException()); - retryInvoked.Should().BeFalse(); + retryInvoked.ShouldBeFalse(); } #region Sync cancellation tests @@ -831,7 +775,12 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -847,12 +796,11 @@ public void Should_not_execute_action_when_cancellationToken_cancelled_before_ex CancellationToken cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(0); + attemptsInvoked.ShouldBe(0); } [Fact] @@ -860,7 +808,12 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -876,12 +829,11 @@ public void Should_report_cancellation_during_otherwise_non_faulting_action_exec { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -889,7 +841,12 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -905,12 +862,11 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -918,7 +874,12 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -934,12 +895,11 @@ public void Should_report_cancellation_during_faulting_initial_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -947,7 +907,12 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -963,12 +928,11 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -976,7 +940,12 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -992,12 +961,11 @@ public void Should_report_cancellation_during_faulting_retried_action_execution_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(2); + attemptsInvoked.ShouldBe(2); } [Fact] @@ -1005,7 +973,12 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1021,12 +994,11 @@ public void Should_report_cancellation_during_faulting_last_retry_execution_when { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -1034,7 +1006,12 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1050,11 +1027,10 @@ public void Should_report_faulting_from_faulting_last_retry_execution_when_user_ { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw(); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)); } - attemptsInvoked.Should().Be(1 + 3); + attemptsInvoked.ShouldBe(1 + 3); } [Fact] @@ -1062,12 +1038,12 @@ public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandr { SystemClock.Sleep = (timeSpan, ct) => Task.Delay(timeSpan, ct).Wait(ct); - TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimeSpan = TimeSpan.FromSeconds(1); TimeSpan retryDelay = shimTimeSpan + shimTimeSpan + shimTimeSpan; var policy = Policy .Handle() - .WaitAndRetry(new[] { retryDelay }); + .WaitAndRetry([retryDelay]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1088,17 +1064,16 @@ public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandr cancellationTokenSource.CancelAfter(shimTimeSpan); - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } watch.Stop(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); - watch.Elapsed.Should().BeLessThan(retryDelay); - watch.Elapsed.Should().BeCloseTo(shimTimeSpan, precision: TimeSpan.FromMilliseconds(shimTimeSpan.TotalMilliseconds / 2)); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. + watch.Elapsed.ShouldBeLessThan(retryDelay); + watch.Elapsed.ShouldBe(shimTimeSpan, TimeSpan.FromMilliseconds(shimTimeSpan.TotalMilliseconds / 2)); // Consider increasing shimTimeSpan, or loosening precision, if test fails transiently in different environments. } [Fact] @@ -1120,18 +1095,19 @@ public void Should_report_cancellation_after_faulting_action_execution_and_cance var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }, - (_, _) => - { - cancellationTokenSource.Cancel(); - }); - - policy.Invoking(x => x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) - .Should().Throw() - .And.CancellationToken.Should().Be(cancellationToken); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ], + (_, _) => cancellationTokenSource.Cancel()); + + Should.Throw(() => policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute)) + .CancellationToken.ShouldBe(cancellationToken); } - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1139,7 +1115,12 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1154,13 +1135,13 @@ public void Should_execute_func_returning_value_when_cancellationToken_not_cance using (var cancellationTokenSource = new CancellationTokenSource()) { - policy.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().NotThrow(); + Should.NotThrow(() => result = policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)); } - result.Should().BeTrue(); + result.ShouldNotBeNull(); + result.Value.ShouldBeTrue(); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } [Fact] @@ -1168,7 +1149,12 @@ public void Should_honour_and_report_cancellation_during_func_execution() { var policy = Policy .Handle() - .WaitAndRetry(new[] { 1.Seconds(), 2.Seconds(), 3.Seconds() }); + .WaitAndRetry( + [ + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(2), + TimeSpan.FromSeconds(3) + ]); int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; @@ -1186,13 +1172,13 @@ public void Should_honour_and_report_cancellation_during_func_execution() { CancellationToken cancellationToken = cancellationTokenSource.Token; - policy.Invoking(x => result = x.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) - .Should().Throw().And.CancellationToken.Should().Be(cancellationToken); + Should.Throw(() => result = policy.RaiseExceptionAndOrCancellation(scenario, cancellationTokenSource, onExecute, true)) + .CancellationToken.ShouldBe(cancellationToken); } - result.Should().Be(null); + result.ShouldBe(null); - attemptsInvoked.Should().Be(1); + attemptsInvoked.ShouldBe(1); } #endregion diff --git a/test/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs index 0f457f2bee..fc2dba2cb5 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryTResultAsyncSpecs.cs @@ -10,8 +10,8 @@ public async Task Should_be_able_to_calculate_retry_timespans_based_on_the_handl { Dictionary expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + [ResultPrimitive.Fault] = TimeSpan.FromSeconds(2), + [ResultPrimitive.FaultAgain] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -38,7 +38,7 @@ await policy.ExecuteAsync(async () => }); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBeSubsetOf(expectedRetryWaits.Values); } [Fact] @@ -46,8 +46,8 @@ public void Should_throw_when_retry_count_is_less_than_zero() { var expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + [ResultPrimitive.Fault] = TimeSpan.FromSeconds(2), + [ResultPrimitive.FaultAgain] = TimeSpan.FromSeconds(4), }; var actualRetryWaits = new List(); @@ -62,7 +62,7 @@ public void Should_throw_when_retry_count_is_less_than_zero() return TaskHelper.EmptyTask; }); - configure.Should().Throw().And.ParamName.Should().Be("retryCount"); + Should.Throw(configure).ParamName.ShouldBe("retryCount"); } [Fact] @@ -70,8 +70,8 @@ public void Should_throw_when_onRetryAsync_is_null() { var expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + [ResultPrimitive.Fault] = TimeSpan.FromSeconds(2), + [ResultPrimitive.FaultAgain] = TimeSpan.FromSeconds(4), }; Action configure = () => Policy @@ -80,7 +80,7 @@ public void Should_throw_when_onRetryAsync_is_null() (_, outcome, _) => expectedRetryWaits[outcome.Result], null); - configure.Should().Throw().And.ParamName.Should().Be("onRetryAsync"); + Should.Throw(configure).ParamName.ShouldBe("onRetryAsync"); } public void Dispose() => diff --git a/test/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs b/test/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs index 1523843047..41c82738a4 100644 --- a/test/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetryTResultSpecs.cs @@ -10,8 +10,8 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau { Dictionary expectedRetryWaits = new Dictionary { - {ResultPrimitive.Fault, 2.Seconds()}, - {ResultPrimitive.FaultAgain, 4.Seconds()}, + {ResultPrimitive.Fault, TimeSpan.FromSeconds(2)}, + {ResultPrimitive.FaultAgain, TimeSpan.FromSeconds(4)}, }; var actualRetryWaits = new List(); @@ -30,7 +30,7 @@ public void Should_be_able_to_calculate_retry_timespans_based_on_the_handled_fau : ResultPrimitive.Undefined); } - actualRetryWaits.Should().ContainInOrder(expectedRetryWaits.Values); + actualRetryWaits.ShouldBeSubsetOf(expectedRetryWaits.Values); } public void Dispose() => diff --git a/test/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs b/test/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs index 3c68f7000d..4ae8f49abd 100644 --- a/test/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs +++ b/test/Polly.Specs/Timeout/TimeoutAsyncSpecs.cs @@ -29,10 +29,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -40,8 +40,8 @@ public void Should_throw_when_timeout_is_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(TimeSpan.Zero); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -49,8 +49,8 @@ public void Should_throw_when_timeout_is_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(0); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -58,8 +58,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(-TimeSpan.FromHours(1)); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -67,8 +67,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(-10); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -76,7 +76,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMilliseconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -84,7 +84,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(3); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -92,7 +92,7 @@ public void Should_not_throw_when_timeout_is_maxvalue() { Action policy = () => Policy.TimeoutAsync(TimeSpan.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -100,7 +100,7 @@ public void Should_not_throw_when_timeout_seconds_is_maxvalue() { Action policy = () => Policy.TimeoutAsync(int.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -108,7 +108,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan() { Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -116,7 +116,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate { Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -125,7 +125,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_ontimeout() Func doNothingAsync = (_, _, _) => TaskHelper.EmptyTask; Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, doNothingAsync); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -134,7 +134,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate Func doNothingAsync = (_, _, _) => TaskHelper.EmptyTask; Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic, doNothingAsync); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -143,8 +143,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan() Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -153,8 +153,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan_with_full_argument Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -163,8 +163,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds() Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -173,8 +173,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds_with_full_argument_ Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -182,8 +182,8 @@ public void Should_throw_when_timeoutProvider_is_null() { Action policy = () => Policy.TimeoutAsync((Func)null!); - policy.Should().Throw() - .And.ParamName.Should().Be("timeoutProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("timeoutProvider"); } [Fact] @@ -192,8 +192,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider() Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -202,8 +202,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider_with_full_a Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -211,7 +211,7 @@ public void Should_be_able_to_configure_with_timeout_func() { Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } #endregion @@ -225,11 +225,11 @@ public async Task Should_throw_when_timeout_is_less_than_execution_duration__pes var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - })).Should().ThrowAsync(); + })); } [Fact] @@ -244,30 +244,29 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe result = await policy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); }; - act.Should().NotThrowAsync(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrowAsync(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public async Task Should_throw_timeout_after_correct_duration__pessimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); + + var watch = Stopwatch.StartNew(); - watch.Start(); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken); - })) - .Should().ThrowAsync(); + })); + watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Elapsed.ShouldBe(timeout, tolerance); } [Fact] @@ -275,7 +274,7 @@ public async Task Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotSupportedException())).Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(() => throw new NotSupportedException())); } [Fact] @@ -296,9 +295,9 @@ public async Task Should_cancel_downstream_token_on_timeout__pessimistic() await SystemClock.SleepAsync(TimeSpan.FromMilliseconds(1000), combinedToken); }, CancellationToken); - await act.Should().ThrowAsync(); + await Should.ThrowAsync(act); - isCancelled.Should().BeTrue(); + isCancelled.ShouldBeTrue(); } #endregion @@ -313,12 +312,11 @@ public async Task Should_throw_when_timeout_is_less_than_execution_duration__opt var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); } [Fact] @@ -337,30 +335,29 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op }, userCancellationToken); }; - act.Should().NotThrowAsync(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrowAsync(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public async Task Should_throw_timeout_after_correct_duration__optimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); + + var watch = Stopwatch.StartNew(); - watch.Start(); - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); + watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Elapsed.ShouldBe(timeout, tolerance); } [Fact] @@ -368,7 +365,7 @@ public async Task Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotSupportedException())).Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(() => throw new NotSupportedException())); } #endregion @@ -382,13 +379,12 @@ public async Task Should_not_be_able_to_cancel_with_unobserved_user_cancellation var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - await policy.Awaiting(p => p.ExecuteAsync(async - _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... await SystemClock.SleepAsync(TimeSpan.FromSeconds(timeout * 2), CancellationToken); // ... but if the executed delegate does not observe it - }, userTokenSource.Token)).Should().ThrowAsync(); // ... it's still the timeout we expect. + }, userTokenSource.Token)); } [Fact] @@ -402,15 +398,14 @@ public async Task Should_not_execute_user_delegate_if_user_cancellationToken_can { cts.Cancel(); - await policy.Awaiting(p => p.ExecuteAsync(_ => + await Should.ThrowAsync(() => policy.ExecuteAsync(_ => { executed = true; return TaskHelper.EmptyTask; - }, cts.Token)) - .Should().ThrowAsync(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -424,14 +419,13 @@ public async Task Should_be_able_to_cancel_with_user_cancellation_token_before_t var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - await policy.Awaiting(p => p.ExecuteAsync( + await Should.ThrowAsync(() => policy.ExecuteAsync( ct => { userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution return TaskHelper.EmptyTask; - }, userTokenSource.Token)) // ... with user token. - .Should().ThrowAsync(); + }, userTokenSource.Token)); // ... with user token. } [Fact] @@ -445,15 +439,14 @@ public async Task Should_not_execute_user_delegate_if_user_cancellationToken_can { cts.Cancel(); - await policy.Awaiting(p => p.ExecuteAsync(_ => + await Should.ThrowAsync(() => policy.ExecuteAsync(_ => { executed = true; return TaskHelper.EmptyTask; - }, cts.Token)) - .Should().ThrowAsync(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } [Fact] @@ -463,31 +456,30 @@ public async Task Should_not_mask_user_exception_if_user_exception_overlaps_with var shimTimeSpan = TimeSpan.FromSeconds(0.2); var policy = Policy.TimeoutAsync(shimTimeSpan, TimeoutStrategy.Optimistic); - var thrown = await policy.Awaiting(p => p.ExecuteAsync(async _ => + var thrown = await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => + { + try { - try - { - await SystemClock.SleepAsync(shimTimeSpan + shimTimeSpan, CancellationToken); - } - catch - { - // Throw a different exception - this exception should not be masked. - // The issue of more interest for issue 620 is an edge-case race condition where a user exception is thrown - // quasi-simultaneously to timeout (rather than in a manual catch of a timeout as here), but this is a good way to simulate it. - // A real-world case can be if timeout occurs while code is marshalling a user-exception into or through the catch block in TimeoutEngine. - throw userException; - } + await SystemClock.SleepAsync(shimTimeSpan + shimTimeSpan, CancellationToken); + } + catch + { + // Throw a different exception - this exception should not be masked. + // The issue of more interest for issue 620 is an edge-case race condition where a user exception is thrown + // quasi-simultaneously to timeout (rather than in a manual catch of a timeout as here), but this is a good way to simulate it. + // A real-world case can be if timeout occurs while code is marshalling a user-exception into or through the catch block in TimeoutEngine. + throw userException; + } - throw new InvalidOperationException("This exception should not be thrown. Test should throw for timeout earlier."); + throw new InvalidOperationException("This exception should not be thrown. Test should throw for timeout earlier."); - }, CancellationToken)) - .Should() - .ThrowAsync(); + }, CancellationToken)); - thrown.NotBeOfType(); - thrown.NotBeOfType(); - thrown.NotBeOfType(); - thrown.Which.Should().BeSameAs(userException); + thrown.ShouldNotBeNull(); + thrown.ShouldNotBeOfType(); + thrown.ShouldNotBeOfType(); + thrown.ShouldNotBeOfType(); + thrown.ShouldBeSameAs(userException); } #endregion @@ -508,13 +500,12 @@ public async Task Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - })) - .Should().ThrowAsync(); + })); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -533,15 +524,14 @@ public async Task Should_call_ontimeout_with_passed_context__pessimistic() TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async _ => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - }, contextPassedToExecute)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); + }, contextPassedToExecute)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -561,13 +551,12 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - })) - .Should().ThrowAsync(); + })); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -590,13 +579,12 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each // Supply a programatically-controlled timeout, via the execution context. Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - await policy.Awaiting(p => p.ExecuteAsync(async _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - }, context)) - .Should().ThrowAsync(); + }, context)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -612,13 +600,12 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action__pes TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - })) - .Should().ThrowAsync(); + })); - taskPassedToOnTimeout.Should().NotBeNull(); + Assert.NotNull(taskPassedToOnTimeout); } [Fact] @@ -642,16 +629,15 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.TimeoutAsync(shimTimespan, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken); throw exceptionToThrow; - })) - .Should().ThrowAsync(); + })); await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken); - exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); - exceptionObservedFromTaskPassedToOnTimeout.Should().Be(exceptionToThrow); + exceptionObservedFromTaskPassedToOnTimeout.ShouldNotBeNull(); + exceptionObservedFromTaskPassedToOnTimeout.ShouldBe(exceptionToThrow); } @@ -669,14 +655,13 @@ public async Task Should_call_ontimeout_with_timing_out_exception__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - })) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); + })); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion @@ -698,13 +683,12 @@ public async Task Should_call_ontimeout_with_configured_timeout__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -724,15 +708,14 @@ public async Task Should_call_ontimeout_with_passed_context__optimistic() var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, contextPassedToExecute, userCancellationToken)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async (_, ct) => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + }, contextPassedToExecute, userCancellationToken)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -753,13 +736,12 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -786,14 +768,13 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + await Should.ThrowAsync(() => policy.ExecuteAsync(async (_, ct) => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, context, userCancellationToken)) - .Should().ThrowAsync(); + }, context, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -810,13 +791,12 @@ public async Task Should_call_ontimeout_but_not_with_task_wrapping_abandoned_act var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - taskPassedToOnTimeout.Should().BeNull(); + taskPassedToOnTimeout.ShouldBeNull(); } [Fact] @@ -834,14 +814,13 @@ public async Task Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion diff --git a/test/Polly.Specs/Timeout/TimeoutSpecs.cs b/test/Polly.Specs/Timeout/TimeoutSpecs.cs index c0b74e92a2..74886f699e 100644 --- a/test/Polly.Specs/Timeout/TimeoutSpecs.cs +++ b/test/Polly.Specs/Timeout/TimeoutSpecs.cs @@ -27,10 +27,10 @@ public void Should_throw_when_action_is_null() var func = () => generic.Invoke(instance, [action, new Context(), CancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -38,8 +38,8 @@ public void Should_throw_when_timeout_is_zero_by_timespan() { Action policy = () => Policy.Timeout(TimeSpan.Zero); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -47,8 +47,8 @@ public void Should_throw_when_timeout_is_zero_by_seconds() { Action policy = () => Policy.Timeout(0); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -56,8 +56,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_timespan() { Action policy = () => Policy.Timeout(-TimeSpan.FromHours(1)); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -65,8 +65,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_seconds() { Action policy = () => Policy.Timeout(-10); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -74,7 +74,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_timespan() { Action policy = () => Policy.Timeout(TimeSpan.FromMilliseconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -82,7 +82,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_seconds() { Action policy = () => Policy.Timeout(3); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -90,7 +90,7 @@ public void Should_not_throw_when_timeout_is_maxvalue() { Action policy = () => Policy.Timeout(TimeSpan.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -98,7 +98,7 @@ public void Should_not_throw_when_timeout_seconds_is_maxvalue() { Action policy = () => Policy.Timeout(int.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -106,7 +106,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan() { Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -114,7 +114,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate { Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -123,7 +123,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_ontimeout() Action doNothing = (_, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -132,7 +132,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_ontimeout_ove Action doNothing = (_, _, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -141,7 +141,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate Action doNothing = (_, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -150,7 +150,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate Action doNothing = (_, _, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -159,8 +159,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan() Action onTimeout = null!; Action policy = () => Policy.Timeout(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -169,8 +169,8 @@ public void Should_throw_when_onTimeout_overload_is_null_with_timespan() Action onTimeout = null!; Action policy = () => Policy.Timeout(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -179,8 +179,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds() Action onTimeout = null!; Action policy = () => Policy.Timeout(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -189,8 +189,8 @@ public void Should_throw_when_onTimeout_overload_is_null_with_seconds() Action onTimeout = null!; Action policy = () => Policy.Timeout(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -198,8 +198,8 @@ public void Should_throw_when_timeoutProvider_is_null() { Action policy = () => Policy.Timeout((Func)null!); - policy.Should().Throw() - .And.ParamName.Should().Be("timeoutProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("timeoutProvider"); } [Fact] @@ -208,8 +208,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider() Action onTimeout = null!; Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -218,8 +218,8 @@ public void Should_throw_when_onTimeout_overload_is_null_with_timeoutprovider() Action onTimeout = null!; Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -227,7 +227,7 @@ public void Should_be_able_to_configure_with_timeout_func() { Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } #endregion @@ -239,8 +239,7 @@ public void Should_throw_when_timeout_is_less_than_execution_duration__pessimist { var policy = Policy.Timeout(TimeSpan.FromMilliseconds(50), TimeoutStrategy.Pessimistic); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))); } [Fact] @@ -260,8 +259,8 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe }, userCancellationToken); }; - act.Should().NotThrow(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrow(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -275,11 +274,10 @@ public void Should_throw_timeout_after_correct_duration__pessimistic() TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken))); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Elapsed.ShouldBe(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -287,7 +285,7 @@ public void Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - policy.Invoking(p => p.Execute(() => throw new NotSupportedException())).Should().Throw(); + Should.Throw(() => policy.Execute(() => throw new NotSupportedException())); } [Fact] @@ -299,11 +297,11 @@ public void Should_rethrow_aggregate_exception_from_inside_delegate__pessimistic // Check to see if nested aggregate exceptions are unwrapped correctly AggregateException exception = new AggregateException(msg, new NotImplementedException()); - policy.Invoking(p => p.Execute(() => { Helper_ThrowException(exception); })) - .Should().Throw() - .WithMessage(exception.Message) - .Where(e => e.InnerException is NotImplementedException) - .And.StackTrace.Should().Contain(nameof(Helper_ThrowException)); + var actual = Should.Throw(() => policy.Execute(() => Helper_ThrowException(exception))); + actual.Message.ShouldBe(exception.Message); + actual.InnerException.ShouldBeOfType(); + actual.StackTrace.ShouldNotBeNull(); + actual.StackTrace.ShouldContain(nameof(Helper_ThrowException)); } [Fact] @@ -318,13 +316,13 @@ public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_ins Action action = () => throw aggregateException; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - action.Should().Throw() - .WithMessage(aggregateException.Message) - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var exception = Should.Throw(action); + exception.Message.ShouldBe(aggregateException.Message); + exception.InnerExceptions.ShouldBe([innerException1, innerException2]); - policy.Invoking(p => p.Execute(action)).Should().Throw() - .WithMessage(aggregateException.Message) - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + exception = Should.Throw(() => policy.Execute(action)); + exception.Message.ShouldBe(aggregateException.Message); + exception.InnerExceptions.ShouldBe([innerException1, innerException2]); } [Fact] @@ -342,11 +340,13 @@ public void Should_rethrow_aggregate_exception_with_example_cause_of_multiple_ex }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - action.Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var exception = Should.Throw(action); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); - policy.Invoking(p => p.Execute(action)).Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + exception = Should.Throw(() => policy.Execute(action)); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); } [Fact] @@ -364,11 +364,13 @@ public void Should_rethrow_aggregate_exception_with_another_example_cause_of_mul }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - action.Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var ex = Should.Throw(action); + ex.InnerExceptions.ShouldContain(innerException1); + ex.InnerExceptions.ShouldContain(innerException2); - policy.Invoking(p => p.Execute(action)).Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + ex = Should.Throw(() => policy.Execute(action)); + ex.InnerExceptions.ShouldContain(innerException1); + ex.InnerExceptions.ShouldContain(innerException2); } #endregion @@ -381,8 +383,8 @@ public void Should_throw_when_timeout_is_less_than_execution_duration__optimisti var policy = Policy.Timeout(TimeSpan.FromMilliseconds(50), TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)) // Delegate observes cancellation token, so permitting optimistic cancellation. - .Should().Throw(); + // Delegate observes cancellation token, so permitting optimistic cancellation. + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)); } [Fact] @@ -401,8 +403,8 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op }, userCancellationToken); }; - act.Should().NotThrow(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrow(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] @@ -417,11 +419,12 @@ public void Should_throw_timeout_after_correct_duration__optimistic() TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. watch.Start(); - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(10), ct), userCancellationToken)) // Delegate observes cancellation token, so permitting optimistic cancellation. - .Should().Throw(); + + // Delegate observes cancellation token, so permitting optimistic cancellation. + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(10), ct), userCancellationToken)); watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Elapsed.ShouldBe(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -429,8 +432,7 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - policy.Invoking(p => p.Execute(() => throw new NotSupportedException())).Should().Throw(); - + Should.Throw(() => policy.Execute(() => throw new NotSupportedException())); } #endregion @@ -444,14 +446,14 @@ public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - policy.Invoking(p => p.Execute( + Should.Throw(() => policy.Execute( _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... SystemClock.Sleep(TimeSpan.FromSeconds(timeout * 2), CancellationToken); // ... but if the executed delegate does not observe it }, - userTokenSource.Token)).Should().Throw(); // ... it's still the timeout we expect. + userTokenSource.Token)); // ... it's still the timeout we expect. } [Fact] @@ -465,11 +467,10 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { cts.Cancel(); - policy.Invoking(p => p.Execute(_ => { executed = true; }, cts.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => executed = true, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -483,10 +484,17 @@ public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - policy.Invoking(p => p.Execute( - ct => { userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); }, // Simulate cancel in the middle of execution - userTokenSource.Token)) // ... with user token. - .Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. + + // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. + Should.Throw(() => policy.Execute( + ct => + { + userTokenSource.Cancel(); + + // Simulate cancel in the middle of execution + ct.ThrowIfCancellationRequested(); + }, + userTokenSource.Token)); // ... with user token. } [Fact] @@ -500,11 +508,10 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { cts.Cancel(); - policy.Invoking(p => p.Execute(_ => { executed = true; }, cts.Token)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => executed = true, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } [Fact] @@ -514,7 +521,7 @@ public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeo var shimTimeSpan = TimeSpan.FromSeconds(0.2); var policy = Policy.Timeout(shimTimeSpan, TimeoutStrategy.Optimistic); - var thrown = policy.Invoking(p => p.Execute(_ => + var thrown = Should.Throw(() => policy.Execute(_ => { try { @@ -531,15 +538,12 @@ public void Should_not_mask_user_exception_if_user_exception_overlaps_with_timeo throw new InvalidOperationException("This exception should not be thrown. Test should throw for timeout earlier."); - }, CancellationToken)) - .Should() - .Throw() - .Which; + }, CancellationToken)); - thrown.Should().NotBeOfType(); - thrown.Should().NotBeOfType(); - thrown.Should().NotBeOfType(); - thrown.Should().BeSameAs(userException); + thrown.ShouldNotBeOfType(); + thrown.ShouldNotBeOfType(); + thrown.ShouldNotBeOfType(); + thrown.ShouldBeSameAs(userException); } #endregion @@ -556,10 +560,9 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -574,12 +577,11 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken), contextPassedToExecute)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken), contextPassedToExecute)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -595,10 +597,9 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.Timeout(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -616,10 +617,9 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu // Supply a programatically-controlled timeout, via the execution context. Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Invoking(p => p.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken), context)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken), context)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -631,10 +631,9 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimist TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))); - taskPassedToOnTimeout.Should().NotBeNull(); + taskPassedToOnTimeout.ShouldNotBeNull(); } [Fact] @@ -657,16 +656,15 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.Timeout(shimTimespan, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(thriceShimTimeSpan, CancellationToken); throw exceptionToThrow; - })) - .Should().Throw(); + })); SystemClock.Sleep(thriceShimTimeSpan, CancellationToken); - exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); - exceptionObservedFromTaskPassedToOnTimeout.Should().Be(exceptionToThrow); + exceptionObservedFromTaskPassedToOnTimeout.ShouldNotBeNull(); + exceptionObservedFromTaskPassedToOnTimeout.ShouldBe(exceptionToThrow); } @@ -680,11 +678,10 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken))); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion @@ -702,10 +699,9 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(1), ct), userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(1), ct), userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -721,12 +717,11 @@ public void Should_call_ontimeout_with_passed_context__optimistic() var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute((_, ct) => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), contextPassedToExecute, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute((_, ct) => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), contextPassedToExecute, userCancellationToken)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -743,10 +738,9 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.Timeout(timeoutFunc, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -769,10 +763,9 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Invoking(p => p.Execute((_, ct) => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), context, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute((_, ct) => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), context, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -785,10 +778,9 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(3), ct), userCancellationToken)); - taskPassedToOnTimeout.Should().BeNull(); + taskPassedToOnTimeout.ShouldBeNull(); } [Fact] @@ -802,11 +794,10 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(1), ct), userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(1), ct), userCancellationToken)); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion diff --git a/test/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs b/test/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs index 8ede3c5cab..c2d9ebd723 100644 --- a/test/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Timeout/TimeoutTResultAsyncSpecs.cs @@ -26,10 +26,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken, false]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -37,8 +37,8 @@ public void Should_throw_when_timeout_is_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(TimeSpan.Zero); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -46,8 +46,8 @@ public void Should_throw_when_timeout_is_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(0); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -55,8 +55,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(-TimeSpan.FromHours(1)); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -64,8 +64,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(-10); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -73,7 +73,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_timespan() { Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMilliseconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -81,7 +81,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_seconds() { Action policy = () => Policy.TimeoutAsync(3); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -89,7 +89,7 @@ public void Should_not_throw_when_timeout_is_maxvalue() { Action policy = () => Policy.TimeoutAsync(TimeSpan.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -97,7 +97,7 @@ public void Should_not_throw_when_timeout_seconds_is_maxvalue() { Action policy = () => Policy.TimeoutAsync(int.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -105,7 +105,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan() { Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -113,7 +113,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate { Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -122,7 +122,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_ontimeout() Func doNothingAsync = (_, _, _) => TaskHelper.EmptyTask; Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, doNothingAsync); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -131,7 +131,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate Func doNothingAsync = (_, _, _) => TaskHelper.EmptyTask; Action policy = () => Policy.TimeoutAsync(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic, doNothingAsync); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -140,8 +140,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan() Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -150,8 +150,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan_with_full_argument Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -160,8 +160,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds() Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -170,8 +170,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds_with_full_argument_ Func onTimeout = null!; Action policy = () => Policy.TimeoutAsync(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -179,8 +179,8 @@ public void Should_throw_when_timeoutProvider_is_null() { Action policy = () => Policy.TimeoutAsync((Func)null!); - policy.Should().Throw() - .And.ParamName.Should().Be("timeoutProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("timeoutProvider"); } [Fact] @@ -189,8 +189,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider() Func onTimeoutAsync = null!; Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(30), onTimeoutAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -199,8 +199,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider_for_full_ar Func onTimeoutAsync = null!; Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(30), onTimeoutAsync); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeoutAsync"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeoutAsync"); } [Fact] @@ -208,7 +208,7 @@ public void Should_be_able_to_configure_with_timeout_func() { Action policy = () => Policy.TimeoutAsync(() => TimeSpan.FromSeconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } #endregion @@ -222,11 +222,11 @@ public async Task Should_throw_when_timeout_is_less_than_execution_duration__pes var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })).Should().ThrowAsync(); + })); } [Fact] @@ -238,30 +238,28 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe Func act = async () => result = await policy.ExecuteAsync(() => Task.FromResult(ResultPrimitive.Good)); - act.Should().NotThrowAsync(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrowAsync(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public async Task Should_throw_timeout_after_correct_duration__pessimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. - watch.Start(); - await policy.Awaiting(p => p.ExecuteAsync(async () => + Stopwatch watch = Stopwatch.StartNew(); + + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().ThrowAsync(); - watch.Stop(); + })); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Stop(); + watch.Elapsed.ShouldBe(timeout, tolerance); } [Fact] @@ -269,7 +267,7 @@ public async Task Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotSupportedException())).Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(() => throw new NotSupportedException())); } #endregion @@ -282,11 +280,11 @@ public async Task Should_throw_when_timeout_is_less_than_execution_duration__opt var policy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(50), TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)).Should().ThrowAsync(); + }, userCancellationToken)); } [Fact] @@ -299,31 +297,28 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op Func act = async () => result = await policy.ExecuteAsync(_ => Task.FromResult(ResultPrimitive.Good), userCancellationToken); - act.Should().NotThrowAsync(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrowAsync(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public async Task Should_throw_timeout_after_correct_duration__optimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. - watch.Start(); - await policy.Awaiting(p => p.ExecuteAsync(async ct => + Stopwatch watch = Stopwatch.StartNew(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(10), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().ThrowAsync(); - watch.Stop(); + }, userCancellationToken)); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Stop(); + watch.Elapsed.ShouldBe(timeout, tolerance); } [Fact] @@ -331,7 +326,7 @@ public async Task Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - await policy.Awaiting(p => p.ExecuteAsync(() => throw new NotSupportedException())).Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(() => throw new NotSupportedException())); } #endregion @@ -345,14 +340,14 @@ public async Task Should_not_be_able_to_cancel_with_unobserved_user_cancellation var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - await policy.Awaiting(p => p.ExecuteAsync(async + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { userTokenSource.Cancel(); // User token cancels in the middle of execution ... await SystemClock.SleepAsync(TimeSpan.FromSeconds(timeout * 2), CancellationToken); // ... but if the executed delegate does not observe it return ResultPrimitive.WhateverButTooLate; - }, userTokenSource.Token)).Should().ThrowAsync(); // ... it's still the timeout we expect. + }, userTokenSource.Token)); } [Fact] @@ -366,16 +361,15 @@ public async Task Should_not_execute_user_delegate_if_user_cancellationToken_can { cts.Cancel(); - await policy.Awaiting(p => p.ExecuteAsync(async _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { executed = true; await TaskHelper.EmptyTask; return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().ThrowAsync(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -388,14 +382,13 @@ public async Task Should_be_able_to_cancel_with_user_cancellation_token_before_t int timeout = 10; var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - await policy.Awaiting(p => p.ExecuteAsync( + await Should.ThrowAsync(() => policy.ExecuteAsync( ct => { userTokenSource.Cancel(); ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution return Task.FromResult(ResultPrimitive.WhateverButTooLate); - }, userTokenSource.Token)) // ... with user token. - .Should().ThrowAsync(); + }, userTokenSource.Token)); // ... with user token. } [Fact] @@ -409,16 +402,15 @@ public async Task Should_not_execute_user_delegate_if_user_cancellationToken_can { cts.Cancel(); - await policy.Awaiting(p => p.ExecuteAsync(async _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { executed = true; await TaskHelper.EmptyTask; return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().ThrowAsync(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -439,14 +431,13 @@ public async Task Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().ThrowAsync(); + })); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -465,16 +456,15 @@ public async Task Should_call_ontimeout_with_passed_context__pessimistic() TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - }, contextPassedToExecute)) - .Should().ThrowAsync(); + }, contextPassedToExecute)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -494,14 +484,13 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + })); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -524,14 +513,13 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each // Supply a programatically-controlled timeout, via the execution context. Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - await policy.Awaiting(p => p.ExecuteAsync(async _ => + await Should.ThrowAsync(() => policy.ExecuteAsync(async _ => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - }, context)) - .Should().ThrowAsync(); + }, context)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -547,14 +535,13 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action__pes TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().ThrowAsync(); + })); - taskPassedToOnTimeout.Should().NotBeNull(); + Assert.NotNull(taskPassedToOnTimeout); } [Fact] @@ -578,16 +565,15 @@ public async Task Should_call_ontimeout_with_task_wrapping_abandoned_action_allo TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.TimeoutAsync(shimTimespan, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => { await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken); throw exceptionToThrow; - })) - .Should().ThrowAsync(); + })); await SystemClock.SleepAsync(thriceShimTimeSpan, CancellationToken); - exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); - exceptionObservedFromTaskPassedToOnTimeout.Should().Be(exceptionToThrow); + exceptionObservedFromTaskPassedToOnTimeout.ShouldNotBeNull(); + exceptionObservedFromTaskPassedToOnTimeout.ShouldBe(exceptionToThrow); } @@ -605,15 +591,14 @@ public async Task Should_call_ontimeout_with_timing_out_exception__pessimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); - await policy.Awaiting(p => p.ExecuteAsync(async () => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async () => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + })); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion @@ -635,14 +620,13 @@ public async Task Should_call_ontimeout_with_configured_timeout__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -662,16 +646,15 @@ public async Task Should_call_ontimeout_with_passed_context__optimistic() var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, contextPassedToExecute, userCancellationToken)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async (_, ct) => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, contextPassedToExecute, userCancellationToken)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout.ShouldNotBeNull(); + contextPassedToOnTimeout.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -692,14 +675,13 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each var policy = Policy.TimeoutAsync(timeoutFunc, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -726,14 +708,13 @@ public async Task Should_call_ontimeout_with_timeout_supplied_different_for_each ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - await policy.Awaiting(p => p.ExecuteAsync(async (_, ct) => + await Should.ThrowAsync(() => policy.ExecuteAsync(async (_, ct) => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, context, userCancellationToken)) - .Should().ThrowAsync(); + }, context, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -750,14 +731,13 @@ public async Task Should_call_ontimeout_but_not_with_task_wrapping_abandoned_act var policy = Policy.TimeoutAsync(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().ThrowAsync(); + }, userCancellationToken)); - taskPassedToOnTimeout.Should().BeNull(); + taskPassedToOnTimeout.ShouldBeNull(); } [Fact] @@ -775,15 +755,14 @@ public async Task Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.TimeoutAsync(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken; - await policy.Awaiting(p => p.ExecuteAsync(async ct => - { - await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().ThrowAsync(); + await Should.ThrowAsync(() => policy.ExecuteAsync(async ct => + { + await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion diff --git a/test/Polly.Specs/Timeout/TimeoutTResultSpecs.cs b/test/Polly.Specs/Timeout/TimeoutTResultSpecs.cs index 369b4cd5ac..1fead71525 100644 --- a/test/Polly.Specs/Timeout/TimeoutTResultSpecs.cs +++ b/test/Polly.Specs/Timeout/TimeoutTResultSpecs.cs @@ -26,10 +26,10 @@ public void Should_throw_when_action_is_null() var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken]); - var exceptionAssertions = func.Should().Throw(); - exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); - exceptionAssertions.And.InnerException.Should().BeOfType() - .Which.ParamName.Should().Be("action"); + var exceptionAssertions = Should.Throw(func); + exceptionAssertions.Message.ShouldBe("Exception has been thrown by the target of an invocation."); + exceptionAssertions.InnerException.ShouldBeOfType() + .ParamName.ShouldBe("action"); } [Fact] @@ -37,8 +37,8 @@ public void Should_throw_when_timeout_is_zero_by_timespan() { Action policy = () => Policy.Timeout(TimeSpan.Zero); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -46,8 +46,8 @@ public void Should_throw_when_timeout_is_zero_by_seconds() { Action policy = () => Policy.Timeout(0); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -55,8 +55,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_timespan() { Action policy = () => Policy.Timeout(-TimeSpan.FromHours(1)); - policy.Should().Throw().And - .ParamName.Should().Be("timeout"); + Should.Throw(policy) + .ParamName.ShouldBe("timeout"); } [Fact] @@ -64,8 +64,8 @@ public void Should_throw_when_timeout_is_less_than_zero_by_seconds() { Action policy = () => Policy.Timeout(-10); - policy.Should().Throw().And - .ParamName.Should().Be("seconds"); + Should.Throw(policy) + .ParamName.ShouldBe("seconds"); } [Fact] @@ -73,7 +73,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_timespan() { Action policy = () => Policy.Timeout(TimeSpan.FromMilliseconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -81,7 +81,7 @@ public void Should_not_throw_when_timeout_is_greater_than_zero_by_seconds() { Action policy = () => Policy.Timeout(3); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -89,7 +89,7 @@ public void Should_not_throw_when_timeout_is_maxvalue() { Action policy = () => Policy.Timeout(TimeSpan.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -97,7 +97,7 @@ public void Should_not_throw_when_timeout_seconds_is_maxvalue() { Action policy = () => Policy.Timeout(int.MaxValue); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -105,7 +105,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan() { Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -113,7 +113,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate { Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -122,7 +122,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_ontimeout() Action doNothing = (_, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -131,7 +131,7 @@ public void Should_not_throw_when_timeout_is_infinitetimespan_with_timeoutstrate Action doNothing = (_, _, _) => { }; Action policy = () => Policy.Timeout(System.Threading.Timeout.InfiniteTimeSpan, TimeoutStrategy.Optimistic, doNothing); - policy.Should().NotThrow(); + Should.NotThrow(policy); } [Fact] @@ -140,8 +140,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan() Action onTimeout = null!; Action policy = () => Policy.Timeout(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -150,8 +150,8 @@ public void Should_throw_when_onTimeout_is_null_with_timespan_and_onTimeout_is_f Action onTimeout = null!; Action policy = () => Policy.Timeout(TimeSpan.FromMinutes(0.5), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -160,8 +160,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds() Action onTimeout = null!; Action policy = () => Policy.Timeout(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -170,8 +170,8 @@ public void Should_throw_when_onTimeout_is_null_with_seconds_and_onTimeout_is_fu Action onTimeout = null!; Action policy = () => Policy.Timeout(30, onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -179,8 +179,8 @@ public void Should_throw_when_timeoutProvider_is_null() { Action policy = () => Policy.Timeout((Func)null!); - policy.Should().Throw() - .And.ParamName.Should().Be("timeoutProvider"); + Should.Throw(policy) + .ParamName.ShouldBe("timeoutProvider"); } [Fact] @@ -189,8 +189,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider() Action onTimeout = null!; Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -199,8 +199,8 @@ public void Should_throw_when_onTimeout_is_null_with_timeoutprovider_and_onTimeo Action onTimeout = null!; Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(30), onTimeout); - policy.Should().Throw() - .And.ParamName.Should().Be("onTimeout"); + Should.Throw(policy) + .ParamName.ShouldBe("onTimeout"); } [Fact] @@ -208,7 +208,7 @@ public void Should_be_able_to_configure_with_timeout_func() { Action policy = () => Policy.Timeout(() => TimeSpan.FromSeconds(1)); - policy.Should().NotThrow(); + Should.NotThrow(policy); } #endregion @@ -222,11 +222,11 @@ public void Should_throw_when_timeout_is_less_than_execution_duration__pessimist var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); - policy.Invoking(p => p.Execute(() => + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })).Should().Throw(); + })); } [Fact] @@ -246,30 +246,28 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe }, userCancellationToken); }; - act.Should().NotThrow(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrow(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public void Should_throw_timeout_after_correct_duration__pessimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. - watch.Start(); - policy.Invoking(p => p.Execute(() => + Stopwatch watch = Stopwatch.StartNew(); + + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); - watch.Stop(); + })); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Stop(); + watch.Elapsed.ShouldBe(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -277,7 +275,7 @@ public void Should_rethrow_exception_from_inside_delegate__pessimistic() { var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); - policy.Invoking(p => p.Execute(() => throw new NotSupportedException())).Should().Throw(); + Should.Throw(() => policy.Execute(() => throw new NotSupportedException())); } [Fact] @@ -289,11 +287,12 @@ public void Should_rethrow_aggregate_exception_from_inside_delegate__pessimistic // Check to see if nested aggregate exceptions are unwrapped correctly AggregateException exception = new AggregateException(msg, new NotImplementedException()); - policy.Invoking(p => p.Execute(() => { Helper_ThrowException(exception); return ResultPrimitive.WhateverButTooLate; })) - .Should().Throw() - .WithMessage(exception.Message) - .Where(e => e.InnerException is NotImplementedException) - .And.StackTrace.Should().Contain(nameof(Helper_ThrowException)); + var actual = Should.Throw(() => policy.Execute(() => { Helper_ThrowException(exception); return ResultPrimitive.WhateverButTooLate; })); + actual.Message.ShouldBe(exception.Message); + + actual.InnerExceptions + .Where(p => p.InnerException is NotImplementedException) + .ShouldAllBe(p => p.StackTrace != null && p.StackTrace.Contains(nameof(Helper_ThrowException))); } [Fact] @@ -305,16 +304,17 @@ public void Should_rethrow_aggregate_exception_with_multiple_exceptions_from_ins Exception innerException1 = new NotImplementedException(); Exception innerException2 = new DivideByZeroException(); AggregateException aggregateException = new AggregateException(msg, innerException1, innerException2); + Func func = () => { Helper_ThrowException(aggregateException); return ResultPrimitive.WhateverButTooLate; }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - func.Should().Throw() - .WithMessage(aggregateException.Message) - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var exception = Should.Throw(() => func()); + exception.Message.ShouldBe(aggregateException.Message); + exception.InnerExceptions.ShouldBe([innerException1, innerException2]); - policy.Invoking(p => p.Execute(func)).Should().Throw() - .WithMessage(aggregateException.Message) - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + exception = Should.Throw(() => policy.Execute(func)); + exception.Message.ShouldBe(aggregateException.Message); + exception.InnerExceptions.ShouldBe([innerException1, innerException2]); } [Fact] @@ -333,11 +333,13 @@ public void Should_rethrow_aggregate_exception_with_example_cause_of_multiple_ex }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - func.Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var exception = Should.Throw(() => func()); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); - policy.Invoking(p => p.Execute(func)).Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + exception = Should.Throw(() => policy.Execute(func)); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); } [Fact] @@ -356,11 +358,13 @@ public void Should_rethrow_aggregate_exception_with_another_example_cause_of_mul }; // Whether executing the delegate directly, or through the policy, exception behavior should be the same. - func.Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + var exception = Should.Throw(() => func()); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); - policy.Invoking(p => p.Execute(func)).Should().Throw() - .And.InnerExceptions.Should().BeEquivalentTo(new[] { innerException1, innerException2 }); + exception = Should.Throw(() => policy.Execute(func)); + exception.InnerExceptions.ShouldContain(innerException1); + exception.InnerExceptions.ShouldContain(innerException2); } #endregion @@ -373,12 +377,11 @@ public void Should_throw_when_timeout_is_less_than_execution_duration__optimisti var policy = Policy.Timeout(TimeSpan.FromMilliseconds(50), TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => + Should.Throw(() => policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + }, userCancellationToken)); } [Fact] @@ -397,31 +400,30 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op }, userCancellationToken); }; - act.Should().NotThrow(); - result.Should().Be(ResultPrimitive.Good); + Should.NotThrow(act); + result.ShouldBe(ResultPrimitive.Good); } [Fact] public void Should_throw_timeout_after_correct_duration__optimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); var userCancellationToken = CancellationToken; - TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. + TimeSpan tolerance = TimeSpan.FromSeconds(3); - watch.Start(); - policy.Invoking(p => p.Execute(ct => + var watch = Stopwatch.StartNew(); + + Should.Throw(() => policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromSeconds(10), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + }, userCancellationToken)); + watch.Stop(); - watch.Elapsed.Should().BeCloseTo(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); + watch.Elapsed.ShouldBe(timeout, TimeSpan.FromMilliseconds(tolerance.TotalMilliseconds)); } [Fact] @@ -429,7 +431,7 @@ public void Should_rethrow_exception_from_inside_delegate__optimistic() { var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Optimistic); - policy.Invoking(p => p.Execute(() => throw new NotSupportedException())).Should().Throw(); + Should.Throw(() => policy.Execute(() => throw new NotSupportedException())); } #endregion @@ -443,14 +445,12 @@ public void Should_not_be_able_to_cancel_with_unobserved_user_cancellation_token var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - policy.Invoking(p => p.Execute( - _ => - { - userTokenSource.Cancel(); // User token cancels in the middle of execution ... - SystemClock.Sleep(TimeSpan.FromSeconds(timeout * 2), - CancellationToken); // ... but if the executed delegate does not observe it - return ResultPrimitive.WhateverButTooLate; - }, userTokenSource.Token)).Should().Throw(); // ... it's still the timeout we expect. + Should.Throw(() => policy.Execute(_ => + { + userTokenSource.Cancel(); // User token cancels in the middle of execution ... + SystemClock.Sleep(TimeSpan.FromSeconds(timeout * 2), CancellationToken); // ... but if the executed delegate does not observe it + return ResultPrimitive.WhateverButTooLate; + }, userTokenSource.Token)); } [Fact] @@ -464,15 +464,14 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { cts.Cancel(); - policy.Invoking(p => p.Execute(_ => + Should.Throw(() => policy.Execute(_ => { executed = true; return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -484,15 +483,13 @@ public void Should_be_able_to_cancel_with_user_cancellation_token_before_timeout { int timeout = 10; var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic); - using CancellationTokenSource userTokenSource = new CancellationTokenSource(); - policy.Invoking(p => p.Execute( - ct => - { - userTokenSource.Cancel(); - ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution - return ResultPrimitive.WhateverButTooLate; - }, userTokenSource.Token)) // ... with user token. - .Should().Throw(); // Not a TimeoutRejectedException; i.e. policy can distinguish user cancellation from timeout cancellation. + using var userTokenSource = new CancellationTokenSource(); + Should.Throw(() => policy.Execute(ct => + { + userTokenSource.Cancel(); + ct.ThrowIfCancellationRequested(); // Simulate cancel in the middle of execution + return ResultPrimitive.WhateverButTooLate; + }, userTokenSource.Token)); // ... with user token. } [Fact] @@ -506,15 +503,14 @@ public void Should_not_execute_user_delegate_if_user_cancellationToken_cancelled { cts.Cancel(); - policy.Invoking(p => p.Execute(_ => + Should.Throw(() => policy.Execute(_ => { executed = true; return ResultPrimitive.WhateverButTooLate; - }, cts.Token)) - .Should().Throw(); + }, cts.Token)); } - executed.Should().BeFalse(); + executed.ShouldBeFalse(); } #endregion @@ -531,14 +527,13 @@ public void Should_call_ontimeout_with_configured_timeout__pessimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + })); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -548,21 +543,20 @@ public void Should_call_ontimeout_with_passed_context__pessimistic() Context contextPassedToExecute = new Context(operationKey); Context? contextPassedToOnTimeout = null; - Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; + Action onTimeout = (ctx, _, _) => contextPassedToOnTimeout = ctx; TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(_ => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - }, contextPassedToExecute)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + }, contextPassedToExecute)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout!.ShouldNotBeNull(); + contextPassedToOnTimeout!.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout!.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -574,18 +568,17 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu Func timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); TimeSpan? timeoutPassedToOnTimeout = null; - Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; + Action onTimeout = (_, span, _) => timeoutPassedToOnTimeout = span; var policy = Policy.Timeout(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + })); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } @@ -604,33 +597,31 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu // Supply a programatically-controlled timeout, via the execution context. Context context = new Context("SomeOperationKey") { ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Invoking(p => p.Execute(_ => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - }, context)) - .Should().Throw(); + Should.Throw(() => policy.Execute(_ => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + }, context)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] public void Should_call_ontimeout_with_task_wrapping_abandoned_action__pessimistic() { Task? taskPassedToOnTimeout = null; - Action onTimeout = (_, _, task) => { taskPassedToOnTimeout = task; }; + Action onTimeout = (_, _, task) => taskPassedToOnTimeout = task; TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + })); - taskPassedToOnTimeout.Should().NotBeNull(); + taskPassedToOnTimeout.ShouldNotBeNull(); } [Fact] @@ -649,21 +640,19 @@ public void Should_call_ontimeout_with_task_wrapping_abandoned_action_allowing_c task.ContinueWith(t => exceptionObservedFromTaskPassedToOnTimeout = t.Exception!.InnerException!); }; - TimeSpan shimTimespan = TimeSpan.FromSeconds(1); // Consider increasing shimTimeSpan if test fails transiently in different environments. + TimeSpan shimTimespan = TimeSpan.FromSeconds(1); TimeSpan thriceShimTimeSpan = shimTimespan + shimTimespan + shimTimespan; var policy = Policy.Timeout(shimTimespan, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => + Should.Throw(() => policy.Execute(() => { SystemClock.Sleep(thriceShimTimeSpan, CancellationToken); throw exceptionToThrow; - })) - .Should().Throw(); + })); SystemClock.Sleep(thriceShimTimeSpan, CancellationToken); - exceptionObservedFromTaskPassedToOnTimeout.Should().NotBeNull(); - exceptionObservedFromTaskPassedToOnTimeout.Should().Be(exceptionToThrow); - + exceptionObservedFromTaskPassedToOnTimeout.ShouldNotBeNull(); + exceptionObservedFromTaskPassedToOnTimeout.ShouldBe(exceptionToThrow); } [Fact] @@ -672,19 +661,18 @@ public void Should_call_ontimeout_with_timing_out_exception__pessimistic() TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); Exception? exceptionPassedToOnTimeout = null; - Action onTimeout = (_, _, _, exception) => { exceptionPassedToOnTimeout = exception; }; + Action onTimeout = (_, _, _, exception) => exceptionPassedToOnTimeout = exception; var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeout); - policy.Invoking(p => p.Execute(() => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); - return ResultPrimitive.WhateverButTooLate; - })) - .Should().Throw(); + Should.Throw(() => policy.Execute(() => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), CancellationToken); + return ResultPrimitive.WhateverButTooLate; + })); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion @@ -697,19 +685,18 @@ public void Should_call_ontimeout_with_configured_timeout__optimistic() TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan? timeoutPassedToOnTimeout = null; - Action onTimeout = (_, span, _) => { timeoutPassedToOnTimeout = span; }; + Action onTimeout = (_, span, _) => timeoutPassedToOnTimeout = span; var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => + Should.Throw(() => policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromSeconds(1), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); + timeoutPassedToOnTimeout.ShouldBe(timeoutPassedToConfiguration); } [Fact] @@ -719,22 +706,21 @@ public void Should_call_ontimeout_with_passed_context__optimistic() Context contextPassedToExecute = new Context(operationKey); Context? contextPassedToOnTimeout = null; - Action onTimeout = (ctx, _, _) => { contextPassedToOnTimeout = ctx; }; + Action onTimeout = (ctx, _, _) => contextPassedToOnTimeout = ctx; TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute((_, ct) => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, contextPassedToExecute, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute((_, ct) => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, contextPassedToExecute, userCancellationToken)); - contextPassedToOnTimeout!.Should().NotBeNull(); - contextPassedToOnTimeout!.OperationKey.Should().Be(operationKey); - contextPassedToOnTimeout!.Should().BeSameAs(contextPassedToExecute); + contextPassedToOnTimeout.ShouldNotBeNull(); + contextPassedToOnTimeout.OperationKey.ShouldBe(operationKey); + contextPassedToOnTimeout.ShouldBeSameAs(contextPassedToExecute); } [Theory] @@ -751,14 +737,13 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu var policy = Policy.Timeout(timeoutFunc, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); + timeoutPassedToOnTimeout.ShouldBe(timeoutFunc()); } [Theory] @@ -780,14 +765,13 @@ public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execu ["timeout"] = TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay) }; - policy.Invoking(p => p.Execute((_, ct) => - { - SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); - return ResultPrimitive.WhateverButTooLate; - }, context, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute((_, ct) => + { + SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); + return ResultPrimitive.WhateverButTooLate; + }, context, userCancellationToken)); - timeoutPassedToOnTimeout.Should().Be(timeoutProvider(context)); + timeoutPassedToOnTimeout.ShouldBe(timeoutProvider(context)); } [Fact] @@ -800,14 +784,13 @@ public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__o var policy = Policy.Timeout(timeout, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => + Should.Throw(() => policy.Execute(ct => { SystemClock.Sleep(TimeSpan.FromSeconds(3), ct); return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + }, userCancellationToken)); - taskPassedToOnTimeout.Should().BeNull(); + taskPassedToOnTimeout.ShouldBeNull(); } [Fact] @@ -821,15 +804,14 @@ public void Should_call_ontimeout_with_timing_out_exception__optimistic() var policy = Policy.Timeout(timeoutPassedToConfiguration, TimeoutStrategy.Optimistic, onTimeout); var userCancellationToken = CancellationToken; - policy.Invoking(p => p.Execute(ct => - { - SystemClock.Sleep(TimeSpan.FromSeconds(1), ct); - return ResultPrimitive.WhateverButTooLate; - }, userCancellationToken)) - .Should().Throw(); + Should.Throw(() => policy.Execute(ct => + { + SystemClock.Sleep(TimeSpan.FromSeconds(1), ct); + return ResultPrimitive.WhateverButTooLate; + }, userCancellationToken)); - exceptionPassedToOnTimeout.Should().NotBeNull(); - exceptionPassedToOnTimeout.Should().BeOfType(); + exceptionPassedToOnTimeout.ShouldNotBeNull(); + exceptionPassedToOnTimeout.ShouldBeOfType(); } #endregion diff --git a/test/Polly.Specs/Utilities/LockTimeoutExceptionTests.cs b/test/Polly.Specs/Utilities/LockTimeoutExceptionTests.cs index 3f140045d4..946531e5cb 100644 --- a/test/Polly.Specs/Utilities/LockTimeoutExceptionTests.cs +++ b/test/Polly.Specs/Utilities/LockTimeoutExceptionTests.cs @@ -8,11 +8,11 @@ public void Ctor_Ok() const string Dummy = "dummy"; var exception = new InvalidOperationException(); - new LockTimeoutException().Message.Should().Be("Timeout waiting for lock"); - new LockTimeoutException(Dummy).Message.Should().Be(Dummy); + new LockTimeoutException().Message.ShouldBe("Timeout waiting for lock"); + new LockTimeoutException(Dummy).Message.ShouldBe(Dummy); var rate = new LockTimeoutException(Dummy, exception); - rate.Message.Should().Be(Dummy); - rate.InnerException.Should().Be(exception); + rate.Message.ShouldBe(Dummy); + rate.InnerException.ShouldBe(exception); } } diff --git a/test/Polly.Specs/Utilities/SystemClockSpecs.cs b/test/Polly.Specs/Utilities/SystemClockSpecs.cs index d94fcf74c0..0709b0f2df 100644 --- a/test/Polly.Specs/Utilities/SystemClockSpecs.cs +++ b/test/Polly.Specs/Utilities/SystemClockSpecs.cs @@ -14,36 +14,36 @@ public SystemClockSpecs() } [Fact] - public void Sleep_ShouldNotThrow_WhenCancellationNotRequested() => - _sleep.Invoking(s => + public void Sleep_Should_NotThrow_WhenCancellationNotRequested() => + Should.NotThrow(() => { using var cts = new CancellationTokenSource(); - s(TimeSpan.FromMilliseconds(1), cts.Token); - }).Should().NotThrow(); + _sleep(TimeSpan.FromMilliseconds(1), cts.Token); + }); [Fact] - public void Sleep_ShouldThrow_WhenCancellationRequested() => - _sleep.Invoking(s => + public void Sleep_Should_Throw_WhenCancellationRequested() => + Should.Throw(() => { using var cts = new CancellationTokenSource(); cts.Cancel(); - s(TimeSpan.FromMilliseconds(1), cts.Token); - }).Should().Throw(); + _sleep(TimeSpan.FromMilliseconds(1), cts.Token); + }); [Fact] - public async Task SleepAsync_ShouldNotThrow_WhenCancellationNotRequested() => - await _sleepAsync.Invoking(async s => + public async Task SleepAsync_Should_NotThrow_WhenCancellationNotRequested() => + await Should.NotThrowAsync(async () => { using var cts = new CancellationTokenSource(); - await s(TimeSpan.FromMilliseconds(1), cts.Token); - }).Should().NotThrowAsync(); + await _sleepAsync(TimeSpan.FromMilliseconds(1), cts.Token); + }); [Fact] - public async Task SleepAsync_ShouldThrow_WhenCancellationRequested() => - await _sleepAsync.Invoking(async s => + public async Task SleepAsync_Should_Throw_WhenCancellationRequested() => + await Should.ThrowAsync(async () => { using var cts = new CancellationTokenSource(); cts.Cancel(); - await s(TimeSpan.FromMilliseconds(1), cts.Token); - }).Should().ThrowAsync(); + await _sleepAsync(TimeSpan.FromMilliseconds(1), cts.Token); + }); } diff --git a/test/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs b/test/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs index e3ced53bb3..64cf49e5ea 100644 --- a/test/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs +++ b/test/Polly.Specs/Wrap/IPolicyWrapExtensionSpecs.cs @@ -7,8 +7,8 @@ public void Should_throw_when_policy_wrap_is_null() { IPolicyWrap policyWrap = null!; - var action = () => policyWrap.GetPolicies(); - action.Should().Throw().And.ParamName.Should().Be("policyWrap"); + var action = policyWrap.GetPolicies; + Should.Throw(action).ParamName.ShouldBe("policyWrap"); } [Fact] @@ -21,10 +21,10 @@ public void Should_pass_all_nested_policies_from_PolicyWrap_in_same_order_they_w PolicyWrap policyWrap = Policy.Wrap(policy0, policy1, policy2); List policies = policyWrap.GetPolicies().ToList(); - policies.Count.Should().Be(3); - policies[0].Should().Be(policy0); - policies[1].Should().Be(policy1); - policies[2].Should().Be(policy2); + policies.Count.ShouldBe(3); + policies[0].ShouldBe(policy0); + policies[1].ShouldBe(policy1); + policies[2].ShouldBe(policy2); } [Fact] @@ -34,11 +34,7 @@ public void Should_return_sequence_from_GetPolicies() Policy policyB = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(policyA, policyB); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies().ShouldBe([policyA, policyB]); } [Fact] @@ -49,11 +45,7 @@ public void Threepolicies_by_static_sequence_should_return_correct_sequence_from Policy policyC = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(policyA, policyB, policyC); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies().ShouldBe([policyA, policyB, policyC]); } [Fact] @@ -64,11 +56,7 @@ public void Threepolicies_lefttree_should_return_correct_sequence_from_GetPolici Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB).Wrap(policyC); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies().ShouldBe([policyA, policyB, policyC]); } [Fact] @@ -79,11 +67,7 @@ public void Threepolicies_righttree_should_return_correct_sequence_from_GetPolic Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyB, policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies().ShouldBe([policyA, policyB, policyC]); } [Fact] @@ -94,11 +78,9 @@ public void GetPoliciesTPolicy_should_return_single_policy_of_type_TPolicy() Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyB }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies() + .OfType() + .ShouldBe([policyB]); } [Fact] @@ -109,7 +91,7 @@ public void GetPoliciesTPolicy_should_return_empty_enumerable_if_no_policy_of_ty Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies().Should().BeEmpty(); + wrap.GetPolicies().ShouldBeEmpty(); } [Fact] @@ -120,11 +102,9 @@ public void GetPoliciesTPolicy_should_return_multiple_policies_of_type_TPolicy() Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies().Should().BeEquivalentTo(new[] { policyA, policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies() + .OfType() + .ShouldBe([policyA, policyC]); } [Fact] @@ -138,11 +118,7 @@ public void GetPoliciesTPolicy_should_return_policies_of_type_TPolicy_matching_p PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies(p => p.CircuitState == CircuitState.Closed).Should().BeEquivalentTo(new[] { policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies(p => p.CircuitState == CircuitState.Closed).ShouldBe([policyC]); } [Fact] @@ -154,7 +130,7 @@ public void GetPoliciesTPolicy_should_return_empty_enumerable_if_none_match_pred PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies(p => p.CircuitState == CircuitState.Open).Should().BeEmpty(); + wrap.GetPolicies(p => p.CircuitState == CircuitState.Open).ShouldBeEmpty(); } [Fact] @@ -165,11 +141,7 @@ public void GetPoliciesTPolicy_with_predicate_should_return_multiple_policies_of Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicies(_ => true).Should().BeEquivalentTo(new[] { policyA, policyC }, - options => options - .WithStrictOrdering() - .Using(ctx => ctx.Subject.Should().BeSameAs(ctx.Expectation)) - .WhenTypeIs()); + wrap.GetPolicies(_ => true).ShouldBe([policyA, policyC]); } [Fact] @@ -181,7 +153,7 @@ public void GetPoliciesTPolicy_with_predicate_should_throw_if_predicate_is_null( Action configure = () => wrap.GetPolicies(null); - configure.Should().Throw().And.ParamName.Should().Be("filter"); + Should.Throw(configure).ParamName.ShouldBe("filter"); } [Fact] @@ -192,7 +164,7 @@ public void GetPolicyTPolicy_should_return_single_policy_of_type_TPolicy() Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicy().Should().BeSameAs(policyB); + wrap.GetPolicy().ShouldBeSameAs(policyB); } [Fact] @@ -203,7 +175,7 @@ public void GetPolicyTPolicy_should_return_null_if_no_TPolicy() Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicy().Should().BeNull(); + wrap.GetPolicy().ShouldBeNull(); } [Fact] @@ -214,7 +186,7 @@ public void GetPolicyTPolicy_should_throw_if_multiple_TPolicy() Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.Invoking(p => p.GetPolicy()).Should().Throw(); + Should.Throw(() => wrap.GetPolicy()); } [Fact] @@ -228,7 +200,7 @@ public void GetPolicyTPolicy_should_return_single_policy_of_type_TPolicy_matchin PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicy(p => p.CircuitState == CircuitState.Closed).Should().BeSameAs(policyC); + wrap.GetPolicy(p => p.CircuitState == CircuitState.Closed).ShouldBeSameAs(policyC); } [Fact] @@ -240,7 +212,7 @@ public void GetPolicyTPolicy_should_return_null_if_none_match_predicate() PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.GetPolicy(p => p.CircuitState == CircuitState.Open).Should().BeNull(); + wrap.GetPolicy(p => p.CircuitState == CircuitState.Open).ShouldBeNull(); } [Fact] @@ -251,7 +223,7 @@ public void GetPolicyTPolicy_with_predicate_should_throw_if_multiple_TPolicy_if_ Policy policyC = Policy.NoOp(); PolicyWrap wrap = policyA.Wrap(policyB.Wrap(policyC)); - wrap.Invoking(p => p.GetPolicy(_ => true)).Should().Throw(); + Should.Throw(() => wrap.GetPolicy(_ => true)); } [Fact] @@ -263,6 +235,6 @@ public void GetPolicyTPolicy_with_predicate_should_throw_if_predicate_is_null() Action configure = () => wrap.GetPolicy(null); - configure.Should().Throw().And.ParamName.Should().Be("filter"); + Should.Throw(configure).ParamName.ShouldBe("filter"); } } diff --git a/test/Polly.Specs/Wrap/PolicyWrapAsyncSpecs.cs b/test/Polly.Specs/Wrap/PolicyWrapAsyncSpecs.cs index 307c491bb1..29ff243046 100644 --- a/test/Polly.Specs/Wrap/PolicyWrapAsyncSpecs.cs +++ b/test/Polly.Specs/Wrap/PolicyWrapAsyncSpecs.cs @@ -12,7 +12,7 @@ public void Nongeneric_wraps_nongeneric_instance_syntax_wrapping_null_should_thr Action config = () => retry.WrapAsync(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -22,7 +22,7 @@ public void Nongeneric_wraps_generic_instance_syntax_wrapping_null_should_throw( Action config = () => retry.WrapAsync(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -33,8 +33,8 @@ public void Nongeneric_wraps_nongeneric_using_instance_wrap_syntax_should_set_ou AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -45,8 +45,8 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -56,21 +56,21 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer [Fact] public void Generic_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.HandleResult(0).RetryAsync(1); + var retry = Policy.HandleResult(0).RetryAsync(1); Action config = () => retry.WrapAsync((AsyncPolicy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] public void Generic_wraps_generic_instance_syntax_wrapping_null_should_throw() { - var retry = Policy.HandleResult(0).RetryAsync(1); + var retry = Policy.HandleResult(0).RetryAsync(1); Action config = () => retry.WrapAsync((AsyncPolicy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -81,8 +81,8 @@ public void Generic_wraps_nongeneric_using_instance_wrap_syntax_should_set_outer AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -93,8 +93,8 @@ public void Generic_wraps_generic_using_instance_wrap_syntax_should_set_outer_in AsyncPolicyWrap wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -109,18 +109,18 @@ public void Nongeneric_interface_wraps_nongeneric_instance_syntax_null_wrapping_ Action config = () => outerNull.WrapAsync(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Nongeneric_interface_wraps_generic_instance_syntax_null_wrapping_should_throw() { IAsyncPolicy outerNull = null!; - IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); + IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); - Action config = () => outerNull.WrapAsync(retry); + Action config = () => outerNull.WrapAsync(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] @@ -130,7 +130,7 @@ public void Nongeneric_interface_wraps_nongeneric_instance_syntax_wrapping_null_ Action config = () => retry.WrapAsync(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -140,7 +140,7 @@ public void Nongeneric_interface_wraps_generic_instance_syntax_wrapping_null_sho Action config = () => retry.WrapAsync(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -149,10 +149,10 @@ public void Nongeneric_interface_wraps_nongeneric_using_instance_wrap_syntax_sho IAsyncPolicy policyA = Policy.NoOpAsync(); IAsyncPolicy policyB = Policy.NoOpAsync(); - IPolicyWrap wrap = policyA.WrapAsync(policyB); + var wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -161,10 +161,10 @@ public void Nongeneric_interface_wraps_generic_using_instance_wrap_syntax_should IAsyncPolicy policyA = Policy.NoOpAsync(); IAsyncPolicy policyB = Policy.NoOpAsync(); - IPolicyWrap wrap = policyA.WrapAsync(policyB); + var wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -179,38 +179,38 @@ public void Generic_interface_wraps_nongeneric_instance_syntax_null_wrapping_sho Action config = () => outerNull.WrapAsync(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Generic_interface_wraps_generic_instance_syntax_null_wrapping_should_throw() { IAsyncPolicy outerNull = null!; - IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); + IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); - Action config = () => outerNull.WrapAsync(retry); + Action config = () => outerNull.WrapAsync(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Generic_interface_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); + IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); Action config = () => retry.WrapAsync((AsyncPolicy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] public void Generic_interface_wraps_generic_instance_syntax_wrapping_null_should_throw() { - IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); + IAsyncPolicy retry = Policy.HandleResult(0).RetryAsync(1); Action config = () => retry.WrapAsync((AsyncPolicy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -219,10 +219,10 @@ public void Generic_interface_wraps_nongeneric_using_instance_wrap_syntax_should IAsyncPolicy policyA = Policy.NoOpAsync(); IAsyncPolicy policyB = Policy.NoOpAsync(); - IPolicyWrap wrap = policyA.WrapAsync(policyB); + var wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -231,10 +231,10 @@ public void Generic_interface_wraps_generic_using_instance_wrap_syntax_should_se IAsyncPolicy policyA = Policy.NoOpAsync(); IAsyncPolicy policyB = Policy.NoOpAsync(); - IPolicyWrap wrap = policyA.WrapAsync(policyB); + var wrap = policyA.WrapAsync(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -246,7 +246,7 @@ public void Wrapping_nothing_using_static_wrap_syntax_should_throw() { Action config = () => Policy.WrapAsync(); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -255,7 +255,7 @@ public void Wrapping_only_one_policy_using_static_wrap_syntax_should_throw() AsyncPolicy singlePolicy = Policy.Handle().RetryAsync(); Action config = () => Policy.WrapAsync(singlePolicy); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -265,7 +265,7 @@ public void Wrapping_two_policies_using_static_wrap_syntax_should_not_throw() AsyncPolicy breaker = Policy.Handle().CircuitBreakerAsync(1, TimeSpan.FromSeconds(10)); Action config = () => Policy.WrapAsync(retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -277,7 +277,7 @@ public void Wrapping_more_than_two_policies_using_static_wrap_syntax_should_not_ Action config = () => Policy.WrapAsync(divideByZeroRetry, retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -288,8 +288,8 @@ public void Wrapping_policies_using_static_wrap_syntax_should_set_outer_inner() AsyncPolicyWrap wrap = Policy.WrapAsync(policyA, policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -301,16 +301,16 @@ public void Wrapping_nothing_using_static_wrap_strongly_typed_syntax_should_thro { Action config = () => Policy.WrapAsync(); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] public void Wrapping_only_one_policy_using_static_wrap_strongly_typed_syntax_should_throw() { AsyncPolicy singlePolicy = Policy.Handle().RetryAsync(); - Action config = () => Policy.WrapAsync(singlePolicy); + Action config = () => Policy.WrapAsync(singlePolicy); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -318,9 +318,9 @@ public void Wrapping_two_policies_using_static_wrap_strongly_typed_syntax_should { AsyncPolicy retry = Policy.Handle().RetryAsync(); AsyncPolicy breaker = Policy.Handle().CircuitBreakerAsync(1, TimeSpan.FromSeconds(10)); - Action config = () => Policy.WrapAsync(retry, breaker); + Action config = () => Policy.WrapAsync(retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -330,9 +330,9 @@ public void Wrapping_more_than_two_policies_using_static_wrap_strongly_typed_syn AsyncPolicy divideByZeroRetry = Policy.Handle().RetryAsync(2); AsyncPolicy breaker = Policy.Handle().CircuitBreakerAsync(1, TimeSpan.FromSeconds(10)); - Action config = () => Policy.WrapAsync(divideByZeroRetry, retry, breaker); + Action config = () => Policy.WrapAsync(divideByZeroRetry, retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -343,8 +343,8 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set AsyncPolicyWrap wrap = Policy.WrapAsync(policyA, policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -362,15 +362,13 @@ public async Task Wrapping_two_policies_by_instance_syntax_and_executing_should_ // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - await retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => retryWrappingBreaker.RaiseExceptionAsync(2)); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - await breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breakerWrappingRetry.RaiseExceptionAsync(2)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -385,14 +383,14 @@ public async Task Wrapping_two_generic_policies_by_instance_syntax_and_executing // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); (await retryWrappingBreaker.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); (await breakerWrappingRetry.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -410,15 +408,13 @@ public async Task Wrapping_two_policies_by_static_syntax_and_executing_should_wr // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - await retryWrappingBreaker.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Open); + await Should.ThrowAsync(() => retryWrappingBreaker.RaiseExceptionAsync(2)); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - await breakerWrappingRetry.Awaiting(x => x.RaiseExceptionAsync(2)) - .Should().ThrowAsync(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + await Should.ThrowAsync(() => breakerWrappingRetry.RaiseExceptionAsync(2)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -433,14 +429,14 @@ public async Task Wrapping_two_generic_policies_by_static_syntax_and_executing_s // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); (await retryWrappingBreaker.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); (await breakerWrappingRetry.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Fault)) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -461,9 +457,9 @@ public async Task Outermost_policy_handling_exception_should_report_as_PolicyWra PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); } [Fact] @@ -480,9 +476,9 @@ public async Task Outermost_policy_not_handling_exception_even_if_inner_policies PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.Unhandled); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.Unhandled); } [Fact] @@ -498,10 +494,10 @@ public async Task Outermost_generic_policy_handling_exception_should_report_as_P PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new ArgumentNullException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ExceptionHandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.ExceptionHandledByThisPolicy); } [Fact] @@ -517,10 +513,10 @@ public async Task Outermost_generic_policy_not_handling_exception_even_if_inner_ PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => { throw new DivideByZeroException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.Unhandled); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.UnhandledException); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.Unhandled); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.UnhandledException); } [Fact] @@ -536,11 +532,11 @@ public async Task Outermost_generic_policy_handling_result_should_report_as_Poli PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.Fault)); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ResultHandledByThisPolicy); - executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(ResultPrimitive.Fault); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull(); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.ResultHandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.FinalHandledResult.ShouldBe(ResultPrimitive.Fault); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBeNull(); } [Fact] @@ -556,11 +552,11 @@ public async Task Outermost_generic_policy_not_handling_result_even_if_inner_pol PolicyResult executeAndCaptureResultOnPolicyWrap = await wrap.ExecuteAndCaptureAsync(() => Task.FromResult(ResultPrimitive.FaultAgain)); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Successful); - executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(default); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull(); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Successful); + executeAndCaptureResultOnPolicyWrap.FinalHandledResult.ShouldBe(default); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBeNull(); } #endregion diff --git a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeyAsyncSpecs.cs b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeyAsyncSpecs.cs index 76e4431c8f..8cea563ff9 100644 --- a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeyAsyncSpecs.cs +++ b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeyAsyncSpecs.cs @@ -24,9 +24,10 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_ await wrap.RaiseExceptionAsync(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBeNull(); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -49,9 +50,10 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_ await wrap.RaiseExceptionAsync(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBeNull(); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -61,8 +63,8 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .FallbackAsync((_, _) => TaskHelper.EmptyTask, (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); return TaskHelper.EmptyTask; }) .WithPolicyKey("FallbackPolicy"); @@ -71,12 +73,12 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .RetryAsync(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); - IAsyncPolicy policyWrap = Policy.WrapAsync(fallback, retry) + var policyWrap = Policy.WrapAsync(fallback, retry) .WithPolicyKey("PolicyWrap"); await policyWrap.ExecuteAsync(() => throw new Exception()); @@ -89,8 +91,8 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .FallbackAsync((_, _) => TaskHelper.EmptyTask, (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); return TaskHelper.EmptyTask; }) .WithPolicyKey("FallbackPolicy"); @@ -99,12 +101,12 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .RetryAsync(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); - IAsyncPolicy policyWrap = Policy.WrapAsync(fallback, retry) + var policyWrap = Policy.WrapAsync(fallback, retry) .WithPolicyKey("PolicyWrap"); await policyWrap.ExecuteAsync(async () => await Task.Run(() => throw new Exception())); // Regression test for issue 510 @@ -135,11 +137,11 @@ public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_i await outerWrap.RaiseExceptionAsync(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } [Fact] @@ -177,11 +179,11 @@ await outerWrap.ExecuteAsync(() => return TaskHelper.EmptyTask; }); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } #endregion @@ -213,9 +215,9 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_ await wrap.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -238,9 +240,9 @@ public async Task Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_ await wrap.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -250,8 +252,8 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .FallbackAsync((_, _) => Task.FromResult(ResultPrimitive.Undefined), (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); return TaskHelper.EmptyTask; }) .WithPolicyKey("FallbackPolicy"); @@ -260,12 +262,12 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .RetryAsync(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); - IAsyncPolicy policyWrap = Policy.WrapAsync(fallback, retry) + var policyWrap = Policy.WrapAsync(fallback, retry) .WithPolicyKey("PolicyWrap"); await policyWrap.ExecuteAsync(() => throw new Exception()); @@ -278,8 +280,8 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .FallbackAsync((_, _) => Task.FromResult(ResultPrimitive.Undefined), (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); return TaskHelper.EmptyTask; }) .WithPolicyKey("FallbackPolicy"); @@ -288,12 +290,12 @@ public async Task Should_restore_PolicyKey_of_outer_policy_to_execution_context_ .Handle() .RetryAsync(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); - IAsyncPolicy policyWrap = Policy.WrapAsync(fallback, retry) + var policyWrap = Policy.WrapAsync(fallback, retry) .WithPolicyKey("PolicyWrap"); await policyWrap.ExecuteAsync(async () => await Task.Run(() => // Regression test for issue 510 @@ -328,11 +330,11 @@ public async Task Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_i await outerWrap.RaiseResultSequenceAsync(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } #endregion diff --git a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs index 72df170806..f2c06bf833 100644 --- a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs +++ b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs @@ -1,4 +1,7 @@ namespace Polly.Specs.Wrap; +using Shouldly; + +namespace Polly.Specs.Wrap; [Collection(Constants.SystemClockDependentTestCollection)] public class PolicyWrapContextAndKeySpecs @@ -24,9 +27,10 @@ public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_Policy wrap.RaiseException(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBeNull(); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -49,33 +53,34 @@ public void Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_Policy wrap.RaiseException(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBeNull(); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_move_outwards_through_PolicyWrap() { - ISyncPolicy fallback = Policy + var fallback = Policy .Handle() .Fallback(_ => { }, onFallback: (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); }) .WithPolicyKey("FallbackPolicy"); - ISyncPolicy retry = Policy + var retry = Policy .Handle() .Retry(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); - ISyncPolicy policyWrap = Policy.Wrap(fallback, retry) + var policyWrap = Policy.Wrap(fallback, retry) .WithPolicyKey("PolicyWrap"); policyWrap.Execute(() => throw new Exception()); @@ -106,11 +111,11 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_P outerWrap.RaiseException(1); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } [Fact] @@ -146,11 +151,11 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_to_innermost_Pol } }); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } #endregion @@ -180,9 +185,9 @@ public void Should_pass_PolicyKey_to_execution_context_of_outer_policy_as_Policy wrap.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -205,9 +210,9 @@ public void Should_pass_PolicyKey_to_execution_context_of_inner_policy_as_Policy wrap.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().Be(wrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldBe(wrapKey); } [Fact] @@ -217,8 +222,8 @@ public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_mov .Handle() .Fallback(ResultPrimitive.Undefined, onFallback: (_, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("FallbackPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("FallbackPolicy"); }) .WithPolicyKey("FallbackPolicy"); @@ -226,8 +231,8 @@ public void Should_restore_PolicyKey_of_outer_policy_to_execution_context_as_mov .Handle() .Retry(1, onRetry: (_, _, context) => { - context.PolicyWrapKey.Should().Be("PolicyWrap"); - context.PolicyKey.Should().Be("RetryPolicy"); + context.PolicyWrapKey.ShouldBe("PolicyWrap"); + context.PolicyKey.ShouldBe("RetryPolicy"); }) .WithPolicyKey("RetryPolicy"); @@ -262,11 +267,11 @@ public void Should_pass_outmost_PolicyWrap_Key_as_PolicyWrapKey_ignoring_inner_P outerWrap.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Good); - policyWrapKeySetOnExecutionContext.Should().NotBe(retryKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(breakerKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(fallbackKey); - policyWrapKeySetOnExecutionContext.Should().NotBe(innerWrapKey); - policyWrapKeySetOnExecutionContext.Should().Be(outerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(retryKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(breakerKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(fallbackKey); + policyWrapKeySetOnExecutionContext.ShouldNotBe(innerWrapKey); + policyWrapKeySetOnExecutionContext.ShouldBe(outerWrapKey); } #endregion diff --git a/test/Polly.Specs/Wrap/PolicyWrapSpecs.cs b/test/Polly.Specs/Wrap/PolicyWrapSpecs.cs index aac912f3ba..a1cdcfc3b6 100644 --- a/test/Polly.Specs/Wrap/PolicyWrapSpecs.cs +++ b/test/Polly.Specs/Wrap/PolicyWrapSpecs.cs @@ -12,7 +12,7 @@ public void Nongeneric_wraps_nongeneric_instance_syntax_wrapping_null_should_thr Action config = () => retry.Wrap(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -22,7 +22,7 @@ public void Nongeneric_wraps_generic_instance_syntax_wrapping_null_should_throw( Action config = () => retry.Wrap(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -33,8 +33,8 @@ public void Nongeneric_wraps_nongeneric_using_instance_wrap_syntax_should_set_ou PolicyWrap wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -45,8 +45,8 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer PolicyWrap wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -56,21 +56,21 @@ public void Nongeneric_wraps_generic_using_instance_wrap_syntax_should_set_outer [Fact] public void Generic_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - RetryPolicy retry = Policy.HandleResult(0).Retry(1); + RetryPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] public void Generic_wraps_generic_instance_syntax_wrapping_null_should_throw() { - RetryPolicy retry = Policy.HandleResult(0).Retry(1); + RetryPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -81,8 +81,8 @@ public void Generic_wraps_nongeneric_using_instance_wrap_syntax_should_set_outer PolicyWrap wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -93,8 +93,8 @@ public void Generic_wraps_generic_using_instance_wrap_syntax_should_set_outer_in PolicyWrap wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -109,18 +109,18 @@ public void Nongeneric_interface_wraps_nongeneric_instance_syntax_null_wrapping_ Action config = () => outerNull.Wrap(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Nongeneric_interface_wraps_generic_instance_syntax_null_wrapping_should_throw() { ISyncPolicy outerNull = null!; - ISyncPolicy retry = Policy.HandleResult(0).Retry(1); + ISyncPolicy retry = Policy.HandleResult(0).Retry(1); - Action config = () => outerNull.Wrap(retry); + Action config = () => outerNull.Wrap(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] @@ -130,7 +130,7 @@ public void Nongeneric_interface_wraps_nongeneric_instance_syntax_wrapping_null_ Action config = () => retry.Wrap(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -140,7 +140,7 @@ public void Nongeneric_interface_wraps_generic_instance_syntax_wrapping_null_sho Action config = () => retry.Wrap(null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -149,10 +149,10 @@ public void Nongeneric_interface_wraps_nongeneric_using_instance_wrap_syntax_sho ISyncPolicy policyA = Policy.NoOp(); ISyncPolicy policyB = Policy.NoOp(); - IPolicyWrap wrap = policyA.Wrap(policyB); + var wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -161,10 +161,10 @@ public void Nongeneric_interface_wraps_generic_using_instance_wrap_syntax_should ISyncPolicy policyA = Policy.NoOp(); ISyncPolicy policyB = Policy.NoOp(); - IPolicyWrap wrap = policyA.Wrap(policyB); + var wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -179,38 +179,38 @@ public void Generic_interface_wraps_nongeneric_instance_syntax_null_wrapping_sho Action config = () => outerNull.Wrap(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Generic_interface_wraps_generic_instance_syntax_null_wrapping_should_throw() { ISyncPolicy outerNull = null!; - ISyncPolicy retry = Policy.HandleResult(0).Retry(1); + ISyncPolicy retry = Policy.HandleResult(0).Retry(1); - Action config = () => outerNull.Wrap(retry); + Action config = () => outerNull.Wrap(retry); - config.Should().Throw().And.ParamName.Should().Be("outerPolicy"); + Should.Throw(config).ParamName.ShouldBe("outerPolicy"); } [Fact] public void Generic_interface_wraps_nongeneric_instance_syntax_wrapping_null_should_throw() { - ISyncPolicy retry = Policy.HandleResult(0).Retry(1); + ISyncPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] public void Generic_interface_wraps_generic_instance_syntax_wrapping_null_should_throw() { - ISyncPolicy retry = Policy.HandleResult(0).Retry(1); + ISyncPolicy retry = Policy.HandleResult(0).Retry(1); Action config = () => retry.Wrap((Policy)null!); - config.Should().Throw().And.ParamName.Should().Be("innerPolicy"); + Should.Throw(config).ParamName.ShouldBe("innerPolicy"); } [Fact] @@ -219,10 +219,10 @@ public void Generic_interface_wraps_nongeneric_using_instance_wrap_syntax_should ISyncPolicy policyA = Policy.NoOp(); ISyncPolicy policyB = Policy.NoOp(); - IPolicyWrap wrap = policyA.Wrap(policyB); + var wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } [Fact] @@ -231,10 +231,10 @@ public void Generic_interface_wraps_generic_using_instance_wrap_syntax_should_se ISyncPolicy policyA = Policy.NoOp(); ISyncPolicy policyB = Policy.NoOp(); - IPolicyWrap wrap = policyA.Wrap(policyB); + var wrap = policyA.Wrap(policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -246,7 +246,7 @@ public void Wrapping_nothing_using_static_wrap_syntax_should_throw() { Action config = () => Policy.Wrap(); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -257,7 +257,7 @@ public void Wrapping_only_one_policy_using_static_wrap_syntax_should_throw() Action config = () => Policy.Wrap(policies); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -267,7 +267,7 @@ public void Wrapping_two_policies_using_static_wrap_syntax_should_not_throw() Policy breaker = Policy.Handle().CircuitBreaker(1, TimeSpan.FromSeconds(10)); Action config = () => Policy.Wrap(retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -279,7 +279,7 @@ public void Wrapping_more_than_two_policies_using_static_wrap_syntax_should_not_ Action config = () => Policy.Wrap(divideByZeroRetry, retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -290,8 +290,8 @@ public void Wrapping_policies_using_static_wrap_syntax_should_set_outer_inner() PolicyWrap wrap = Policy.Wrap(policyA, policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -303,16 +303,16 @@ public void Wrapping_nothing_using_static_wrap_strongly_typed_syntax_should_thro { Action config = () => Policy.Wrap(); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] public void Wrapping_only_one_policy_using_static_wrap_strongly_typed_syntax_should_throw() { Policy singlePolicy = Policy.Handle().Retry(); - Action config = () => Policy.Wrap(singlePolicy); + Action config = () => Policy.Wrap(singlePolicy); - config.Should().Throw().And.ParamName.Should().Be("policies"); + Should.Throw(config).ParamName.ShouldBe("policies"); } [Fact] @@ -322,7 +322,7 @@ public void Wrapping_two_policies_using_static_wrap_strongly_typed_syntax_should Policy breaker = Policy.Handle().CircuitBreaker(1, TimeSpan.FromSeconds(10)); Action config = () => Policy.Wrap(retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -332,9 +332,9 @@ public void Wrapping_more_than_two_policies_using_static_wrap_strongly_typed_syn Policy divideByZeroRetry = Policy.Handle().Retry(2); Policy breaker = Policy.Handle().CircuitBreaker(1, TimeSpan.FromSeconds(10)); - Action config = () => Policy.Wrap(divideByZeroRetry, retry, breaker); + Action config = () => Policy.Wrap(divideByZeroRetry, retry, breaker); - config.Should().NotThrow(); + Should.NotThrow(config); } [Fact] @@ -345,8 +345,8 @@ public void Wrapping_policies_using_static_wrap_strongly_typed_syntax_should_set PolicyWrap wrap = Policy.Wrap(policyA, policyB); - wrap.Outer.Should().BeSameAs(policyA); - wrap.Inner.Should().BeSameAs(policyB); + wrap.Outer.ShouldBeSameAs(policyA); + wrap.Inner.ShouldBeSameAs(policyB); } #endregion @@ -364,15 +364,13 @@ public void Wrapping_two_policies_by_instance_syntax_and_executing_should_wrap_o // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - retryWrappingBreaker.Invoking(x => x.RaiseException(2)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => retryWrappingBreaker.RaiseException(2)); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - breakerWrappingRetry.Invoking(x => x.RaiseException(2)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breakerWrappingRetry.RaiseException(2)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -387,14 +385,14 @@ public void Wrapping_two_generic_policies_by_instance_syntax_and_executing_shoul // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); retryWrappingBreaker.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); breakerWrappingRetry.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -412,15 +410,13 @@ public void Wrapping_two_policies_by_static_syntax_and_executing_should_wrap_out // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); - retryWrappingBreaker.Invoking(x => x.RaiseException(2)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Open); + Should.Throw(() => retryWrappingBreaker.RaiseException(2)); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); - breakerWrappingRetry.Invoking(x => x.RaiseException(2)) - .Should().Throw(); - breaker.CircuitState.Should().Be(CircuitState.Closed); + Should.Throw(() => breakerWrappingRetry.RaiseException(2)); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } [Fact] @@ -435,14 +431,14 @@ public void Wrapping_two_generic_policies_by_static_syntax_and_executing_should_ // When the retry wraps the breaker, the retry (being outer) should cause the call to be put through the breaker twice - causing the breaker to break. breaker.Reset(); retryWrappingBreaker.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Open); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Open); // When the breaker wraps the retry, the retry (being inner) should retry twice before throwing the exception back on the breaker - the exception only hits the breaker once - so the breaker should not break. breaker.Reset(); breakerWrappingRetry.RaiseResultSequence(ResultPrimitive.Fault, ResultPrimitive.Fault) - .Should().Be(ResultPrimitive.Fault); - breaker.CircuitState.Should().Be(CircuitState.Closed); + .ShouldBe(ResultPrimitive.Fault); + breaker.CircuitState.ShouldBe(CircuitState.Closed); } #endregion @@ -462,9 +458,9 @@ public void Outermost_policy_handling_exception_should_report_as_PolicyWrap_hand PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); } [Fact] @@ -480,9 +476,9 @@ public void Outermost_policy_not_handling_exception_even_if_inner_policies_do_sh PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.Unhandled); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.Unhandled); } [Fact] @@ -498,10 +494,10 @@ public void Outermost_generic_policy_handling_exception_should_report_as_PolicyW PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new ArgumentNullException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.HandledByThisPolicy); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ExceptionHandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.HandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.ExceptionHandledByThisPolicy); } [Fact] @@ -517,10 +513,10 @@ public void Outermost_generic_policy_not_handling_exception_even_if_inner_polici PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => { throw new DivideByZeroException(); }); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeOfType(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().Be(ExceptionType.Unhandled); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.UnhandledException); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeOfType(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBe(ExceptionType.Unhandled); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.UnhandledException); } [Fact] @@ -536,11 +532,11 @@ public void Outermost_generic_policy_handling_result_should_report_as_PolicyWrap PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.Fault); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Failure); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().Be(FaultType.ResultHandledByThisPolicy); - executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(ResultPrimitive.Fault); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull(); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Failure); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBe(FaultType.ResultHandledByThisPolicy); + executeAndCaptureResultOnPolicyWrap.FinalHandledResult.ShouldBe(ResultPrimitive.Fault); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBeNull(); } [Fact] @@ -556,11 +552,11 @@ public void Outermost_generic_policy_not_handling_result_even_if_inner_policies_ PolicyResult executeAndCaptureResultOnPolicyWrap = wrap.ExecuteAndCapture(() => ResultPrimitive.FaultAgain); - executeAndCaptureResultOnPolicyWrap.Outcome.Should().Be(OutcomeType.Successful); - executeAndCaptureResultOnPolicyWrap.FinalHandledResult.Should().Be(default); - executeAndCaptureResultOnPolicyWrap.FaultType.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.FinalException.Should().BeNull(); - executeAndCaptureResultOnPolicyWrap.ExceptionType.Should().BeNull(); + executeAndCaptureResultOnPolicyWrap.Outcome.ShouldBe(OutcomeType.Successful); + executeAndCaptureResultOnPolicyWrap.FinalHandledResult.ShouldBe(default); + executeAndCaptureResultOnPolicyWrap.FaultType.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.FinalException.ShouldBeNull(); + executeAndCaptureResultOnPolicyWrap.ExceptionType.ShouldBeNull(); } #endregion diff --git a/test/Polly.Testing.Tests/Polly.Testing.Tests.csproj b/test/Polly.Testing.Tests/Polly.Testing.Tests.csproj index 9bc8ef23c2..5bd1053492 100644 --- a/test/Polly.Testing.Tests/Polly.Testing.Tests.csproj +++ b/test/Polly.Testing.Tests/Polly.Testing.Tests.csproj @@ -13,9 +13,5 @@ - - - - From 9882803711bba9fa89841767f84bc5782b21ffa2 Mon Sep 17 00:00:00 2001 From: martincostello Date: Sun, 19 Jan 2025 19:05:51 +0000 Subject: [PATCH 2/3] Fix compilation error Fix broken file header. --- test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs index f2c06bf833..19417b6141 100644 --- a/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs +++ b/test/Polly.Specs/Wrap/PolicyWrapContextAndKeySpecs.cs @@ -1,7 +1,4 @@ namespace Polly.Specs.Wrap; -using Shouldly; - -namespace Polly.Specs.Wrap; [Collection(Constants.SystemClockDependentTestCollection)] public class PolicyWrapContextAndKeySpecs From 7124fb6b626259a966193de58608cc5e03c73c67 Mon Sep 17 00:00:00 2001 From: martincostello Date: Sun, 19 Jan 2025 19:19:57 +0000 Subject: [PATCH 3/3] Use Stopwatch.StartNew Use `Stopwatch.StartNew()` instead of creating one then manually starting it. --- test/Polly.Specs/Retry/WaitAndRetrySpecs.cs | 3 +-- test/Polly.Specs/Timeout/TimeoutSpecs.cs | 8 ++------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs b/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs index 4a515f88e5..474ed0fc71 100644 --- a/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs +++ b/test/Polly.Specs/Retry/WaitAndRetrySpecs.cs @@ -1048,8 +1048,7 @@ public void Should_honour_cancellation_immediately_during_wait_phase_of_waitandr int attemptsInvoked = 0; Action onExecute = () => attemptsInvoked++; - Stopwatch watch = new Stopwatch(); - watch.Start(); + var watch = Stopwatch.StartNew(); PolicyExtensions.ExceptionAndOrCancellationScenario scenario = new PolicyExtensions.ExceptionAndOrCancellationScenario { diff --git a/test/Polly.Specs/Timeout/TimeoutSpecs.cs b/test/Polly.Specs/Timeout/TimeoutSpecs.cs index 74886f699e..1ac980b4eb 100644 --- a/test/Polly.Specs/Timeout/TimeoutSpecs.cs +++ b/test/Polly.Specs/Timeout/TimeoutSpecs.cs @@ -266,14 +266,12 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__pe [Fact] public void Should_throw_timeout_after_correct_duration__pessimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic); TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. - watch.Start(); + var watch = Stopwatch.StartNew(); Should.Throw(() => policy.Execute(() => SystemClock.Sleep(TimeSpan.FromSeconds(10), CancellationToken))); watch.Stop(); @@ -410,15 +408,13 @@ public void Should_not_throw_when_timeout_is_greater_than_execution_duration__op [Fact] public void Should_throw_timeout_after_correct_duration__optimistic() { - Stopwatch watch = new Stopwatch(); - TimeSpan timeout = TimeSpan.FromSeconds(1); var policy = Policy.Timeout(timeout); var userCancellationToken = CancellationToken; TimeSpan tolerance = TimeSpan.FromSeconds(3); // Consider increasing tolerance, if test fails transiently in different test/build environments. - watch.Start(); + var watch = Stopwatch.StartNew(); // Delegate observes cancellation token, so permitting optimistic cancellation. Should.Throw(() => policy.Execute(ct => SystemClock.Sleep(TimeSpan.FromSeconds(10), ct), userCancellationToken));