PlotDirector/PlotLine.Tests/ProjectExportDatabaseTests.cs

138 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Concurrent;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using Dapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
// Called only after the parent harness verifies the literal synthetic-only database and creates its own actors/data.
internal static class ProjectExportDatabaseTests
{
private sealed record Packet(string Action,string Parameter,int ID,string[] Expected,bool Ordered=false,bool BookMetadata=false);
public static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,int owner,int other,int project,int book,int chapter,int scene,int character)
{
using(var db=factory.CreateConnection())
{
if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!="PlotDirector_Phase2_20261103_2305" || await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")!=1)
throw new InvalidOperationException("Export fixtures require the verified synthetic-only database.");
await db.ExecuteAsync("IF NOT EXISTS(SELECT 1 FROM dbo.SceneNoteTypes WHERE TypeName=N'Research Note') INSERT dbo.SceneNoteTypes(TypeName,SortOrder) VALUES(N'Research Note',20);INSERT dbo.SceneNotes(SceneID,SceneNoteTypeID,NoteTitle,NoteText,SortOrder) SELECT @scene,SceneNoteTypeID,N'Research Ω',@longNote,2 FROM dbo.SceneNoteTypes WHERE TypeName=N'Research Note';",new{scene,longNote="<script>fixture_only()</script>\n"+string.Concat(Enumerable.Repeat("Long research — 雪 café 🖋\n",5000))});
var foreign=await db.ExecuteScalarAsync<int>("SELECT TOP(1) ProjectID FROM dbo.ProjectUserAccess WHERE UserID=@other AND AccessRole=N'Owner' ORDER BY ProjectID",new{other});
await db.ExecuteAsync("INSERT dbo.Characters(ProjectID,CharacterName) VALUES(@foreign,N'Foreign-only marker Ω')",new{foreign});
}
var sourceBackup=(await new ProjectBackupRepository(factory).GetProjectBackupAsync(project,owner))!;
await files.CaptureAsync(sourceBackup);
var point=await new ProjectRestorePointRepository(factory).CreateAsync(project,"Synthetic downloadable restore point","Manual",JsonSerializer.Serialize(sourceBackup),"HTTP transfer fixture");
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});
builder.WebHost.UseUrls("http://127.0.0.1:0");builder.Logging.ClearProviders();
builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();
builder.Services.AddAuthentication("ExportFixture").AddCookie("ExportFixture",options=>options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;return Task.CompletedTask;});
builder.Services.AddAuthorization();builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(factory);builder.Services.AddSingleton(files);
builder.Services.AddScoped<ICurrentUserService,CurrentUserService>();
builder.Services.AddScoped<IExportRepository,ExportRepository>();builder.Services.AddScoped<IExportService,ExportService>();
builder.Services.AddScoped<IProjectAccessRepository,ProjectAccessRepository>();builder.Services.AddScoped<IProjectAccessService,ProjectAccessService>();
builder.Services.AddScoped<IProjectBackupRepository,ProjectBackupRepository>();builder.Services.AddScoped<IProjectExportService,ProjectExportService>();
builder.Services.AddScoped<IProjectRepository,ProjectRepository>();
builder.Services.AddScoped<IProjectRestorePointRepository,ProjectRestorePointRepository>();builder.Services.AddScoped<IProjectRestorePointService,ProjectRestorePointService>();
builder.Services.AddScoped<IProjectRestoreService,ProjectRestoreService>();
builder.Services.AddSingleton<IProjectActivityService>(new NoActivity());
builder.Services.AddScoped<ProjectAccessFilter>();
builder.Services.AddControllersWithViews(options=>options.Filters.Add<ProjectAccessFilter>()).AddApplicationPart(typeof(ExportsController).Assembly);
await using var app=builder.Build();var errors=new ConcurrentQueue<string>();
app.Use(async(context,next)=>{
if(int.TryParse(context.Request.Headers["X-Synthetic-Actor"],out var actor) && (actor==owner||actor==other))context.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,actor.ToString())],"ExportFixture"));
try {await next();} catch(Exception ex){errors.Enqueue(ex.Message);context.Response.StatusCode=500;await context.Response.WriteAsync("Synthetic export failed.");}
});
app.UseAuthorization();app.MapControllerRoute("default","{controller=Exports}/{action=StoryBible}/{id?}");
await app.StartAsync();var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
using var client=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){BaseAddress=new Uri(address)};
var packets=new[]{
new Packet("StoryBible","projectId",project,["Narrator Ω","Notebook 雨","Room Ω","Scene café"]),
new Packet("NarrativeTimeline","projectId",project,["Scene café","Second empty scene"],true,true),
new Packet("Character","id",character,["Narrator Ω","Knows the secret 雨","Observer 雪"]),
new Packet("SceneBrief","id",scene,["Scene café","“Hello”—雪 🖋"],false,true),
new Packet("ChapterBrief","id",chapter,["Chapter 雨","Goal Ω","Question café","Second empty scene"],true,true),
new Packet("WritingSession","sceneId",scene,["Scene café","Check continuity 雨"],false,true),
new Packet("ResearchPack","projectId",project,["Research Ω","Empty text attachment","Long research — 雪 café 🖋"],false,true),
new Packet("Search","projectId",project,["Narrator Ω","Envelope Ω"])
};
var failures=new List<string>();var coverage=new List<string>{"Workflow,Format,HTTP,ContentAndMetadata,Ownership,IntendedScope"};
async Task<HttpResponseMessage> Get(string route,int? actor)
{
using var request=new HttpRequestMessage(HttpMethod.Get,route);if(actor.HasValue)request.Headers.Add("X-Synthetic-Actor",actor.Value.ToString());return await client.SendAsync(request);
}
foreach(var packet in packets)
{
var canonical=new Dictionary<string,string>();
foreach(var format in new[]{"html","markdown","text","md","txt"})
{
var route=$"/Exports/{packet.Action}?{packet.Parameter}={packet.ID}&format={format}&q=%CE%A9";
using var response=await Get(route,owner);var content=await response.Content.ReadAsStringAsync();
if(response.StatusCode!=HttpStatusCode.OK){failures.Add($"{packet.Action}/{format}: HTTP {(int)response.StatusCode}; {errors.LastOrDefault()}");continue;}
var decoded=format=="html"?WebUtility.HtmlDecode(content):content;
foreach(var expected in packet.Expected)if(!decoded.Contains(expected,StringComparison.Ordinal))failures.Add($"{packet.Action}/{format}: missing expected fixture content {expected}");
if(decoded.Contains("Foreign-only marker",StringComparison.Ordinal))failures.Add(packet.Action+": foreign project content escaped scope");
if(packet.Ordered && !(decoded.IndexOf("Scene café",StringComparison.Ordinal)<decoded.IndexOf("Second empty scene",StringComparison.Ordinal)))failures.Add(packet.Action+": scene ordering differs");
if(packet.BookMetadata&&!decoded.Contains("Subtitle é",StringComparison.Ordinal))failures.Add(packet.Action+": book subtitle omitted");
var expectedType=format switch {"html"=>"text/html","markdown" or "md"=>"text/markdown",_=>"text/plain"};
if(response.Content.Headers.ContentType?.MediaType!=expectedType)failures.Add(packet.Action+": wrong content type");
if(format!="html" && response.Content.Headers.ContentDisposition?.FileName is null && response.Content.Headers.ContentDisposition?.FileNameStar is null)failures.Add(packet.Action+": missing download filename");
if(format=="html" && content.Contains("<script>fixture_only()",StringComparison.Ordinal))failures.Add(packet.Action+": HTML contains unescaped fixture markup");
if(packet.Action=="ResearchPack" && decoded.Split("Long research — 雪 café 🖋").Length-1!=5000)failures.Add(packet.Action+": long research content truncated");
if(format=="md" && canonical.GetValueOrDefault("markdown")!=content || format=="txt" && canonical.GetValueOrDefault("text")!=content)failures.Add(packet.Action+": format alias content differs");
canonical[format]=content;
coverage.Add($"{packet.Action},{format},{(int)response.StatusCode},Unicode metadata order and applicable long/empty content compared,Other author and anonymous cases checked separately,Reference/brief document; no import or full-project fidelity claim");
}
using(var denied=await Get($"/Exports/{packet.Action}?{packet.Parameter}={packet.ID}&q=%CE%A9",other))
if(denied.StatusCode!=HttpStatusCode.NotFound)failures.Add(packet.Action+": another author could access an export");
using(var anonymous=await Get($"/Exports/{packet.Action}?{packet.Parameter}={packet.ID}",null))
if(anonymous.StatusCode!=HttpStatusCode.Unauthorized)failures.Add(packet.Action+": anonymous export not rejected");
using(var absent=await Get($"/Exports/{packet.Action}?{packet.Parameter}=2147483647",owner))
if(absent.StatusCode!=HttpStatusCode.NotFound)failures.Add(packet.Action+": missing positive identifier not rejected");
using(var empty=await Get($"/Exports/{packet.Action}?{packet.Parameter}=0",owner))
if(empty.IsSuccessStatusCode)failures.Add(packet.Action+": missing/zero identifier returned a successful empty document");
}
using(var response=await Get($"/Exports/ProjectBackup?projectId={project}",owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("ProjectBackup HTTP failed");
else
{
var backup=JsonSerializer.Deserialize<ProjectBackupExport>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
if(backup.FormatVersion!="1.4" || backup.Files.Count!=12 || backup.Data.CharacterImages.Count!=2)failures.Add("ProjectBackup HTTP omitted embedded files/gallery");
}
}
using(var response=await Get($"/Exports/ProjectBackup?projectId={project}",other))if(response.StatusCode!=HttpStatusCode.NotFound)failures.Add("Full project backup crossed author boundary");
var pointRoute=$"/ProjectRestorePoints/Download?projectId={project}&id={point.ProjectRestorePointID}";
using(var response=await Get(pointRoute,owner))
{
if(response.StatusCode!=HttpStatusCode.OK)failures.Add("Restore point download HTTP failed");
else if(JsonSerializer.Deserialize<ProjectBackupExport>(await response.Content.ReadAsStringAsync(),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!.Files.Count!=12)failures.Add("Restore point download omitted embedded files");
}
using(var response=await Get(pointRoute,other))if(response.StatusCode!=HttpStatusCode.NotFound)failures.Add("Restore point download crossed author boundary");
using(var response=await Get(pointRoute,null))if(response.StatusCode!=HttpStatusCode.Unauthorized)failures.Add("Anonymous restore point download was not rejected");
coverage.Add("ProjectBackup,json,200,Twelve files and gallery metadata,Other author rejected,Portable project data with explicitly recorded remaining SI scope limits");
coverage.Add("RestorePointDownload,json,200,Twelve embedded files retained,Other author and anonymous rejected,Stored project restore point; same backup format");
await app.StopAsync();
if(failures.Count>0)throw new InvalidOperationException(string.Join(Environment.NewLine,failures.Distinct()));
await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-export-coverage.csv",coverage);
Console.WriteLine("PASS real HTTP/SQL exports: 8 packets × 5 formats/aliases, Unicode/order/subtitle/empty and long content, HTML encoding, owner/other/anonymous/missing boundaries; full project and restore point downloads retain 12 files/gallery metadata.");
}
private sealed class NoActivity:IProjectActivityService
{
public Task<PlotLine.ViewModels.ProjectActivityViewModel?> GetActivityAsync(int projectId)=>throw new NotSupportedException();
public Task RecordAsync(int projectId,string actionType,string entityType,int? entityId=null,string? entityName=null,string? summary=null)=>Task.CompletedTask;
}
}