using System.Net;
using System.Net.Http.Json;
using Khaemhat.Web.Hosting;
using Microsoft.AspNetCore.Builder;
namespace Khaemhat.Web.Tests.Hosting;
///
/// Starts the real host on a free loopback port (no test-host package: SPEC ยง1.2) and calls it over HTTP.
///
[TestClass]
public sealed class HostTests
{
private static WebApplication? _app;
private static HttpClient? _client;
[ClassInitialize]
public static async Task StartAsync(TestContext context)
{
_app = KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--environment", "Production"]);
await _app.StartAsync(context.CancellationToken);
_client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) };
}
[ClassCleanup]
public static async Task StopAsync()
{
_client?.Dispose();
if (_app is not null)
{
await _app.StopAsync();
await _app.DisposeAsync();
}
}
[TestMethod]
[DataRow("/health/live", "live")]
[DataRow("/health/ready", "ready")]
public async Task HealthProbes_AnswerOk(string path, string body)
{
using var response = await Client.GetAsync(new Uri(path, UriKind.Relative));
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.AreEqual(body, await response.Content.ReadAsStringAsync());
}
[TestMethod]
public async Task Health_ReportsStatusAndVersion()
{
var report = await Client.GetFromJsonAsync(new Uri("/health", UriKind.Relative));
Assert.IsNotNull(report);
Assert.AreEqual("ok", report.Status);
Assert.IsTrue(report.Live);
Assert.IsTrue(report.Ready);
Assert.IsFalse(string.IsNullOrEmpty(report.Version));
}
[TestMethod]
public async Task HomePage_ShowsTheUnderConstructionPage()
{
var html = await Client.GetStringAsync(new Uri("/", UriKind.Relative));
StringAssert.Contains(html, "Khaemhat");
StringAssert.Contains(html, "in costruzione");
StringAssert.Contains(html, "lang=\"it\"");
}
[TestMethod]
public async Task UnknownPage_AnswersNotFound()
{
using var response = await Client.GetAsync(new Uri("/does-not-exist", UriKind.Relative));
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
}
private static HttpClient Client => _client ?? throw new InvalidOperationException("Host not started.");
}