288 lines
13 KiB
C#
288 lines
13 KiB
C#
using System.Text.Json;
|
|
using FluentAssertions;
|
|
using FsCheck;
|
|
using FsCheck.Fluent;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using SlpModularCms.Core.Hosting.Website;
|
|
using SlpModularCms.Core.Media;
|
|
using SlpModularCms.Modules.Hero.Models;
|
|
using SlpModularCms.Modules.Hero.Services;
|
|
|
|
namespace SlpModularCms.Modules.Hero.Tests;
|
|
|
|
/// <summary>
|
|
/// The HTML written between the hero markers must be exactly what the website expects: the golden files of the website
|
|
/// repository (Golden/SOURCE.md names the commit) are run through <see cref="HeroPictureRenderer"/>.
|
|
/// </summary>
|
|
public class HeroGoldenTests
|
|
{
|
|
private static string Dir => Path.Combine(AppContext.BaseDirectory, "Golden", "host-injection", "hero");
|
|
|
|
private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
|
|
|
|
public static IEnumerable<object[]> Cases()
|
|
=> Directory.GetFiles(Dir, "*.input.json").Select(f => new object[] { Path.GetFileName(f)[..^".input.json".Length] }).OrderBy(o => (string)o[0]);
|
|
|
|
// The expected files end with one newline that is not part of the HTML.
|
|
private static string Expected(string file)
|
|
{
|
|
var text = File.ReadAllText(Path.Combine(Dir, file)).Replace("\r\n", "\n");
|
|
return text.EndsWith('\n') ? text[..^1] : text;
|
|
}
|
|
|
|
private static PublicHeroDto? Input(string name)
|
|
=> JsonSerializer.Deserialize<PublicHeroDto?>(File.ReadAllText(Path.Combine(Dir, name + ".input.json")), Web);
|
|
|
|
[Fact]
|
|
public void TheGoldenFiles_AreThere() => Cases().Count().Should().BeGreaterThanOrEqualTo(6);
|
|
|
|
[Theory]
|
|
[MemberData(nameof(Cases))]
|
|
public void TheRegion_MatchesTheGoldenFile(string name)
|
|
=> HeroPictureRenderer.Render(Input(name)).Region.Should().Be(Expected(name + ".expected.html"));
|
|
|
|
[Theory]
|
|
[MemberData(nameof(Cases))]
|
|
public void ThePreload_MatchesTheGoldenFile(string name)
|
|
=> HeroPictureRenderer.Render(Input(name)).Preload.Should().Be(Expected(name + ".expected-preload.html"));
|
|
|
|
[Fact]
|
|
public void ThePreloadAndThePicture_ShareTheirSrcsetSizesAndMedia()
|
|
{
|
|
var injection = HeroPictureRenderer.Render(Input("hero-standard"));
|
|
|
|
foreach (var set in new[] { "/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w", "/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" })
|
|
{
|
|
injection.Region.Should().Contain($"srcset=\"{set}\"");
|
|
injection.Preload.Should().Contain($"imagesrcset=\"{set}\"");
|
|
}
|
|
|
|
injection.Region.Should().Contain("media=\"(orientation: portrait)\"");
|
|
injection.Preload.Should().Contain("media=\"(orientation: portrait)\"").And.Contain("media=\"(orientation: landscape)\"");
|
|
}
|
|
}
|
|
|
|
public class HeroPictureRendererTests
|
|
{
|
|
private static PublicHeroDto Hero(PublicImageDto? image = null, string title = "Titel", string? tagline = null, params HeroButtonDto[] buttons)
|
|
=> new("single", title, tagline, null, buttons,
|
|
[new PublicSlideDto("s1", "Een foto", false, image ?? Image())]);
|
|
|
|
private static PublicImageDto Image(FocusDto? focus = null, params HeroVariantDto[] variants)
|
|
=> new(1600, 1067, focus ?? new FocusDto(0.5, 0.5, 1), "/media/hero/0123456789abcdef/wide-1600.webp", variants);
|
|
|
|
[Theory]
|
|
[InlineData(0.5, 0.55, "50% 55%")]
|
|
[InlineData(0.455, 0.0, "45.5% 0%")]
|
|
[InlineData(1.0, 1.0, "100% 100%")]
|
|
[InlineData(0.123456, 0.987654, "12.35% 98.77%")]
|
|
public void TheFocus_BecomesAnObjectPosition(double x, double y, string expected)
|
|
=> HeroPictureRenderer.Render(Hero(Image(new FocusDto(x, y, 1)))).Region.Should().Contain($" style=\"object-position:{expected}\"");
|
|
|
|
[Theory]
|
|
[InlineData(-0.1, 0.5)]
|
|
[InlineData(0.5, 1.1)]
|
|
[InlineData(double.NaN, 0.5)]
|
|
public void AnInvalidFocus_GivesNoStyle(double x, double y)
|
|
=> HeroPictureRenderer.Render(Hero(Image(new FocusDto(x, y, 1)))).Region.Should().NotContain("style=");
|
|
|
|
[Fact]
|
|
public void WithoutATall_ThereIsOnePreload_WithoutMedia()
|
|
{
|
|
var wide = new HeroVariantDto("wide", 960, 640, "image/webp", "/media/hero/0123456789abcdef/wide-960.webp");
|
|
|
|
var injection = HeroPictureRenderer.Render(Hero(Image(null, wide)));
|
|
|
|
injection.Preload.Should().Be("<link rel=\"preload\" as=\"image\" imagesrcset=\"/media/hero/0123456789abcdef/wide-960.webp 960w\" imagesizes=\"100vw\" fetchpriority=\"high\">");
|
|
}
|
|
|
|
[Fact]
|
|
public void AvifVariants_NeverAppearInThePictureOrThePreload()
|
|
{
|
|
var variants = new[]
|
|
{
|
|
new HeroVariantDto("wide", 960, 640, "image/webp", "/media/hero/0123456789abcdef/wide-960.webp"),
|
|
new HeroVariantDto("wide", 960, 640, "image/avif", "/media/hero/0123456789abcdef/wide-960.avif"),
|
|
};
|
|
|
|
var injection = HeroPictureRenderer.Render(Hero(Image(null, variants)));
|
|
|
|
(injection.Region + injection.Preload).Should().NotContain("avif");
|
|
}
|
|
|
|
[Fact]
|
|
public void ASlideThatIsUnusable_OrNoTitle_RendersNothing()
|
|
{
|
|
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();
|
|
}
|
|
|
|
[Fact]
|
|
public void ThePictureIsTheFirstUsableSlide_NotJustTheFirst()
|
|
{
|
|
var hero = new PublicHeroDto("slideshow", "Titel", null, null, [], [
|
|
new PublicSlideDto("a", "", false, Image()),
|
|
new PublicSlideDto("b", "Tweede", false, Image()),
|
|
]);
|
|
|
|
HeroPictureRenderer.Render(hero).Region.Should().Contain("alt=\"Tweede\"");
|
|
}
|
|
|
|
[Fact]
|
|
public void NoTextOfTheCmsCanBreakOutOfTheHtml()
|
|
{
|
|
var hero = Hero(Image(), "<script>alert(1)</script>\n\"x\" & 'y'", "<img src=x onerror=alert(1)>", new HeroButtonDto("<b>", "/ok?a=1&b=\"2\""));
|
|
|
|
var html = HeroPictureRenderer.Render(hero).Region;
|
|
|
|
html.Should().NotContain("<script").And.NotContain("<img src=x").And.NotContain("<b>");
|
|
html.Should().Contain("<script>alert(1)</script><br>"x" & 'y'");
|
|
}
|
|
|
|
[Fact]
|
|
public void ARendererNeverThrows_OnArbitraryText()
|
|
=> Prop.ForAll(
|
|
Gen.Elements("a", "<", ">", "&", "\"", "'", "\n", " ", "é", "\\", "/", "#").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(),
|
|
text =>
|
|
{
|
|
var hero = new PublicHeroDto("single", "T" + text, text, text, [new HeroButtonDto(text, "/" + text)],
|
|
[new PublicSlideDto("id", "a" + text, false, new PublicImageDto(10, 10, new FocusDto(0.5, 0.5, 1), "/media/x/" + text.Replace("\\", string.Empty), []))]);
|
|
var html = HeroPictureRenderer.Render(hero).Region;
|
|
html.Should().NotContain("<script");
|
|
return true;
|
|
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1000));
|
|
}
|
|
|
|
public class HeroHtmlTransformTests
|
|
{
|
|
private static readonly HtmlTransformContext Context = new("https://test.andreaslop.nl");
|
|
|
|
private const string Page =
|
|
"<head><!--CMS:HERO-PRELOAD-->baked preload<!--/CMS:HERO-PRELOAD--></head>" +
|
|
"<body><!--CMS:HERO-HTML-->baked hero<!--/CMS:HERO-HTML--><p>rest</p></body>";
|
|
|
|
private static PublicHeroDto Hero() => new("single", "Andrea Slop", null, null, [],
|
|
[new PublicSlideDto("s1", "Een foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), "/media/hero/0123456789abcdef/wide-1600.webp",
|
|
[new HeroVariantDto("wide", 1600, 1067, "image/webp", "/media/hero/0123456789abcdef/wide-1600.webp")]))]);
|
|
|
|
private static HeroHtmlTransform Sut(PublicHeroDto? hero)
|
|
{
|
|
var model = Substitute.For<IHeroPageModel>();
|
|
model.GetAsync(default).ReturnsForAnyArgs(hero);
|
|
return new HeroHtmlTransform(model);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("<p>nothing</p>", false)]
|
|
[InlineData("<!--CMS:HERO-HTML--><!--/CMS:HERO-HTML-->", true)]
|
|
[InlineData("<!--CMS:HERO-PRELOAD--><!--/CMS:HERO-PRELOAD-->", true)]
|
|
[InlineData("<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->", false)]
|
|
public void Wants_OnlyPagesWithHeroMarkers(string html, bool expected) => Sut(null).Wants(html).Should().Be(expected);
|
|
|
|
[Fact]
|
|
public async Task TheRegions_AreFilled_AndTheMarkersStay()
|
|
{
|
|
var html = await Sut(Hero()).ApplyAsync(Page, Context, default);
|
|
|
|
html.Should().Contain("<!--CMS:HERO-HTML--><picture class=\"cms-hero-picture\">").And.Contain("</h1><!--/CMS:HERO-HTML-->");
|
|
html.Should().Contain("<!--CMS:HERO-PRELOAD--><link rel=\"preload\" as=\"image\"").And.Contain("><!--/CMS:HERO-PRELOAD-->");
|
|
html.Should().NotContain("baked").And.Contain("<p>rest</p>");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithoutAHero_ThePageStaysAsItWasBuilt()
|
|
{
|
|
(await Sut(null).ApplyAsync(Page, Context, default)).Should().Be(Page);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AHeroWithoutAUsableSlide_LeavesTheBakedHero()
|
|
{
|
|
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(unusable).ApplyAsync(Page, Context, default)).Should().Be(Page);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task APageWithOnlyOneMarker_OnlyGetsThatPart()
|
|
{
|
|
var html = await Sut(Hero()).ApplyAsync("<body><!--CMS:HERO-HTML-->x<!--/CMS:HERO-HTML--></body>", Context, default);
|
|
|
|
html.Should().Contain("cms-hero-picture").And.NotContain("preload");
|
|
}
|
|
}
|
|
|
|
public class HeroPageModelTests
|
|
{
|
|
private static PublicHeroDto Hero(string src = "/media/hero/0123456789abcdef/wide-1600.webp") => new("single", "Titel", null, null, [],
|
|
[new PublicSlideDto("s1", "Foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), src,
|
|
[new HeroVariantDto("wide", 1600, 1067, "image/webp", src), new HeroVariantDto("tall", 640, 800, "image/webp", "/media/hero/0123456789abcdef/tall-640.webp")]))]);
|
|
|
|
private static (HeroPageModel Model, IMediaStore Store) Make(PublicHeroDto? hero)
|
|
{
|
|
var publicHero = Substitute.For<IPublicHeroService>();
|
|
publicHero.GetActiveAsync(default).ReturnsForAnyArgs(hero);
|
|
var store = Substitute.For<IMediaStore>();
|
|
store.ExistsAsync(default!, default).ReturnsForAnyArgs(true);
|
|
return (new HeroPageModel(publicHero, store, NullLogger<HeroPageModel>.Instance), store);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WhenTheFilesOfTheFirstSlideExist_TheHeroIsReturned()
|
|
{
|
|
var (model, _) = Make(Hero());
|
|
|
|
(await model.GetAsync(default)).Should().NotBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WhenAFileOfTheFirstSlideIsMissing_NothingIsReturned()
|
|
{
|
|
var (model, store) = Make(Hero());
|
|
store.ExistsAsync("hero/0123456789abcdef/tall-640.webp", default).Returns(false);
|
|
|
|
(await model.GetAsync(default)).Should().BeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithoutAHero_OrWithoutSlides_ThereIsNothingToCheck()
|
|
{
|
|
(await Make(null).Model.GetAsync(default)).Should().BeNull();
|
|
var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []);
|
|
var (model, store) = Make(textOnly);
|
|
|
|
(await model.GetAsync(default)).Should().Be(textOnly);
|
|
await store.DidNotReceiveWithAnyArgs().ExistsAsync(default!, default);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheDataContributor_WritesTheHero_OrNull()
|
|
{
|
|
var withHero = Make(Hero()).Model;
|
|
var without = Make(null).Model;
|
|
|
|
(await new HeroDataContributor(withHero).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeOfType<PublicHeroDto>();
|
|
(await new HeroDataContributor(without).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeNull();
|
|
new HeroDataContributor(withHero).Key.Should().Be("hero");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheDataBlock_CarriesTheOfferingsFirst_ThenTheHero()
|
|
{
|
|
var offerings = Substitute.For<ICmsDataBlockContributor>();
|
|
offerings.Key.Returns("offerings");
|
|
offerings.Order.Returns(100);
|
|
offerings.GetAsync(default!, default).ReturnsForAnyArgs(new[] { 1 });
|
|
var block = new CmsDataBlockTransform([new HeroDataContributor(Make(Hero()).Model), offerings]);
|
|
|
|
var html = await block.ApplyAsync("<!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{}</script>", new HtmlTransformContext("https://x"), default);
|
|
|
|
var json = html["<script type=\"application/json\" id=\"cms-data\">".Length..^"</script>".Length];
|
|
using var doc = JsonDocument.Parse(json);
|
|
doc.RootElement.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "hero");
|
|
doc.RootElement.GetProperty("hero").GetProperty("slides")[0].GetProperty("image").GetProperty("variants").GetArrayLength().Should().Be(2);
|
|
}
|
|
}
|