Files
slp-modular-cms/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs
T
SluijsensandClaude Sonnet 5.5 e53b318c31 Contactbeheer: berichten, schakelaar en tweelaagse poort voor het formulier
Beheerroutes zonder /admin-segment op contact-messages (lijst met spam apart en ongelezen-teller zonder spam, detail, status, verwijderen, opnieuw versturen met eigen limiet) en contact-settings voor de CMS-schakelaar, allemaal AdminOnly. Het formulier is alleen open als de hostvlag EN de CMS-schakelaar (standaard uit) aan staan; de hostvlag wordt eerst gecontroleerd zodat de database niet wordt aangeraakt. Bij uitgeschakelde host antwoorden de beheerroutes 404. OpenAPI-document bijgewerkt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 13:07:28 +01:00

165 lines
6.1 KiB
C#

using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Contact.Data;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>
/// Starts the real, composed SlpSoftware host (all modules, the real pipeline) against a real
/// MariaDB/MySQL. Like <c>SlpModularCms.Api.Tests</c> this needs a reachable database: set the
/// environment variable <c>ConnectionStrings__DefaultConnection</c> to a server you may create
/// databases on. Every factory uses its own freshly created database and drops it again.
/// To run only the pure unit tests use <c>--filter "FullyQualifiedName!~Pipeline"</c>.
/// </summary>
public class ContactHostFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
/// <summary>Whether the CMS switch (layer 2 of the gate) is turned on right after start-up.</summary>
protected virtual bool OpenCmsSwitch => false;
Task IAsyncLifetime.InitializeAsync() => OpenCmsSwitch ? OpenCmsSwitchAsync() : Task.CompletedTask;
Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask;
private async Task OpenCmsSwitchAsync()
{
_ = CreateClient(); // starts the host (migrates the contact tables)
await WithDb(async db =>
{
db.ContactSettings.Add(new Data.Entities.ContactSettings
{
Enabled = true,
UpdatedAt = DateTimeOffset.UtcNow,
UpdatedByUserId = Guid.NewGuid(),
});
await db.SaveChangesAsync();
return 0;
});
}
private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection";
private readonly Dictionary<string, string?> _settings;
private readonly string _databaseName = "SlpContactPipeline_" + Guid.NewGuid().ToString("N")[..12];
public ContactHostFactory(Dictionary<string, string?>? settings = null)
{
_settings = settings ?? [];
}
public static string BaseConnectionString =>
Environment.GetEnvironmentVariable(EnvironmentVariable)
?? throw new InvalidOperationException(
$"Set {EnvironmentVariable} to a MariaDB/MySQL server for the contact pipeline tests " +
"(or run the unit tests only with --filter \"FullyQualifiedName!~Pipeline\").");
public string ConnectionString =>
Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase)
? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase)
: $"{BaseConnectionString};Database={_databaseName}";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) =>
{
var all = new Dictionary<string, string?>
{
["ConnectionStrings:DefaultConnection"] = ConnectionString,
// Fresh availability answers instead of a cached one.
["Availability:StatusCacheSeconds"] = "0",
};
foreach (var (key, value) in _settings)
{
all[key] = value;
}
config.AddInMemoryCollection(all);
});
}
public async Task<T> WithDb<T>(Func<ContactDbContext, Task<T>> action)
{
await using var scope = Services.CreateAsyncScope();
return await action(scope.ServiceProvider.GetRequiredService<ContactDbContext>());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
using var scope = Services.CreateScope();
scope.ServiceProvider.GetRequiredService<ContactDbContext>().Database.EnsureDeleted();
}
catch
{
// Best effort clean-up of the throwaway database.
}
}
base.Dispose(disposing);
}
}
/// <summary>Host switch on, CMS switch ON: the contact form is fully open.</summary>
public sealed class EnabledContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Host switch on, CMS switch OFF (its default): the public routes are closed, the admin routes work.</summary>
public sealed class ClosedCmsSwitchContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
/// <summary>Host switch OFF (the default): the whole module is inactive.</summary>
public sealed class DisabledContactHostFactory() : ContactHostFactory;
/// <summary>Only the form policy is tight, so a token can still be fetched freely.</summary>
public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "2",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Only the token policy is tight.</summary>
public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "2",
})
{
protected override bool OpenCmsSwitch => true;
}
/// <summary>Only the resend policy is tight; the CMS switch is off.</summary>
public sealed class TightResendContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["RateLimiting:ContactResend:PermitLimit"] = "2",
});