Skip to content

Commit

Permalink
Fix S6608/IDE1006/SA1414/CA1508 warnings (#1935)
Browse files Browse the repository at this point in the history
- Fix S6608/IDE1006/SA1414/CA1508 warnings in Polly.Specs project.
- Use PascalCase in named tuples and fix SA1316 warnings from change.
  • Loading branch information
baranyaimate committed Jan 27, 2024
1 parent 0064b4d commit 19b5e73
Show file tree
Hide file tree
Showing 23 changed files with 475 additions and 476 deletions.
3 changes: 1 addition & 2 deletions eng/analyzers/Stylecop.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
"maintainabilityRules": {
},
"namingRules": {
"tupleElementNameCasing": "camelCase"
},
"readabilityRules": {
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion src/Polly/RateLimit/IRateLimiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ internal interface IRateLimiter
/// Returns whether the execution is permitted; if not, returns what <see cref="TimeSpan"/> should be waited before retrying.
/// <remarks>Calling this method consumes an execution permit if one is available: a caller receiving a return value true should make an execution.</remarks>
/// </summary>
(bool permitExecution, TimeSpan retryAfter) PermitExecution();
(bool PermitExecution, TimeSpan RetryAfter) PermitExecution();
}
2 changes: 1 addition & 1 deletion src/Polly/RateLimit/LockFreeTokenBucketRateLimiter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public LockFreeTokenBucketRateLimiter(TimeSpan onePer, long bucketCapacity)
/// <summary>
/// Returns whether the execution is permitted; if not, returns what <see cref="TimeSpan"/> should be waited before retrying.
/// </summary>
public (bool permitExecution, TimeSpan retryAfter) PermitExecution()
public (bool PermitExecution, TimeSpan RetryAfter) PermitExecution()
{
while (true)
{
Expand Down
222 changes: 111 additions & 111 deletions test/Polly.Specs/Caching/CacheAsyncSpecs.cs

Large diffs are not rendered by default.

226 changes: 113 additions & 113 deletions test/Polly.Specs/Caching/CacheSpecs.cs

Large diffs are not rendered by default.

156 changes: 78 additions & 78 deletions test/Polly.Specs/Caching/CacheTResultAsyncSpecs.cs

Large diffs are not rendered by default.

156 changes: 78 additions & 78 deletions test/Polly.Specs/Caching/CacheTResultSpecs.cs

Large diffs are not rendered by default.

18 changes: 9 additions & 9 deletions test/Polly.Specs/Caching/GenericCacheProviderAsyncSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,49 @@ 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<Context, string, Exception> onError = (_, _, _) => { onErrorCalled = true; };

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();

ResultPrimitive result = await cache.ExecuteAsync(async _ =>
{
await TaskHelper.EmptyTask;
return ResultPrimitive.Substitute;
}, new Context(operationKey));
}, new Context(OperationKey));

onErrorCalled.Should().BeFalse();
}

[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();

(await cache.ExecuteAsync(async _ =>
{
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() =>
Expand Down
18 changes: 9 additions & 9 deletions test/Polly.Specs/Caching/GenericCacheProviderSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,43 @@ 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<Context, string, Exception> onError = (_, _, _) => { onErrorCalled = true; };

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();
}

[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() =>
Expand Down
6 changes: 3 additions & 3 deletions test/Polly.Specs/Caching/ResultTtlSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Context, dynamic?, Ttl> func = (context, result) => context.OperationKey == specialKey ? new Ttl(TimeSpan.Zero) : new Ttl(result!.Ttl);
Func<Context, dynamic?, Ttl> func = (context, result) => context.OperationKey == SpecialKey ? new Ttl(TimeSpan.Zero) : new Ttl(result!.Ttl);

ResultTtl<dynamic> ttlStrategy = new ResultTtl<dynamic>(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);
}
}
22 changes: 11 additions & 11 deletions test/Polly.Specs/Helpers/Bulkhead/AnnotatedOutputHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,30 +21,30 @@ public Item(string format, object[] args)
public object[] Args { get; }
}

private readonly ConcurrentDictionary<Guid, Item> items = new();
private readonly ConcurrentDictionary<Guid, Item> _items = new();

private readonly object[] noArgs = Array.Empty<object>();
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));
}
18 changes: 9 additions & 9 deletions test/Polly.Specs/Helpers/Bulkhead/TraceableAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class TraceableAction : IDisposable
private readonly ITestOutputHelper _testOutputHelper;

private readonly TaskCompletionSource<object?> _tcsProxyForRealWork = new();
private readonly CancellationTokenSource CancellationSource = new();
private readonly CancellationTokenSource _cancellationSource = new();
private readonly AutoResetEvent _statusChanged;

private TraceableActionStatus _status;
Expand Down Expand Up @@ -41,15 +41,15 @@ public void SignalStateChange()

public Task ExecuteOnBulkhead(BulkheadPolicy bulkhead) =>
ExecuteThroughSyncBulkheadOuter(
() => bulkhead.Execute(_ => ExecuteThroughSyncBulkheadInner(), CancellationSource.Token));
() => bulkhead.Execute(_ => ExecuteThroughSyncBulkheadInner(), _cancellationSource.Token));

public Task ExecuteOnBulkhead<TResult>(BulkheadPolicy<TResult?> bulkhead) =>
ExecuteThroughSyncBulkheadOuter(
() => bulkhead.Execute(_ =>
{
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)
Expand Down Expand Up @@ -123,15 +123,15 @@ 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<TResult>(AsyncBulkheadPolicy<TResult?> bulkhead) =>
ExecuteThroughAsyncBulkheadOuter(
() => bulkhead.ExecuteAsync(async _ =>
{
await ExecuteThroughAsyncBulkheadInner();
return default;
}, CancellationSource.Token));
}, _cancellationSource.Token));

public Task ExecuteThroughAsyncBulkheadOuter(Func<Task> executeThroughBulkheadInner)
{
Expand Down Expand Up @@ -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)
{
Expand All @@ -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();
}
6 changes: 3 additions & 3 deletions test/Polly.Specs/Helpers/Caching/StubCacheKeyStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
/// </summary>
internal class StubCacheKeyStrategy : ICacheKeyStrategy
{
private readonly Func<Context, string> strategy;
private readonly Func<Context, string> _strategy;

public StubCacheKeyStrategy(Func<Context, string> strategy) =>
this.strategy = strategy;
_strategy = strategy;

public string GetCacheKey(Context context) =>
strategy(context);
_strategy(context);
}
12 changes: 6 additions & 6 deletions test/Polly.Specs/Helpers/Caching/StubCacheProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,27 @@ public CacheItem(object? value, Ttl ttl)
public readonly object? Value;
}

private readonly Dictionary<string, CacheItem> cachedValues = [];
private readonly Dictionary<string, CacheItem> _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);
}
}

return (false, null);
}

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

Expand Down
6 changes: 3 additions & 3 deletions test/Polly.Specs/Helpers/Caching/StubErroringCacheProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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
Expand Down
Loading

0 comments on commit 19b5e73

Please sign in to comment.