PlotDirector/PlotLine.Tests/StoryElementReferenceTests.cs

145 lines
8.7 KiB
C#

using System.IO.Compression;
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
internal static class StoryElementReferenceTests
{
public static async Task Run()
{
var guest = new StoryElementReferencesController(new Guest(), null!, null!, null!, null!, null!, null!, null!);
foreach (var entity in Enum.GetValues<StoryElementType>())
{
Check(await guest.List(entity, 1) is NotFoundResult, "Reference lists require authentication.");
Check(await guest.Download(entity, 1, 2) is NotFoundResult, "Reference files require authentication.");
Check(await guest.Add(entity, 1, "Characteristic", "A characteristic", null) is NotFoundResult,
"Creating references requires authentication.");
Check(await guest.Change(entity, 1, 2, "delete", "AAAAAAAAAAA=", null) is NotFoundResult,
"Removing references requires authentication.");
}
Check(StoryElementAttachmentPolicy.IsImage("reference.PNG"), "Image routing is case insensitive.");
Check(StoryElementAttachmentPolicy.IsAudio("interview.wav", "RIFF0000WAVE"u8), "WAV has an audio type.");
Check(!StoryElementAttachmentPolicy.IsAudio("video.wav", "RIFF0000AVI "u8), "A renamed video is rejected.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.csv", "name,description"u8.ToArray()), "CSV text is accepted.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.pdf", "%PDF-1.7"u8.ToArray()), "PDF is accepted.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.txt", [77, 90, 0, 0]), "A binary renamed to text is rejected.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("setup.js", "alert(1)"u8.ToArray()), "Scripts are rejected.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml")), "Word documents are accepted.");
Check(StoryElementAttachmentPolicy.IsAllowedDocument("plan.xlsx", OfficeFile("xl/workbook.xml")), "Excel workbooks are accepted.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("notes.docx", OfficeFile("word/document.xml", "word/vbaProject.bin")),
"An Office archive with a macro project is rejected.");
Check(!StoryElementAttachmentPolicy.IsAllowedDocument("archive.zip", OfficeFile("word/document.xml")), "ZIP uploads are rejected.");
var legacy = new ProjectBackupExport { Project = new() { ProjectID = 4 } };
var legacyJson = JsonSerializer.Serialize(legacy);
Check(!legacyJson.Contains("\"StoryElementReferences\"", StringComparison.Ordinal),
"Legacy package fingerprints must omit the absent reference collection.");
Check(JsonSerializer.Serialize(JsonSerializer.Deserialize<ProjectBackupExport>(legacyJson)) == legacyJson,
"Reading and reserializing a legacy package must preserve its fingerprint.");
const string oldReference = """{"ReferenceID":1,"CharacterID":7,"LocationID":null,"StoryAssetID":null,"Kind":"Characteristic","Note":"Left-handed","StoragePath":null,"OriginalFileName":null}""";
Check(JsonSerializer.Serialize(JsonSerializer.Deserialize<ProjectBackupStoryElementReference>(oldReference)) == oldReference,
"Older backups with references retain their serialized fingerprint.");
string root = Directory.CreateTempSubdirectory("plotdirector-reference-test-").FullName;
try
{
var environment = new TestEnvironment { WebRootPath = root, ContentRootPath = root };
var uploads = new UploadStorageService(Options.Create(new StorageSettings { UploadsRoot = root }), environment);
var files = new ProjectBackupFiles(uploads);
var image = MapReferenceImageService.Normalize(MapAppearanceTests.Image(), "Sketch.png").ImageData!;
var attachment = "An attachment's original bytes"u8.ToArray();
var folder = StoryElementReferenceStorage.Folder;
uploads.GetDirectory(folder);
await File.WriteAllBytesAsync(uploads.GetFilePath(folder, "image.blob"), image);
await File.WriteAllBytesAsync(uploads.GetFilePath(folder, "document.blob"), attachment);
var backup = new ProjectBackupExport
{
Project = new() { ProjectID = 4 },
Data = new()
{
Characters = [new() { CharacterID = 7, ProjectID = 4 }],
Locations = [new() { LocationID = 7, ProjectID = 4 }],
StoryAssets = [new() { StoryAssetID = 7, ProjectID = 4 }],
StoryElementReferences =
[
new() { ReferenceID = 1, CharacterID = 7, Kind = "Characteristic", Note = "Left-handed" },
new() { ReferenceID = 2, LocationID = 7, Kind = "Image", Note = "Doorway", IsPrimary = true,
OriginalFileName = "Sketch.png", StoragePath = uploads.GetPublicPath(folder, "image.blob") },
new() { ReferenceID = 3, StoryAssetID = 7, Kind = "Attachment",
OriginalFileName = "Document.txt", Title = "Research notes", StoragePath = uploads.GetPublicPath(folder, "document.blob") }
]
}
};
await files.CaptureAsync(backup);
var restored = JsonSerializer.Deserialize<ProjectBackupExport>(JsonSerializer.Serialize(backup))!;
Check(ProjectBackupFiles.Validate(restored) is null, "All uploaded reference bytes survive serialization.");
var items = restored.Data.StoryElementReferences!;
Check(items[1].IsPrimary == true && items[2].Title == "Research notes",
"Primary-image selection and attachment titles survive backup serialization.");
Check(items[0].Note == "Left-handed" && items[0].StoragePath is null, "Notes are independent of files.");
Check(!StoryElementReferenceStorage.ValidBackupImage(attachment), "Arbitrary attachments cannot serve as images.");
using (await files.StageAsync(restored, importingCopy: true))
{
Check(items[1].StoragePath != backup.Data.StoryElementReferences![1].StoragePath,
"Staging a restored generation must preserve the current reference file.");
Check(File.ReadAllBytes(uploads.TryResolvePublicPath(items[1].StoragePath)!).SequenceEqual(image),
"Restored images retain their normalized bytes.");
Check(File.ReadAllBytes(uploads.TryResolvePublicPath(items[2].StoragePath)!).SequenceEqual(attachment),
"Restored attachments retain their original bytes.");
Check(items[2].OriginalFileName == "Document.txt", "Restored filenames remain available for downloads.");
}
Check(!File.Exists(uploads.TryResolvePublicPath(items[2].StoragePath)),
"An abandoned restore cleans up its staged reference files.");
Check(File.Exists(uploads.GetFilePath(folder, "document.blob")), "An abandoned restore keeps current files.");
}
finally
{
Directory.Delete(root, recursive: true);
}
Console.WriteLine("PASS reference authentication, attachment validation and backup round-trip");
}
private static byte[] OfficeFile(params string[] parts)
{
using var bytes = new MemoryStream();
using (var zip = new ZipArchive(bytes, ZipArchiveMode.Create, leaveOpen: true))
{
zip.CreateEntry("[Content_Types].xml");
foreach (var part in parts) zip.CreateEntry(part);
}
return bytes.ToArray();
}
private static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private sealed class Guest : ICurrentUserService
{
public int? UserId => null;
public string? Email => null;
public string? DisplayName => null;
public bool IsAuthenticated => false;
}
private sealed class TestEnvironment : IWebHostEnvironment
{
public string ApplicationName { get; set; } = "";
public string EnvironmentName { get; set; } = "";
public string ContentRootPath { get; set; } = "";
public string WebRootPath { get; set; } = "";
public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; } = null!;
public Microsoft.Extensions.FileProviders.IFileProvider WebRootFileProvider { get; set; } = null!;
}
}