using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Khaemhat.Web.Hosting;
using Microsoft.AspNetCore.Builder;
namespace Khaemhat.Web.Tests.Hosting;
///
/// The variables of a test instance: in-memory SQLite databases with unique names (tests run in one process), a fresh
/// secret key, a super user, one company and licences in test mode.
///
internal static partial class TestInstance
{
/// The super user of the test instances.
public const string SuperUser = "root";
/// Its first password (test value, valid for the password policy).
public const string SuperUserPassword = "Test-Password-2026";
/// The arguments that start an instance, plus .
/// The company created at the first start.
/// More arguments (they win over the defaults).
/// The command line.
public static string[] Arguments(out string companyCode, params string[] extra)
{
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(4));
companyCode = "T" + id;
string[] defaults =
[
"--urls", "http://127.0.0.1:0",
"--environment", "Production",
"--KHAEMHAT_SYSTEM_DB=sqlite://memory/system_" + id,
"--KHAEMHAT_SECRET_KEY=" + Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
"--KHAEMHAT_DATA_DIR=" + Path.Combine(Path.GetTempPath(), "khaemhat-tests", id),
"--KHAEMHAT_SUPERUSER=" + SuperUser,
"--KHAEMHAT_SUPERUSER_PASSWORD=" + SuperUserPassword,
"--KHAEMHAT_COMPANY_CODE=" + companyCode,
"--KHAEMHAT_LICENSE_MODE=test",
];
return [.. defaults, .. extra];
}
/// Builds and starts an instance and waits until the start sequence is over.
/// Cancellation.
/// The running instance, its address and the company code.
public static Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken) =>
StartAsync(null, cancellationToken);
/// Builds and starts an instance with changes to its services (fake external services).
/// The changes.
/// Cancellation.
/// The running instance, its address and the company code.
public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(
Action? configureServices, CancellationToken cancellationToken)
{
var app = KhaemhatApp.Build(Arguments(out var company), configureServices);
await app.StartAsync(cancellationToken);
var address = new Uri(app.Urls.First());
using var client = new HttpClient { BaseAddress = address };
var deadline = DateTime.UtcNow.AddSeconds(60);
while (true)
{
using var response = await client.GetAsync(new Uri("/health/ready", UriKind.Relative), cancellationToken);
if (response.StatusCode == HttpStatusCode.OK)
{
return (app, address, company);
}
if (DateTime.UtcNow > deadline || await response.Content.ReadAsStringAsync(cancellationToken) == "failed")
{
throw new InvalidOperationException("The test instance did not become ready.");
}
await Task.Delay(100, cancellationToken);
}
}
/// The antiforgery token of a page with a form.
/// The page.
/// The token.
public static string AntiforgeryToken(string html)
{
var match = TokenPattern().Match(html);
return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value) : throw new InvalidOperationException("No antiforgery token in the page.");
}
[GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")]
private static partial Regex TokenPattern();
}