You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have configured a retry based pipeline with Polly.
// Using Polly for retry logicprivatereadonlyResiliencePipeline_retryPipeline=new ResiliencePipelineBuilder {TimeProvider=timeProvider}.AddRetry(new RetryStrategyOptions
{ShouldHandle=new PredicateBuilder().Handle<ConditionalCheckFailedException>(),Delay= TimeSpan.FromMilliseconds(_backoffFactor),MaxRetryAttempts=_maxAttempts-1,// Linear backoff increases the delay each time by the backoff factorBackoffType= DelayBackoffType.Linear,OnRetry=onRetryArguments =>{ logger.LogWarning("Failed to acquire lock. Retrying. {@LogContext}",new{ onRetryArguments });return ValueTask.CompletedTask;}}).Build();
Which I execute using
// Attempt to store the lock with backoff retry LockResultresult=await _retryPipeline.ExecuteAsync(async _ =>await AttemptLockStorageAsync(lockId, expiryMilliseconds,attempts++),
cancellationTokenSource.Token);
When unit testing, I find that I have to add a Task.Delay(1) in order for Polly to perform the retries
// ActFunc<Task<DistributedLock>>func=async()=>{Task<DistributedLock>result= _distributedLockService.AcquireLockAsync(lockId);for(inti=1;i <= 4;i++){ _timeProvider.Advance(TimeSpan.FromMilliseconds(1000*i+1));await Task.Delay(1);}returnawait result;};// Assert// We expect that we should be able to attempt 5 full times, rather than getting a TaskCancelledException.(await func.Should().ThrowAsync<TimeoutException>()).WithMessage($"Could not acquire lock {lockId}. Attempted 5 times.");
Why is the Task.Delay necessary?
Edit
TimeProvider provided to the SUT via the primary constructor.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have configured a retry based pipeline with Polly.
Which I execute using
When unit testing, I find that I have to add a
Task.Delay(1)
in order for Polly to perform the retriesWhy is the
Task.Delay
necessary?Edit
TimeProvider provided to the SUT via the primary constructor.
FakeTimer is provided in the unit test constructor
You can answer here as well if you prefer
https://stackoverflow.com/questions/77876331/why-is-task-delay1-necessary-to-advance-clock-when-unit-testing-with-net-time
Beta Was this translation helpful? Give feedback.
All reactions