Skip to content

Commit

Permalink
feat(#715): Add HttpWaitStrategy (#717)
Browse files Browse the repository at this point in the history
Co-authored-by: Nuwan Sumihiran <[email protected]>
Co-authored-by: Alfred Neequaye <[email protected]>
Co-authored-by: Kevin Wittek <[email protected]>
  • Loading branch information
4 people authored Dec 21, 2022
1 parent 768dfd2 commit 67bdd1d
Show file tree
Hide file tree
Showing 9 changed files with 322 additions and 22 deletions.
4 changes: 2 additions & 2 deletions docs/api/create_docker_container.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Instead of running the NGINX application, the following container configuration
```csharp
_ = new TestcontainersBuilder<TestcontainersContainer>()
.WithEntrypoint("nginx")
.WithCommand("-t")
.WithCommand("-t");
```

## Configure container app or service
Expand All @@ -29,7 +29,7 @@ _ = new TestcontainersBuilder<TestcontainersContainer>()
.WithEnvironment("ASPNETCORE_URLS", "https://+")
.WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Path", "/app/certificate.crt")
.WithEnvironment("ASPNETCORE_Kestrel__Certificates__Default__Password", "password")
.WithResourceMapping("certificate.crt", "/app/certificate.crt")
.WithResourceMapping("certificate.crt", "/app/certificate.crt");
```

`WithBindMount(string, string)` is another option to provide access to directories or files. It mounts a host directory or file into the container. Note, this does not follow our best practices. Host paths differ between environments and may not be available on every system or Docker setup, e.g. CI.
Expand Down
2 changes: 1 addition & 1 deletion docs/api/create_docker_image.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ _ = await new ImageFromDockerfileBuilder()
.WithName(Guid.NewGuid().ToString("D"))
.WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), "src")
.WithDockerfile("Dockerfile")
.Build()
.Build();
```

!!!tip
Expand Down
36 changes: 35 additions & 1 deletion docs/api/wait_strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,40 @@ _ = Wait.ForUnixContainer()
.AddCustomWaitStrategy(new MyCustomWaitStrategy());
```

## Wait until an HTTP(S) endpoint is available

You can choose to wait for an HTTP(S) endpoint to return a particular HTTP response status code or to match a predicate.
The default configuration tries to access the HTTP endpoint running inside the container. Chose `ForPort(ushort)` or `ForPath(string)` to adjust the endpoint or `UsingTls()` to switch to HTTPS.
When using `UsingTls()` port 443 is used as a default.
If your container exposes a different HTTPS port, make sure that the correct waiting port is configured accordingly.

### Waiting for HTTP response status code _200 OK_ on port 80

```csharp
_ = Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(request => request
.ForPath("/"));
```

### Waiting for HTTP response status code _200 OK_ or _301 Moved Permanently_

```csharp
_ = Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(request => request
.ForPath("/")
.ForStatusCode(HttpStatusCode.OK)
.ForStatusCode(HttpStatusCode.MovedPermanently));
```

### Waiting for the HTTP response status code to match a predicate

```csharp
_ = Wait.ForUnixContainer()
.UntilHttpRequestIsSucceeded(request => request
.ForPath("/")
.ForStatusCodeMatching(statusCode => statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices));
```

## Wait until the container is healthy

If the Docker image supports Dockers's [HEALTHCHECK][docker-docs-healthcheck] feature, like the following configuration:
Expand All @@ -24,7 +58,7 @@ You can leverage the container's health status as your wait strategy to report r

```csharp
_ = new TestcontainersBuilder<TestcontainersContainer>()
.WithWaitStrategy(Wait.ForUnixContainer().UntilContainerIsHealthy())
.WithWaitStrategy(Wait.ForUnixContainer().UntilContainerIsHealthy());
```

[docker-docs-healthcheck]: https://docs.docker.com/engine/reference/builder/#healthcheck
212 changes: 212 additions & 0 deletions src/Testcontainers/Configurations/WaitStrategies/HttpWaitStrategy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
namespace DotNet.Testcontainers.Configurations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using DotNet.Testcontainers.Containers;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;

/// <summary>
/// Wait for an HTTP(S) endpoint to return a particular status code.
/// </summary>
[PublicAPI]
public sealed class HttpWaitStrategy : IWaitUntil
{
private const ushort HttpPort = 80;

private const ushort HttpsPort = 443;

private readonly IDictionary<string, string> httpHeaders = new Dictionary<string, string>();

private readonly ISet<HttpStatusCode> httpStatusCodes = new HashSet<HttpStatusCode>();

private Predicate<HttpStatusCode> httpStatusCodePredicate;

private HttpMethod httpMethod;

private string schemeName;

private string pathValue;

private ushort? portNumber;

/// <summary>
/// Initializes a new instance of the <see cref="HttpWaitStrategy" /> class.
/// </summary>
public HttpWaitStrategy()
{
_ = this.WithMethod(HttpMethod.Get).UsingTls(false).ForPath("/");
}

/// <inheritdoc />
public async Task<bool> Until(ITestcontainersContainer testcontainers, ILogger logger)
{
// Java fall back to the first exposed port. The .NET wait strategies do not have access to the exposed port information yet.
var containerPort = this.portNumber.GetValueOrDefault(Uri.UriSchemeHttp.Equals(this.schemeName, StringComparison.OrdinalIgnoreCase) ? HttpPort : HttpsPort);

string host;

ushort port;

try
{
host = testcontainers.Hostname;
port = testcontainers.GetMappedPublicPort(containerPort);
}
catch
{
return false;
}

using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(this.httpMethod, new UriBuilder(this.schemeName, host, port, this.pathValue).Uri))
{
foreach (var httpHeader in this.httpHeaders)
{
httpRequestMessage.Headers.Add(httpHeader.Key, httpHeader.Value);
}

HttpResponseMessage httpResponseMessage;

try
{
httpResponseMessage = await httpClient.SendAsync(httpRequestMessage)
.ConfigureAwait(false);
}
catch
{
return false;
}

Predicate<HttpStatusCode> predicate;

if (!this.httpStatusCodes.Any() && this.httpStatusCodePredicate == null)
{
predicate = statusCode => HttpStatusCode.OK.Equals(statusCode);
}
else if (this.httpStatusCodes.Any() && this.httpStatusCodePredicate == null)
{
predicate = statusCode => this.httpStatusCodes.Contains(statusCode);
}
else if (this.httpStatusCodes.Any())
{
predicate = statusCode => this.httpStatusCodes.Contains(statusCode) || this.httpStatusCodePredicate.Invoke(statusCode);
}
else
{
predicate = this.httpStatusCodePredicate;
}

return predicate.Invoke(httpResponseMessage.StatusCode);
}
}
}

/// <summary>
/// Waits for the status code.
/// </summary>
/// <param name="statusCode">The expected status code.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy ForStatusCode(HttpStatusCode statusCode)
{
this.httpStatusCodes.Add(statusCode);
return this;
}

/// <summary>
/// Waits for the status code to pass the predicate.
/// </summary>
/// <param name="statusCodePredicate">The predicate to test the HTTP response against.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy ForStatusCodeMatching(Predicate<HttpStatusCode> statusCodePredicate)
{
this.httpStatusCodePredicate = statusCodePredicate;
return this;
}

/// <summary>
/// Waits for the path.
/// </summary>
/// <param name="path">The path to check.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy ForPath(string path)
{
this.pathValue = path;
return this;
}

/// <summary>
/// Waits for the port.
/// </summary>
/// <remarks>
/// <see cref="HttpPort" /> default value.
/// </remarks>
/// <param name="port">The port to check.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy ForPort(ushort port)
{
this.portNumber = port;
return this;
}

/// <summary>
/// Indicates that the HTTP request use HTTPS.
/// </summary>
/// <remarks>
/// <see cref="bool.FalseString" /> default value.
/// </remarks>
/// <param name="tlsEnabled">True if the HTTP request use HTTPS, otherwise false.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy UsingTls(bool tlsEnabled = true)
{
this.schemeName = tlsEnabled ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
return this;
}

/// <summary>
/// Indicates the HTTP request method.
/// </summary>
/// <remarks>
/// <see cref="HttpMethod.Get" /> default value.
/// </remarks>
/// <param name="method">The HTTP method.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy WithMethod(HttpMethod method)
{
this.httpMethod = method;
return this;
}

/// <summary>
/// Adds a custom HTTP header to the HTTP request.
/// </summary>
/// <param name="name">The HTTP header name.</param>
/// <param name="value">The HTTP header value.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy WithHeader(string name, string value)
{
this.httpHeaders.Add(name, value);
return this;
}

/// <summary>
/// Adds custom HTTP headers to the HTTP request.
/// </summary>
/// <param name="headers">A list of HTTP headers.</param>
/// <returns>A configured instance of <see cref="HttpWaitStrategy" />.</returns>
public HttpWaitStrategy WithHeaders(IReadOnlyDictionary<string, string> headers)
{
foreach (var header in headers)
{
_ = this.WithHeader(header.Key, header.Value);
}

return this;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ namespace DotNet.Testcontainers.Configurations
using JetBrains.Annotations;

/// <summary>
/// Collection of pre-configured strategies to wait until the Testcontainer is up and running.
/// Waits until all wait strategies are completed.
/// Collection of pre-configured strategies to wait until the container is up and running.
/// </summary>
[PublicAPI]
public interface IWaitForContainerOS
Expand Down Expand Up @@ -42,6 +41,14 @@ public interface IWaitForContainerOS
[PublicAPI]
IWaitForContainerOS UntilCommandIsCompleted(params string[] command);

/// <summary>
/// Waits until the port is available.
/// </summary>
/// <param name="port">The port to be checked.</param>
/// <returns>A configured instance of <see cref="IWaitForContainerOS" />.</returns>
[PublicAPI]
IWaitForContainerOS UntilPortIsAvailable(int port);

/// <summary>
/// Waits until the file exists.
/// </summary>
Expand Down Expand Up @@ -70,12 +77,12 @@ public interface IWaitForContainerOS
IWaitForContainerOS UntilOperationIsSucceeded(Func<bool> operation, int maxCallCount);

/// <summary>
/// Waits until the port is available.
/// Waits until the http request is completed successfully.
/// </summary>
/// <param name="port">The port to be checked.</param>
/// <param name="request">The http request to be executed.</param>
/// <returns>A configured instance of <see cref="IWaitForContainerOS" />.</returns>
[PublicAPI]
IWaitForContainerOS UntilPortIsAvailable(int port);
IWaitForContainerOS UntilHttpRequestIsSucceeded(Func<HttpWaitStrategy, HttpWaitStrategy> request);

/// <summary>
/// Waits until the container is healthy.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ public virtual IWaitForContainerOS UntilOperationIsSucceeded(Func<bool> operatio
}

/// <inheritdoc />
public virtual IWaitForContainerOS UntilContainerIsHealthy(long failingStreak = 20)
public virtual IWaitForContainerOS UntilHttpRequestIsSucceeded(Func<HttpWaitStrategy, HttpWaitStrategy> request)
{
return this.AddCustomWaitStrategy(request.Invoke(new HttpWaitStrategy()));
}

/// <inheritdoc />
public virtual IWaitForContainerOS UntilContainerIsHealthy(long failingStreak = 3)
{
return this.AddCustomWaitStrategy(new UntilContainerIsHealthy(failingStreak));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,19 @@ internal sealed class WaitForContainerUnix : WaitForContainerOS
/// <inheritdoc />
public override IWaitForContainerOS UntilCommandIsCompleted(string command)
{
this.AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command));
return this;
return this.AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command));
}

/// <inheritdoc />
public override IWaitForContainerOS UntilCommandIsCompleted(params string[] command)
{
this.AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command));
return this;
return this.AddCustomWaitStrategy(new UntilUnixCommandIsCompleted(command));
}

/// <inheritdoc />
public override IWaitForContainerOS UntilPortIsAvailable(int port)
{
this.AddCustomWaitStrategy(new UntilUnixPortIsAvailable(port));
return this;
return this.AddCustomWaitStrategy(new UntilUnixPortIsAvailable(port));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,19 @@ internal sealed class WaitForContainerWindows : WaitForContainerOS
/// <inheritdoc />
public override IWaitForContainerOS UntilCommandIsCompleted(string command)
{
this.AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command));
return this;
return this.AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command));
}

/// <inheritdoc />
public override IWaitForContainerOS UntilCommandIsCompleted(params string[] command)
{
this.AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command));
return this;
return this.AddCustomWaitStrategy(new UntilWindowsCommandIsCompleted(command));
}

/// <inheritdoc />
public override IWaitForContainerOS UntilPortIsAvailable(int port)
{
this.AddCustomWaitStrategy(new UntilWindowsPortIsAvailable(port));
return this;
return this.AddCustomWaitStrategy(new UntilWindowsPortIsAvailable(port));
}
}
}
Loading

0 comments on commit 67bdd1d

Please sign in to comment.