Hero: tekst-only regio voor een hero zonder slides (SLP), e2e-test op de echte ASF-build, bijgewerkte aannames en contract

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 16:54:37 +01:00
co-authored by Claude Sonnet 5.5
parent b749902f4a
commit d3525c1316
7 changed files with 271 additions and 16 deletions
@@ -0,0 +1,140 @@
using System.Net;
using System.Text.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Hero.Data;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Api.Tests;
/// <summary>
/// Runs the real master host with ASF settings over the REAL build of the ASF website (its <c>dist/client</c>), with the
/// hero of ASF's seed made through the module's services. Optional: it only runs when <c>ASF_WEB_DIR</c> points at the
/// <c>web</c> folder of the ASF website repository (with a build in <c>dist/client</c>); otherwise it does nothing.
/// With <c>HERO_E2E_OUT</c> set it also writes the served page and the API answer there, so they can be compared
/// with the website's own renderer.
/// </summary>
public sealed class AsfSiteFactory : AsfVariantFactory, IDisposable
{
public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-asf-site-" + Guid.NewGuid().ToString("N"));
public string MediaDirectory { get; } = Path.Combine(Path.GetTempPath(), "slp-asf-media-" + Guid.NewGuid().ToString("N"));
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
var web = Environment.GetEnvironmentVariable("ASF_WEB_DIR");
if (!string.IsNullOrEmpty(web))
{
CopyDirectory(Path.Combine(web, "dist", "client"), Path.Combine(WebRoot, "web"));
}
builder.UseWebRoot(WebRoot);
builder.ConfigureAppConfiguration((_, config) =>
config.AddInMemoryCollection(new Dictionary<string, string?> { ["Media:Directory"] = MediaDirectory, ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" }));
}
private static void CopyDirectory(string from, string to)
{
Directory.CreateDirectory(to);
foreach (var file in Directory.GetFiles(from)) File.Copy(file, Path.Combine(to, Path.GetFileName(file)), overwrite: true);
foreach (var dir in Directory.GetDirectories(from)) CopyDirectory(dir, Path.Combine(to, Path.GetFileName(dir)));
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
foreach (var directory in new[] { WebRoot, MediaDirectory })
{
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
}
}
}
}
[Collection("HeroDatabase")]
public class HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
{
private readonly AsfSiteFactory _factory;
public HeroAsfSiteE2ETests(AsfSiteFactory factory) => _factory = factory;
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> action)
{
await using var scope = _factory.Services.CreateAsyncScope();
return await action(scope.ServiceProvider);
}
[Fact]
public async Task TheRealAsfBuild_GetsTheSeededHero_InItsFirstHtml()
{
var web = Environment.GetEnvironmentVariable("ASF_WEB_DIR");
if (string.IsNullOrEmpty(web) || !File.Exists(Path.Combine(web, "dist", "client", "index.html")))
{
return; // optional check: needs the ASF website repository and its build
}
var client = _factory.CreateClient();
var caller = Guid.NewGuid();
await InScope(async sp =>
{
var db = sp.GetRequiredService<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
try
{
var seed = JsonDocument.Parse(File.ReadAllText(Path.Combine(web, "contract", "host-injection", "hero", "seed.json"))).RootElement;
var slides = new List<HeroSlideRequest>();
foreach (var slide in seed.GetProperty("slides").EnumerateArray())
{
var photo = File.ReadAllBytes(Path.Combine(web, "src", "assets", slide.GetProperty("file").GetString()!));
var image = await InScope(sp => sp.GetRequiredService<IHeroImageService>().UploadAsync(new MemoryStream(photo), photo.Length, caller, default));
var focus = slide.GetProperty("focus");
await InScope(sp => sp.GetRequiredService<IHeroImageService>().SetFocusAsync(
Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(focus.GetProperty("x").GetDouble(), focus.GetProperty("y").GetDouble(), 1)), caller, default));
slides.Add(new HeroSlideRequest(null, Guid.Parse(image.Id), slide.GetProperty("alt").GetString()));
}
await InScope(sp => sp.GetRequiredService<IHeroService>().SaveAsync(
new HeroSaveRequest(seed.GetProperty("title").GetString(), seed.GetProperty("tagline").GetString(), null, seed.GetProperty("display").GetString(),
seed.GetProperty("buttons").EnumerateArray().Select(b => new HeroButtonRequest(b.GetProperty("label").GetString(), b.GetProperty("target").GetString())).ToList(),
true, null, null, slides), caller, default));
var response = await client.GetAsync("/");
var page = await response.Content.ReadAsStringAsync();
var api = await client.GetStringAsync("/api/v1/hero");
response.StatusCode.Should().Be(HttpStatusCode.OK);
page.Should().Contain("<picture class=\"cms-hero-picture\">").And.Contain("<link rel=\"preload\" as=\"image\"");
page.Should().Contain("<!--CMS:HERO-HTML--><picture").And.Contain("</p><!--/CMS:HERO-HTML-->");
page.Should().NotContain("<!--CMS:DATA-->").And.Contain("\"hero\":{");
JsonDocument.Parse(api).RootElement.GetProperty("slides").GetArrayLength().Should().Be(8);
var outDir = Environment.GetEnvironmentVariable("HERO_E2E_OUT");
if (!string.IsNullOrEmpty(outDir))
{
Directory.CreateDirectory(outDir);
File.WriteAllText(Path.Combine(outDir, "page.html"), page);
File.WriteAllText(Path.Combine(outDir, "api.json"), api);
}
}
finally
{
await InScope(async sp =>
{
var db = sp.GetRequiredService<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
}
}
}
@@ -112,9 +112,9 @@ public class HeroPictureRendererTests
}
[Fact]
public void ATitleWithoutSlides_OrWithoutATitle_RendersNothing()
public void ASlideThatIsUnusable_OrNoTitle_RendersNothing()
{
HeroPictureRenderer.Render(new PublicHeroDto("single", "Titel", null, null, [], [])).IsEmpty.Should().BeTrue();
HeroPictureRenderer.Render(new PublicHeroDto("single", "Titel", null, null, [], [new PublicSlideDto("x", "", false, new PublicImageDto(1, 1, new FocusDto(0.5, 0.5, 1), "/m.webp", []))])).IsEmpty.Should().BeTrue();
HeroPictureRenderer.Render(Hero(title: " ")).IsEmpty.Should().BeTrue();
HeroPictureRenderer.Render(null).IsEmpty.Should().BeTrue();
}
@@ -200,9 +200,9 @@ public class HeroHtmlTransformTests
[Fact]
public async Task AHeroWithoutAUsableSlide_LeavesTheBakedHero()
{
var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []);
var unusable = new PublicHeroDto("single", "Titel", null, null, [], [new PublicSlideDto("x", "", false, new PublicImageDto(1, 1, new FocusDto(0.5, 0.5, 1), "/m.webp", []))]);
(await Sut(textOnly).ApplyAsync(Page, Context, default)).Should().Be(Page);
(await Sut(unusable).ApplyAsync(Page, Context, default)).Should().Be(Page);
}
[Fact]
@@ -0,0 +1,67 @@
using FluentAssertions;
using NSubstitute;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Modules.Hero.Tests;
/// <summary>A hero without slides (SLP Software): the host writes the title, the lead and the buttons into the first HTML.</summary>
public class HeroTextOnlyTests
{
private static PublicHeroDto TextOnly(string title = "Websites,\napps\n& meer.", string? tagline = null, string? lead = "Een lead.", params HeroButtonDto[] buttons)
=> new("single", title, tagline, lead, buttons, []);
[Fact]
public void ADisplayedHeroWithoutSlides_IsATextOnlyRegion_WithNothingToPreload()
{
var hero = TextOnly(buttons: [new HeroButtonDto("Bekijk pakketten", "#pakketten"), new HeroButtonDto("Plan een gesprek", "#contact")]);
var injection = HeroPictureRenderer.Render(hero);
injection.Region.Should().Be(
"<h1 class=\"cms-hero-title\"><span class=\"cms-hero-title-lines\">Websites,<br>apps<br>&amp; meer.</span></h1>" +
"<p class=\"cms-hero-lead\">Een lead.</p>" +
"<p class=\"cms-hero-buttons\"><a class=\"cms-hero-button\" href=\"#pakketten\">Bekijk pakketten</a><a class=\"cms-hero-button\" href=\"#contact\">Plan een gesprek</a></p>");
injection.Preload.Should().BeEmpty();
injection.IsEmpty.Should().BeFalse();
}
[Fact]
public void WithoutALead_OrButtons_ThosePartsAreLeftOut_AndATaglineComesFirst()
{
var injection = HeroPictureRenderer.Render(TextOnly("Titel", "Label", null));
injection.Region.Should().Be("<h1 class=\"cms-hero-title\"><span class=\"cms-hero-tagline\">Label</span> <span class=\"cms-hero-title-lines\">Titel</span></h1>");
}
[Fact]
public void TheLead_KeepsItsLineBreaks_AndEverythingIsEncoded()
{
var injection = HeroPictureRenderer.Render(TextOnly("<b>x</b>", null, "a & b\nc \"d\"", new HeroButtonDto("<i>", "/p?a=1&b=2")));
injection.Region.Should().Contain("&lt;b&gt;x&lt;/b&gt;").And.Contain("a &amp; b<br>c &quot;d&quot;").And.Contain("href=\"/p?a=1&amp;b=2\">&lt;i&gt;</a>");
injection.Region.Should().NotContain("<b>").And.NotContain("<i>");
}
[Fact]
public void AHeroWithSlidesThatAreAllUnusable_StaysEmpty_AsForTheAsfSite()
{
var hero = new PublicHeroDto("single", "Titel", null, null, [], [new PublicSlideDto("x", "", false, new PublicImageDto(1, 1, new FocusDto(0.5, 0.5, 1), "/m.webp", []))]);
HeroPictureRenderer.Render(hero).IsEmpty.Should().BeTrue();
}
[Fact]
public async Task TheTransform_FillsTheTextRegion_AndLeavesThePreloadRegionAlone()
{
var model = Substitute.For<IHeroPageModel>();
model.GetAsync(default).ReturnsForAnyArgs(TextOnly());
const string page = "<head><!--CMS:HERO-PRELOAD--><!--/CMS:HERO-PRELOAD--></head><body><!--CMS:HERO-HTML-->baked<!--/CMS:HERO-HTML--></body>";
var html = await new HeroHtmlTransform(model).ApplyAsync(page, new HtmlTransformContext("https://x"), default);
html.Should().Contain("<!--CMS:HERO-HTML--><h1 class=\"cms-hero-title\">").And.NotContain("baked");
html.Should().Contain("<!--CMS:HERO-PRELOAD--><!--/CMS:HERO-PRELOAD-->");
}
}
@@ -64,7 +64,9 @@ public sealed class HeroHtmlTransform(IHeroPageModel model) : IHtmlPageTransform
}
html = HtmlMarkerEditor.ReplaceRegion(html, HtmlRegion, rendered.Region);
return HtmlMarkerEditor.ReplaceRegion(html, PreloadRegion, rendered.Preload);
// A text-only hero has nothing to preload: the page keeps whatever its build put there.
return rendered.Preload.Length == 0 ? html : HtmlMarkerEditor.ReplaceRegion(html, PreloadRegion, rendered.Preload);
}
}
@@ -36,7 +36,14 @@ public static class HeroPictureRenderer
return HeroInjection.None;
}
var slide = (hero.Slides ?? []).FirstOrDefault(IsUsable);
// A hero without any slide is a text-only hero (SLP Software): the region holds the title lines, the lead and
// the buttons, and there is nothing to preload. A hero WITH slides of which none is usable stays empty (ASF).
if ((hero.Slides ?? []).Count == 0)
{
return new HeroInjection(TextOnlyRegion(hero), string.Empty);
}
var slide = hero.Slides.FirstOrDefault(IsUsable);
if (slide is null)
{
return HeroInjection.None;
@@ -81,23 +88,54 @@ public static class HeroPictureRenderer
html.Append("<span class=\"cms-hero-tagline\">").Append(Encode(hero.Tagline)).Append("</span> ");
}
html.Append("<span class=\"cms-hero-name\">").Append(string.Join("<br>", hero.Title.Replace("\r\n", "\n").Split('\n').Select(Encode))).Append("</span></h1>");
html.Append("<span class=\"cms-hero-name\">").Append(Lines(hero.Title)).Append("</span></h1>");
AppendButtons(html, hero);
return html.ToString();
}
var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList();
if (buttons.Count > 0)
/// <summary>
/// The text-only hero: <c>h1.cms-hero-title</c> with the tagline (when there is one) and the title lines in
/// <c>span.cms-hero-title-lines</c> separated by <c>&lt;br&gt;</c> (no brand prefix: the site adds it to its own
/// screen-reader title), then <c>p.cms-hero-lead</c> and the buttons row.
/// </summary>
private static string TextOnlyRegion(PublicHeroDto hero)
{
var html = new StringBuilder();
html.Append("<h1 class=\"cms-hero-title\">");
if (!string.IsNullOrWhiteSpace(hero.Tagline))
{
html.Append("<p class=\"cms-hero-buttons\">");
foreach (var button in buttons)
{
html.Append("<a class=\"cms-hero-button\" href=\"").Append(Encode(button.Target)).Append("\">").Append(Encode(button.Label)).Append("</a>");
}
html.Append("</p>");
html.Append("<span class=\"cms-hero-tagline\">").Append(Encode(hero.Tagline)).Append("</span> ");
}
html.Append("<span class=\"cms-hero-title-lines\">").Append(Lines(hero.Title)).Append("</span></h1>");
if (!string.IsNullOrWhiteSpace(hero.Lead))
{
html.Append("<p class=\"cms-hero-lead\">").Append(Lines(hero.Lead.Trim())).Append("</p>");
}
AppendButtons(html, hero);
return html.ToString();
}
private static string Lines(string text) => string.Join("<br>", text.Replace("\r\n", "\n").Split('\n').Select(Encode));
private static void AppendButtons(StringBuilder html, PublicHeroDto hero)
{
var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList();
if (buttons.Count == 0)
{
return;
}
html.Append("<p class=\"cms-hero-buttons\">");
foreach (var button in buttons)
{
html.Append("<a class=\"cms-hero-button\" href=\"").Append(Encode(button.Target)).Append("\">").Append(Encode(button.Label)).Append("</a>");
}
html.Append("</p>");
}
private static string Preload(string src, string wide, string tall)
{
const string head = "<link rel=\"preload\" as=\"image\"";