Skip to content

Commit

Permalink
Accept more types of failures when retrying HTTP requests in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lbussell committed Nov 15, 2024
1 parent c680888 commit 02e88c3
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions tests/Microsoft.DotNet.Docker.Tests/TestScenarios/WebScenario.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,15 @@ public static async Task<HttpResponseMessage> GetHttpResponseFromContainerAsync(
const int RetryAttempts = 4;
const int RetryDelaySeconds = 3;

if (!string.IsNullOrEmpty(pathAndQuery))
{
pathAndQuery = "/" + pathAndQuery;
}

// Can't use localhost when running inside containers or Windows.
string url = !Config.IsRunningInContainer && DockerHelper.IsLinuxContainerModeEnabled
? $"http://localhost:{dockerHelper.GetContainerHostPort(containerName, containerPort)}/{pathAndQuery}"
: $"http://{dockerHelper.GetContainerAddress(containerName)}:{containerPort}/{pathAndQuery}";
? $"http://localhost:{dockerHelper.GetContainerHostPort(containerName, containerPort)}{pathAndQuery}"
: $"http://{dockerHelper.GetContainerAddress(containerName)}:{containerPort}{pathAndQuery}";

ResiliencePipeline pipeline = new ResiliencePipelineBuilder()
.AddRetry(new RetryStrategyOptions()
Expand All @@ -84,10 +89,10 @@ public static async Task<HttpResponseMessage> GetHttpResponseFromContainerAsync(
Delay = TimeSpan.FromSeconds(RetryDelaySeconds),

// If the container is still starting up, it will refuse connections until it's ready.
// Otherwise, stop retrying immediately.
// If it crashed, stop retrying immediately.
ShouldHandle = new PredicateBuilder()
.Handle<HttpRequestException>(exception =>
DockerHelper.ContainerIsRunning(containerName) && exception.Message.Contains("Connection refused")),
DockerHelper.ContainerIsRunning(containerName)),
})
.Build();

Expand All @@ -101,8 +106,15 @@ public static async Task<HttpResponseMessage> GetHttpResponseFromContainerAsync(
try
{
result = await pipeline.ExecuteAsync(async cancellationToken =>
await client.GetAsync(url, cancellationToken));
outputHelper.WriteLine($"HTTP {result.StatusCode}\n{await result.Content.ReadAsStringAsync()}");
{
outputHelper.WriteLine($"Sending request: GET {url}");
return await client.GetAsync(url, cancellationToken);
});

outputHelper.WriteLine($"""
Response: HTTP {result.StatusCode}
Content: {await result.Content.ReadAsStringAsync()}
""");

// Store response in local that will not be disposed
HttpResponseMessage returnResult = result;
Expand Down

0 comments on commit 02e88c3

Please sign in to comment.