Files
Khaemhat/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs
T
Alby96andClaude Opus 5.5 3401271483 feat: parties with radar, record, checks, VIES and demo data (#41)
Customers, suppliers, prospects and leads live in one parties archive
with a kind and a subject type (ADR 0029). A customer that also supplies
carries is_also_supplier, so it shows in both radars with one code.

- Three radars (/anagrafiche/clienti, /fornitori, /contatti) with search,
  quick filters and bulk disable/enable; the record has eight tabs
  (main data, addresses, contacts, terms, fiscal and SDI, banks, notes and
  attachments, history) on the MasterDataPage base.
- PartyService saves the whole record in one transaction, checks it with
  the fiscal pack (VAT number, tax code, recipient code, country), treats
  a duplicate VAT number or a consumer without tax code as warnings, fills
  the default recipient code, runs VIES after commit for EU companies, and
  converts prospects/leads (new customer code, old one kept as
  previous_code) and suppliers (become customers that also supply).
- Delete falls back to disable when the party is referenced.
- DemoPartiesSeeder adds 3 salespeople and 21 parties with fictitious but
  formally valid identifiers; SeedAsync now runs demo seeders when asked.
- Test host accepts service overrides so VIES can be stubbed.

Docs: ADR 0029, wiki Anagrafiche and demo data pages, regenerated data
model, CHANGELOG and STATUS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:06:33 +01:00

91 lines
4.2 KiB
C#

using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Khaemhat.Web.Hosting;
using Microsoft.AspNetCore.Builder;
namespace Khaemhat.Web.Tests.Hosting;
/// <summary>
/// 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.
/// </summary>
internal static partial class TestInstance
{
/// <summary>The super user of the test instances.</summary>
public const string SuperUser = "root";
/// <summary>Its first password (test value, valid for the password policy).</summary>
public const string SuperUserPassword = "Test-Password-2026";
/// <summary>The arguments that start an instance, plus <paramref name="extra"/>.</summary>
/// <param name="companyCode">The company created at the first start.</param>
/// <param name="extra">More arguments (they win over the defaults).</param>
/// <returns>The command line.</returns>
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];
}
/// <summary>Builds and starts an instance and waits until the start sequence is over.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The running instance, its address and the company code.</returns>
public static Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken) =>
StartAsync(null, cancellationToken);
/// <summary>Builds and starts an instance with changes to its services (fake external services).</summary>
/// <param name="configureServices">The changes.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The running instance, its address and the company code.</returns>
public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(
Action<Microsoft.Extensions.DependencyInjection.IServiceCollection>? 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);
}
}
/// <summary>The antiforgery token of a page with a form.</summary>
/// <param name="html">The page.</param>
/// <returns>The token.</returns>
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();
}