H4: hero in de eerste HTML (regio, preload), gedeeld datablok met contributors (Offerings byte-identiek), ASF golden files, volledige pijplijntest
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using ImageMagick;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SlpModularCms.Modules.Hero.Data;
|
||||
using SlpModularCms.Modules.Hero.Models;
|
||||
using SlpModularCms.Modules.Hero.Services;
|
||||
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>The hero on the master host with Andrea Slop Fotografie's settings: a prerendered page with the hero markers, a media directory and a real database.</summary>
|
||||
public sealed class HeroInjectionFactory : AsfVariantFactory, IDisposable
|
||||
{
|
||||
public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-web-" + Guid.NewGuid().ToString("N"));
|
||||
public string MediaDirectory { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-media-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public HeroInjectionFactory() => Directory.CreateDirectory(Path.Combine(WebRoot, "web"));
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
builder.UseWebRoot(WebRoot);
|
||||
builder.ConfigureAppConfiguration((_, config) =>
|
||||
config.AddInMemoryCollection(new Dictionary<string, string?> { ["Media:Directory"] = MediaDirectory, ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" }));
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
base.Dispose(disposing);
|
||||
if (disposing)
|
||||
{
|
||||
foreach (var directory in new[] { WebRoot, MediaDirectory })
|
||||
{
|
||||
if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Collection("HeroDatabase")]
|
||||
public class HeroInjectionPipelineTests : IClassFixture<HeroInjectionFactory>
|
||||
{
|
||||
private const string Page =
|
||||
"<!doctype html><html><head><!--CMS:HERO-PRELOAD-->baked preload<!--/CMS:HERO-PRELOAD-->" +
|
||||
"<!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>" +
|
||||
"<body><!--CMS:HERO-HTML-->baked hero<!--/CMS:HERO-HTML--></body></html>";
|
||||
|
||||
private readonly HeroInjectionFactory _factory;
|
||||
|
||||
public HeroInjectionPipelineTests(HeroInjectionFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
File.WriteAllText(Path.Combine(factory.WebRoot, "web", "hero.html"), Page);
|
||||
}
|
||||
|
||||
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> action)
|
||||
{
|
||||
_ = _factory.CreateClient(); // starts the host, migrates and runs the start-up checks
|
||||
await using var scope = _factory.Services.CreateAsyncScope();
|
||||
return await action(scope.ServiceProvider);
|
||||
}
|
||||
|
||||
private static byte[] Photo()
|
||||
{
|
||||
using var image = new MagickImage(MagickColors.Red, 1600, 1067);
|
||||
using var blue = new MagickImage(MagickColors.Blue, 800, 1067);
|
||||
image.Composite(blue, 800, 0, CompositeOperator.Over);
|
||||
using var stream = new MemoryStream();
|
||||
image.Write(stream, MagickFormat.Jpeg);
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
private static string DataBlock(string body)
|
||||
{
|
||||
const string open = "<script type=\"application/json\" id=\"cms-data\">";
|
||||
var start = body.IndexOf(open, StringComparison.Ordinal) + open.Length;
|
||||
return body[start..body.IndexOf("</script>", start, StringComparison.Ordinal)];
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AHeroMadeThroughTheModule_ShowsInTheFirstHtml_AndItsImagesAreServed()
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ClearHeroes();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ClearHeroes()
|
||||
=> await InScope(async sp =>
|
||||
{
|
||||
var db = sp.GetRequiredService<HeroDbContext>();
|
||||
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
var caller = Guid.NewGuid();
|
||||
|
||||
// Clean slate: the database is shared with other tests.
|
||||
await InScope(async sp =>
|
||||
{
|
||||
var db = sp.GetRequiredService<HeroDbContext>();
|
||||
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
|
||||
// Without a hero the page stays as it was built, and the data block says so.
|
||||
var before = await client.GetAsync("/hero");
|
||||
before.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
var beforeBody = await before.Content.ReadAsStringAsync();
|
||||
beforeBody.Should().Contain("baked hero").And.Contain("baked preload");
|
||||
JsonDocument.Parse(DataBlock(beforeBody)).RootElement.GetProperty("hero").ValueKind.Should().Be(JsonValueKind.Null);
|
||||
var etagBefore = before.Headers.ETag!.Tag;
|
||||
|
||||
// Upload a photo and publish a hero through the module's services.
|
||||
var image = await InScope(sp => sp.GetRequiredService<IHeroImageService>().UploadAsync(new MemoryStream(Photo()), Photo().Length, caller, default));
|
||||
await InScope(async sp => await sp.GetRequiredService<IHeroService>().SaveAsync(
|
||||
new HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null,
|
||||
[new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default));
|
||||
|
||||
var live = await client.GetAsync("/hero");
|
||||
var body = await live.Content.ReadAsStringAsync();
|
||||
live.Headers.ETag!.Tag.Should().NotBe(etagBefore);
|
||||
body.Should().NotContain("baked hero").And.NotContain("baked preload");
|
||||
body.Should().Contain("<picture class=\"cms-hero-picture\"><source media=\"(orientation: portrait)\"");
|
||||
body.Should().Contain("alt=\"Zwangerschapsfoto in de duinen\"").And.Contain("<span class=\"cms-hero-name\">Andrea Slop</span>");
|
||||
body.Should().Contain("<a class=\"cms-hero-button\" href=\"/over-mij\">Lees meer</a>");
|
||||
body.Should().Contain("<link rel=\"preload\" as=\"image\"").And.Contain("media=\"(orientation: landscape)\"");
|
||||
|
||||
// The data block carries the same hero as the public endpoint, after the site address.
|
||||
var data = JsonDocument.Parse(DataBlock(body)).RootElement;
|
||||
data.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "banners", "hero");
|
||||
var api = JsonDocument.Parse(await client.GetStringAsync("/api/v1/hero")).RootElement;
|
||||
System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(data.GetProperty("hero").GetRawText()), System.Text.Json.Nodes.JsonNode.Parse(api.GetRawText()))
|
||||
.Should().BeTrue("the data block carries the same JSON as GET /api/v1/hero");
|
||||
|
||||
// Every address in the page is served by the host: immutable, same origin.
|
||||
var src = api.GetProperty("slides")[0].GetProperty("image").GetProperty("src").GetString()!;
|
||||
body.Should().Contain($"src=\"{src}\"");
|
||||
foreach (var url in api.GetProperty("slides")[0].GetProperty("image").GetProperty("variants").EnumerateArray().Select(v => v.GetProperty("url").GetString()!))
|
||||
{
|
||||
var media = await client.GetAsync(url);
|
||||
media.StatusCode.Should().Be(HttpStatusCode.OK, url);
|
||||
media.Headers.CacheControl!.ToString().Should().Be("public, max-age=31536000, immutable");
|
||||
(await media.Content.ReadAsByteArrayAsync()).Length.Should().BeGreaterThan(100);
|
||||
}
|
||||
|
||||
// A matching ETag is a 304.
|
||||
var conditional = new HttpRequestMessage(HttpMethod.Get, "/hero");
|
||||
conditional.Headers.IfNoneMatch.Add(live.Headers.ETag);
|
||||
(await client.SendAsync(conditional)).StatusCode.Should().Be(HttpStatusCode.NotModified);
|
||||
|
||||
// Switching the hero off puts the baked page back at once.
|
||||
await InScope(async sp =>
|
||||
{
|
||||
var service = sp.GetRequiredService<IHeroService>();
|
||||
var current = await service.GetAsync(default);
|
||||
await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: false, null, null,
|
||||
current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default);
|
||||
return 0;
|
||||
});
|
||||
var off = await client.GetStringAsync("/hero");
|
||||
off.Should().Contain("baked hero").And.Contain("baked preload").And.NotContain("cms-hero-picture");
|
||||
|
||||
// And a media directory that lost its files leaves the baked hero too (no broken first image).
|
||||
await InScope(async sp =>
|
||||
{
|
||||
var service = sp.GetRequiredService<IHeroService>();
|
||||
var current = await service.GetAsync(default);
|
||||
await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: true, null, null,
|
||||
current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default);
|
||||
return 0;
|
||||
});
|
||||
(await client.GetStringAsync("/hero")).Should().Contain("cms-hero-picture");
|
||||
Directory.Delete(Path.Combine(_factory.MediaDirectory, "hero"), recursive: true);
|
||||
await InScope(sp => { sp.GetRequiredService<SlpModularCms.Core.Hosting.Website.IIndexHtmlCache>().Invalidate(); return Task.FromResult(0); });
|
||||
var missing = await client.GetStringAsync("/hero");
|
||||
missing.Should().Contain("baked hero").And.NotContain("cms-hero-picture");
|
||||
|
||||
// Clean up for the other tests.
|
||||
await InScope(async sp =>
|
||||
{
|
||||
var db = sp.GetRequiredService<HeroDbContext>();
|
||||
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using SlpModularCms.Modules.Hero.Data;
|
||||
namespace SlpModularCms.Api.Tests;
|
||||
|
||||
/// <summary>The Hero module on the real master host and the real, migrated database.</summary>
|
||||
[Collection("HeroDatabase")]
|
||||
public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
|
||||
{
|
||||
private readonly ApiWebApplicationFactory _factory;
|
||||
@@ -25,6 +26,15 @@ public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
|
||||
[Fact]
|
||||
public async Task WithoutAHero_ThePublicEndpointAnswers204_WithTheShortCache()
|
||||
{
|
||||
// The database is shared with other tests (and earlier runs): start without a hero.
|
||||
_ = _factory.CreateClient();
|
||||
using (var scope = _factory.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<HeroDbContext>();
|
||||
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var response = await _factory.CreateClient().GetAsync("/api/v1/hero");
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
|
||||
|
||||
Reference in New Issue
Block a user