PlotDirector/PlotLine.Tests/ManuscriptReaderTests.cs

116 lines
9.1 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.Manuscript;
using PlotDirector.Companion.Protocol.Manuscript;
internal static class ManuscriptReaderTests
{
internal static readonly Chapter[] Chapters = [
new() { ChapterID = 21, BookID = 12, ChapterNumber = 1, ChapterTitle = "The crossing" },
new() { ChapterID = 22, BookID = 12, ChapterNumber = 2, ChapterTitle = "Arrival" },
new() { ChapterID = 23, BookID = 12, ChapterNumber = 3, ChapterTitle = "Unwritten" }
];
internal static ParagraphManuscript Snapshot()
{
var heading = Guid.NewGuid();
return new() {
BookId = 12, UpdatedUtc = new DateTime(2026, 11, 13, 10, 11, 12, DateTimeKind.Utc),
Chapters = [new() { CanonicalId = 21, HeadingId = heading }],
ChapterCheckpoints = [new() { ChapterId = 21, LastSuccessfulSyncUtc = new DateTime(2026, 11, 13, 10, 12, 13, DateTimeKind.Utc) }],
Paragraphs = [
new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 2, Text = "Second paragraph.\r", Outline = 10 } },
new() { ChapterId = 21, Story = false, Occurrence = new() { Id = heading, Ordinal = 0, Text = "The crossing\r", Outline = 1 } },
new() { ChapterId = 21, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 1, Text = "First paragraph: <script>unsafe()</script> & <b>plain text</b>.\r", Outline = 10 } },
new() { ChapterId = 22, Story = true, Occurrence = new() { Id = Guid.NewGuid(), Ordinal = 3, Text = "Another chapter only.\r", Outline = 10 } },
new() { ChapterId = null, Story = false, Occurrence = new() { Ordinal = 4, Text = "Excluded section." } }
]
};
}
internal static ManuscriptReaderService FixtureService(Func<ParagraphManuscript?>? snapshot = null, Action? onRead = null)
{
var fixture = Snapshot();
var repository = NativeWorkflowTests.Proxy<IParagraphManuscriptRepository>((name, args) => {
if (name is not ("Get" or "Status")) throw new Exception("Reader attempted manuscript mutation: " + name);
if ((int)args![0]! != 4 || (int)args[1]! != 12) throw new UnauthorizedAccessException();
if (name == "Get") onRead?.Invoke();
var current = snapshot is null ? fixture : snapshot();
return name == "Get" ? Task.FromResult(current) : Task.FromResult(current is null ? null : new ParagraphSyncStatus { Revision = current.Revision });
});
var books = NativeWorkflowTests.Proxy<IBookRepository>((name, _) => name == "GetAsync"
? Task.FromResult<Book?>(new() { BookID = 12, BookTitle = "A Distant Shore", ProjectID = 7 }) : throw new Exception(name));
var chapters = NativeWorkflowTests.Proxy<IChapterRepository>((name, args) => name switch {
"ListByBookAsync" => Task.FromResult<IReadOnlyList<Chapter>>(Chapters),
"GetAsync" => Task.FromResult(Chapters.FirstOrDefault(c => c.ChapterID == (int)args![0]!)),
_ => throw new Exception(name)
});
return new(repository, books, chapters);
}
internal static ParagraphManuscript LongSnapshot()
{
var state = Snapshot();
state.Paragraphs.AddRange(Enumerable.Range(0,80).Select(i => new StoryParagraph {
ChapterId = 21, Story = true,
Occurrence = new() { Id = Guid.NewGuid(), Ordinal = i + 10, Outline = 10,
Text = $"Synthetic reading paragraph {i + 1}. " + string.Join(" ", Enumerable.Repeat("This is selectable captured prose used only for browser verification.", 5)) }
}));
return state;
}
public static async Task Run()
{
void Check(bool value, string message) { if (!value) throw new Exception(message); }
var state = Snapshot(); var reads = 0; var service = FixtureService(() => state, () => reads++);
var first = (await service.Read(4, 12, null))!;
Check(first.Chapters.Count == 3 && first.Chapter!.ChapterID == 21, "Book context and canonical chapter ordering");
Check(first.PreviousId is null && first.NextId == 22, "First chapter navigation");
Check(first.Paragraphs.Select(p => p.Text).SequenceEqual(state.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(3).Select(p => p.Occurrence.Text)), "Exact accepted paragraph order, heading and boundaries");
Check(first.Paragraphs.All(p => p.Id != Guid.Empty), "Paragraph identities retained internally");
Check(first.LastSuccessfulSyncUtc == state.ChapterCheckpoints[0].LastSuccessfulSyncUtc && first.SnapshotCapturedUtc == state.UpdatedUtc, "Distinct exact timestamp sources");
var last = (await service.Read(4, 12, 23))!;
Check(last.PreviousId == 22 && last.NextId is null && last.Paragraphs.Count == 0, "Last chapter navigation and empty state");
Check(await service.Read(4, 12, 999) is null, "Cross-book or unknown chapter rejected");
try { await service.Read(5, 12, 21); throw new Exception("Foreign account retrieved manuscript"); } catch (UnauthorizedAccessException) { }
try { await service.Read(4, 13, 21); throw new Exception("Foreign book retrieved manuscript"); } catch (UnauthorizedAccessException) { }
var windows = Snapshot();
windows.Paragraphs = windows.Paragraphs.OrderBy(p => p.Occurrence.Ordinal).Take(4).ToList();
windows.Chapters.Add(new() { CanonicalId = 22, HeadingId = windows.Paragraphs[3].Occurrence.Id });
windows.Paragraphs.Insert(2, new() { Occurrence = new() { Id = Guid.NewGuid(), Text = " ", Ordinal = 1 } });
var complete = ManuscriptReaderService.Project(first.Book, Chapters, Chapters[0], windows);
Check(complete.Paragraphs.Count == 4 && complete.Paragraphs.Any(p => p.Text == " "), "Heading windows preserve unassigned blank paragraphs and scene separators");
var baseline = first.ContentVersion;
Check(!(await service.Check(4,12,21,state.Revision,baseline))!.Changed, "Initial poll checks accepted metadata without a false update");
Check(reads == 3, "Unchanged poll never transfers the paragraph aggregate");
state.Revision++;
state.ChapterCheckpoints[0].LastSuccessfulSyncUtc = DateTime.UtcNow;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Successful unchanged synchronisation does not change the chapter fingerprint");
state.Paragraphs.Single(p => p.ChapterId == 22).Occurrence.Text = "Other chapter accepted change";
state.Revision++;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Another chapter revision does not rerender the selected chapter");
Check(await service.Check(4,12,999,state.Revision,baseline) is null, "Poll rejects a chapter outside the book even on unchanged revision");
try { await service.Check(5,12,21,state.Revision,baseline); throw new Exception("Foreign poll allowed"); } catch (UnauthorizedAccessException) { }
var pending = ParagraphManuscriptEngine.Clone(state); pending.Paragraphs[2].Occurrence.Text = "Pending change";
Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text != "Pending change", "Uncommitted or rejected submissions cannot enter Reader");
pending.Revision++;
Check(!(await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Pending or rejected text is absent from change checks");
state = pending;
Check((await service.Check(4,12,21,first.Revision,baseline))!.Changed, "Genuine accepted chapter change has a different fingerprint");
Check((await service.Read(4, 12, 21))!.Paragraphs[1].Text == "Pending change", "Next read sees newly committed snapshot without cache");
var empty = await FixtureService(() => null).Read(4, 12, 21);
Check(empty!.Paragraphs.Count == 0 && empty.SnapshotCapturedUtc is null, "Missing accepted snapshot remains empty without bootstrap");
var user = NativeWorkflowTests.Proxy<ICurrentUserService>((_, _) => 5);
var controller = new ManuscriptReaderController(service, user, NullLogger<ManuscriptReaderController>.Instance) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } };
Check(await controller.Index(12, 21) is NotFoundResult, "Controller does not leak unauthorised book existence");
Check(typeof(ManuscriptReaderController).IsDefined(typeof(AuthorizeAttribute), true), "Reader requires authentication");
var cache = (ResponseCacheAttribute)System.Attribute.GetCustomAttribute(typeof(ManuscriptReaderController), typeof(ResponseCacheAttribute))!;
Check(cache.NoStore && cache.Location == ResponseCacheLocation.None, "Private manuscript responses cannot be cached");
Check(controller.Response.Headers["X-Robots-Tag"] == "noindex, nofollow, noarchive", "Manuscript indexing disabled");
Console.WriteLine("PASS Manuscript Reader: scoped read-only retrieval, ordering, navigation, empty snapshot, accepted updates, pending isolation and accurate timestamps");
}
}