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("", 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);
}
}