Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added HTTP Wait Strategry #700

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/api/wait_strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,30 @@ _ = new TestcontainersBuilder<TestcontainersContainer>()
.Build();
```

## Wait until Http Request is successful

You can wait for an HttpResponseCode or even compare the Response Body of an http request to an exposed port on your container

```csharp
_ = new TestcontainersBuilder<TestcontainersContainer>()
.WithWaitStrategy(
Wait.ForUnixContainer()
.UntilHttp() //Default to a GET to localhost:80 [ExposedfromContianer] Expecting 200 with no response body Validation
.Build();
```
or with Options
```csharp
_ = new TestcontainersBuilder<TestcontainersContainer>()
.WithWaitStrategy(
Wait.ForUnixContainer()
.UntilHttp( options => {
options.Port = [YourServiceExposedPort];
options.Path = [RequestPath];
options.Method = [HttpRequestMethod];
options.ExpectedResponseCodes = new(){ HttpStatusCode.OK, HttpStatusCode.Accepted };
})
.Build();
```

[docker-docs-healthcheck]: https://docs.docker.com/engine/reference/builder/#healthcheck

44 changes: 44 additions & 0 deletions src/Testcontainers/Configurations/UntilHttpOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#nullable enable
namespace DotNet.Testcontainers.Configurations
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security;

/// <summary>
/// Configured the Request and Response Behaviour of the UntilHttp Wait
/// </summary>
public class UntilHttpOptions
{
public UntilHttpOptions()
{
this.Method = HttpMethod.Get;
this.Path = "/";
this.Host = "localhost";
this.Port = 80;
this.ExpectedResponseCodes = new() { HttpStatusCode.OK };
this.TimeOut = TimeSpan.FromMinutes(1);
this.RequestDelay = 1;
this.MaxRetries = 10;
}

public HttpMethod Method { get; set; }
public string Path { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public HashSet<HttpStatusCode> ExpectedResponseCodes { get; set; }
public string? ExpectedOutput { get; set; }
public HttpContent? RequestContent { get; set; }
public bool UseSecure { get; set; }
public SecureString? AuthString { get; set; }
public bool UseAuth { get; set; }
public TimeSpan TimeOut { get; set; }
public bool ValidateContent { get; set; }
public double RequestDelay { get; set; }
public int MaxRetries { get; set; }

public Uri Uri => new($"{(this.UseSecure ? "https" : "http")}://{this.Host}:{this.Port}{this.Path}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ public interface IWaitForContainerOS
[PublicAPI]
IWaitForContainerOS UntilContainerIsHealthy(long failingStreak = 20);

/// <summary>
/// Waits until Http Requests returns Ok
/// </summary>
/// <returns>A configured instance of <see cref="IWaitForContainerOS" />.</returns>
[PublicAPI]
IWaitForContainerOS UntilHttpSuccess(Action<UntilHttpOptions>? action = null);

/// <summary>
/// Returns a collection with all configured wait strategies.
/// </summary>
Expand Down
84 changes: 84 additions & 0 deletions src/Testcontainers/Configurations/WaitStrategies/UntilHttp.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
namespace DotNet.Testcontainers.Configurations
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DotNet.Testcontainers.Containers;
using Microsoft.Extensions.Logging;

public class UntilHttp : IWaitUntil
{
private readonly UntilHttpOptions Options;
private int RetryCount = 0;

public UntilHttp(string path)
{
this.Options = new() { Path = path, Method = HttpMethod.Get };
}

public UntilHttp(UntilHttpOptions options)
{
this.Options = options;
}

public async Task<bool> Until(ITestcontainersContainer testcontainers, ILogger logger)
{

try
{
var mappedPort = testcontainers.GetMappedPublicPort(this.Options.Port);
this.Options.Port = mappedPort;
var client = new HttpClient();
var message = new HttpRequestMessage(this.Options.Method, this.Options.Uri);
if (this.Options.RequestContent is not null && (this.Options.Method == HttpMethod.Post || this.Options.Method == HttpMethod.Put))
{
message.Content = this.Options.RequestContent;
}

if (this.Options.UseAuth && this.Options.AuthString is not null)
{
message.Headers.Authorization = AuthenticationHeaderValue.Parse(this.Options.AuthString.ToString());
}

var sendTask = Task.Run(async () =>
{
HttpResponseMessage response = null;
while (response is null || !this.Options.ExpectedResponseCodes.Contains(response.StatusCode))
{
response = await client.SendAsync(message);
if (++this.RetryCount > this.Options.MaxRetries)
{
throw new TimeoutException($"Http Wait Failed {this.Options.MaxRetries} Times");
}

if (!this.Options.ExpectedResponseCodes.Contains(response.StatusCode))
{
Thread.Sleep(TimeSpan.FromSeconds(this.Options.RequestDelay));
}
}
return response;
});
var completed = sendTask.Wait(this.Options.TimeOut);
if (!completed)
{
throw new TimeoutException($"Http Wait Failed Timed Out after {this.Options.TimeOut}");
}

var responseContent = await sendTask.Result.Content.ReadAsStringAsync();
return !this.Options.ValidateContent || Regex.Match(this.Options.ExpectedOutput, responseContent).Success;
}
catch (Exception)
{
if (++this.RetryCount > this.Options.MaxRetries)
{
throw new TimeoutException($"Http Wait Failed {this.Options.MaxRetries} Times");
}

return false;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ public virtual IWaitForContainerOS UntilContainerIsHealthy(long failingStreak =
return this.AddCustomWaitStrategy(new UntilContainerIsHealthy(failingStreak));
}

/// <inheritdoc />
public IWaitForContainerOS UntilHttpSuccess(Action<UntilHttpOptions> action = null)
{
var options = new UntilHttpOptions();
action?.Invoke(options);
var httpWait = new UntilHttp(options);
return this.AddCustomWaitStrategy(httpWait);
}

/// <inheritdoc />
public IEnumerable<IWaitUntil> Build()
{
Expand Down
1 change: 1 addition & 0 deletions src/Testcontainers/Testcontainers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Configurations>Debug;Release</Configurations>
<Platforms>AnyCPU</Platforms>
<RootNamespace>DotNet.Testcontainers</RootNamespace>
<LangVersion>10</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" />
Expand Down