Fase B2: ASF-testproject opgeheven; tests verhuisd naar de master-Api (geen testverlies, 18 -> 18)
Tellijst Api.AndreaSlopFotografie.Tests (18): - HostConfigurationTests (7) -> Api.Tests/SiteContractTests: NoIndex (beide sites), StrictSite+padbeleid, https-only site-origins, geen geheimen (beide), Contact uit + SiteId (beide), 'ASF zonder Master' (nu exacte modulelijst per csproj), mail uit (beide) + logo-urls. - HostPipelineTests (7) -> Api.Tests: AsfVariantPipelineTests (health, setup/status, 404+CSP+noindex, robots; master-host met de gedragsinstellingen van ASF) en OfferingsOnTheMasterHostTests (capabilities, banner 204, migraties == model). - ContactHostTests (4) -> Contact.Tests/Pipeline/SiteVariantContactTests (defaults dicht, poort + SiteId andreaslop, proxy bekend/onbekend). Nieuw: sitecontract per site (modules, Website:Mode, Program.cs dun), WebsiteModeSelection (modus eenmalig bepaald), Api.Tests serieel (MySql.Data). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
// The pipeline tests start several real hosts against MariaDB/MySQL. The MySql.Data driver keeps a static,
|
||||
// non-thread-safe dictionary that is touched while a connection is opened (MySql.Data.Common.Ssl.StartSSL), so opening
|
||||
// connections from several hosts at the same time can fail with "Operations that change non-concurrent collections
|
||||
// must have exclusive access". The suite is small and fast (the pure unit tests take about a second), so the whole
|
||||
// assembly runs serially instead of guessing which classes touch the driver.
|
||||
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
||||
@@ -0,0 +1,155 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// What every site (client project) must look like, checked from its files alone: the modules it references and
|
||||
/// the defaults it commits. The sites carry no logic of their own (all behaviour lives in Core and the modules and
|
||||
/// is tested against the master <c>SlpModularCms.Api</c> host), so a site can only go wrong in its composition:
|
||||
/// a module reference that is missing or too much, or an unsafe default. These tests need no database.
|
||||
/// </summary>
|
||||
public class SiteContractTests
|
||||
{
|
||||
public static IEnumerable<object[]> Sites() =>
|
||||
[
|
||||
[SiteFiles.SlpSoftware],
|
||||
[SiteFiles.AndreaSlopFotografie],
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public void TheMasterCms_ReferencesEveryModule()
|
||||
{
|
||||
SiteFiles.Modules("SlpModularCms.Api").Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Master", "Offerings"],
|
||||
"the master Api is the all-modules composition the CI builds and tests");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SlpSoftware_IsTheFullComposition()
|
||||
{
|
||||
SiteFiles.Modules(SiteFiles.SlpSoftware).Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Master", "Offerings"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AndreaSlopFotografie_HasEverythingExceptTheMasterModule()
|
||||
{
|
||||
// Not a master/slave setup: no Master module, so /System/capabilities does not list it.
|
||||
SiteFiles.Modules(SiteFiles.AndreaSlopFotografie).Should().BeEquivalentTo(
|
||||
["Availability", "Contact", "Identity", "Offerings"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Sites))]
|
||||
public void NoSiteReferencesAModuleTheMasterDoesNot(string site)
|
||||
{
|
||||
SiteFiles.Modules(site).Should().BeSubsetOf(SiteFiles.Modules("SlpModularCms.Api"),
|
||||
"a module that the CI does not build and test must not ship in a site");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(SiteFiles.SlpSoftware, "SpaFallback")]
|
||||
[InlineData(SiteFiles.AndreaSlopFotografie, "PrerenderedPages")]
|
||||
public void EachSite_ServesItsWebsiteTheRightWay(string site, string mode)
|
||||
{
|
||||
// Missing means SpaFallback (the host's default); Andrea's prerendered site must say so explicitly,
|
||||
// otherwise it would start as an SPA and answer 200 for every unknown path.
|
||||
var configured = SiteFiles.Committed(site)["Website:Mode"];
|
||||
(configured ?? "SpaFallback").Should().Be(mode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Sites))]
|
||||
public void WebsiteIsNoIndex_ByDefault(string site)
|
||||
{
|
||||
SiteFiles.Committed(site).GetValue<bool>("Website:NoIndex").Should().BeTrue(
|
||||
"indexing is switched on per environment, never by the committed defaults");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Sites))]
|
||||
public void NoSecretsAreCommitted(string site)
|
||||
{
|
||||
var config = SiteFiles.Committed(site);
|
||||
|
||||
config["JwtSettings:Secret"].Should().StartWith("<");
|
||||
config["ConnectionStrings:DefaultConnection"].Should().Contain("<db-password>");
|
||||
config["Identity:Setup:Token"].Should().BeNullOrEmpty();
|
||||
config["Observability:SentryDsn"].Should().BeNullOrEmpty();
|
||||
config.GetSection("ForwardedHeaders:KnownProxies").Get<string[]>().Should().BeNullOrEmpty(
|
||||
"the proxy address is environment configuration");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(SiteFiles.SlpSoftware, "slpsoftware")]
|
||||
[InlineData(SiteFiles.AndreaSlopFotografie, "andreaslop")]
|
||||
public void Contact_IsOffByDefault_ForTheRightSite_WithNoRecipientOrCaptchaSecretCommitted(string site, string siteId)
|
||||
{
|
||||
var config = SiteFiles.Committed(site);
|
||||
|
||||
config.GetValue<bool>("Contact:Enabled").Should().BeFalse();
|
||||
config["Contact:SiteId"].Should().Be(siteId);
|
||||
config.GetValue<bool>("Contact:Captcha:Enabled").Should().BeFalse();
|
||||
config["Contact:RecipientEmail"].Should().BeNullOrEmpty("the address comes from the environment only");
|
||||
config["Contact:Captcha:Secret"].Should().BeNullOrEmpty();
|
||||
config["Contact:Captcha:SiteKey"].Should().BeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Sites))]
|
||||
public void Mail_IsOffByDefault_AndNoCredentialIsCommitted(string site)
|
||||
{
|
||||
var config = SiteFiles.Committed(site);
|
||||
|
||||
config["Email:Smtp:Host"].Should().BeNullOrEmpty("mail is switched on per environment");
|
||||
config["Email:Smtp:Username"].Should().BeNullOrEmpty();
|
||||
config["Email:Smtp:Password"].Should().BeNullOrEmpty();
|
||||
config["Email:FromAddress"].Should().NotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AndreaSlopFotografie_DefaultPolicyIsStrictSite_AndAdminApiHealthStayStrict()
|
||||
{
|
||||
var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie);
|
||||
|
||||
config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite");
|
||||
var rules = config.GetSection("SecurityHeaders:PathPolicies").GetChildren()
|
||||
.ToDictionary(c => c["PathPrefix"]!, c => c["Policy"]!);
|
||||
rules.Should().Contain(new KeyValuePair<string, string>("/admin", "Strict"))
|
||||
.And.Contain(new KeyValuePair<string, string>("/api/v1", "Strict"))
|
||||
.And.Contain(new KeyValuePair<string, string>("/health", "Strict"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AndreaSlopFotografie_SiteOrigins_AreHttpsOnly_AndNotAddedToTheAdminLists()
|
||||
{
|
||||
var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie);
|
||||
var site = config.GetSection("SecurityHeaders:AllowedSiteScriptOrigins").Get<string[]>()!
|
||||
.Concat(config.GetSection("SecurityHeaders:AllowedSiteConnectOrigins").Get<string[]>()!);
|
||||
|
||||
site.Should().NotBeEmpty().And.OnlyContain(o => o.StartsWith("https://"));
|
||||
config.GetSection("SecurityHeaders:AllowedScriptOrigins").Get<string[]>().Should().BeEmpty();
|
||||
config.GetSection("SecurityHeaders:AllowedConnectOrigins").Get<string[]>().Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AndreaSlopFotografie_MailBrandingPointsAtTheAdminAssets()
|
||||
{
|
||||
var config = SiteFiles.Committed(SiteFiles.AndreaSlopFotografie);
|
||||
|
||||
config["Email:LogoUrl"].Should().Be("/admin/brand-logo-mail.png");
|
||||
config["Email:LogoDarkUrl"].Should().Be("/admin/brand-logo-on-dark.png");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Sites))]
|
||||
public void EachSiteProgram_IsAThinComposition(string site)
|
||||
{
|
||||
// The site's Program.cs may only compose: no mode, module or option decisions in code.
|
||||
var program = File.ReadAllText(Path.Combine(SiteFiles.SourceRoot(), site, "Program.cs"));
|
||||
|
||||
program.Should().Contain("CmsHost.ConfigureServices").And.Contain("CmsHost.ConfigurePipeline");
|
||||
program.Should().NotContain("WebsiteMode.", "the mode is chosen with Website:Mode in appsettings.json");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the site (client) projects in the repository without referencing or building them. The sites are thin
|
||||
/// compositions (a Program.cs, a list of modules and an appsettings.json); what these tests check about them is
|
||||
/// read from those files.
|
||||
/// </summary>
|
||||
internal static class SiteFiles
|
||||
{
|
||||
public const string SlpSoftware = "SlpModularCms.Api.SlpSoftware";
|
||||
public const string AndreaSlopFotografie = "SlpModularCms.Api.AndreaSlopFotografie";
|
||||
|
||||
/// <summary>The directory that holds the project folders (<c>src</c>).</summary>
|
||||
public static string SourceRoot()
|
||||
{
|
||||
// Walks up from the test output and from the working directory, so it also works when the build output
|
||||
// is redirected elsewhere in the repository (for example with --artifacts-path).
|
||||
foreach (var start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() })
|
||||
{
|
||||
for (var dir = new DirectoryInfo(start); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "SlpModularCms.Api", "appsettings.json")))
|
||||
return dir.FullName;
|
||||
if (File.Exists(Path.Combine(dir.FullName, "src", "SlpModularCms.Api", "appsettings.json")))
|
||||
return Path.Combine(dir.FullName, "src");
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("The src folder with the SlpModularCms.* projects was not found above the test output.");
|
||||
}
|
||||
|
||||
public static string AppSettingsPath(string site) => Path.Combine(SourceRoot(), site, "appsettings.json");
|
||||
|
||||
public static string CsprojPath(string site) => Path.Combine(SourceRoot(), site, site + ".csproj");
|
||||
|
||||
/// <summary>The committed appsettings.json of a site, exactly as deployed (no environment on top).</summary>
|
||||
public static IConfigurationRoot Committed(string site)
|
||||
{
|
||||
File.Exists(AppSettingsPath(site)).Should().BeTrue($"{site} must have an appsettings.json");
|
||||
return new ConfigurationBuilder().AddJsonFile(AppSettingsPath(site), optional: false).Build();
|
||||
}
|
||||
|
||||
/// <summary>The module projects a site references, as short names (<c>Offerings</c>, <c>Identity</c>, ...).</summary>
|
||||
public static IReadOnlySet<string> Modules(string site)
|
||||
{
|
||||
var doc = System.Xml.Linq.XDocument.Load(CsprojPath(site));
|
||||
return doc.Descendants("ProjectReference")
|
||||
.Select(e => (string?)e.Attribute("Include") ?? string.Empty)
|
||||
.Select(include => Path.GetFileNameWithoutExtension(include.Replace('\\', '/')))
|
||||
.Where(name => name.StartsWith("SlpModularCms.Modules.", StringComparison.Ordinal))
|
||||
.Select(name => name["SlpModularCms.Modules.".Length..])
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The site's own settings that shape behaviour (never connection strings or secrets), as in-memory key/values
|
||||
/// to put on top of the master host's configuration. That is how a test runs the master composition "as" a site.
|
||||
/// </summary>
|
||||
public static Dictionary<string, string?> BehaviourSettings(string site)
|
||||
{
|
||||
string[] sections =
|
||||
[
|
||||
"Website", "SecurityHeaders", "Contact", "Email", "Identity", "ForwardedHeaders", "Cors", "App", "RateLimiting",
|
||||
];
|
||||
var committed = Committed(site);
|
||||
return committed.AsEnumerable()
|
||||
.Where(kv => kv.Value is not null && sections.Any(s => kv.Key.StartsWith(s + ":", StringComparison.Ordinal)))
|
||||
.ToDictionary(kv => kv.Key, kv => kv.Value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Net;
|
||||
using FluentAssertions;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Modules.Offerings.Data;
|
||||
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The master host with the behaviour settings of Andrea Slop Fotografie on top (website mode, security headers,
|
||||
/// contact and mail defaults). The sites have no logic of their own, so this is how a site's behaviour is tested
|
||||
/// without building the site project: same code, the site's committed configuration.
|
||||
/// </summary>
|
||||
public class AsfVariantFactory : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.UseEnvironment("Development");
|
||||
// Each setting both as a host setting (visible while the services are registered) and as configuration.
|
||||
var settings = SiteFiles.BehaviourSettings(SiteFiles.AndreaSlopFotografie);
|
||||
foreach (var (key, value) in settings)
|
||||
{
|
||||
builder.UseSetting(key, value);
|
||||
}
|
||||
|
||||
builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(settings));
|
||||
}
|
||||
}
|
||||
|
||||
public class AsfVariantPipelineTests : IClassFixture<AsfVariantFactory>
|
||||
{
|
||||
private readonly AsfVariantFactory _factory;
|
||||
|
||||
public AsfVariantPipelineTests(AsfVariantFactory factory) => _factory = factory;
|
||||
|
||||
[Fact]
|
||||
public async Task Health_IsReachable()
|
||||
{
|
||||
(await _factory.CreateClient().GetAsync("/health")).IsSuccessStatusCode.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetupStatus_ReportsNoTokenRequired_WhenNoneConfigured()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/Setup/status");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await response.Content.ReadAsStringAsync()).Should().Contain("\"tokenRequired\":false");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnknownWebsitePath_Returns404_WithTheSiteSecurityHeaders_AndNoIndex()
|
||||
{
|
||||
// Website:Mode=PrerenderedPages comes from the site's settings: an SPA would answer 200 here.
|
||||
var response = await _factory.CreateClient().GetAsync("/some-page-that-does-not-exist");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
response.Headers.GetValues("Content-Security-Policy").Single()
|
||||
.Should().Contain("https://analytics.slpsoftware.nl");
|
||||
response.Headers.GetValues("X-Robots-Tag").Single().Should().Be("noindex, nofollow");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RobotsTxt_DisallowsEverything_OnTheDefaultNoIndexConfiguration()
|
||||
{
|
||||
var body = await _factory.CreateClient().GetStringAsync("/robots.txt");
|
||||
|
||||
body.Should().Contain("Disallow: /");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheVariantReallyUsesTheSitesSettings()
|
||||
{
|
||||
var config = _factory.Services.GetRequiredService<IConfiguration>();
|
||||
|
||||
config["Website:Mode"].Should().Be("PrerenderedPages");
|
||||
config["Contact:SiteId"].Should().Be("andreaslop");
|
||||
config["SecurityHeaders:DefaultPolicy"].Should().Be("StrictSite");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Offerings behaviour that needs the real, migrated database (Offerings is part of the master host).</summary>
|
||||
public class OfferingsOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
|
||||
{
|
||||
private readonly ApiWebApplicationFactory _factory;
|
||||
|
||||
public OfferingsOnTheMasterHostTests(ApiWebApplicationFactory factory) => _factory = factory;
|
||||
|
||||
[Fact]
|
||||
public async Task Capabilities_ListEveryModule()
|
||||
{
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var modules = doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).ToList();
|
||||
modules.Should().Contain(["Identity", "Availability", "Offerings", "Contact", "Master"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OfferingBanner_Is204_WhenNoneIsActive_AndOfferingsAreListed_OnAMigratedDatabase()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
(await client.GetAsync("/api/v1/offerings/banner")).StatusCode.Should().Be(HttpStatusCode.NoContent);
|
||||
(await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OfferingsMigrations_MatchTheModel()
|
||||
{
|
||||
_ = _factory.CreateClient(); // starts the host and migrates
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<OfferingsDbContext>();
|
||||
|
||||
db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user