From 6c100ff7599a7005d2bf6d636df4da0ce6f8b9d4 Mon Sep 17 00:00:00 2001 From: Paul Schneider Date: Sun, 12 Jul 2026 06:01:42 +0100 Subject: [PATCH] use an available port for authority --- src/Yavsc.Org.Tests/WebServerFixture.cs | 29 ++++++++++++++++++++----- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/Yavsc.Org.Tests/WebServerFixture.cs b/src/Yavsc.Org.Tests/WebServerFixture.cs index 69629b8e..a623bc9e 100644 --- a/src/Yavsc.Org.Tests/WebServerFixture.cs +++ b/src/Yavsc.Org.Tests/WebServerFixture.cs @@ -8,6 +8,8 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using System.Net; +using System.Net.Sockets; using Yavsc; using Yavsc.Extensions; using Yavsc.Interfaces; @@ -39,7 +41,9 @@ namespace Yavsc.Org.Tests; [CollectionDefinition("Yavsc Server")] public sealed class WebServerFixture : WebHostFixture { - protected override int HttpsPort => 5101; + private static readonly int _httpsPort = GetAvailableLoopbackPort(); + + protected override int HttpsPort => _httpsPort; private static IConfiguration? _sharedConfiguration; private static SiteSettings? _sharedSiteSettings; @@ -66,6 +70,8 @@ public sealed class WebServerFixture : WebHostFixture protected override WebApplication BuildApp(WebApplicationBuilder builder) { + var authority = $"https://localhost:{_httpsPort}"; + // WebApplication.CreateBuilder defaults WebRootPath to // {ContentRoot}/wwwroot. The test assembly runs from // src/Yavsc.Org.Tests/bin/.../, which has no wwwroot of @@ -83,11 +89,7 @@ public sealed class WebServerFixture : WebHostFixture ["Smtp:Port"] = "465", ["Smtp:UserName"] = "test-user", ["Smtp:Password"] = "test-pass", - // Kestrel test config: override the default port from - // WebApplication.CreateBuilder() so that the test host - // binds to the same port as the production host would. - ["Kestrel:Endpoints:Http:Url"] = "http://localhost:5100", - ["Kestrel:Endpoints:Https:Url"] = builder.Configuration["Site:Authority"] ?? "https://localhost:5101" + ["Site:Authority"] = authority }); Configuration = builder.Configuration; @@ -283,4 +285,19 @@ public sealed class WebServerFixture : WebHostFixture TestingUser = dbContext.Users.FirstOrDefault(u => u.UserName == testingUserName); } } + + private static int GetAvailableLoopbackPort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + + try + { + return ((IPEndPoint)listener.LocalEndpoint).Port; + } + finally + { + listener.Stop(); + } + } }