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;
///
/// Starts the real, composed SlpSoftware host (all modules, the real pipeline) against a real
/// MariaDB/MySQL. Like SlpModularCms.Api.Tests this needs a reachable database: set the
/// environment variable ConnectionStrings__DefaultConnection 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 --filter "FullyQualifiedName!~Pipeline".
///
public class ContactHostFactory : WebApplicationFactory, IAsyncLifetime
{
/// Whether the CMS switch (layer 2 of the gate) is turned on right after start-up.
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 _settings;
private readonly string _databaseName = "SlpContactPipeline_" + Guid.NewGuid().ToString("N")[..12];
public ContactHostFactory(Dictionary? 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
{
["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 WithDb(Func> action)
{
await using var scope = Services.CreateAsyncScope();
return await action(scope.ServiceProvider.GetRequiredService());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
using var scope = Services.CreateScope();
scope.ServiceProvider.GetRequiredService().Database.EnsureDeleted();
}
catch
{
// Best effort clean-up of the throwaway database.
}
}
base.Dispose(disposing);
}
}
/// Host switch on, CMS switch ON: the contact form is fully open.
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;
}
/// Host switch on, CMS switch OFF (its default): the public routes are closed, the admin routes work.
public sealed class ClosedCmsSwitchContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
});
/// Host switch OFF (the default): the whole module is inactive.
public sealed class DisabledContactHostFactory() : ContactHostFactory;
/// Only the form policy is tight, so a token can still be fetched freely.
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;
}
/// Only the token policy is tight.
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;
}
/// Only the resend policy is tight; the CMS switch is off.
public sealed class TightResendContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["RateLimiting:ContactResend:PermitLimit"] = "2",
});