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;
}
/// A hero module over an in-memory database, a temporary media directory and the real image library.
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();
public HeroRenderSignal Signal { get; } = new();
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, SlpModularCms.Core.Media.Library.IMediaLibrarySync? librarySync = null)
{
HeroOptions.MaxPublishedSlides = maxPublishedSlides;
Media = new MediaOptions { Directory = Directory, BusyWaitSeconds = 0 };
var mediaOptions = Options.Create(Media);
Db = new HeroDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase("hero-" + Guid.NewGuid()).Options);
Repository = new HeroRepository(Db);
Store = new FileSystemMediaStore(mediaOptions);
Processor = new MagickImageProcessor(mediaOptions, NullLogger.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.Instance, Time, IndexCache, Signal, librarySync);
Service = new HeroService(Repository, Images, Options.Create(HeroOptions), NullLogger.Instance, Time, IndexCache, null, librarySync);
Public = new PublicHeroService(Repository, Options.Create(HeroOptions), Time);
Cleanup = new HeroMediaCleanup(Repository, Store, mediaOptions, NullLogger.Instance, Time, librarySync);
}
/// A photo-like fixture: the left half red, the right half blue, with a camera tag.
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();
}
/// Changes the focus of an image the way the admin does: with the next save of the hero (the slides of the hero are left empty here).
public async Task SetFocus(Guid imageId, SlpModularCms.Modules.Hero.Models.HeroFocusRequest request)
{
await Service.SaveAsync(
new SlpModularCms.Modules.Hero.Models.HeroSaveRequest("Titel", null, null, "single", [], [],
[new SlpModularCms.Modules.Hero.Models.HeroImageFocusRequest(imageId, request.Focus, request.Wide, request.Tall)]),
Admin, CancellationToken.None);
await RenderPending();
return SlpModularCms.Modules.Hero.Services.HeroMapping.ToImageDto((await Repository.GetImageAsync(imageId, CancellationToken.None))!);
}
/// Uploads an image and lets the background renderer cut its variants (here: at once, the way the worker would).
public async Task Upload(byte[] bytes)
{
var dto = await UploadWithoutRendering(bytes);
await RenderPending();
return SlpModularCms.Modules.Hero.Services.HeroMapping.ToImageDto((await Repository.GetImageAsync(Guid.Parse(dto.Id), CancellationToken.None))!);
}
/// The upload request as such: the image is stored and its variants are still to be cut.
public Task UploadWithoutRendering(byte[] bytes)
=> Images.UploadAsync(new MemoryStream(bytes), bytes.Length, Admin, CancellationToken.None);
/// Does the work of the background renderer until nothing is pending.
public async Task RenderPending()
{
var count = 0;
while (await Images.RenderNextPendingAsync(new HashSet(), CancellationToken.None) is not null)
{
count++;
if (count > 100)
{
throw new InvalidOperationException("The renderer does not settle.");
}
}
return count;
}
public void Dispose()
{
Db.Dispose();
if (System.IO.Directory.Exists(Directory))
{
System.IO.Directory.Delete(Directory, recursive: true);
}
}
}