Files
AI-Studio/app/Tests/Tools/PowerPoint/PresentationFileTests.cs
T

250 lines
13 KiB
C#

using System.IO.Compression;
using AIStudio.Tests.Tools.OpenXml;
using AIStudio.Tools.PowerPoint;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools.PowerPoint;
/// <summary>
/// Checks that a presentation file comes about without anything next to the file the user chose, and without its
/// template or its pictures in memory.
/// </summary>
/// <remarks>
/// Inside the Flatpak, the save dialog grants access to exactly the chosen file. A temporary file next
/// to it, or a file moved there, fails, which no test on another system would notice otherwise. The
/// test template reads as L1 "Title" and L2 "Content".
/// </remarks>
[TestFixture]
public sealed class PresentationFileTests
{
private static readonly SlideDeckSpec DECK = new("Mars",
[
new SlideSpec("L1", false, "Mars", "A plan", [], [], [], null),
new SlideSpec("L2", false, "Why Mars", string.Empty, [new SlideTextBlock([new SlideParagraph("Close to Earth", 0)])], [], [], null),
]);
private static readonly PresentationWriteOptions OPTIONS = new(null, string.Empty, false);
private static readonly byte[] PREVIOUS_CONTENT = [1, 2, 3];
/// <summary>
/// A video of a template, large enough that the update mode of ZipArchive would show in the allocations.
/// </summary>
private const int VIDEO_SIZE = 32 * 1024 * 1024;
private static readonly SlotBounds PICTURE_BOUNDS = new(6_200_000, 1_825_625, 5_150_000, 3_500_000);
private static readonly byte[] TEMPLATE_PICTURE = [11, 12, 13];
private static readonly byte[] SAMPLE_PICTURE = [21, 22, 23];
private static readonly byte[] PHOTO = [31, 32, 33, 34];
private string templateFolder = string.Empty;
private string targetFolder = string.Empty;
[SetUp]
public void CreateFolders()
{
var testFolder = Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"));
this.templateFolder = Directory.CreateDirectory(Path.Join(testFolder, "templates")).FullName;
this.targetFolder = Directory.CreateDirectory(Path.Join(testFolder, "presentations")).FullName;
}
[TearDown]
public void RemoveFolders() => Directory.Delete(Path.GetDirectoryName(this.templateFolder)!, true);
[Test]
public async Task ThePresentationGoesIntoTheChosenFileOnly()
{
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var stagedFiles = StagingFolder.Files();
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, BasisOf(templatePath), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
using var document = PresentationDocument.Open(targetPath, false);
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(Directory.GetFileSystemEntries(this.targetFolder), Is.EqualTo(new[] { targetPath }), "Nothing else came about next to the chosen file.");
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The chosen file holds the presentation instead of what it held before.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
[Test]
public async Task AChangedTemplateLeavesTheChosenFileAlone()
{
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var stagedFiles = StagingFolder.Files();
// Without a basis, nothing is known to fit, as after a change of the template:
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, new Dictionary<string, string>(), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
var targetContent = await File.ReadAllBytesAsync(targetPath);
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.False);
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT));
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
[Test]
public async Task TheTemplateItselfMayBeTheChosenFile()
{
var templatePath = await this.CreateTemplateAsync();
var basis = BasisOf(templatePath);
var result = await PresentationFile.CreateAsync(templatePath, templatePath, DECK, basis, OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
using var document = PresentationDocument.Open(templatePath, false);
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was read completely before it was written over.");
}
}
[Test]
public async Task APictureWhichFailsLeavesNothingBehind()
{
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var deck = new SlideDeckSpec("Mars", [new SlideSpec("L2", false, "Why Mars", string.Empty, [], [], [1, 2], null)]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var stagedFiles = StagingFolder.Files();
// The first picture is staged already when the second one fails:
await Assert.ThrowsAsync<IOException>(() => PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new FailingAtSecondPicture(), NullLogger.Instance, CancellationToken.None));
var targetContent = await File.ReadAllBytesAsync(targetPath);
using (Assert.EnterMultipleScope())
{
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT), "The chosen file stays as it was.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template and the staged picture are gone.");
}
}
[TestCase(false)]
[TestCase(true)]
public async Task TheMediaOfTheTemplateStreamThroughAsTheyAre(bool asTemplate)
{
// The deck keeps slide 1 with its picture and video, and leaves out slide 2, a sample with a picture and a video of its own:
var templatePath = Path.Join(this.templateFolder, asTemplate ? "template.potx" : "template.pptx");
var templateOptions = new TestTemplateOptions(AsTemplate: asTemplate, Slides:
[
new TestSlide(1, (TestPlaceholder.Title(), "Mars")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, TEMPLATE_PICTURE)] },
new TestSlide(1, (TestPlaceholder.Title(), "Sample")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, SAMPLE_PICTURE)] },
]);
using (var template = TestTemplate.Create(templateOptions,
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)),
new TestLayout("Picture", TestPlaceholder.Title(), TestPlaceholder.Picture(11, PICTURE_BOUNDS))))
await File.WriteAllBytesAsync(templatePath, template.ToArray());
var video = TestTemplate.VideoOf(VIDEO_SIZE);
TestTemplate.AddVideo(templatePath, 1, video);
TestTemplate.AddVideo(templatePath, 2, TestTemplate.VideoOf(1024 * 1024, 2), "/ppt/media/video2.mp4");
var deck = new SlideDeckSpec("Mars",
[
new SlideSpec(string.Empty, false, string.Empty, string.Empty, [], [], [], null, 1),
new SlideSpec("L3", false, "The rocket", string.Empty, [], [], [1], null),
]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
var stagedFiles = StagingFolder.Files();
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new OnePhoto(), NullLogger.Instance, CancellationToken.None);
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
List<string> templateErrors;
using (var template = PresentationDocument.Open(templatePath, false))
templateErrors = ValidationErrorsOf(template);
using var archive = ZipFile.OpenRead(targetPath);
var targetVideo = archive.GetEntry("ppt/media/video1.mp4");
var smallEntries = archive.Entries.Where(entry => entry.Length < 1024).Select(ContentOf).ToList();
using var document = PresentationDocument.Open(targetPath, false);
var slides = document.PresentationPart!.Presentation!.SlideIdList!.Elements<DocumentFormat.OpenXml.Presentation.SlideId>()
.Select(slideId => (SlidePart)document.PresentationPart.GetPartById(slideId.RelationshipId!.Value!))
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(targetVideo, Is.Not.Null, "The video of the kept slide comes along.");
Assert.That(targetVideo is null ? Array.Empty<byte>() : ContentOf(targetVideo), Is.EqualTo(video), "The video keeps its bytes.");
Assert.That(targetVideo?.CompressedLength, Is.EqualTo(targetVideo?.Length), "The video stays stored.");
Assert.That(archive.GetEntry("ppt/media/video2.mp4"), Is.Null, "The video of the sample slide stays out.");
Assert.That(smallEntries, Has.None.EqualTo(SAMPLE_PICTURE), "The picture of the sample slide stays out.");
Assert.That(slides.Select(slide => slide.ImageParts.Select(ContentOf).Single()), Is.EqualTo(new[] { TEMPLATE_PICTURE, PHOTO }), "The kept slide keeps its picture, and the new slide shows the photo.");
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 4), $"The template goes through streams, not through memory; {allocated / 1024 / 1024} MB were allocated.");
Assert.That(ValidationErrorsOf(document), Is.EquivalentTo(templateErrors), "The presentation is as valid as its template.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton, the photo, and the presentation leave nothing behind in the staging folder.");
}
}
private async Task<string> CreateTemplateAsync()
{
var templatePath = Path.Join(this.templateFolder, "template.pptx");
using var template = TestTemplate.Create(
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)));
await File.WriteAllBytesAsync(templatePath, template.ToArray());
return templatePath;
}
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(DECK);
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
.Validate(document)
.Select(error => $"{error.Path?.XPath}: {error.Description}")
.ToList();
private static byte[] ContentOf(ZipArchiveEntry entry)
{
using var stream = entry.Open();
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private static byte[] ContentOf(ImagePart part)
{
using var stream = part.GetStream(FileMode.Open, FileAccess.Read);
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private sealed class NoPictures : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult<SlidePicture?>(null);
}
private sealed class OnePhoto : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult(number == 1 ? new SlidePicture(PHOTO, "image/jpeg", 400, 300) : null);
}
private sealed class FailingAtSecondPicture : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => number < 2
? Task.FromResult<SlidePicture?>(new SlidePicture([1, 2, 3], "image/png", 400, 100))
: throw new IOException("The picture cannot be read.");
}
}