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

feat(#715): Add HttpWaitStrategy #717

Merged
merged 8 commits into from
Dec 21, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
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);
HofmeisterAn marked this conversation as resolved.
Show resolved Hide resolved

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));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
namespace DotNet.Testcontainers.Tests.Unit.Configurations
{
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Commons;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Containers;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

public sealed class WaitUntilHttpRequestIsSucceededTest
{
public static IEnumerable<object[]> GetHttpWaitStrategies()
{
yield return new object[] { new HttpWaitStrategy() };
yield return new object[] { new HttpWaitStrategy().ForStatusCode(HttpStatusCode.OK) };
yield return new object[] { new HttpWaitStrategy().ForStatusCodeMatching(statusCode => HttpStatusCode.OK.Equals(statusCode)) };
yield return new object[] { new HttpWaitStrategy().ForStatusCode(HttpStatusCode.Moved).ForStatusCodeMatching(statusCode => HttpStatusCode.OK.Equals(statusCode)) };
}

[Theory]
[MemberData(nameof(GetHttpWaitStrategies))]
public async Task HttpWaitStrategyShouldSucceeded(HttpWaitStrategy httpWaitStrategy)
{
// Given
const ushort httpPort = 80;

var container = new TestcontainersBuilder<TestcontainersContainer>()
.WithImage(CommonImages.Nginx)
.WithPortBinding(httpPort, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(httpPort))
.Build();

// When
await container.StartAsync()
.ConfigureAwait(false);

var succeeded = await httpWaitStrategy.Until(container, NullLogger.Instance)
.ConfigureAwait(false);

// Then
Assert.True(succeeded);
}
}
}