Skip to content
Merged
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
39 changes: 31 additions & 8 deletions test/CloudNative.CloudEvents.UnitTests/Http/HttpTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ namespace CloudNative.CloudEvents.Http.UnitTests;
/// </summary>
public abstract class HttpTestBase : IDisposable
{
private const int MaxListenerStartAttempts = 5;
internal static readonly DateTimeOffset SampleTimestamp = new DateTimeOffset(2018, 4, 5, 17, 31, 0, TimeSpan.Zero);
internal string ListenerAddress { get; }
internal string ListenerAddress { get; } = string.Empty;
internal const string TestContextHeader = "testcontext";
private readonly HttpListener listener;
private readonly Task processingTask;
Expand All @@ -28,14 +29,36 @@ public abstract class HttpTestBase : IDisposable

public HttpTestBase()
{
var port = GetRandomUnusedPort();
ListenerAddress = $"http://localhost:{port}/";
listener = new HttpListener()
Exception? lastException = null;

for (int attempt = 0; attempt < MaxListenerStartAttempts; attempt++)
{
var port = GetRandomUnusedPort();
var candidateListenerAddress = $"http://localhost:{port}/";
var candidateListener = new HttpListener
{
AuthenticationSchemes = AuthenticationSchemes.Anonymous,
Prefixes = { candidateListenerAddress }
};

try
{
candidateListener.Start();
listener = candidateListener;
ListenerAddress = candidateListenerAddress;
break;
}
catch (HttpListenerException e)
{
lastException = e;
}
}

if (listener == null)
{
AuthenticationSchemes = AuthenticationSchemes.Anonymous,
Prefixes = { ListenerAddress }
};
listener.Start();
throw new InvalidOperationException($"Unable to start HttpListener after {MaxListenerStartAttempts} attempts.", lastException);
}

processingTask = ProcessRequestsAsync();
}

Expand Down