H2: Hero-module (tabellen en migratie, beheer-API, publieke GET /hero, afbeeldingsupload met focus, opschoonservice, teksten) en OpenAPI-snapshot
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,388 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using FluentAssertions;
|
||||
using FsCheck;
|
||||
using FsCheck.Fluent;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroTextsTests
|
||||
{
|
||||
[Fact]
|
||||
public void TheTextFiles_MatchTheDeclaredKeys_InDutchAndEnglish()
|
||||
=> SlpModularCms.Core.Texts.TextAudit.Verify(typeof(HeroTexts).Assembly, SlpModularCms.Core.Texts.TextAudit.KeysOf(typeof(HeroTexts)), "nl", "en").Should().BeEmpty();
|
||||
}
|
||||
|
||||
public class ButtonTargetValidatorTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("#contact", ButtonTargetKind.Anchor)]
|
||||
[InlineData("#pakketten", ButtonTargetKind.Anchor)]
|
||||
[InlineData("#a-b_c9", ButtonTargetKind.Anchor)]
|
||||
[InlineData("/over-mij", ButtonTargetKind.Path)]
|
||||
[InlineData("/", ButtonTargetKind.Path)]
|
||||
[InlineData("/a/b/c?x=1&y=2", ButtonTargetKind.Path)]
|
||||
[InlineData("https://andreaslop.nl/portfolio", ButtonTargetKind.Https)]
|
||||
[InlineData("https://sub.example.com:8443/p?q=1#top", ButtonTargetKind.Https)]
|
||||
public void AcceptedTargets(string target, ButtonTargetKind kind) => ButtonTargetValidator.Validate(target).Should().Be(kind);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("contact")]
|
||||
[InlineData("#")]
|
||||
[InlineData("#1abc")]
|
||||
[InlineData("# contact")]
|
||||
[InlineData("#a b")]
|
||||
[InlineData("//evil.example/x")]
|
||||
[InlineData("/\\evil.example")]
|
||||
[InlineData("/a b")]
|
||||
[InlineData("http://example.com")]
|
||||
[InlineData("HTTPS://example.com")]
|
||||
[InlineData("https://user:pw@example.com")]
|
||||
[InlineData("https://")]
|
||||
[InlineData("https:///path")]
|
||||
[InlineData("javascript:alert(1)")]
|
||||
[InlineData("JaVaScRiPt:alert(1)")]
|
||||
[InlineData("data:text/html;base64,AAAA")]
|
||||
[InlineData("mailto:a@b.nl")]
|
||||
[InlineData("tel:+31612345678")]
|
||||
[InlineData("ftp://example.com/x")]
|
||||
[InlineData("/ok\"onmouseover=\"x")]
|
||||
[InlineData("/ok<script>")]
|
||||
[InlineData(" /leading-space")]
|
||||
[InlineData("/trailing-space ")]
|
||||
[InlineData("/tab\tx")]
|
||||
[InlineData("/new\nline")]
|
||||
public void RejectedTargets(string target) => ButtonTargetValidator.Validate(target).Should().Be(ButtonTargetKind.Invalid);
|
||||
|
||||
[Fact]
|
||||
public void Null_IsInvalid() => ButtonTargetValidator.Validate(null).Should().Be(ButtonTargetKind.Invalid);
|
||||
|
||||
[Fact]
|
||||
public void WhateverIsAccepted_IsOneOfTheThreeSafeForms()
|
||||
=> Prop.ForAll(Gen.Elements("a", "#", "/", ":", "\\", " ", "\"", "<", ">", "h", "t", "p", "s", "x", ".", "-", "1", "\n", "\t", "%").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), text =>
|
||||
{
|
||||
var kind = ButtonTargetValidator.Validate(text);
|
||||
if (kind != ButtonTargetKind.Invalid)
|
||||
{
|
||||
text.Should().NotMatchRegex("[\\s\\\\\"<>`]");
|
||||
(text.StartsWith('#') || (text.StartsWith('/') && !text.StartsWith("//")) || text.StartsWith("https://")).Should().BeTrue();
|
||||
}
|
||||
|
||||
return true;
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(3000));
|
||||
}
|
||||
|
||||
public class HeroSaveRequestValidationTests
|
||||
{
|
||||
private static HeroSaveRequest Valid() => new(
|
||||
"Websites,\napps\n& meer.", null, "Een lead.", "single",
|
||||
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")],
|
||||
true, null, null, []);
|
||||
|
||||
private static List<ValidationResult> Run(HeroSaveRequest request)
|
||||
{
|
||||
var results = new List<ValidationResult>();
|
||||
Validator.TryValidateObject(request, new ValidationContext(request), results, validateAllProperties: true);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static string[] Members(List<ValidationResult> results) => results.SelectMany(r => r.MemberNames).ToArray();
|
||||
|
||||
[Fact]
|
||||
public void AValidHero_HasNoErrors() => Run(Valid()).Should().BeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void TheTitle_IsRequired_AndBounded()
|
||||
{
|
||||
Members(Run(Valid() with { Title = " " })).Should().Contain("Title");
|
||||
Members(Run(Valid() with { Title = new string('x', 201) })).Should().Contain("Title");
|
||||
Members(Run(Valid() with { Title = "a\nb\nc\nd\ne\nf" })).Should().Contain("Title");
|
||||
Run(Valid() with { Title = "a\nb\nc\nd\ne" }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheOtherTexts_AreBounded()
|
||||
{
|
||||
Members(Run(Valid() with { Tagline = new string('t', 121) })).Should().Contain("Tagline");
|
||||
Members(Run(Valid() with { Lead = new string('l', 601) })).Should().Contain("Lead");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("single", true)]
|
||||
[InlineData("slideshow", true)]
|
||||
[InlineData(null, true)]
|
||||
[InlineData("carousel", false)]
|
||||
[InlineData("SINGLE", false)]
|
||||
public void TheDisplay_IsOneOfTheTwo(string? display, bool valid)
|
||||
=> Run(Valid() with { Display = display }).Any(r => r.MemberNames.Contains("Display")).Should().Be(!valid);
|
||||
|
||||
[Fact]
|
||||
public void Buttons_AreLimitedAndChecked()
|
||||
{
|
||||
var three = new[] { new HeroButtonRequest("a", "#a"), new HeroButtonRequest("b", "#b"), new HeroButtonRequest("c", "#c") };
|
||||
Members(Run(Valid() with { Buttons = three })).Should().Contain("Buttons");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest("Lees meer", null)] })).Should().Contain("Buttons[0]");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest(null, "/x")] })).Should().Contain("Buttons[0]");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest("x", "javascript:alert(1)")] })).Should().Contain("Buttons[0].Target");
|
||||
Members(Run(Valid() with { Buttons = [new HeroButtonRequest(new string('l', 51), "/x")] })).Should().Contain("Buttons[0].Label");
|
||||
Run(Valid() with { Buttons = [new HeroButtonRequest("", ""), new HeroButtonRequest(null, null)] }).Should().BeEmpty("empty buttons are ignored");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSchedule_MustRunForward()
|
||||
{
|
||||
var t = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
Members(Run(Valid() with { StartsAt = t, EndsAt = t })).Should().Contain("EndsAt");
|
||||
Members(Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(-1) })).Should().Contain("EndsAt");
|
||||
Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(1) }).Should().BeEmpty();
|
||||
Run(Valid() with { StartsAt = null, EndsAt = t }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASlide_NeedsAnImage_AndAnAltTextOrTheDecorativeFlag()
|
||||
{
|
||||
var image = Guid.NewGuid();
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, Guid.Empty, "alt")] })).Should().Contain("Slides[0].ImageId");
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, image, " ")] })).Should().Contain("Slides[0].Alt");
|
||||
Members(Run(Valid() with { Slides = [new HeroSlideRequest(null, image, new string('a', 301))] })).Should().Contain("Slides[0].Alt");
|
||||
Run(Valid() with { Slides = [new HeroSlideRequest(null, image, null, Decorative: true)] }).Should().BeEmpty();
|
||||
Run(Valid() with { Slides = [new HeroSlideRequest(null, image, "Een foto")] }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThereIsNoAdministratorLimitOnTheNumberOfSlides()
|
||||
{
|
||||
var slides = Enumerable.Range(0, 120).Select(_ => new HeroSlideRequest(null, Guid.NewGuid(), "foto")).ToList();
|
||||
|
||||
Run(Valid() with { Slides = slides }).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FocusValues_AreChecked()
|
||||
{
|
||||
var ok = new FocusDto(0.5, 0.5, 1);
|
||||
void Check(HeroFocusRequest r, bool valid)
|
||||
{
|
||||
var results = new List<ValidationResult>();
|
||||
Validator.TryValidateObject(r, new ValidationContext(r), results, true);
|
||||
results.Any().Should().Be(!valid);
|
||||
}
|
||||
|
||||
Check(new HeroFocusRequest(ok), true);
|
||||
Check(new HeroFocusRequest(ok, new FocusDto(0.2, 0.9, 2.5), new FocusDto(1, 0, 4)), true);
|
||||
Check(new HeroFocusRequest(new FocusDto(-0.1, 0.5, 1)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 1.1, 1)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 0.5, 0.5)), false);
|
||||
Check(new HeroFocusRequest(new FocusDto(0.5, 0.5, 4.5)), false);
|
||||
Check(new HeroFocusRequest(ok, new FocusDto(double.NaN, 0.5, 1)), false);
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroTextCleanTests
|
||||
{
|
||||
[Fact]
|
||||
public void LineBreaksAreNormalised_AndControlCharactersRemoved()
|
||||
{
|
||||
HeroText.Clean("a\r\nb\rc\u0007d", keepLineBreaks: true).Should().Be("a\nb\ncd");
|
||||
HeroText.Clean("a\nb", keepLineBreaks: false).Should().Be("a b");
|
||||
HeroText.Clean(" x ", keepLineBreaks: false).Should().Be("x");
|
||||
HeroText.Clean(null, keepLineBreaks: true).Should().BeEmpty();
|
||||
HeroText.Clean("a\u2028b\u2029c", keepLineBreaks: true).Should().Be("abc");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HtmlStaysAsTypedText()
|
||||
=> HeroText.Clean("<b>Hallo</b> & \"dag\"", keepLineBreaks: false).Should().Be("<b>Hallo</b> & \"dag\"");
|
||||
|
||||
[Fact]
|
||||
public void CleaningIsIdempotent()
|
||||
=> Prop.ForAll(Gen.Elements("a", " ", "\n", "\r", "\t", "<", "&", "\u0007", "\u2028", "é", "x").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), text =>
|
||||
{
|
||||
var once = HeroText.Clean(text, keepLineBreaks: true);
|
||||
HeroText.Clean(once, keepLineBreaks: true).Should().Be(once);
|
||||
return true;
|
||||
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
|
||||
}
|
||||
|
||||
public class HeroMappingTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static HeroImage Image(Guid? id = null, string set = "0123456789abcdef", string? wideFocus = null)
|
||||
{
|
||||
var image = new HeroImage
|
||||
{
|
||||
Id = id ?? Guid.NewGuid(),
|
||||
SetHash = set,
|
||||
Width = 1600,
|
||||
Height = 1067,
|
||||
Variants =
|
||||
[
|
||||
new HeroVariant("wide", 960, 640, "image/webp", "wide-960.webp", 10),
|
||||
new HeroVariant("wide", 1600, 1067, "image/webp", "wide-1600.webp", 20),
|
||||
new HeroVariant("wide", 1600, 1067, "image/avif", "wide-1600.avif", 15),
|
||||
new HeroVariant("tall", 640, 800, "image/webp", "tall-640.webp", 8),
|
||||
],
|
||||
};
|
||||
if (wideFocus is not null)
|
||||
{
|
||||
image.WideFocusX = 0.2;
|
||||
image.WideFocusY = 0.3;
|
||||
image.WideZoom = 2;
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
private static HeroSlide Slide(int order, bool active = true, string alt = "Een foto", bool decorative = false, HeroImage? image = null)
|
||||
=> new() { Id = Guid.NewGuid(), SortOrder = order, IsActive = active, Alt = alt, Decorative = decorative, Image = image ?? Image(), ImageId = (image ?? Image()).Id };
|
||||
|
||||
private static HeroContent Hero(params HeroSlide[] slides) => new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Title = "Andrea Slop",
|
||||
Tagline = "Lifestyle fotograaf",
|
||||
Display = "slideshow",
|
||||
Button1Label = "Lees meer",
|
||||
Button1Target = "/over-mij",
|
||||
Slides = [.. slides],
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void ALiveHero_IsPublished_WithItsSlidesInOrder()
|
||||
{
|
||||
var hero = Hero(Slide(2, alt: "derde"), Slide(0, alt: "eerste"), Slide(1, alt: "tweede"));
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Select(s => s.Alt).Should().Equal("eerste", "tweede", "derde");
|
||||
pub.Buttons.Should().ContainSingle().Which.Should().Be(new HeroButtonDto("Lees meer", "/over-mij"));
|
||||
pub.Display.Should().Be("slideshow");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSrc_IsTheLargestWideWebP_AndAllVariantsAreListedWithMediaAddresses()
|
||||
{
|
||||
var pub = HeroMapping.ToPublic(Hero(Slide(0)), Now, 50)!;
|
||||
|
||||
var image = pub.Slides[0].Image;
|
||||
image.Src.Should().Be("/media/hero/0123456789abcdef/wide-1600.webp");
|
||||
image.Variants.Should().HaveCount(4);
|
||||
image.Variants.Should().OnlyContain(v => v.Url.StartsWith("/media/hero/0123456789abcdef/"));
|
||||
image.Width.Should().Be(1600);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WhenNothingIsWide_TheSrcFallsBackToTheLargestWebP()
|
||||
{
|
||||
var image = Image();
|
||||
image.Variants = [new HeroVariant("tall", 640, 800, "image/webp", "tall-640.webp", 8), new HeroVariant("tall", 960, 1200, "image/webp", "tall-960.webp", 9)];
|
||||
|
||||
HeroMapping.SrcFor(image).Should().EndWith("tall-960.webp");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ADecorativeSlide_HasNoAlt_AndAnInactiveOrEmptyOneIsLeftOut()
|
||||
{
|
||||
var hero = Hero(
|
||||
Slide(0, decorative: true, alt: "ignored"),
|
||||
Slide(1, active: false),
|
||||
Slide(2, alt: " "),
|
||||
new HeroSlide { Id = Guid.NewGuid(), SortOrder = 3, Alt = "x", Image = new HeroImage { SetHash = "0123456789abcdef" }, ImageId = Guid.NewGuid() });
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Should().ContainSingle().Which.Should().Match<PublicSlideDto>(s => s.Decorative && s.Alt == "");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASafetyCeiling_LimitsThePublishedSlides_NotTheSavedOnes()
|
||||
{
|
||||
var hero = Hero(Enumerable.Range(0, 80).Select(i => Slide(i)).ToArray());
|
||||
|
||||
HeroMapping.ToPublic(hero, Now, 50)!.Slides.Should().HaveCount(50);
|
||||
HeroMapping.ToPublic(hero, Now, 50)!.Slides.Select(s => s.Id).Should().Equal(hero.Slides.OrderBy(s => s.SortOrder).Take(50).Select(s => s.Id.ToString()));
|
||||
hero.Slides.Should().HaveCount(80);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, null, null, true)]
|
||||
[InlineData(false, null, null, false)]
|
||||
[InlineData(true, "2026-11-17", null, false)]
|
||||
[InlineData(true, "2026-11-16T12:00:00Z", null, true)]
|
||||
[InlineData(true, null, "2026-11-16T12:00:00Z", false)]
|
||||
[InlineData(true, null, "2026-11-16T12:00:01Z", true)]
|
||||
[InlineData(true, "2026-11-01", "2026-12-01", true)]
|
||||
public void TheScheduleAndTheSwitch_DecideWhetherItIsLive(bool active, string? start, string? end, bool live)
|
||||
{
|
||||
var hero = Hero(Slide(0));
|
||||
hero.IsActive = active;
|
||||
hero.StartsAt = start is null ? null : DateTimeOffset.Parse(start, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
|
||||
hero.EndsAt = end is null ? null : DateTimeOffset.Parse(end, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
|
||||
|
||||
(HeroMapping.ToPublic(hero, Now, 50) is not null).Should().Be(live);
|
||||
HeroMapping.ToAdmin(hero, Now, 50).IsLive.Should().Be(live);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHeroWithoutATitle_IsNotPublished()
|
||||
{
|
||||
var hero = Hero(Slide(0));
|
||||
hero.Title = " ";
|
||||
|
||||
HeroMapping.ToPublic(hero, Now, 50).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AHeroWithoutSlides_IsPublished_ForSitesThatShowOnlyText()
|
||||
{
|
||||
var hero = Hero();
|
||||
hero.Button1Label = "Bekijk pakketten";
|
||||
hero.Button1Target = "#pakketten";
|
||||
hero.Button2Label = "Plan een gesprek";
|
||||
hero.Button2Target = "#contact";
|
||||
|
||||
var pub = HeroMapping.ToPublic(hero, Now, 50)!;
|
||||
|
||||
pub.Slides.Should().BeEmpty();
|
||||
pub.Buttons.Should().HaveCount(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FocusPerRatio_IsOnlyInTheDataWhenSet()
|
||||
{
|
||||
var plain = HeroMapping.ToPublic(Hero(Slide(0)), Now, 50)!.Slides[0].Image;
|
||||
var withWide = HeroMapping.ToPublic(Hero(Slide(0, image: Image(wideFocus: "x"))), Now, 50)!.Slides[0].Image;
|
||||
|
||||
plain.FocusByRatio.Should().BeNull();
|
||||
plain.Focus.Should().Be(new FocusDto(0.5, 0.5, 1));
|
||||
withWide.FocusByRatio!["wide"].Should().Be(new FocusDto(0.2, 0.3, 2));
|
||||
withWide.FocusByRatio.Should().NotContainKey("tall");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheJson_DoesNotCarryTheScheduleOrSwitches_AndOmitsAnAbsentFocusByRatio()
|
||||
{
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(HeroMapping.ToPublic(Hero(Slide(0)), Now, 50), new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web));
|
||||
|
||||
json.Should().NotContain("startsAt").And.NotContain("endsAt").And.NotContain("isActive").And.NotContain("focusByRatio");
|
||||
json.Should().Contain("\"title\":\"Andrea Slop\"").And.Contain("\"lead\":null");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheAdminView_ListsInactiveSlidesAndTheCeiling()
|
||||
{
|
||||
var hero = Hero(Slide(0), Slide(1, active: false));
|
||||
|
||||
var admin = HeroMapping.ToAdmin(hero, Now, 50);
|
||||
|
||||
admin.Slides.Should().HaveCount(2);
|
||||
admin.MaxPublishedSlides.Should().Be(50);
|
||||
HeroMapping.ToAdmin(null, Now, 50).Should().Match<HeroAdminDto>(d => d.Id == null && !d.IsLive && d.Slides.Count == 0 && d.Display == "single");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
using FluentAssertions;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Modules.Hero.Data.Entities;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public class HeroImageServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AnUpload_IsProcessedIntoVariantsOfBothRatios_AndStored()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
(image.Width, image.Height).Should().Be((1600, 1067));
|
||||
image.Variants.Select(v => v.Ratio).Distinct().Should().BeEquivalentTo("wide", "tall");
|
||||
image.Variants.Should().Contain(v => v.Type == "image/webp" && v.Ratio == "wide" && v.Width == 1600);
|
||||
image.Variants.Should().OnlyContain(v => v.Width <= 1600, "an image is never scaled up");
|
||||
image.Src.Should().Be(image.Variants.Single(v => v.Ratio == "wide" && v.Width == 1600 && v.Type == "image/webp").Url);
|
||||
|
||||
foreach (var variant in image.Variants)
|
||||
{
|
||||
var key = variant.Url["/media/".Length..];
|
||||
(await rig.Store.ExistsAsync(key, CancellationToken.None)).Should().BeTrue(key);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOriginal_IsKeptWithoutMetadata_AndNotPublic()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
var stored = (await rig.Db.HeroImages.FindAsync(Guid.Parse((await rig.Repository.GetImageBySha256Async(rig.Db.HeroImages.Single().OriginalSha256, default))!.Id.ToString())))!;
|
||||
stored.OriginalKey.Should().StartWith("originals/");
|
||||
await using var file = (await rig.Store.OpenReadAsync(stored.OriginalKey, CancellationToken.None))!.Content;
|
||||
var bytes = new MemoryStream();
|
||||
await file.CopyToAsync(bytes);
|
||||
using var back = new ImageMagick.MagickImage();
|
||||
back.Ping(bytes.ToArray());
|
||||
back.GetExifProfile().Should().BeNull("the camera tag was removed from the stored original");
|
||||
SlpModularCms.Core.Media.MediaPaths.TryParse(stored.OriginalKey, out _).Should().BeFalse("originals are never an address");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSamePhotoTwice_IsOneImage()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
|
||||
var first = await rig.Upload(photo);
|
||||
var second = await rig.Upload(photo);
|
||||
|
||||
second.Id.Should().Be(first.Id);
|
||||
rig.Db.HeroImages.Count().Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADefaultFocus_IsTheCentre_ForEveryRatio()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
image.Focus.Should().Be(new FocusDto(0.5, 0.5, 1));
|
||||
image.WideFocus.Should().BeNull();
|
||||
image.TallFocus.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangingTheFocus_CutsNewVariants_AtNewAddresses_AndRetiresTheOldSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var oldSet = rig.Db.HeroImages.Single().SetHash;
|
||||
|
||||
var changed = await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(1.0, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var newSet = rig.Db.HeroImages.Single().SetHash;
|
||||
newSet.Should().NotBe(oldSet);
|
||||
changed.Variants.Should().OnlyContain(v => v.Url.Contains(newSet));
|
||||
changed.TallFocus.Should().Be(new FocusDto(1.0, 0.5, 1));
|
||||
changed.WideFocus.Should().BeNull();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(s => s.SetHash).Should().BeEquivalentTo(oldSet, newSet);
|
||||
rig.Db.HeroRetiredFiles.Should().ContainSingle(f => f.Kind == "set" && f.Key == oldSet);
|
||||
rig.IndexCache.Received().Invalidate();
|
||||
|
||||
// The tall variant now shows the right (blue) side of the photo.
|
||||
var tall = changed.Variants.First(v => v.Ratio == "tall" && v.Type == "image/webp");
|
||||
await using var file = (await rig.Store.OpenReadAsync(tall.Url["/media/".Length..], CancellationToken.None))!.Content;
|
||||
var bytes = new MemoryStream();
|
||||
await file.CopyToAsync(bytes);
|
||||
using var pixels = new ImageMagick.MagickImage(bytes.ToArray());
|
||||
pixels.GetPixels().GetPixel((int)(pixels.Width / 2), (int)(pixels.Height / 2)).ToColor()!.ToString().Should().StartWith("#0000FF");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSameFocus_DoesNotMakeANewSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResettingARatioToTheGeneralPoint_ReturnsToTheSameSet()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var original = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1), null, new FocusDto(0.9, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await rig.Images.SetFocusAsync(Guid.Parse(image.Id), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(original);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADeletedImage_IsRefused_WhileASlideUsesIt_AndRetiredOtherwise()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var inUse = async () => await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
await inUse.Should().ThrowAsync<HeroImageInUseException>();
|
||||
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, []), HeroTestRig.Admin, CancellationToken.None);
|
||||
await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
rig.Db.HeroRetiredFiles.Select(f => f.Kind).Should().BeEquivalentTo("set", "original");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnknownImage_IsNotFound()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var focus = async () => await rig.Images.SetFocusAsync(Guid.NewGuid(), new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)), HeroTestRig.Admin, CancellationToken.None);
|
||||
var delete = async () => await rig.Images.DeleteAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
await focus.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
await delete.Should().ThrowAsync<HeroImageNotFoundException>();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>", "unsupported_format")]
|
||||
[InlineData("not an image at all", "unsupported_format")]
|
||||
public async Task ARefusedUpload_StoresNothing(string text, string code)
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
|
||||
|
||||
var act = async () => await rig.Upload(bytes);
|
||||
|
||||
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be(code);
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATruncatedPhoto_StoresNothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
|
||||
var act = async () => await rig.Upload(photo.AsMemory(0, photo.Length / 4).ToArray());
|
||||
|
||||
await act.Should().ThrowAsync<ImageRejectedException>();
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheMediaStorageIsFull_TheUploadIsRefused_AndNothingIsStored()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
rig.Media.MaxTotalBytes = 1000;
|
||||
|
||||
var act = async () => await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await act.Should().ThrowAsync<MediaStorageFullException>();
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APhoto_ThatIsTallerThanItIsWide_GetsSensibleVariants()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var image = await rig.Upload(HeroTestRig.Photo(width: 800, height: 1200, seed: 1));
|
||||
|
||||
image.Variants.Where(v => v.Ratio == "wide").Should().OnlyContain(v => v.Width <= 800);
|
||||
image.Variants.Where(v => v.Ratio == "tall").Should().OnlyContain(v => v.Width <= 800);
|
||||
image.Variants.Should().NotBeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroServiceTests
|
||||
{
|
||||
private static HeroSaveRequest Request(IReadOnlyList<HeroSlideRequest>? slides = null, string title = "Andrea Slop") => new(
|
||||
title, "Lifestyle fotograaf", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null, slides ?? []);
|
||||
|
||||
[Fact]
|
||||
public async Task TheFirstSave_CreatesTheHero_WithItsSlidesInOrder()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
|
||||
var saved = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede foto"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Id.Should().NotBeNull();
|
||||
saved.Slides.Select(s => s.Alt).Should().Equal("tweede foto", "eerste foto");
|
||||
saved.Slides.Select(s => s.SortOrder).Should().Equal(0, 1);
|
||||
saved.IsLive.Should().BeTrue();
|
||||
rig.IndexCache.Received().Invalidate();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASecondSave_ReplacesTheWholeHero_KeepingTheIdsOfTheSlidesItKeeps()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var first = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var keep = Guid.Parse(first.Slides[1].Id);
|
||||
|
||||
var second = await rig.Service.SaveAsync(Request([new HeroSlideRequest(keep, Guid.Parse(b.Id), "twee, aangepast")], "Nieuwe titel"), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
second.Id.Should().Be(first.Id);
|
||||
second.Title.Should().Be("Nieuwe titel");
|
||||
second.Slides.Should().ContainSingle().Which.Should().Match<HeroSlideAdminDto>(s => s.Id == keep.ToString() && s.Alt == "twee, aangepast" && s.SortOrder == 0);
|
||||
rig.Db.HeroSlides.Count().Should().Be(1);
|
||||
rig.Db.Heroes.Count().Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReorderingSlides_ChangesTheirOrder_NotTheirIds()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
var first = await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "een"), new HeroSlideRequest(null, Guid.Parse(b.Id), "twee")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var ids = first.Slides.Select(s => Guid.Parse(s.Id)).ToArray();
|
||||
|
||||
var second = await rig.Service.SaveAsync(Request([new HeroSlideRequest(ids[1], Guid.Parse(b.Id), "twee"), new HeroSlideRequest(ids[0], Guid.Parse(a.Id), "een")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
second.Slides.Select(s => s.Id).Should().Equal(ids[1].ToString(), ids[0].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ADecorativeSlide_StoresNoAlt_AndAnInactiveOneIsKept_ButNotPublished()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
|
||||
var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
|
||||
await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.Parse(a.Id), "wordt genegeerd", Decorative: true), new HeroSlideRequest(null, Guid.Parse(b.Id), "uit", IsActive: false)]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
var pub = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
|
||||
admin.Slides.Should().HaveCount(2);
|
||||
admin.Slides[0].Alt.Should().BeEmpty();
|
||||
pub.Slides.Should().ContainSingle().Which.Decorative.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnknownImage_OrASlideOfAnotherHero_IsRejected()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var a = await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
var unknownImage = async () => await rig.Service.SaveAsync(Request([new HeroSlideRequest(null, Guid.NewGuid(), "x")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
var unknownSlide = async () => await rig.Service.SaveAsync(Request([new HeroSlideRequest(Guid.NewGuid(), Guid.Parse(a.Id), "x")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await unknownImage.Should().ThrowAsync<HeroSaveRejectedException>()).Which.Field.Should().Be("Slides[0].ImageId");
|
||||
(await unknownSlide.Should().ThrowAsync<HeroSaveRejectedException>()).Which.Field.Should().Be("Slides[0].Id");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheTexts_AreStoredAsPlainText_WithoutControlCharacters()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var saved = await rig.Service.SaveAsync(
|
||||
new HeroSaveRequest("Websites,\r\napps\u0007\n& meer.", " <b>tag</b> ", "lead\nregel twee", "single", [new HeroButtonRequest(" Knop ", " #contact ")], true, null, null, []),
|
||||
HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Title.Should().Be("Websites,\napps\n& meer.");
|
||||
saved.Tagline.Should().Be("<b>tag</b>");
|
||||
saved.Lead.Should().Be("lead\nregel twee");
|
||||
saved.Buttons.Should().ContainSingle().Which.Should().Be(new HeroButtonDto("Knop", "#contact"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASiteWithoutImages_CanHaveATextOnlyHero_WithTwoButtons()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Websites,\napps\n& meer.", null, "Lead.", "single",
|
||||
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")], true, null, null, null), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
var pub = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
|
||||
pub.Title.Should().Be("Websites,\napps\n& meer.");
|
||||
pub.Tagline.Should().BeNull();
|
||||
pub.Buttons.Select(b => b.Target).Should().Equal("#pakketten", "#contact");
|
||||
pub.Slides.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePublicHero_FollowsTheScheduleOfTheClock()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var start = rig.Time.Now.AddDays(1);
|
||||
await rig.Service.SaveAsync(Request() with { StartsAt = start, EndsAt = start.AddDays(7) }, HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
rig.Time.Now = start.AddHours(1);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().NotBeNull();
|
||||
rig.Time.Now = start.AddDays(7);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutAHero_TheAdminGetsEmptyDefaults_AndThePublicGetsNothing()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
|
||||
var admin = await rig.Service.GetAsync(CancellationToken.None);
|
||||
|
||||
admin.Id.Should().BeNull();
|
||||
admin.IsLive.Should().BeFalse();
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ManySlides_AreSaved_ButOnlyTheCeilingIsPublished()
|
||||
{
|
||||
using var rig = new HeroTestRig(maxPublishedSlides: 3);
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var slides = Enumerable.Range(0, 7).Select(i => new HeroSlideRequest(null, Guid.Parse(image.Id), "foto " + i)).ToList();
|
||||
|
||||
var saved = await rig.Service.SaveAsync(Request(slides), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
saved.Slides.Should().HaveCount(7);
|
||||
(await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides.Should().HaveCount(3);
|
||||
}
|
||||
}
|
||||
|
||||
public class HeroMediaCleanupTests
|
||||
{
|
||||
private static async Task<(string Set, string Original)> RetireAnImage(HeroTestRig rig)
|
||||
{
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
var row = rig.Db.HeroImages.Single();
|
||||
var keys = (row.SetHash, row.OriginalKey);
|
||||
await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
return keys;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RetiredFiles_StayForTheRetentionTime_ThenGo()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var (set, original) = await RetireAnImage(rig);
|
||||
|
||||
(await rig.Cleanup.RunOnceAsync(CancellationToken.None)).Should().Be(0);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().ContainSingle(s => s.SetHash == set);
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeTrue();
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
(await rig.Cleanup.RunOnceAsync(CancellationToken.None)).Should().Be(2);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
(await rig.Store.ExistsAsync(original, CancellationToken.None)).Should().BeFalse();
|
||||
rig.Db.HeroRetiredFiles.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARetiredSet_ThatIsUsedAgain_IsNeverDeleted()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var photo = HeroTestRig.Photo();
|
||||
var first = await rig.Upload(photo);
|
||||
var set = rig.Db.HeroImages.Single().SetHash;
|
||||
await rig.Images.DeleteAsync(Guid.Parse(first.Id), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
// The same photo with the same focus comes back: the same set again, referenced by a new row.
|
||||
var again = await rig.Upload(photo);
|
||||
rig.Db.HeroImages.Single().SetHash.Should().Be(set);
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(again.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().ContainSingle(s => s.SetHash == set);
|
||||
again.Variants.Should().OnlyContain(v => v.Url.Contains(set));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageNobodyUsed_IsRetiredAndRemoved_AfterTheRetentionTime()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
await rig.Upload(HeroTestRig.Photo());
|
||||
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(8);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().BeEmpty();
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnImageASlideUses_IsNeverRemoved()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
var image = await rig.Upload(HeroTestRig.Photo());
|
||||
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
|
||||
|
||||
rig.Time.Now = rig.Time.Now.AddDays(30);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
|
||||
rig.Db.HeroImages.Should().HaveCount(1);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ASetNoRowKnows_AndIsOld_IsRemoved_ButARecentOneIsNot()
|
||||
{
|
||||
using var rig = new HeroTestRig();
|
||||
await rig.Store.PutSetAsync("hero", "aaaaaaaaaaaaaaaa", new Dictionary<string, byte[]> { ["wide-960.webp"] = [1] }, CancellationToken.None);
|
||||
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().HaveCount(1);
|
||||
|
||||
rig.Time.Now = DateTimeOffset.UtcNow.AddDays(30);
|
||||
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
|
||||
(await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using ImageMagick;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using SlpModularCms.Core.Media;
|
||||
using SlpModularCms.Core.Media.Magick;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Repositories;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Hero.Tests;
|
||||
|
||||
public sealed class TestTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = now;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
/// <summary>A hero module over an in-memory database, a temporary media directory and the real image library.</summary>
|
||||
public sealed class HeroTestRig : IDisposable
|
||||
{
|
||||
public static readonly Guid Admin = Guid.Parse("11111111-2222-3333-4444-555555555555");
|
||||
|
||||
public TestTime Time { get; } = new(new DateTimeOffset(2026, 11, 16, 12, 0, 0, TimeSpan.Zero));
|
||||
public string Directory { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-tests-" + Guid.NewGuid().ToString("N"));
|
||||
public MediaOptions Media { get; }
|
||||
public HeroDbContext Db { get; }
|
||||
public IHeroRepository Repository { get; }
|
||||
public FileSystemMediaStore Store { get; }
|
||||
public MagickImageProcessor Processor { get; }
|
||||
public MediaStatus Status { get; } = new();
|
||||
public IIndexHtmlCache IndexCache { get; } = Substitute.For<IIndexHtmlCache>();
|
||||
public HeroImageService Images { get; }
|
||||
public HeroService Service { get; }
|
||||
public PublicHeroService Public { get; }
|
||||
public HeroMediaCleanup Cleanup { get; }
|
||||
public HeroOptions HeroOptions { get; } = new();
|
||||
|
||||
public HeroTestRig(int maxPublishedSlides = 50)
|
||||
{
|
||||
HeroOptions.MaxPublishedSlides = maxPublishedSlides;
|
||||
Media = new MediaOptions { Directory = Directory, BusyWaitSeconds = 0 };
|
||||
var mediaOptions = Options.Create(Media);
|
||||
Db = new HeroDbContext(new DbContextOptionsBuilder<HeroDbContext>().UseInMemoryDatabase("hero-" + Guid.NewGuid()).Options);
|
||||
Repository = new HeroRepository(Db);
|
||||
Store = new FileSystemMediaStore(mediaOptions);
|
||||
Processor = new MagickImageProcessor(mediaOptions, NullLogger<MagickImageProcessor>.Instance);
|
||||
Status.SetProcessor(true, Processor.SupportedInput, Processor.SupportedOutput);
|
||||
Status.SetDirectory(true);
|
||||
var gate = new MediaProcessingGate(mediaOptions);
|
||||
var guard = new MediaUploadGuard(Processor, gate, Status, mediaOptions);
|
||||
Images = new HeroImageService(guard, Processor, Store, gate, Repository, mediaOptions, NullLogger<HeroImageService>.Instance, Time, IndexCache);
|
||||
Service = new HeroService(Repository, Options.Create(HeroOptions), NullLogger<HeroService>.Instance, Time, IndexCache);
|
||||
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
|
||||
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger<HeroMediaCleanup>.Instance, Time);
|
||||
}
|
||||
|
||||
/// <summary>A photo-like fixture: the left half red, the right half blue, with a camera tag.</summary>
|
||||
public static byte[] Photo(int width = 1600, int height = 1067, MagickFormat format = MagickFormat.Jpeg, byte seed = 0)
|
||||
{
|
||||
using var image = new MagickImage(MagickColors.Red, (uint)width, (uint)height);
|
||||
using var blue = new MagickImage(MagickColors.Blue, (uint)(width / 2), (uint)height);
|
||||
image.Composite(blue, width - width / 2, 0, CompositeOperator.Over);
|
||||
if (seed > 0)
|
||||
{
|
||||
using var dot = new MagickImage(new MagickColor((byte)(seed * 20), 0, 0), 10, 10);
|
||||
image.Composite(dot, 3, 3, CompositeOperator.Over);
|
||||
}
|
||||
|
||||
var exif = new ExifProfile();
|
||||
exif.SetValue(ExifTag.Software, "camera firmware");
|
||||
image.SetProfile(exif);
|
||||
using var stream = new MemoryStream();
|
||||
image.Write(stream, format);
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
public Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> Upload(byte[] bytes)
|
||||
=> Images.UploadAsync(new MemoryStream(bytes), bytes.Length, Admin, CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Db.Dispose();
|
||||
if (System.IO.Directory.Exists(Directory))
|
||||
{
|
||||
System.IO.Directory.Delete(Directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="FluentAssertions" Version="8.10.0" />
|
||||
<PackageReference Include="FsCheck.Xunit" Version="3.4.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="10.0.9" />
|
||||
<!-- Pinned above the version DataProtection pulls transitively (FR-22, OPEN-03) - see Core.csproj -->
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.14" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.9" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="NSubstitute" Version="5.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Microsoft.Extensions.Options" />
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in New Issue
Block a user