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; /// /// 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 . /// 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 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(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(""); } [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(), "\n\"x\" & 'y'", "", new HeroButtonDto("", "/ok?a=1&b=\"2\"")); var html = HeroPictureRenderer.Render(hero).Region; html.Should().NotContain(""); html.Should().Contain("<script>alert(1)</script>
"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("baked hero

rest

"; 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(); model.GetAsync(default).ReturnsForAnyArgs(hero); return new HeroHtmlTransform(model); } [Theory] [InlineData("

nothing

", false)] [InlineData("", true)] [InlineData("", true)] [InlineData("", 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("").And.Contain(""); html.Should().Contain(""); html.Should().NotContain("baked").And.Contain("

rest

"); } [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("x", 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(); publicHero.GetActiveAsync(default).ReturnsForAnyArgs(hero); var store = Substitute.For(); store.ExistsAsync(default!, default).ReturnsForAnyArgs(true); return (new HeroPageModel(publicHero, store, NullLogger.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(); (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(); 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("", new HtmlTransformContext("https://x"), default); var json = html["".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); } }