From e5e0e7aad22d61ca35a0cc34000dff2b2e9f22b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baranyai=20M=C3=A1t=C3=A9?= Date: Sat, 27 Jan 2024 10:07:38 +0100 Subject: [PATCH 1/5] Fix S6608/IDE1006/SA1414/CA1508 warnings in Polly.Specs project --- test/Polly.Specs/Caching/CacheAsyncSpecs.cs | 222 ++++++++--------- test/Polly.Specs/Caching/CacheSpecs.cs | 226 +++++++++--------- .../Caching/CacheTResultAsyncSpecs.cs | 156 ++++++------ test/Polly.Specs/Caching/CacheTResultSpecs.cs | 156 ++++++------ .../Caching/GenericCacheProviderAsyncSpecs.cs | 18 +- .../Caching/GenericCacheProviderSpecs.cs | 18 +- test/Polly.Specs/Caching/ResultTtlSpecs.cs | 6 +- .../Helpers/Bulkhead/AnnotatedOutputHelper.cs | 22 +- .../Helpers/Bulkhead/TraceableAction.cs | 18 +- .../Helpers/Caching/StubCacheKeyStrategy.cs | 6 +- .../Helpers/Caching/StubCacheProvider.cs | 12 +- .../Caching/StubErroringCacheProvider.cs | 6 +- .../PolicyContextAndKeyAsyncSpecs.cs | 12 +- test/Polly.Specs/PolicyContextAndKeySpecs.cs | 12 +- test/Polly.Specs/Polly.Specs.csproj | 4 +- .../RateLimit/RateLimitPolicySpecsBase.cs | 2 +- .../Registry/ConcurrentPolicyRegistrySpecs.cs | 12 +- 17 files changed, 454 insertions(+), 454 deletions(-) diff --git a/test/Polly.Specs/Caching/CacheAsyncSpecs.cs b/test/Polly.Specs/Caching/CacheAsyncSpecs.cs index 0436500b9bc..c8d352084ec 100644 --- a/test/Polly.Specs/Caching/CacheAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/CacheAsyncSpecs.cs @@ -38,13 +38,13 @@ public void Should_throw_when_cache_key_strategy_is_null() [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -52,9 +52,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -62,34 +62,34 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } [Fact] public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); TimeSpan ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -98,49 +98,49 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp { delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(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); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(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); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(2); } [Fact] public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -148,8 +148,8 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); @@ -158,16 +158,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri { delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); } @@ -225,18 +225,18 @@ public async Task Should_allow_custom_ICacheKeyStrategy() public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_reference_type() { ResultClass? valueToReturn = null; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -246,11 +246,11 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { ResultClass? valueToReturnFromCache = null; ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -259,7 +259,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac delegateExecuted = true; await TaskHelper.EmptyTask; return valueToReturnFromExecution; - }, new Context(operationKey))) + }, new Context(OperationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -269,18 +269,18 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type() { ResultPrimitive valueToReturn = default; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -291,11 +291,11 @@ 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); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -304,7 +304,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac delegateExecuted = true; await TaskHelper.EmptyTask; return valueToReturnFromExecution; - }, new Context(operationKey))) + }, new Context(OperationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -317,16 +317,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_outermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(cache, noop); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -334,9 +334,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -344,16 +344,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_innermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -361,9 +361,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -371,16 +371,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_mid_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache, noop); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -388,9 +388,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -445,8 +445,8 @@ public void Should_always_execute_delegate_if_execution_is_void_returning() [Fact] public async Task Should_honour_cancellation_even_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); @@ -458,15 +458,15 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( // delegate does not observe cancellation token; test is whether CacheEngine does. delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); tokenSource.Cancel(); - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) .Should().ThrowAsync(); delegateInvocations.Should().Be(1); } @@ -474,8 +474,8 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( [Fact] public async Task Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); @@ -487,13 +487,13 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p tokenSource.Cancel(); // simulate cancellation raised during delegate execution ct.ThrowIfCancellationRequested(); await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) .Should().ThrowAsync(); - (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -510,15 +510,15 @@ public async Task Should_call_onError_delegate_if_cache_get_errors() Exception? exceptionFromCacheProvider = null; - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -527,10 +527,10 @@ public async Task Should_call_onError_delegate_if_cache_get_errors() { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; + return ValueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromExecution); + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromExecution); delegateExecuted.Should().BeTrue(); // And error should be captured by onError delegate. @@ -545,24 +545,24 @@ public async Task Should_call_onError_delegate_if_cache_put_errors() Exception? exceptionFromCacheProvider = null; - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(ValueToReturn); // error should be captured by onError delegate. exceptionFromCacheProvider.Should().Be(ex); // failed to put it in the cache - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -570,13 +570,13 @@ public async Task Should_call_onError_delegate_if_cache_put_errors() [Fact] public async Task Should_execute_oncacheget_after_got_from_cache() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToDelegate = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToDelegate = null; Action noErrorHandling = (_, _, _) => { }; @@ -585,32 +585,32 @@ public async Task Should_execute_oncacheget_after_got_from_cache() IAsyncCacheProvider 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.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; (await cache.ExecuteAsync(async _ => { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; + return ValueToReturnFromExecution; }, contextToExecute)) - .Should().Be(valueToReturnFromCache); + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); contextPassedToDelegate.Should().BeSameAs(contextToExecute); - keyPassedToDelegate.Should().Be(operationKey); + keyPassedToDelegate.Should().Be(OperationKey); } [Fact] public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_value_and_put() { - const string valueToReturn = "valueToReturn"; + const string ValueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToOnCacheMiss = null; string? keyPassedToOnCachePut = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToOnCacheMiss = null; Context? contextPassedToOnCachePut = null; @@ -622,18 +622,18 @@ public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_ho IAsyncCacheProvider 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.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, contextToExecute)).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); contextPassedToOnCachePut.Should().BeSameAs(contextToExecute); - keyPassedToOnCachePut.Should().Be(operationKey); + keyPassedToOnCachePut.Should().Be(OperationKey); contextPassedToOnCacheMiss.Should().NotBeNull(); keyPassedToOnCacheMiss.Should().Be("SomeOperationKey"); } @@ -641,13 +641,13 @@ public async Task Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_ho [Fact] public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold_value_and_returned_value_not_worth_caching() { - const string valueToReturn = "valueToReturn"; + const string ValueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToOnCacheMiss = null; string? keyPassedToOnCachePut = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToOnCacheMiss = null; Context? contextPassedToOnCachePut = null; @@ -659,11 +659,11 @@ public async Task Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_no IAsyncCacheProvider 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.None, false); + (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); - (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return valueToReturn; }, contextToExecute)).Should().Be(valueToReturn); + (await cache.ExecuteAsync(async _ => { await TaskHelper.EmptyTask; return ValueToReturn; }, contextToExecute)).Should().Be(ValueToReturn); contextPassedToOnCachePut.Should().BeNull(); keyPassedToOnCachePut.Should().BeNull(); diff --git a/test/Polly.Specs/Caching/CacheSpecs.cs b/test/Polly.Specs/Caching/CacheSpecs.cs index be5b7ecc911..cae6c4e5d9b 100644 --- a/test/Polly.Specs/Caching/CacheSpecs.cs +++ b/test/Polly.Specs/Caching/CacheSpecs.cs @@ -38,22 +38,22 @@ public void Should_throw_when_cache_key_strategy_is_null() [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; cache.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -61,34 +61,34 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } [Fact] public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); TimeSpan ttl = TimeSpan.FromMinutes(30); CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -96,50 +96,50 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e Func func = _ => { delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(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); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(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); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(2); } [Fact] public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -147,8 +147,8 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); @@ -156,16 +156,16 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe Func func = _ => { delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); } @@ -223,18 +223,18 @@ public void Should_allow_custom_ICacheKeyStrategy() public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_reference_type() { ResultClass? valueToReturn = null; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -244,11 +244,11 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { ResultClass? valueToReturnFromCache = null; ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; @@ -256,7 +256,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { delegateExecuted = true; return valueToReturnFromExecution; - }, new Context(operationKey)) + }, new Context(OperationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -266,18 +266,18 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type() { ResultPrimitive valueToReturn = default; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -288,11 +288,11 @@ 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); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; @@ -300,7 +300,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { delegateExecuted = true; return valueToReturnFromExecution; - }, new Context(operationKey)) + }, new Context(OperationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -313,25 +313,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_outermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(cache, noop); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -339,25 +339,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_innermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -365,25 +365,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_mid_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache, noop); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -437,8 +437,8 @@ public void Should_always_execute_delegate_if_execution_is_void_returning() [Fact] public void Should_honour_cancellation_even_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); @@ -449,15 +449,15 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() { // delegate does not observe cancellation token; test is whether CacheEngine does. delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; - cache.Execute(func, new Context(operationKey), tokenSource.Token).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey), tokenSource.Token).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); tokenSource.Cancel(); - cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) + cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) .Should().Throw(); delegateInvocations.Should().Be(1); } @@ -465,8 +465,8 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() [Fact] public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); @@ -477,13 +477,13 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ { tokenSource.Cancel(); // simulate cancellation raised during delegate execution ct.ThrowIfCancellationRequested(); - return valueToReturn; + return ValueToReturn; }; - cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) + cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) .Should().Throw(); - (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } @@ -500,15 +500,15 @@ public void Should_call_onError_delegate_if_cache_get_errors() Exception? exceptionFromCacheProvider = null; - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; @@ -516,9 +516,9 @@ public void Should_call_onError_delegate_if_cache_get_errors() cache.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromExecution); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromExecution); delegateExecuted.Should().BeTrue(); // And error should be captured by onError delegate. @@ -533,24 +533,24 @@ public void Should_call_onError_delegate_if_cache_put_errors() Exception? exceptionFromCacheProvider = null; - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; Action onError = (_, _, exc) => { exceptionFromCacheProvider = exc; }; CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); // error should be captured by onError delegate. exceptionFromCacheProvider.Should().Be(ex); // failed to put it in the cache - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); @@ -559,13 +559,13 @@ public void Should_call_onError_delegate_if_cache_put_errors() [Fact] public void Should_execute_oncacheget_after_got_from_cache() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToDelegate = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToDelegate = null; Action noErrorHandling = (_, _, _) => { }; @@ -574,31 +574,31 @@ public void Should_execute_oncacheget_after_got_from_cache() ISyncCacheProvider 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)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; cache.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; + return ValueToReturnFromExecution; }, contextToExecute) - .Should().Be(valueToReturnFromCache); + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); contextPassedToDelegate.Should().BeSameAs(contextToExecute); - keyPassedToDelegate.Should().Be(operationKey); + keyPassedToDelegate.Should().Be(OperationKey); } [Fact] public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_value_and_put() { - const string valueToReturn = "valueToReturn"; + const string ValueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToOnCacheMiss = null; string? keyPassedToOnCachePut = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToOnCacheMiss = null; Context? contextPassedToOnCachePut = null; @@ -610,33 +610,33 @@ public void Should_execute_oncachemiss_and_oncacheput_if_cache_does_not_hold_val ISyncCacheProvider 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); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, contextToExecute).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, contextToExecute).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute); - keyPassedToOnCacheMiss.Should().Be(operationKey); + keyPassedToOnCacheMiss.Should().Be(OperationKey); contextPassedToOnCachePut.Should().BeSameAs(contextToExecute); - keyPassedToOnCachePut.Should().Be(operationKey); + keyPassedToOnCachePut.Should().Be(OperationKey); } [Fact] public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold_value_and_returned_value_not_worth_caching() { - const string valueToReturn = "valueToReturn"; + const string ValueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; string? keyPassedToOnCacheMiss = null; string? keyPassedToOnCachePut = null; - Context contextToExecute = new Context(operationKey); + Context contextToExecute = new Context(OperationKey); Context? contextPassedToOnCacheMiss = null; Context? contextPassedToOnCachePut = null; @@ -648,14 +648,14 @@ public void Should_execute_oncachemiss_but_not_oncacheput_if_cache_does_not_hold ISyncCacheProvider 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); + (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); - cache.Execute(_ => valueToReturn, contextToExecute).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, contextToExecute).Should().Be(ValueToReturn); contextPassedToOnCacheMiss.Should().BeSameAs(contextToExecute); - keyPassedToOnCacheMiss.Should().Be(operationKey); + keyPassedToOnCacheMiss.Should().Be(OperationKey); contextPassedToOnCachePut.Should().BeNull(); keyPassedToOnCachePut.Should().BeNull(); diff --git a/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs b/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs index 51d0b3514c6..ff4d038bc2b 100644 --- a/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs @@ -37,13 +37,13 @@ public void Should_throw_when_cache_key_strategy_is_null() [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -51,9 +51,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -61,34 +61,34 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } [Fact] public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); TimeSpan ttl = TimeSpan.FromMinutes(30); var cache = Policy.CacheAsync(stubCacheProvider, ttl); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -97,50 +97,50 @@ public async Task Should_execute_delegate_and_put_value_in_cache_but_when_it_exp { delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(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); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(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); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(2); } [Fact] public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.Zero); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -148,8 +148,8 @@ public async Task Should_execute_delegate_but_not_put_value_in_cache_if_cache_do [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); @@ -158,16 +158,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_pri { delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (await cache.ExecuteAsync(func, new Context(operationKey))).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey))).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); } @@ -226,18 +226,18 @@ public async Task Should_allow_custom_ICacheKeyStrategy() public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_reference_type() { ResultClass? valueToReturn = null; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -247,11 +247,11 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { ResultClass? valueToReturnFromCache = null; ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -260,7 +260,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac delegateExecuted = true; await TaskHelper.EmptyTask; return valueToReturnFromExecution; - }, new Context(operationKey))) + }, new Context(OperationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -270,18 +270,18 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac public async Task Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type() { ResultPrimitive valueToReturn = default; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - (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))).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -292,11 +292,11 @@ 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); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -305,7 +305,7 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac delegateExecuted = true; await TaskHelper.EmptyTask; return valueToReturnFromExecution; - }, new Context(operationKey))) + }, new Context(OperationKey))) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -318,16 +318,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_outermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = cache.WrapAsync(noop); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -335,9 +335,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -345,16 +345,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_innermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = noop.WrapAsync(cache); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -362,9 +362,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -372,16 +372,16 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac [Fact] public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_mid_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); var noop = Policy.NoOpAsync(); var wrap = Policy.WrapAsync(noop, cache, noop); - await stubCacheProvider.PutAsync(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); + await stubCacheProvider.PutAsync(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue), CancellationToken.None, false); bool delegateExecuted = false; @@ -389,9 +389,9 @@ public async Task Should_return_value_from_cache_and_not_execute_delegate_if_cac { delegateExecuted = true; await TaskHelper.EmptyTask; - return valueToReturnFromExecution; - }, new Context(operationKey))) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey))) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -429,8 +429,8 @@ public async Task Should_always_execute_delegate_if_execution_key_not_set() [Fact] public async Task Should_honour_cancellation_even_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; var cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); @@ -442,15 +442,15 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( // delegate does not observe cancellation token; test is whether CacheEngine does. delegateInvocations++; await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - (await cache.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)).Should().Be(valueToReturn); + (await cache.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); tokenSource.Cancel(); - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) .Should().ThrowAsync(); delegateInvocations.Should().Be(1); } @@ -458,8 +458,8 @@ public async Task Should_honour_cancellation_even_if_prior_execution_has_cached( [Fact] public async Task Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); @@ -471,13 +471,13 @@ public async Task Should_honour_cancellation_during_delegate_execution_and_not_p tokenSource.Cancel(); // simulate cancellation raised during delegate execution ct.ThrowIfCancellationRequested(); await TaskHelper.EmptyTask; - return valueToReturn; + return ValueToReturn; }; - await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(operationKey), tokenSource.Token)) + await cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(OperationKey), tokenSource.Token)) .Should().ThrowAsync(); - (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } diff --git a/test/Polly.Specs/Caching/CacheTResultSpecs.cs b/test/Polly.Specs/Caching/CacheTResultSpecs.cs index 966446a92cb..9115491e1f3 100644 --- a/test/Polly.Specs/Caching/CacheTResultSpecs.cs +++ b/test/Polly.Specs/Caching/CacheTResultSpecs.cs @@ -38,22 +38,22 @@ public void Should_throw_when_cache_key_strategy_is_null() [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; cache.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -61,34 +61,34 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } [Fact] public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_execute_delegate_again() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); TimeSpan ttl = TimeSpan.FromMinutes(30); CachePolicy cache = Policy.Cache(stubCacheProvider, ttl); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -96,50 +96,50 @@ public void Should_execute_delegate_and_put_value_in_cache_but_when_it_expires_e Func func = _ => { delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; DateTimeOffset fixedTime = SystemClock.DateTimeOffsetUtcNow(); SystemClock.DateTimeOffsetUtcNow = () => fixedTime; // First execution should execute delegate and put result in the cache. - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(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); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(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); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(2); } [Fact] public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not_hold_value_but_ttl_indicates_not_worth_caching() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.Zero); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeFalse(); fromCache2.Should().BeNull(); } @@ -147,8 +147,8 @@ public void Should_execute_delegate_but_not_put_value_in_cache_if_cache_does_not [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); @@ -156,16 +156,16 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_prior_exe Func func = _ => { delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); - cache.Execute(func, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey)).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); } @@ -223,18 +223,18 @@ public void Should_allow_custom_ICacheKeyStrategy() public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_reference_type() { ResultClass? valueToReturn = null; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -244,11 +244,11 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { ResultClass? valueToReturnFromCache = null; ResultClass valueToReturnFromExecution = new ResultClass(ResultPrimitive.Good); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; @@ -256,7 +256,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { delegateExecuted = true; return valueToReturnFromExecution; - }, new Context(operationKey)) + }, new Context(OperationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -266,18 +266,18 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol public void Should_execute_delegate_and_put_value_in_cache_if_cache_does_not_hold_value__default_for_value_type() { ResultPrimitive valueToReturn = default; - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => valueToReturn, new Context(OperationKey)).Should().Be(valueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); fromCache2.Should().Be(valueToReturn); } @@ -288,11 +288,11 @@ 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); - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; @@ -300,7 +300,7 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol { delegateExecuted = true; return valueToReturnFromExecution; - }, new Context(operationKey)) + }, new Context(OperationKey)) .Should().Be(valueToReturnFromCache); delegateExecuted.Should().BeFalse(); @@ -313,25 +313,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_outermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = cache.Wrap(noop); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -339,25 +339,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_innermost_in_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = noop.Wrap(cache); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -365,25 +365,25 @@ public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_hol [Fact] public void Should_return_value_from_cache_and_not_execute_delegate_if_cache_holds_value_when_mid_policywrap() { - const string valueToReturnFromCache = "valueToReturnFromCache"; - const string valueToReturnFromExecution = "valueToReturnFromExecution"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturnFromCache = "valueToReturnFromCache"; + const string ValueToReturnFromExecution = "valueToReturnFromExecution"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); Policy noop = Policy.NoOp(); PolicyWrap wrap = Policy.Wrap(noop, cache, noop); - stubCacheProvider.Put(operationKey, valueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); + stubCacheProvider.Put(OperationKey, ValueToReturnFromCache, new Ttl(TimeSpan.MaxValue)); bool delegateExecuted = false; wrap.Execute(_ => { delegateExecuted = true; - return valueToReturnFromExecution; - }, new Context(operationKey)) - .Should().Be(valueToReturnFromCache); + return ValueToReturnFromExecution; + }, new Context(OperationKey)) + .Should().Be(ValueToReturnFromCache); delegateExecuted.Should().BeFalse(); } @@ -420,8 +420,8 @@ public void Should_always_execute_delegate_if_execution_key_not_set() [Fact] public void Should_honour_cancellation_even_if_prior_execution_has_cached() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; CachePolicy cache = Policy.Cache(new StubCacheProvider(), TimeSpan.MaxValue); @@ -432,15 +432,15 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() { // delegate does not observe cancellation token; test is whether CacheEngine does. delegateInvocations++; - return valueToReturn; + return ValueToReturn; }; - cache.Execute(func, new Context(operationKey), tokenSource.Token).Should().Be(valueToReturn); + cache.Execute(func, new Context(OperationKey), tokenSource.Token).Should().Be(ValueToReturn); delegateInvocations.Should().Be(1); tokenSource.Cancel(); - cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) + cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) .Should().Throw(); delegateInvocations.Should().Be(1); } @@ -448,8 +448,8 @@ public void Should_honour_cancellation_even_if_prior_execution_has_cached() [Fact] public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache() { - const string valueToReturn = "valueToReturn"; - const string operationKey = "SomeOperationKey"; + const string ValueToReturn = "valueToReturn"; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); @@ -460,13 +460,13 @@ public void Should_honour_cancellation_during_delegate_execution_and_not_put_to_ { tokenSource.Cancel(); // simulate cancellation raised during delegate execution ct.ThrowIfCancellationRequested(); - return valueToReturn; + return ValueToReturn; }; - cache.Invoking(policy => policy.Execute(func, new Context(operationKey), tokenSource.Token)) + cache.Invoking(policy => policy.Execute(func, new Context(OperationKey), tokenSource.Token)) .Should().Throw(); - (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); } diff --git a/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs b/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs index df5871f95c2..3eb93b50402 100644 --- a/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs +++ b/test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs @@ -6,7 +6,7 @@ public class GenericCacheProviderAsyncSpecs : IDisposable [Fact] public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache_does_not_hold_value() { - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; bool onErrorCalled = false; Action onError = (_, _, _) => { onErrorCalled = true; }; @@ -14,7 +14,7 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue, onError); - (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit, object? fromCache) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); @@ -22,7 +22,7 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache { await TaskHelper.EmptyTask; return ResultPrimitive.Substitute; - }, new Context(operationKey)); + }, new Context(OperationKey)); onErrorCalled.Should().BeFalse(); } @@ -30,13 +30,13 @@ public async Task Should_not_error_for_executions_on_non_nullable_types_if_cache [Fact] public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullable_types_if_cache_does_not_hold_value() { - const ResultPrimitive valueToReturn = ResultPrimitive.Substitute; - const string operationKey = "SomeOperationKey"; + const ResultPrimitive ValueToReturn = ResultPrimitive.Substitute; + const string OperationKey = "SomeOperationKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); var cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit1, object? fromCache1) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); @@ -44,11 +44,11 @@ public async Task Should_execute_delegate_and_put_value_in_cache_for_non_nullabl { await TaskHelper.EmptyTask; return ResultPrimitive.Substitute; - }, new Context(operationKey))).Should().Be(valueToReturn); + }, new Context(OperationKey))).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(operationKey, CancellationToken.None, false); + (bool cacheHit2, object? fromCache2) = await stubCacheProvider.TryGetAsync(OperationKey, CancellationToken.None, false); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } public void Dispose() => diff --git a/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs b/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs index 8efe5f802f1..8c0d2cbe92e 100644 --- a/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs +++ b/test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs @@ -6,7 +6,7 @@ public class GenericCacheProviderSpecs : IDisposable [Fact] public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_not_hold_value() { - const string operationKey = "SomeOperationKey"; + const string OperationKey = "SomeOperationKey"; bool onErrorCalled = false; Action onError = (_, _, _) => { onErrorCalled = true; }; @@ -14,11 +14,11 @@ public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_ ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue, onError); - (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit, object? fromCache) = stubCacheProvider.TryGet(OperationKey); cacheHit.Should().BeFalse(); fromCache.Should().BeNull(); - ResultPrimitive result = cache.Execute(_ => ResultPrimitive.Substitute, new Context(operationKey)); + ResultPrimitive result = cache.Execute(_ => ResultPrimitive.Substitute, new Context(OperationKey)); onErrorCalled.Should().BeFalse(); } @@ -26,23 +26,23 @@ public void Should_not_error_for_executions_on_non_nullable_types_if_cache_does_ [Fact] public void Should_execute_delegate_and_put_value_in_cache_for_non_nullable_types_if_cache_does_not_hold_value() { - const ResultPrimitive valueToReturn = ResultPrimitive.Substitute; - const string operationKey = "SomeOperationKey"; + const ResultPrimitive ValueToReturn = ResultPrimitive.Substitute; + const string OperationKey = "SomeOperationKey"; ISyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.Cache(stubCacheProvider, TimeSpan.MaxValue); - (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit1, object? fromCache1) = stubCacheProvider.TryGet(OperationKey); cacheHit1.Should().BeFalse(); fromCache1.Should().BeNull(); - cache.Execute(_ => valueToReturn, new Context(operationKey)).Should().Be(valueToReturn); + cache.Execute(_ => ValueToReturn, new Context(OperationKey)).Should().Be(ValueToReturn); - (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(operationKey); + (bool cacheHit2, object? fromCache2) = stubCacheProvider.TryGet(OperationKey); cacheHit2.Should().BeTrue(); - fromCache2.Should().Be(valueToReturn); + fromCache2.Should().Be(ValueToReturn); } public void Dispose() => diff --git a/test/Polly.Specs/Caching/ResultTtlSpecs.cs b/test/Polly.Specs/Caching/ResultTtlSpecs.cs index d89befc02eb..5dd0f5909fb 100644 --- a/test/Polly.Specs/Caching/ResultTtlSpecs.cs +++ b/test/Polly.Specs/Caching/ResultTtlSpecs.cs @@ -50,14 +50,14 @@ public void Should_return_func_result() [Fact] public void Should_return_func_result_using_context() { - const string specialKey = "specialKey"; + const string SpecialKey = "specialKey"; TimeSpan ttl = TimeSpan.FromMinutes(1); - Func func = (context, result) => context.OperationKey == specialKey ? new Ttl(TimeSpan.Zero) : new Ttl(result!.Ttl); + Func func = (context, result) => context.OperationKey == SpecialKey ? new Ttl(TimeSpan.Zero) : new Ttl(result!.Ttl); 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(SpecialKey), new { Ttl = ttl }).Timespan.Should().Be(TimeSpan.Zero); } } diff --git a/test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs b/test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs index 48358718d4c..c6b47575084 100644 --- a/test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs +++ b/test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs @@ -4,12 +4,12 @@ public class AnnotatedOutputHelper : ITestOutputHelper { private class Item { - private static int monotonicSequence; + private static int MonotonicSequence; public Item(string format, object[] args) { TimeStamp = DateTimeOffset.UtcNow; - Position = Interlocked.Increment(ref monotonicSequence); + Position = Interlocked.Increment(ref MonotonicSequence); Format = format; Args = args; @@ -21,30 +21,30 @@ public Item(string format, object[] args) public object[] Args { get; } } - private readonly ConcurrentDictionary items = new(); + private readonly ConcurrentDictionary _items = new(); - private readonly object[] noArgs = Array.Empty(); + private readonly object[] _noArgs = []; - private readonly ITestOutputHelper innerOutputHelper; + private readonly ITestOutputHelper _innerOutputHelper; public AnnotatedOutputHelper(ITestOutputHelper innerOutputHelper) => - this.innerOutputHelper = innerOutputHelper ?? throw new ArgumentNullException(nameof(innerOutputHelper)); + _innerOutputHelper = innerOutputHelper ?? throw new ArgumentNullException(nameof(innerOutputHelper)); public void Flush() { // Some IDEs limit the number of lines of output displayed in a test result. Display the lines in reverse order so that we always see the most recent. - var toOutput = items.Select(kvp => kvp.Value).OrderBy(i => i.Position).Reverse(); + var toOutput = _items.Select(kvp => kvp.Value).OrderBy(i => i.Position).Reverse(); foreach (var item in toOutput) { - innerOutputHelper.WriteLine(item.TimeStamp.ToString("o") + ": " + item.Format, item.Args); + _innerOutputHelper.WriteLine(item.TimeStamp.ToString("o") + ": " + item.Format, item.Args); } - items.Clear(); + _items.Clear(); } public void WriteLine(string message) => - items.TryAdd(Guid.NewGuid(), new Item(message ?? string.Empty, noArgs)); + _items.TryAdd(Guid.NewGuid(), new Item(message ?? string.Empty, _noArgs)); public void WriteLine(string format, params object[] args) => - items.TryAdd(Guid.NewGuid(), new Item(format ?? string.Empty, args == null || args.Length == 0 ? noArgs : args)); + _items.TryAdd(Guid.NewGuid(), new Item(format ?? string.Empty, args == null || args.Length == 0 ? _noArgs : args)); } diff --git a/test/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs b/test/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs index 7db6027db15..4300bd4a6df 100644 --- a/test/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs +++ b/test/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs @@ -10,7 +10,7 @@ public class TraceableAction : IDisposable private readonly ITestOutputHelper _testOutputHelper; private readonly TaskCompletionSource _tcsProxyForRealWork = new(); - private readonly CancellationTokenSource CancellationSource = new(); + private readonly CancellationTokenSource _cancellationSource = new(); private readonly AutoResetEvent _statusChanged; private TraceableActionStatus _status; @@ -41,7 +41,7 @@ public void SignalStateChange() public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) => ExecuteThroughSyncBulkheadOuter( - () => bulkhead.Execute(_ => ExecuteThroughSyncBulkheadInner(), CancellationSource.Token)); + () => bulkhead.Execute(_ => ExecuteThroughSyncBulkheadInner(), _cancellationSource.Token)); public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) => ExecuteThroughSyncBulkheadOuter( @@ -49,7 +49,7 @@ public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) => { ExecuteThroughSyncBulkheadInner(); return default; - }, CancellationSource.Token)); + }, _cancellationSource.Token)); // Note re TaskCreationOptions.LongRunning: Testing the parallelization of the bulkhead policy efficiently requires the ability to start large numbers of parallel tasks in a short space of time. The ThreadPool's algorithm of only injecting extra threads (when necessary) at a rate of two-per-second however makes high-volume tests using the ThreadPool both slow and flaky. For PCL tests further, ThreadPool.SetMinThreads(...) is not available, to mitigate this. Using TaskCreationOptions.LongRunning allows us to force tasks to be started near-instantly on non-ThreadPool threads. private Task ExecuteThroughSyncBulkheadOuter(Action executeThroughBulkheadInner) @@ -123,7 +123,7 @@ private void ExecuteThroughSyncBulkheadInner() public Task ExecuteOnBulkheadAsync(AsyncBulkheadPolicy bulkhead) => ExecuteThroughAsyncBulkheadOuter( - () => bulkhead.ExecuteAsync(async _ => await ExecuteThroughAsyncBulkheadInner(), CancellationSource.Token)); + () => bulkhead.ExecuteAsync(async _ => await ExecuteThroughAsyncBulkheadInner(), _cancellationSource.Token)); public Task ExecuteOnBulkheadAsync(AsyncBulkheadPolicy bulkhead) => ExecuteThroughAsyncBulkheadOuter( @@ -131,7 +131,7 @@ public Task ExecuteOnBulkheadAsync(AsyncBulkheadPolicy bulkhe { await ExecuteThroughAsyncBulkheadInner(); return default; - }, CancellationSource.Token)); + }, _cancellationSource.Token)); public Task ExecuteThroughAsyncBulkheadOuter(Func executeThroughBulkheadInner) { @@ -195,7 +195,7 @@ private async Task ExecuteThroughAsyncBulkheadInner() _testOutputHelper.WriteLine(_id + "Cancelling execution."); Status = TraceableActionStatus.Canceled; - throw new OperationCanceledException(CancellationSource.Token); // Exception rethrown for the purpose of testing exceptions thrown through the BulkheadEngine. + throw new OperationCanceledException(_cancellationSource.Token); // Exception rethrown for the purpose of testing exceptions thrown through the BulkheadEngine. } else if (t.IsFaulted) { @@ -220,16 +220,16 @@ public void AllowCompletion() => public void Cancel() { - if (CancellationSource.IsCancellationRequested) + if (_cancellationSource.IsCancellationRequested) { throw new InvalidOperationException(_id + "Action has already been cancelled."); } - CancellationSource.Cancel(); + _cancellationSource.Cancel(); _tcsProxyForRealWork.SetCanceled(); } public void Dispose() => - CancellationSource.Dispose(); + _cancellationSource.Dispose(); } diff --git a/test/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs b/test/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs index 85aee76fc54..1329e5aa6fb 100644 --- a/test/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs +++ b/test/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs @@ -5,11 +5,11 @@ /// internal class StubCacheKeyStrategy : ICacheKeyStrategy { - private readonly Func strategy; + private readonly Func _strategy; public StubCacheKeyStrategy(Func strategy) => - this.strategy = strategy; + _strategy = strategy; public string GetCacheKey(Context context) => - strategy(context); + _strategy(context); } diff --git a/test/Polly.Specs/Helpers/Caching/StubCacheProvider.cs b/test/Polly.Specs/Helpers/Caching/StubCacheProvider.cs index dce2456be56..3b693028ebc 100644 --- a/test/Polly.Specs/Helpers/Caching/StubCacheProvider.cs +++ b/test/Polly.Specs/Helpers/Caching/StubCacheProvider.cs @@ -17,19 +17,19 @@ public CacheItem(object? value, Ttl ttl) public readonly object? Value; } - private readonly Dictionary cachedValues = []; + private readonly Dictionary _cachedValues = []; public (bool, object?) TryGet(string key) { - if (cachedValues.ContainsKey(key)) + if (_cachedValues.ContainsKey(key)) { - if (SystemClock.DateTimeOffsetUtcNow() < cachedValues[key].Expiry) + if (SystemClock.DateTimeOffsetUtcNow() < _cachedValues[key].Expiry) { - return (true, cachedValues[key].Value); + return (true, _cachedValues[key].Value); } else { - cachedValues.Remove(key); + _cachedValues.Remove(key); } } @@ -37,7 +37,7 @@ public CacheItem(object? value, Ttl ttl) } public void Put(string key, object? value, Ttl ttl) => - cachedValues[key] = new CacheItem(value, ttl); + _cachedValues[key] = new CacheItem(value, ttl); #region Naive async-over-sync implementation diff --git a/test/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs b/test/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs index b78a72398d4..ad253c82fbd 100644 --- a/test/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs +++ b/test/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs @@ -5,7 +5,7 @@ internal class StubErroringCacheProvider : ISyncCacheProvider, IAsyncCacheProvid private readonly Exception? _getException; private readonly Exception? _putException; - private readonly StubCacheProvider innerProvider = new(); + private readonly StubCacheProvider _innerProvider = new(); public StubErroringCacheProvider(Exception? getException, Exception? putException) { @@ -17,14 +17,14 @@ public StubErroringCacheProvider(Exception? getException, Exception? putExceptio { if (_getException != null) throw _getException; - return innerProvider.TryGet(key); + return _innerProvider.TryGet(key); } public void Put(string key, object? value, Ttl ttl) { if (_putException != null) throw _putException; - innerProvider.Put(key, value, ttl); + _innerProvider.Put(key, value, ttl); } #region Naive async-over-sync implementation diff --git a/test/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs b/test/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs index 46c407a4518..7e10400b443 100644 --- a/test/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs +++ b/test/Polly.Specs/PolicyContextAndKeyAsyncSpecs.cs @@ -24,11 +24,11 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() [Fact] public void PolicyKey_property_should_be_the_fluently_configured_policy_key() { - const string key = "SomePolicyKey"; + const string Key = "SomePolicyKey"; - var policy = Policy.Handle().RetryAsync().WithPolicyKey(key); + var policy = Policy.Handle().RetryAsync().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(key); + policy.PolicyKey.Should().Be(Key); } [Fact] @@ -208,11 +208,11 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() [Fact] public void PolicyKey_property_should_be_the_fluently_configured_policy_key() { - const string key = "SomePolicyKey"; + const string Key = "SomePolicyKey"; - var policy = Policy.HandleResult(0).RetryAsync().WithPolicyKey(key); + var policy = Policy.HandleResult(0).RetryAsync().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(key); + policy.PolicyKey.Should().Be(Key); } [Fact] diff --git a/test/Polly.Specs/PolicyContextAndKeySpecs.cs b/test/Polly.Specs/PolicyContextAndKeySpecs.cs index 45ed28d2026..4c17f00c718 100644 --- a/test/Polly.Specs/PolicyContextAndKeySpecs.cs +++ b/test/Polly.Specs/PolicyContextAndKeySpecs.cs @@ -24,11 +24,11 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() [Fact] public void PolicyKey_property_should_be_the_fluently_configured_policy_key() { - const string key = "SomePolicyKey"; + const string Key = "SomePolicyKey"; - var policy = Policy.Handle().Retry().WithPolicyKey(key); + var policy = Policy.Handle().Retry().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(key); + policy.PolicyKey.Should().Be(Key); } [Fact] @@ -205,11 +205,11 @@ public void Should_be_able_fluently_to_configure_the_policy_key_via_interface() [Fact] public void PolicyKey_property_should_be_the_fluently_configured_policy_key() { - const string key = "SomePolicyKey"; + const string Key = "SomePolicyKey"; - var policy = Policy.HandleResult(0).Retry().WithPolicyKey(key); + var policy = Policy.HandleResult(0).Retry().WithPolicyKey(Key); - policy.PolicyKey.Should().Be(key); + policy.PolicyKey.Should().Be(Key); } [Fact] diff --git a/test/Polly.Specs/Polly.Specs.csproj b/test/Polly.Specs/Polly.Specs.csproj index 43cf95ff43e..c69d15f0651 100644 --- a/test/Polly.Specs/Polly.Specs.csproj +++ b/test/Polly.Specs/Polly.Specs.csproj @@ -8,8 +8,8 @@ 75,60,70 [Polly]* true - $(NoWarn);S103;S104;CA2000;IDE0011;SA1600;SA1204;SA1602;S6608;IDE1006;CA2008;CA1806;CA2201; - $(NoWarn);SA1414;CA1508;S3878;CA1030;S4144;S3717;SA1129;SA1407;S1402;SA1649;SA1402;S4056;CA1031 + $(NoWarn);S103;S104;CA2000;IDE0011;SA1600;SA1204;SA1602;CA2008;CA1806;CA2201; + $(NoWarn);S3878;CA1030;S4144;S3717;SA1129;SA1407;S1402;SA1649;SA1402;S4056;CA1031 $(NoWarn);S2184; diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs index abeeaaa11f8..510234347bb 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs @@ -11,7 +11,7 @@ protected abstract IRateLimitPolicy GetPolicyViaSyntax( TimeSpan perTimeSpan, int maxBurst); - protected abstract (bool, TimeSpan) TryExecuteThroughPolicy(IRateLimitPolicy policy); + protected abstract (bool permitExecution, TimeSpan retryAfter) TryExecuteThroughPolicy(IRateLimitPolicy policy); protected void ShouldPermitAnExecution(IRateLimitPolicy policy) { diff --git a/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs b/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs index fb36bfc9548..51b0694d6c2 100644 --- a/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs +++ b/test/Polly.Specs/Registry/ConcurrentPolicyRegistrySpecs.cs @@ -215,18 +215,18 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addvalue_ string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); - const string policyKeyToDecorate = "SomePolicyKey"; + const string PolicyKeyToDecorate = "SomePolicyKey"; Policy otherPolicyNotExpectingToAdd = Policy.Handle().Retry(); var returnedPolicy = _registry.AddOrUpdate( key, otherPolicyNotExpectingToAdd, - (_, _) => existingPolicy.WithPolicyKey(policyKeyToDecorate)); + (_, _) => existingPolicy.WithPolicyKey(PolicyKeyToDecorate)); returnedPolicy.Should().NotBeSameAs(otherPolicyNotExpectingToAdd); returnedPolicy.Should().BeSameAs(existingPolicy); - returnedPolicy.PolicyKey.Should().Be(policyKeyToDecorate); + returnedPolicy.PolicyKey.Should().Be(PolicyKeyToDecorate); } [Fact] @@ -236,17 +236,17 @@ public void Should_update_with_AddOrUpdate_with_updatefactory_ignoring_addfactor string key = Guid.NewGuid().ToString(); _registry.Add(key, existingPolicy); - const string policyKeyToDecorate = "SomePolicyKey"; + const string PolicyKeyToDecorate = "SomePolicyKey"; Policy otherPolicyNotExpectingToAdd = Policy.Handle().Retry(); var returnedPolicy = _registry.AddOrUpdate( key, _ => otherPolicyNotExpectingToAdd, - (_, _) => existingPolicy.WithPolicyKey(policyKeyToDecorate)); + (_, _) => existingPolicy.WithPolicyKey(PolicyKeyToDecorate)); returnedPolicy.Should().NotBeSameAs(otherPolicyNotExpectingToAdd); returnedPolicy.Should().BeSameAs(existingPolicy); - returnedPolicy.PolicyKey.Should().Be(policyKeyToDecorate); + returnedPolicy.PolicyKey.Should().Be(PolicyKeyToDecorate); } } From dffbf32e4a37c55931b36646b52afda6ff643b3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baranyai=20M=C3=A1t=C3=A9?= Date: Sat, 27 Jan 2024 10:34:41 +0100 Subject: [PATCH 2/5] Use PascalCase in named tuples --- test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs index 510234347bb..e2f0134d8d6 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs @@ -11,7 +11,7 @@ protected abstract IRateLimitPolicy GetPolicyViaSyntax( TimeSpan perTimeSpan, int maxBurst); - protected abstract (bool permitExecution, TimeSpan retryAfter) TryExecuteThroughPolicy(IRateLimitPolicy policy); + protected abstract (bool PermitExecution, TimeSpan RetryAfter) TryExecuteThroughPolicy(IRateLimitPolicy policy); protected void ShouldPermitAnExecution(IRateLimitPolicy policy) { From 3697a1ebbab4b5d3c5d60b5eb0be3551749d2570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baranyai=20M=C3=A1t=C3=A9?= Date: Sat, 27 Jan 2024 11:09:18 +0100 Subject: [PATCH 3/5] Remove tupleElementNameCasing override and fix new warnings --- eng/analyzers/Stylecop.json | 3 +-- src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/eng/analyzers/Stylecop.json b/eng/analyzers/Stylecop.json index 9cad70f365d..d1034436502 100644 --- a/eng/analyzers/Stylecop.json +++ b/eng/analyzers/Stylecop.json @@ -19,9 +19,8 @@ "maintainabilityRules": { }, "namingRules": { - "tupleElementNameCasing": "camelCase" }, "readabilityRules": { } } -} \ No newline at end of file +} diff --git a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs index 10b7f937f8a..fb826066e7d 100644 --- a/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs +++ b/src/Polly.Core/Registry/RegistryPipelineComponentBuilder.cs @@ -30,7 +30,7 @@ public RegistryPipelineComponentBuilder( _configure = configure; } - internal (ResilienceContextPool? contextPool, PipelineComponent component) CreateComponent() + internal (ResilienceContextPool? ContextPool, PipelineComponent Component) CreateComponent() { var builder = CreateBuilder(); var component = builder.ComponentFactory(); From 098d48e1aabeaa5498b43e0f9d18d05947b64cea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baranyai=20M=C3=A1t=C3=A9?= Date: Sat, 27 Jan 2024 11:29:18 +0100 Subject: [PATCH 4/5] Fix new warnings --- src/Polly/RateLimit/IRateLimiter.cs | 2 +- .../RateLimit/LockFreeTokenBucketRateLimiter.cs | 2 +- .../Helpers/RateLimit/IRateLimiterExtensions.cs | 14 +++++++------- .../RateLimit/RateLimitPolicySpecsBase.cs | 14 +++++++------- .../RateLimit/TokenBucketRateLimiterTestsBase.cs | 6 +++--- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/Polly/RateLimit/IRateLimiter.cs b/src/Polly/RateLimit/IRateLimiter.cs index 67ab7e1dda0..a6c702e68f9 100644 --- a/src/Polly/RateLimit/IRateLimiter.cs +++ b/src/Polly/RateLimit/IRateLimiter.cs @@ -11,5 +11,5 @@ internal interface IRateLimiter /// Returns whether the execution is permitted; if not, returns what should be waited before retrying. /// Calling this method consumes an execution permit if one is available: a caller receiving a return value true should make an execution. /// - (bool permitExecution, TimeSpan retryAfter) PermitExecution(); + (bool PermitExecution, TimeSpan RetryAfter) PermitExecution(); } diff --git a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs index 5333dd90b1e..7a5ef950006 100644 --- a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs +++ b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs @@ -40,7 +40,7 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) /// /// Returns whether the execution is permitted; if not, returns what should be waited before retrying. /// - public (bool permitExecution, TimeSpan retryAfter) PermitExecution() + public (bool PermitExecution, TimeSpan RetryAfter) PermitExecution() { while (true) { diff --git a/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs b/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs index b01d5ee3c41..cae57bb82a7 100644 --- a/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs +++ b/test/Polly.Specs/Helpers/RateLimit/IRateLimiterExtensions.cs @@ -4,10 +4,10 @@ internal static class IRateLimiterExtensions { public static void ShouldPermitAnExecution(this IRateLimiter rateLimiter) { - (bool permitExecution, TimeSpan retryAfter) canExecute = rateLimiter.PermitExecution(); + (bool PermitExecution, TimeSpan RetryAfter) canExecute = rateLimiter.PermitExecution(); - canExecute.permitExecution.Should().BeTrue(); - canExecute.retryAfter.Should().Be(TimeSpan.Zero); + canExecute.PermitExecution.Should().BeTrue(); + canExecute.RetryAfter.Should().Be(TimeSpan.Zero); } public static void ShouldPermitNExecutions(this IRateLimiter rateLimiter, long numberOfExecutions) @@ -20,16 +20,16 @@ public static void ShouldPermitNExecutions(this IRateLimiter rateLimiter, long n public static void ShouldNotPermitAnExecution(this IRateLimiter rateLimiter, TimeSpan? retryAfter = null) { - (bool permitExecution, TimeSpan retryAfter) canExecute = rateLimiter.PermitExecution(); + (bool PermitExecution, TimeSpan RetryAfter) canExecute = rateLimiter.PermitExecution(); - canExecute.permitExecution.Should().BeFalse(); + canExecute.PermitExecution.Should().BeFalse(); if (retryAfter == null) { - canExecute.retryAfter.Should().BeGreaterThan(TimeSpan.Zero); + canExecute.RetryAfter.Should().BeGreaterThan(TimeSpan.Zero); } else { - canExecute.retryAfter.Should().Be(retryAfter.Value); + canExecute.RetryAfter.Should().Be(retryAfter.Value); } } } diff --git a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs index e2f0134d8d6..e215e497441 100644 --- a/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs +++ b/test/Polly.Specs/RateLimit/RateLimitPolicySpecsBase.cs @@ -31,16 +31,16 @@ protected void ShouldPermitNExecutions(IRateLimitPolicy policy, long numberOfExe protected void ShouldNotPermitAnExecution(IRateLimitPolicy policy, TimeSpan? retryAfter = null) { - (bool permitExecution, TimeSpan retryAfter) canExecute = TryExecuteThroughPolicy(policy); + (bool PermitExecution, TimeSpan RetryAfter) canExecute = TryExecuteThroughPolicy(policy); - canExecute.permitExecution.Should().BeFalse(); + canExecute.PermitExecution.Should().BeFalse(); if (retryAfter == null) { - canExecute.retryAfter.Should().BeGreaterThan(TimeSpan.Zero); + canExecute.RetryAfter.Should().BeGreaterThan(TimeSpan.Zero); } else { - canExecute.retryAfter.Should().Be(retryAfter.Value); + canExecute.RetryAfter.Should().Be(retryAfter.Value); } } @@ -282,7 +282,7 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o // Arrange - parallel tasks all waiting on a manual reset event. ManualResetEventSlim gate = new(); - Task<(bool permitExecution, TimeSpan retryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; + Task<(bool PermitExecution, TimeSpan RetryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; for (int i = 0; i < parallelContention; i++) { tasks[i] = Task.Run(() => @@ -300,7 +300,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).Should().Be(1); + results.Count(r => !r.PermitExecution).Should().Be(parallelContention - 1); } } diff --git a/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs b/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs index 74d9afffc4b..cdf067bd52b 100644 --- a/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs +++ b/test/Polly.Specs/RateLimit/TokenBucketRateLimiterTestsBase.cs @@ -181,7 +181,7 @@ public void Given_immediate_parallel_contention_ratelimiter_still_only_permits_o // Arrange - parallel tasks all waiting on a manual reset event. ManualResetEventSlim gate = new ManualResetEventSlim(); - Task<(bool permitExecution, TimeSpan retryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; + Task<(bool PermitExecution, TimeSpan RetryAfter)>[] tasks = new Task<(bool, TimeSpan)>[parallelContention]; for (int i = 0; i < parallelContention; i++) { tasks[i] = Task.Run(() => @@ -199,7 +199,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).Should().Be(1); + results.Count(r => !r.PermitExecution).Should().Be(parallelContention - 1); } } From 2850db2968f6aa77183c7dd7a7a4b3d5d66b0c94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baranyai=20M=C3=A1t=C3=A9?= Date: Sun, 28 Jan 2024 11:44:53 +0100 Subject: [PATCH 5/5] Fix SA1113/CA1200/SA1805/SA1629/SA1407/SA1127 warnings --- .../Bulkhead/BulkheadRejectedException.cs | 12 ++++--- src/Polly/Caching/AbsoluteTtl.cs | 3 +- src/Polly/Caching/Ttl.cs | 3 +- .../AdvancedCircuitController.cs | 3 +- .../AsyncCircuitBreakerPolicy.cs | 6 ++-- .../CircuitBreaker/CircuitBreakerPolicy.cs | 6 ++-- .../ConsecutiveCountCircuitController.cs | 3 +- src/Polly/Context.Dictionary.cs | 6 ++-- src/Polly/Fallback/AsyncFallbackPolicy.cs | 3 +- src/Polly/Fallback/FallbackPolicy.cs | 3 +- src/Polly/Policy.HandleSyntax.cs | 32 ++++++++++++++----- src/Polly/PolicyBuilder.OrSyntax.cs | 26 +++++++++------ src/Polly/PolicyBuilder.cs | 8 ++--- src/Polly/Polly.csproj | 8 ++--- .../LockFreeTokenBucketRateLimiter.cs | 4 +-- .../RateLimit/RateLimitRejectedException.cs | 18 ++++++----- .../Registry/IConcurrentPolicyRegistry.cs | 21 ++++++++---- src/Polly/Registry/IPolicyRegistry.cs | 3 +- src/Polly/Registry/IReadOnlyPolicyRegistry.cs | 6 ++-- src/Polly/Registry/PolicyRegistry.cs | 32 ++++++++++++------- src/Polly/Timeout/TimeoutEngine.cs | 4 +-- src/Polly/Utilities/TimedLock.cs | 3 +- .../AdvancedCircuitBreakerAsyncSpecs.cs | 8 ++--- .../AdvancedCircuitBreakerSpecs.cs | 12 +++---- test/Polly.Specs/Polly.Specs.csproj | 2 +- 25 files changed, 148 insertions(+), 87 deletions(-) diff --git a/src/Polly/Bulkhead/BulkheadRejectedException.cs b/src/Polly/Bulkhead/BulkheadRejectedException.cs index c77f51afb2e..39b7d3a15e8 100644 --- a/src/Polly/Bulkhead/BulkheadRejectedException.cs +++ b/src/Polly/Bulkhead/BulkheadRejectedException.cs @@ -16,7 +16,8 @@ public class BulkheadRejectedException : ExecutionRejectedException /// /// Initializes a new instance of the class. /// - public BulkheadRejectedException() : this("The bulkhead semaphore and queue are full and execution was rejected.") + public BulkheadRejectedException() + : this("The bulkhead semaphore and queue are full and execution was rejected.") { } @@ -24,7 +25,8 @@ public BulkheadRejectedException() : this("The bulkhead semaphore and queue are /// Initializes a new instance of the class. /// /// The message. - public BulkheadRejectedException(string message) : base(message) + public BulkheadRejectedException(string message) + : base(message) { } @@ -33,7 +35,8 @@ public BulkheadRejectedException(string message) : base(message) /// /// The message. /// The inner exception. - public BulkheadRejectedException(string message, Exception innerException) : base(message, innerException) + public BulkheadRejectedException(string message, Exception innerException) + : base(message, innerException) { } @@ -44,7 +47,8 @@ public BulkheadRejectedException(string message, Exception innerException) : bas /// /// The information. /// The context. - protected BulkheadRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) + protected BulkheadRejectedException(SerializationInfo info, StreamingContext context) + : base(info, context) { } #endif diff --git a/src/Polly/Caching/AbsoluteTtl.cs b/src/Polly/Caching/AbsoluteTtl.cs index cf1d6f93b33..1f0da8c6408 100644 --- a/src/Polly/Caching/AbsoluteTtl.cs +++ b/src/Polly/Caching/AbsoluteTtl.cs @@ -10,7 +10,8 @@ public class AbsoluteTtl : NonSlidingTtl /// Initializes a new instance of the class. /// /// The UTC point in time until which to consider the cache item valid. - public AbsoluteTtl(DateTimeOffset absoluteExpirationTime) : base(absoluteExpirationTime) + public AbsoluteTtl(DateTimeOffset absoluteExpirationTime) + : base(absoluteExpirationTime) { } } diff --git a/src/Polly/Caching/Ttl.cs b/src/Polly/Caching/Ttl.cs index bdaf3b909c3..1259620710e 100644 --- a/src/Polly/Caching/Ttl.cs +++ b/src/Polly/Caching/Ttl.cs @@ -21,7 +21,8 @@ public struct Ttl /// /// The timespan for which this cache-item remains valid. /// Will be considered as not denoting sliding expiration. - public Ttl(TimeSpan timeSpan) : this(timeSpan, false) + public Ttl(TimeSpan timeSpan) + : this(timeSpan, false) { } diff --git a/src/Polly/CircuitBreaker/AdvancedCircuitController.cs b/src/Polly/CircuitBreaker/AdvancedCircuitController.cs index 6c959aac478..8980cc4698e 100644 --- a/src/Polly/CircuitBreaker/AdvancedCircuitController.cs +++ b/src/Polly/CircuitBreaker/AdvancedCircuitController.cs @@ -17,7 +17,8 @@ public AdvancedCircuitController( Action, CircuitState, TimeSpan, Context> onBreak, Action onReset, Action onHalfOpen - ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) + ) + : base(durationOfBreak, onBreak, onReset, onHalfOpen) { _metrics = samplingDuration.Ticks < ResolutionOfCircuitTimer * NumberOfWindows ? new SingleHealthMetrics(samplingDuration) diff --git a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs index 99f93a860a9..4988a3819f9 100644 --- a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs @@ -10,7 +10,8 @@ public class AsyncCircuitBreakerPolicy : AsyncPolicy, ICircuitBreakerPolicy internal AsyncCircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) => + ) + : base(policyBuilder) => _breakerController = breakerController; /// @@ -64,7 +65,8 @@ public class AsyncCircuitBreakerPolicy : AsyncPolicy, ICircuit internal AsyncCircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) => + ) + : base(policyBuilder) => _breakerController = breakerController; /// diff --git a/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs index 015e80d9975..d83e260a9a0 100644 --- a/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/CircuitBreakerPolicy.cs @@ -10,7 +10,8 @@ public class CircuitBreakerPolicy : Policy, ICircuitBreakerPolicy internal CircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) => + ) + : base(policyBuilder) => _breakerController = breakerController; /// @@ -62,7 +63,8 @@ public class CircuitBreakerPolicy : Policy, ICircuitBreakerPol internal CircuitBreakerPolicy( PolicyBuilder policyBuilder, ICircuitController breakerController - ) : base(policyBuilder) => + ) + : base(policyBuilder) => _breakerController = breakerController; /// diff --git a/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs b/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs index d4214391997..331dd9f011e 100644 --- a/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs +++ b/src/Polly/CircuitBreaker/ConsecutiveCountCircuitController.cs @@ -11,7 +11,8 @@ public ConsecutiveCountCircuitController( Action, CircuitState, TimeSpan, Context> onBreak, Action onReset, Action onHalfOpen - ) : base(durationOfBreak, onBreak, onReset, onHalfOpen) => + ) + : base(durationOfBreak, onBreak, onReset, onHalfOpen) => _exceptionsAllowedBeforeBreaking = exceptionsAllowedBeforeBreaking; public override void OnCircuitReset(Context context) diff --git a/src/Polly/Context.Dictionary.cs b/src/Polly/Context.Dictionary.cs index d0090ceba72..c8a42c0b679 100644 --- a/src/Polly/Context.Dictionary.cs +++ b/src/Polly/Context.Dictionary.cs @@ -18,10 +18,12 @@ public partial class Context : IDictionary, IDictionary, IReadOn /// /// The operation key. /// The context data. - public Context(string operationKey, IDictionary contextData) : this(contextData) => + public Context(string operationKey, IDictionary contextData) + : this(contextData) => OperationKey = operationKey; - internal Context(IDictionary contextData) : this() + internal Context(IDictionary contextData) + : this() { if (contextData == null) throw new ArgumentNullException(nameof(contextData)); wrappedDictionary = new Dictionary(contextData); diff --git a/src/Polly/Fallback/AsyncFallbackPolicy.cs b/src/Polly/Fallback/AsyncFallbackPolicy.cs index 284d8a6cef8..9765dd03b4e 100644 --- a/src/Polly/Fallback/AsyncFallbackPolicy.cs +++ b/src/Polly/Fallback/AsyncFallbackPolicy.cs @@ -61,7 +61,8 @@ internal AsyncFallbackPolicy( PolicyBuilder policyBuilder, Func, Context, Task> onFallbackAsync, Func, Context, CancellationToken, Task> fallbackAction - ) : base(policyBuilder) + ) + : base(policyBuilder) { _onFallbackAsync = onFallbackAsync ?? throw new ArgumentNullException(nameof(onFallbackAsync)); _fallbackAction = fallbackAction ?? throw new ArgumentNullException(nameof(fallbackAction)); diff --git a/src/Polly/Fallback/FallbackPolicy.cs b/src/Polly/Fallback/FallbackPolicy.cs index c4cb6c58819..7581427079d 100644 --- a/src/Polly/Fallback/FallbackPolicy.cs +++ b/src/Polly/Fallback/FallbackPolicy.cs @@ -57,7 +57,8 @@ internal FallbackPolicy( PolicyBuilder policyBuilder, Action, Context> onFallback, Func, Context, CancellationToken, TResult> fallbackAction - ) : base(policyBuilder) + ) + : base(policyBuilder) { _onFallback = onFallback ?? throw new ArgumentNullException(nameof(onFallback)); _fallbackAction = fallbackAction ?? throw new ArgumentNullException(nameof(fallbackAction)); diff --git a/src/Polly/Policy.HandleSyntax.cs b/src/Polly/Policy.HandleSyntax.cs index af18cccc647..99dc69af7db 100644 --- a/src/Polly/Policy.HandleSyntax.cs +++ b/src/Polly/Policy.HandleSyntax.cs @@ -7,7 +7,9 @@ public partial class Policy /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder Handle() where TException : Exception => + public static PolicyBuilder Handle() + where TException : Exception + => new(exception => exception is TException ? exception : null); /// @@ -16,7 +18,9 @@ public static PolicyBuilder Handle() where TException : Exception => /// The type of the exception. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder Handle(Func exceptionPredicate) where TException : Exception => + public static PolicyBuilder Handle(Func exceptionPredicate) + where TException : Exception + => new(exception => exception is TException texception && exceptionPredicate(texception) ? exception : null); /// @@ -24,7 +28,9 @@ public static PolicyBuilder Handle(Func exceptionP /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder HandleInner() where TException : Exception => + public static PolicyBuilder HandleInner() + where TException : Exception + => new(PolicyBuilder.HandleInner(ex => ex is TException)); /// @@ -32,7 +38,9 @@ public static PolicyBuilder HandleInner() where TException : Excepti /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder HandleInner(Func exceptionPredicate) where TException : Exception => + public static PolicyBuilder HandleInner(Func exceptionPredicate) + where TException : Exception + => new(PolicyBuilder.HandleInner(ex => ex is TException texception && exceptionPredicate(texception))); /// @@ -62,7 +70,9 @@ public partial class Policy /// /// The type of the exception to handle. /// The PolicyBuilder instance. - public static PolicyBuilder Handle() where TException : Exception => + public static PolicyBuilder Handle() + where TException : Exception + => new(exception => exception is TException ? exception : null); /// @@ -71,7 +81,9 @@ public static PolicyBuilder Handle() where TException : Exc /// The type of the exception. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance. - public static PolicyBuilder Handle(Func exceptionPredicate) where TException : Exception => + public static PolicyBuilder Handle(Func exceptionPredicate) + where TException : Exception + => new(exception => exception is TException texception && exceptionPredicate(texception) ? exception : null); /// @@ -79,7 +91,9 @@ public static PolicyBuilder Handle(Func e /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder HandleInner() where TException : Exception => + public static PolicyBuilder HandleInner() + where TException : Exception + => new(PolicyBuilder.HandleInner(ex => ex is TException)); /// @@ -87,7 +101,9 @@ public static PolicyBuilder HandleInner() where TException /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public static PolicyBuilder HandleInner(Func exceptionPredicate) where TException : Exception => + public static PolicyBuilder HandleInner(Func exceptionPredicate) + where TException : Exception + => new(PolicyBuilder.HandleInner(ex => ex is TException texception && exceptionPredicate(texception))); /// diff --git a/src/Polly/PolicyBuilder.OrSyntax.cs b/src/Polly/PolicyBuilder.OrSyntax.cs index 21d6c754754..9edbf05b7f8 100644 --- a/src/Polly/PolicyBuilder.OrSyntax.cs +++ b/src/Polly/PolicyBuilder.OrSyntax.cs @@ -9,7 +9,8 @@ public partial class PolicyBuilder /// /// The type of the exception to handle. /// The PolicyBuilder instance. - public PolicyBuilder Or() where TException : Exception + public PolicyBuilder Or() + where TException : Exception { ExceptionPredicates.Add(exception => exception is TException ? exception : null); return this; @@ -21,7 +22,8 @@ public PolicyBuilder Or() where TException : Exception /// The type of the exception. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance. - public PolicyBuilder Or(Func exceptionPredicate) where TException : Exception + public PolicyBuilder Or(Func exceptionPredicate) + where TException : Exception { ExceptionPredicates.Add(exception => exception is TException texception && exceptionPredicate(texception) ? exception : null); return this; @@ -32,7 +34,8 @@ public PolicyBuilder Or(Func exceptionPredicate) w /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public PolicyBuilder OrInner() where TException : Exception + public PolicyBuilder OrInner() + where TException : Exception { ExceptionPredicates.Add(HandleInner(ex => ex is TException)); return this; @@ -44,7 +47,8 @@ public PolicyBuilder OrInner() where TException : Exception /// The type of the exception to handle. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance, for fluent chaining. - public PolicyBuilder OrInner(Func exceptionPredicate) where TException : Exception + public PolicyBuilder OrInner(Func exceptionPredicate) + where TException : Exception { ExceptionPredicates.Add(HandleInner(exception => exception is TException innerEx && exceptionPredicate(innerEx))); return this; @@ -134,7 +138,8 @@ public PolicyBuilder OrResult(TResult result) => /// /// The type of the exception to handle. /// The PolicyBuilder instance. - public PolicyBuilder Or() where TException : Exception + public PolicyBuilder Or() + where TException : Exception { ExceptionPredicates.Add(exception => exception is TException ? exception : null); return this; @@ -146,9 +151,10 @@ public PolicyBuilder Or() where TException : Exception /// The type of the exception. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance. - public PolicyBuilder Or(Func exceptionPredicate) where TException : Exception + public PolicyBuilder Or(Func exceptionPredicate) + where TException : Exception { - ExceptionPredicates.Add(exception => exception is TException texception && exceptionPredicate(texception) ? exception : null); + ExceptionPredicates.Add(exception => exception is TException texception && exceptionPredicate(texception) ? exception : null); return this; } @@ -157,7 +163,8 @@ public PolicyBuilder Or(Func exceptionPre /// /// The type of the exception to handle. /// The PolicyBuilder instance, for fluent chaining. - public PolicyBuilder OrInner() where TException : Exception + public PolicyBuilder OrInner() + where TException : Exception { ExceptionPredicates.Add(PolicyBuilder.HandleInner(ex => ex is TException)); return this; @@ -169,7 +176,8 @@ public PolicyBuilder OrInner() where TException : Exception /// The type of the exception to handle. /// The exception predicate to filter the type of exception this policy can handle. /// The PolicyBuilder instance, for fluent chaining. - public PolicyBuilder OrInner(Func exceptionPredicate) where TException : Exception + public PolicyBuilder OrInner(Func exceptionPredicate) + where TException : Exception { ExceptionPredicates.Add(PolicyBuilder.HandleInner(ex => ex is TException texception && exceptionPredicate(texception))); return this; diff --git a/src/Polly/PolicyBuilder.cs b/src/Polly/PolicyBuilder.cs index 1304d1da739..875da928104 100644 --- a/src/Polly/PolicyBuilder.cs +++ b/src/Polly/PolicyBuilder.cs @@ -75,11 +75,11 @@ private PolicyBuilder() ResultPredicates = new ResultPredicates(); } - internal PolicyBuilder(Func resultPredicate) : this() => - OrResult(resultPredicate); + internal PolicyBuilder(Func resultPredicate) + : this() => OrResult(resultPredicate); - internal PolicyBuilder(ExceptionPredicate predicate) : this() => - ExceptionPredicates.Add(predicate); + internal PolicyBuilder(ExceptionPredicate predicate) + : this() => ExceptionPredicates.Add(predicate); internal PolicyBuilder(ExceptionPredicates exceptionPredicates) : this() => diff --git a/src/Polly/Polly.csproj b/src/Polly/Polly.csproj index e4a0c4388cf..fc36ee1af45 100644 --- a/src/Polly/Polly.csproj +++ b/src/Polly/Polly.csproj @@ -6,12 +6,12 @@ Library 70 true - $(NoWarn);IDE0011;SA1501;S103;IDE0055;SA1111;S3872;SA1127;SA1128;SA1402;SA1513;SA1414;S3215;S2955 - $(NoWarn);IDE1006;CA1062;S107;CA1068;S4039;SA1121;CA1000;CA1063;SA1113;CA1031;CA1051;CA1200 - $(NoWarn);SA1629;SA1612;CA2211;S2223;CA1032;CA1815;CA1816;S4457;SA1615;S109;SA1618;SA1407;CA1033 + $(NoWarn);IDE0011;SA1501;S103;IDE0055;SA1111;S3872;SA1402;SA1513;SA1414;S3215;S2955 + $(NoWarn);IDE1006;CA1062;S107;CA1068;S4039;SA1121;CA1000;CA1063;CA1031;CA1051 + $(NoWarn);SA1612;CA2211;S2223;CA1032;CA1815;CA1816;S4457;SA1615;S109;SA1618;CA1033 $(NoWarn);SA1515;S4023;CA1010;S2681;S3442;S3880;CA1064;SA1110;SA1203;SA1649;SA1625;SA1623;SA1118 $(NoWarn);S3253;S3971;S6605;CA1724;CA1716;SA1108;CA1710;S4049;S3246 - $(NoWarn);SA1805;SA1805;CA1805;CA1821 + $(NoWarn);CA1805;CA1821 $(NoWarn);RS0037; diff --git a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs index 7a5ef950006..dc33e21459a 100644 --- a/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs +++ b/src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs @@ -71,13 +71,13 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity) // Passing addNextTokenAtTicks merits one token 1 + // And any whole token tick intervals further each merit another. - -ticksTillAddNextToken / addTokenTickInterval; + (-ticksTillAddNextToken / addTokenTickInterval); // We mustn't exceed bucket capacity though. long tokensToAdd = Math.Min(bucketCapacity, tokensMissedAdding); // Work out when tokens would next be due to be added, if we add these tokens. - long newAddNextTokenAtTicks = currentAddNextTokenAtTicks + tokensToAdd * addTokenTickInterval; + long newAddNextTokenAtTicks = currentAddNextTokenAtTicks + (tokensToAdd * addTokenTickInterval); // But if we were way overdue refilling the bucket (there was inactivity for a while), that value would be out-of-date: the next time we add tokens must be at least addTokenTickInterval from now. newAddNextTokenAtTicks = Math.Max(newAddNextTokenAtTicks, now + addTokenTickInterval); diff --git a/src/Polly/RateLimit/RateLimitRejectedException.cs b/src/Polly/RateLimit/RateLimitRejectedException.cs index 6820473e7fc..85d38a2f78a 100644 --- a/src/Polly/RateLimit/RateLimitRejectedException.cs +++ b/src/Polly/RateLimit/RateLimitRejectedException.cs @@ -25,7 +25,8 @@ public class RateLimitRejectedException : ExecutionRejectedException /// Initializes a new instance of the class. /// /// The timespan after which the operation may be retried. - public RateLimitRejectedException(TimeSpan retryAfter) : this(retryAfter, DefaultMessage(retryAfter)) + public RateLimitRejectedException(TimeSpan retryAfter) + : this(retryAfter, DefaultMessage(retryAfter)) { } @@ -34,16 +35,16 @@ public RateLimitRejectedException(TimeSpan retryAfter) : this(retryAfter, Defaul /// /// The timespan after which the operation may be retried. /// The inner exception. - public RateLimitRejectedException(TimeSpan retryAfter, Exception innerException) : base(DefaultMessage(retryAfter), innerException) => - SetRetryAfter(retryAfter); + public RateLimitRejectedException(TimeSpan retryAfter, Exception innerException) + : base(DefaultMessage(retryAfter), innerException) => SetRetryAfter(retryAfter); /// /// Initializes a new instance of the class. /// /// The timespan after which the operation may be retried. /// The message. - public RateLimitRejectedException(TimeSpan retryAfter, string message) : base(message) => - SetRetryAfter(retryAfter); + public RateLimitRejectedException(TimeSpan retryAfter, string message) + : base(message) => SetRetryAfter(retryAfter); /// /// Initializes a new instance of the class. @@ -51,8 +52,8 @@ public RateLimitRejectedException(TimeSpan retryAfter, string message) : base(me /// The message. /// The timespan after which the operation may be retried. /// The inner exception. - public RateLimitRejectedException(TimeSpan retryAfter, string message, Exception innerException) : base(message, innerException) => - SetRetryAfter(retryAfter); + public RateLimitRejectedException(TimeSpan retryAfter, string message, Exception innerException) + : base(message, innerException) => SetRetryAfter(retryAfter); private static string DefaultMessage(TimeSpan retryAfter) => $"The operation has been rate-limited and should be retried after {retryAfter}"; @@ -69,7 +70,8 @@ private void SetRetryAfter(TimeSpan retryAfter) /// /// The information. /// The context. - protected RateLimitRejectedException(SerializationInfo info, StreamingContext context) : base(info, context) + protected RateLimitRejectedException(SerializationInfo info, StreamingContext context) + : base(info, context) { } #endif diff --git a/src/Polly/Registry/IConcurrentPolicyRegistry.cs b/src/Polly/Registry/IConcurrentPolicyRegistry.cs index 9ed179e31f1..0d43ba3993c 100644 --- a/src/Polly/Registry/IConcurrentPolicyRegistry.cs +++ b/src/Polly/Registry/IConcurrentPolicyRegistry.cs @@ -13,7 +13,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// The policy to store in the registry. /// The type of Policy. /// True if Policy was added. False otherwise. - bool TryAdd(TKey key, TPolicy policy) where TPolicy : IsPolicy; + bool TryAdd(TKey key, TPolicy policy) + where TPolicy : IsPolicy; /// /// Removes the policy stored under the specified from the registry. @@ -26,7 +27,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// /// The type of Policy. /// True if the policy is successfully removed. Otherwise false. - bool TryRemove(TKey key, out TPolicy policy) where TPolicy : IsPolicy; + bool TryRemove(TKey key, out TPolicy policy) + where TPolicy : IsPolicy; /// /// Compares the existing policy for the specified key with a specified policy, and if they are equal, updates the policy with a third value. @@ -36,7 +38,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// The policy that replaces the value for the specified , if the comparison results in equality. /// The policy that is compared to the existing policy at the specified key. /// - bool TryUpdate(TKey key, TPolicy newPolicy, TPolicy comparisonPolicy) where TPolicy : IsPolicy; + bool TryUpdate(TKey key, TPolicy newPolicy, TPolicy comparisonPolicy) + where TPolicy : IsPolicy; /// /// Adds a policy with the provided key and policy to the registry @@ -47,7 +50,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// The policy for the key. This will be either the existing policy for the key if the /// key is already in the registry, or the new policy for the key as returned by policyFactory /// if the key was not in the registry. - TPolicy GetOrAdd(TKey key, Func policyFactory) where TPolicy : IsPolicy; + TPolicy GetOrAdd(TKey key, Func policyFactory) + where TPolicy : IsPolicy; /// /// Adds a key/policy pair to the registry @@ -57,7 +61,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// the value to be added, if the key does not already exist /// The policy for the key. This will be either the existing policy for the key if the /// key is already in the registry, or the new policy if the key was not in the registry. - TPolicy GetOrAdd(TKey key, TPolicy policy) where TPolicy : IsPolicy; + TPolicy GetOrAdd(TKey key, TPolicy policy) + where TPolicy : IsPolicy; /// /// Adds a key/policy pair to the registry if the key does not already @@ -70,7 +75,8 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// based on the key's existing value /// The new policy for the key. This will be either be the result of addPolicyFactory (if the key was /// absent) or the result of updatePolicyFactory (if the key was present). - TPolicy AddOrUpdate(TKey key, Func addPolicyFactory, Func updatePolicyFactory) where TPolicy : IsPolicy; + TPolicy AddOrUpdate(TKey key, Func addPolicyFactory, Func updatePolicyFactory) + where TPolicy : IsPolicy; /// /// Adds a key/policy pair to the registry if the key does not already @@ -83,5 +89,6 @@ public interface IConcurrentPolicyRegistry : IPolicyRegistry /// the key's existing value /// The new policy for the key. This will be either be addPolicy (if the key was /// absent) or the result of updatePolicyFactory (if the key was present). - TPolicy AddOrUpdate(TKey key, TPolicy addPolicy, Func updatePolicyFactory) where TPolicy : IsPolicy; + TPolicy AddOrUpdate(TKey key, TPolicy addPolicy, Func updatePolicyFactory) + where TPolicy : IsPolicy; } diff --git a/src/Polly/Registry/IPolicyRegistry.cs b/src/Polly/Registry/IPolicyRegistry.cs index 5ba13b4d559..e9fd8360328 100644 --- a/src/Polly/Registry/IPolicyRegistry.cs +++ b/src/Polly/Registry/IPolicyRegistry.cs @@ -14,7 +14,8 @@ public interface IPolicyRegistry : IReadOnlyPolicyRegistry /// The type of Policy. /// is null. /// A Policy with same already exists. - void Add(TKey key, TPolicy policy) where TPolicy : IsPolicy; + void Add(TKey key, TPolicy policy) + where TPolicy : IsPolicy; /// /// Gets or sets the with the specified key. diff --git a/src/Polly/Registry/IReadOnlyPolicyRegistry.cs b/src/Polly/Registry/IReadOnlyPolicyRegistry.cs index 56f68fadd9e..477a2fa388b 100644 --- a/src/Polly/Registry/IReadOnlyPolicyRegistry.cs +++ b/src/Polly/Registry/IReadOnlyPolicyRegistry.cs @@ -22,7 +22,8 @@ public interface IReadOnlyPolicyRegistry : IEnumerableThe type of Policy. /// The policy stored in the registry under the given key. /// is null. - TPolicy Get(TKey key) where TPolicy : IsPolicy; + TPolicy Get(TKey key) + where TPolicy : IsPolicy; /// /// Gets the policy stored under the provided key, casting to . @@ -35,7 +36,8 @@ public interface IReadOnlyPolicyRegistry : IEnumerable /// The type of Policy. /// True if Policy exists for the provided Key. False otherwise. - bool TryGet(TKey key, out TPolicy policy) where TPolicy : IsPolicy; + bool TryGet(TKey key, out TPolicy policy) + where TPolicy : IsPolicy; /// /// Total number of policies in the registry. diff --git a/src/Polly/Registry/PolicyRegistry.cs b/src/Polly/Registry/PolicyRegistry.cs index e9a5106c403..fb57d7da094 100644 --- a/src/Polly/Registry/PolicyRegistry.cs +++ b/src/Polly/Registry/PolicyRegistry.cs @@ -51,8 +51,8 @@ private ConcurrentDictionary ThrowIfNotConcurrentImplementatio /// The type of Policy. /// is null. /// A Policy with same already exists. - public void Add(string key, TPolicy policy) where TPolicy : IsPolicy => - _registry.Add(key, policy); + public void Add(string key, TPolicy policy) + where TPolicy : IsPolicy => _registry.Add(key, policy); /// /// Adds a policy with the provided key and policy to the registry. @@ -61,7 +61,8 @@ public void Add(string key, TPolicy policy) where TPolicy : IsPolicy => /// The policy to store in the registry. /// The type of Policy. /// True if Policy was added. False otherwise. - public bool TryAdd(string key, TPolicy policy) where TPolicy : IsPolicy + public bool TryAdd(string key, TPolicy policy) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -90,8 +91,8 @@ public IsPolicy this[string key] /// The policy stored in the registry under the given key. /// is null. /// The given key was not present in the registry. - public TPolicy Get(string key) where TPolicy : IsPolicy => - (TPolicy) _registry[key]; + public TPolicy Get(string key) + where TPolicy : IsPolicy => (TPolicy) _registry[key]; /// /// Gets the policy stored under the provided key, casting to . @@ -104,7 +105,8 @@ public TPolicy Get(string key) where TPolicy : IsPolicy => /// /// The type of Policy. /// True if Policy exists for the provided Key. False otherwise. - public bool TryGet(string key, out TPolicy policy) where TPolicy : IsPolicy + public bool TryGet(string key, out TPolicy policy) + where TPolicy : IsPolicy { bool got = _registry.TryGetValue(key, out IsPolicy value); policy = got ? (TPolicy)value : default; @@ -146,7 +148,8 @@ public bool Remove(string key) => /// /// The type of Policy. /// True if the policy is successfully removed. Otherwise false. - public bool TryRemove(string key, out TPolicy policy) where TPolicy : IsPolicy + public bool TryRemove(string key, out TPolicy policy) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -166,7 +169,8 @@ public bool TryRemove(string key, out TPolicy policy) where TPolicy : I /// if the value with was equal to and /// replaced with ; otherwise, . /// - public bool TryUpdate(string key, TPolicy newPolicy, TPolicy comparisonPolicy) where TPolicy : IsPolicy + public bool TryUpdate(string key, TPolicy newPolicy, TPolicy comparisonPolicy) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -182,7 +186,8 @@ public bool TryUpdate(string key, TPolicy newPolicy, TPolicy comparison /// The policy for the key. This will be either the existing policy for the key if the /// key is already in the registry, or the new policy for the key as returned by policyFactory /// if the key was not in the registry. - public TPolicy GetOrAdd(string key, Func policyFactory) where TPolicy : IsPolicy + public TPolicy GetOrAdd(string key, Func policyFactory) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -197,7 +202,8 @@ public TPolicy GetOrAdd(string key, Func policyFactory /// the policy to be added, if the key does not already exist /// The policy for the key. This will be either the existing policy for the key if the /// key is already in the registry, or the new policy if the key was not in the registry. - public TPolicy GetOrAdd(string key, TPolicy policy) where TPolicy : IsPolicy + public TPolicy GetOrAdd(string key, TPolicy policy) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -215,7 +221,8 @@ public TPolicy GetOrAdd(string key, TPolicy policy) where TPolicy : IsP /// based on the key's existing value /// The new policy for the key. This will be either be the result of addPolicyFactory (if the key was /// absent) or the result of updatePolicyFactory (if the key was present). - public TPolicy AddOrUpdate(string key, Func addPolicyFactory, Func updatePolicyFactory) where TPolicy : IsPolicy + public TPolicy AddOrUpdate(string key, Func addPolicyFactory, Func updatePolicyFactory) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); @@ -233,7 +240,8 @@ public TPolicy AddOrUpdate(string key, Func addPolicyF /// the key's existing value /// The new policy for the key. This will be either be addPolicy (if the key was /// absent) or the result of updatePolicyFactory (if the key was present). - public TPolicy AddOrUpdate(string key, TPolicy addPolicy, Func updatePolicyFactory) where TPolicy : IsPolicy + public TPolicy AddOrUpdate(string key, TPolicy addPolicy, Func updatePolicyFactory) + where TPolicy : IsPolicy { var registry = ThrowIfNotConcurrentImplementation(); diff --git a/src/Polly/Timeout/TimeoutEngine.cs b/src/Polly/Timeout/TimeoutEngine.cs index b49f6ee1f7a..150adf32c22 100644 --- a/src/Polly/Timeout/TimeoutEngine.cs +++ b/src/Polly/Timeout/TimeoutEngine.cs @@ -34,8 +34,8 @@ internal static TResult Implementation( SystemClock.CancelTokenAfter(timeoutCancellationTokenSource, timeout); actionTask = Task.Run(() => - action(context, combinedToken) // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException. - , combinedToken); // cancellation token here only allows Task.Run() to not begin the passed delegate at all, if cancellation occurs prior to invoking the delegate. + action(context, combinedToken), // cancellation token here allows the user delegate to react to cancellation: possibly clear up; then throw an OperationCanceledException. + combinedToken); // cancellation token here only allows Task.Run() to not begin the passed delegate at all, if cancellation occurs prior to invoking the delegate. try { actionTask.Wait(timeoutCancellationTokenSource.Token); // cancellation token here cancels the Wait() and causes it to throw, but does not cancel actionTask. We use only timeoutCancellationTokenSource.Token here, not combinedToken. If we allowed the user's cancellation token to cancel the Wait(), in this pessimistic scenario where the user delegate may not observe that cancellation, that would create a no-longer-observed task. That task could in turn later fault before completing, risking an UnobservedTaskException. diff --git a/src/Polly/Utilities/TimedLock.cs b/src/Polly/Utilities/TimedLock.cs index d42f5aa5113..9eb0ecd940b 100644 --- a/src/Polly/Utilities/TimedLock.cs +++ b/src/Polly/Utilities/TimedLock.cs @@ -84,7 +84,8 @@ private class Sentinel internal class LockTimeoutException : Exception { - public LockTimeoutException() : base("Timeout waiting for lock") + public LockTimeoutException() + : base("Timeout waiting for lock") { } } diff --git a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs index 42911a81b9f..fb73ee5b2ba 100644 --- a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerAsyncSpecs.cs @@ -313,7 +313,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); await breaker.Awaiting(x => x.RaiseExceptionAsync()) .Should().ThrowAsync(); @@ -404,7 +404,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) .Should().ThrowAsync() @@ -491,7 +491,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); var ex = await breaker.Awaiting(x => x.RaiseExceptionAsync()) .Should().ThrowAsync() @@ -1318,7 +1318,7 @@ await breaker.Awaiting(x => x.RaiseExceptionAsync()) // 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 - var anotherWindowDuration = samplingDuration.Seconds / 2d + 1; + var anotherWindowDuration = (samplingDuration.Seconds / 2d) + 1; SystemClock.UtcNow = () => time.AddSeconds(anotherWindowDuration); await breaker.Awaiting(x => x.RaiseExceptionAsync()) diff --git a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs index d2140938f8b..5b6fe1621e0 100644 --- a/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs +++ b/test/Polly.Specs/CircuitBreaker/AdvancedCircuitBreakerSpecs.cs @@ -313,7 +313,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); breaker.Invoking(x => x.RaiseException()) .Should().Throw(); @@ -404,7 +404,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); breaker.Invoking(x => x.RaiseException()) .Should().Throw() @@ -491,7 +491,7 @@ public void Should_open_circuit_with_the_last_raised_exception_if_failure_thresh // 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); + SystemClock.UtcNow = () => time.AddSeconds((samplingDuration.Seconds / 2d) + 1); breaker.Invoking(x => x.RaiseException()) .Should().Throw() @@ -1318,8 +1318,8 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with // 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 - var anotherwindowDuration = samplingDuration.Seconds / 2d + 1; - SystemClock.UtcNow = () => time.AddSeconds(anotherwindowDuration); + var anotherWindowDuration = (samplingDuration.Seconds / 2d) + 1; + SystemClock.UtcNow = () => time.AddSeconds(anotherWindowDuration); breaker.Invoking(x => x.RaiseException()) .Should().Throw(); @@ -1331,7 +1331,7 @@ public void Should_halfopen_circuit_after_the_specified_duration_has_passed_with // 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); + SystemClock.UtcNow = () => time.Add(durationOfBreak).AddSeconds(anotherWindowDuration); // duration has passed, circuit now half open breaker.CircuitState.Should().Be(CircuitState.HalfOpen); diff --git a/test/Polly.Specs/Polly.Specs.csproj b/test/Polly.Specs/Polly.Specs.csproj index c69d15f0651..ad52e9b1835 100644 --- a/test/Polly.Specs/Polly.Specs.csproj +++ b/test/Polly.Specs/Polly.Specs.csproj @@ -9,7 +9,7 @@ [Polly]* true $(NoWarn);S103;S104;CA2000;IDE0011;SA1600;SA1204;SA1602;CA2008;CA1806;CA2201; - $(NoWarn);S3878;CA1030;S4144;S3717;SA1129;SA1407;S1402;SA1649;SA1402;S4056;CA1031 + $(NoWarn);S3878;CA1030;S4144;S3717;SA1129;S1402;SA1649;SA1402;S4056;CA1031 $(NoWarn);S2184;