From a42c0913d223dd74dc15a2a97900cfcd84a94105 Mon Sep 17 00:00:00 2001 From: ZLoo Date: Mon, 22 Jul 2024 21:41:19 +0300 Subject: [PATCH] Fix warning CA1062#AsyncCircuitBreakerPolicy --- .../AsyncCircuitBreakerPolicy.cs | 17 +++++++-- .../CircuitBreakerTResultAsyncSpecs.cs | 37 +++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs index 738a2a5af80..d9bb2545e41 100644 --- a/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs +++ b/src/Polly/CircuitBreaker/AsyncCircuitBreakerPolicy.cs @@ -3,7 +3,6 @@ /// /// A circuit-breaker policy that can be applied to async delegates. /// -#pragma warning disable CA1062 // Validate arguments of public methods public class AsyncCircuitBreakerPolicy : AsyncPolicy, ICircuitBreakerPolicy { internal readonly ICircuitController BreakerController; @@ -99,9 +98,18 @@ public void Reset() => /// [DebuggerStepThrough] - protected override Task ImplementationAsync(Func> action, Context context, CancellationToken cancellationToken, - bool continueOnCapturedContext) => - AsyncCircuitBreakerEngine.ImplementationAsync( + protected override Task ImplementationAsync( + Func> action, + Context context, + CancellationToken cancellationToken, + bool continueOnCapturedContext) + { + if (action is null) + { + throw new ArgumentNullException(nameof(action)); + } + + return AsyncCircuitBreakerEngine.ImplementationAsync( action, context, continueOnCapturedContext, @@ -109,4 +117,5 @@ protected override Task ImplementationAsync(Func> action = null!; + PolicyBuilder policyBuilder = new PolicyBuilder(exception => exception); + + var exceptionsAllowedBeforeBreaking = 1; + var durationOfBreak = TimeSpan.Zero; + Action, CircuitState, TimeSpan, Context> onBreak = null!; + Action onReset = null!; + Action onHalfOpen = null!; + ICircuitController breakerController = new ConsecutiveCountCircuitController( + exceptionsAllowedBeforeBreaking, + durationOfBreak, + onBreak, + onReset, + onHalfOpen); + + var instance = Activator.CreateInstance( + typeof(AsyncCircuitBreakerPolicy), + flags, + null, + [policyBuilder, breakerController], + null)!; + var instanceType = instance.GetType(); + var methods = instanceType.GetMethods(flags); + var methodInfo = methods.First(method => method is { Name: "ImplementationAsync", ReturnType.Name: "Task`1" }); + + var func = () => methodInfo.Invoke(instance, [action, new Context(), CancellationToken.None, false]); + + var exceptionAssertions = func.Should().Throw(); + exceptionAssertions.And.Message.Should().Be("Exception has been thrown by the target of an invocation."); + exceptionAssertions.And.InnerException.Should().BeOfType() + .Which.ParamName.Should().Be("action"); + } + [Fact] public async Task Should_be_able_to_handle_a_duration_of_timespan_maxvalue() {