-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestingRetryMechanisms.cs
More file actions
63 lines (48 loc) · 2.41 KB
/
Copy pathTestingRetryMechanisms.cs
File metadata and controls
63 lines (48 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#if NET
using Microsoft.Extensions.Http;
using Polly;
using Polly.Extensions.Http;
using Polly.Retry;
using static TestableHttpClient.Responses;
namespace TestableHttpClient.IntegrationTests;
public sealed class TestingRetryMechanisms
{
[Fact]
public async Task TestingRetryPolicies()
{
// Create TestableHttpMessageHandler as usual.
using TestableHttpMessageHandler testableHttpMessageHandler = new();
testableHttpMessageHandler.RespondWith(
Sequenced(
StatusCode(HttpStatusCode.ServiceUnavailable),
StatusCode(HttpStatusCode.ServiceUnavailable),
StatusCode(HttpStatusCode.OK)
));
// Configure the retry policy
AsyncRetryPolicy<HttpResponseMessage> policy = HttpPolicyExtensions.HandleTransientHttpError().RetryAsync(2);
using PolicyHttpMessageHandler retryPolicyHandler = new(policy);
using HttpClient client = testableHttpMessageHandler.CreateClient(retryPolicyHandler);
// Make a request, which should pass
HttpResponseMessage response = await client.GetAsync("https://httpbin.com/get", TestContext.Current.CancellationToken);
// Now use the assertions to make sure the request was actually made multiple times.
_ = testableHttpMessageHandler.ShouldHaveMadeRequestsTo("https://httpbin.com/get", 3);
// Make sure the response is correct
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public void SimulateTimeoutDoesNotRetry()
{
// Create TestableHttpMessageHandler as usual.
using TestableHttpMessageHandler testableHttpMessageHandler = new();
testableHttpMessageHandler.RespondWith(Timeout());
// Configure the retry policy
AsyncRetryPolicy<HttpResponseMessage> policy = HttpPolicyExtensions.HandleTransientHttpError().RetryAsync(2);
using PolicyHttpMessageHandler retryPolicyHandler = new(policy);
using HttpClient client = testableHttpMessageHandler.CreateClient(retryPolicyHandler);
Task<HttpResponseMessage> task = client.GetAsync("https://httpbin.com/get", TestContext.Current.CancellationToken);
Assert.True(task.IsCanceled);
// Now use the assertions to make sure the request was actually made once, so polly didn't run.
_ = testableHttpMessageHandler.ShouldHaveMadeRequestsTo("https://httpbin.com/get", 1);
}
}
#endif