using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Titano.Server.Configuration;
using Titano.Server.Hosting;
using Titano.Testing;
namespace Titano.Server.Tests;
/// In-process Kestrel on ephemeral ports with temporary archive/data folders (BRIEF ยง20.1).
public sealed class TestServer : IAsyncDisposable
{
private readonly WebApplication _app;
private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https)
{
_app = app;
Options = options;
HttpBase = http;
HttpsBase = https;
Client = new HttpClient { BaseAddress = http, Timeout = TimeSpan.FromSeconds(30) };
}
public ServerOptions Options { get; }
public Uri HttpBase { get; }
public Uri? HttpsBase { get; }
public HttpClient Client { get; }
public IServiceProvider Services => _app.Services;
public static async Task StartAsync(TestContext context, Action? configure = null)
{
var root = context.CreateTempDirectory("server");
var options = new ServerOptions
{
DataPath = Path.Combine(root, "data"),
ArchivePath = Path.Combine(root, "archive"),
HttpPort = 0,
HttpsPort = 0,
TlsMode = TlsMode.Auto,
Database = DatabaseKind.Sqlite,
};
Directory.CreateDirectory(options.ArchivePath);
configure?.Invoke(options);
var app = ServerHost.Build(options, []);
await app.StartAsync(context.Cancellation);
var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses
.Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal)))
.ToList();
var http = addresses.First(a => a.Scheme == "http");
var https = addresses.FirstOrDefault(a => a.Scheme == "https");
return new TestServer(app, options, http, https);
}
public async ValueTask DisposeAsync()
{
Client.Dispose();
await _app.StopAsync();
await _app.DisposeAsync();
}
}