using System.Security.Cryptography; using EvilEngine.Formats; using EvilEngine.Mounts; namespace EvilEngine.Conversion.Tests; public sealed class SharedParseTests { private const int Kept = 8; private static readonly VirtualPath Box = VirtualPath.Parse("maps/box.bin"); private static readonly VirtualPath Lit = VirtualPath.Parse("maps/box.lit"); private static (ConversionPipeline Pipeline, MemorySource Files, ParseConverter Converter) Alpha() { var files = new MemorySource("alpha", CaseRule.Insensitive).Add(Box, Bytes(1)); var pipeline = new ConversionPipeline(new MemoryConversionCache()); var converter = new ParseConverter(); pipeline.AddNamespace(new ContentNamespace("alpha", files)); pipeline.Bind("alpha", converter); return (pipeline, files, converter); } private static byte[] Bytes(byte seed, int length = 256) { return Enumerable.Range(0, length).Select(index => (byte)(index * seed)).ToArray(); } private static string Hash(byte[] bytes) { return Convert.ToHexStringLower(SHA256.HashData(bytes)); } private static ConversionResult Item(ConversionPipeline pipeline, int index, string key = "box") { return pipeline.Get(ContentKind.Record, ContentId.Parse($"alpha:{key}/{index}")); } [Fact] public void ParsesAFileOnceForEveryItemOverIt() { var (pipeline, _, converter) = Alpha(); var results = Enumerable.Range(0, 16).Select(index => Item(pipeline, index)).ToArray(); Assert.Equal(1, converter.Builds); Assert.All(results, result => { Assert.Equal(ConversionStatus.Converted, result.Status); Assert.Equal([(Box, Hash(Bytes(1))), (Lit, null)], result.Content!.Inputs.Select(input => (input.Path, input.Hash))); Assert.Equal([new ContentReference(ContentKind.Texture, ContentId.Parse("alpha:box/palette"))], result.Content.References); Assert.Equal(["box parsed"], result.Diagnostics); }); Assert.Equal(Bytes(1)[4..8], results[1].Content!.Data.ToArray()); } [Fact] public void ParsesAFileOnceWhenItsItemsConvertTogether() { var (pipeline, _, converter) = Alpha(); var results = new ConversionResult[64]; Parallel.For(0, results.Length, index => results[index] = Item(pipeline, index % 32)); Assert.Equal(1, converter.Builds); Assert.All(results, result => Assert.True(result.Succeeded)); } [Fact] public void InvalidatingAFileTheParseReadParsesItAgain() { var (pipeline, files, converter) = Alpha(); Item(pipeline, 0); files.Add(Box, Bytes(3)); pipeline.Invalidate("alpha", [VirtualPath.Parse("MAPS/Box.bin")]); var item = Item(pipeline, 1); Assert.Equal(2, converter.Builds); Assert.Equal(Bytes(3)[4..8], item.Content!.Data.ToArray()); Assert.Equal(Hash(Bytes(3)), item.Content.Inputs[0].Hash); } [Fact] public void InvalidatingAFileTheParseMissedParsesItAgain() { var (pipeline, files, converter) = Alpha(); Item(pipeline, 0); files.Add(Lit.Value, "lit"); pipeline.Invalidate("alpha", [Lit]); var item = Item(pipeline, 1); Assert.Equal(2, converter.Builds); Assert.Equal(["box parsed", "box parsed with its lit"], item.Diagnostics); Assert.NotNull(item.Content!.Inputs[1].Hash); } [Fact] public void InvalidatingAnotherFileKeepsTheParse() { var (pipeline, files, converter) = Alpha(); Item(pipeline, 0); files.Add("maps/other.bin", "other"); pipeline.Invalidate("alpha", [VirtualPath.Parse("maps/other.bin")]); Item(pipeline, 1); Assert.Equal(1, converter.Builds); } [Fact] public void AFileOfAnotherLengthIsParsedAgain() { var (pipeline, files, converter) = Alpha(); Item(pipeline, 0); files.Add(Box, Bytes(3, 512)); var item = Item(pipeline, 1); Assert.Equal(2, converter.Builds); Assert.Equal(Bytes(3, 512)[4..8], item.Content!.Data.ToArray()); } [Fact] public void ANamespaceAddedAgainParsesAgain() { var (pipeline, _, converter) = Alpha(); Item(pipeline, 0); Assert.True(pipeline.RemoveNamespace("alpha")); pipeline.AddNamespace(new ContentNamespace("alpha", new MemorySource("alpha", CaseRule.Insensitive).Add(Box, Bytes(3)))); var item = Item(pipeline, 1); Assert.Equal(2, converter.Builds); Assert.Equal(Bytes(3)[4..8], item.Content!.Data.ToArray()); } [Fact] public void AFailedParseIsTriedAgainByTheNextItem() { var (pipeline, _, converter) = Alpha(); converter.Fail = true; var failed = Item(pipeline, 0); var next = Item(pipeline, 1); Assert.Equal(ConversionStatus.Failed, failed.Status); Assert.Equal(["box parsed", "test.parse failed on alpha:box/0 while reading 'maps/box.bin': box is broken."], failed.Diagnostics); Assert.Equal(ConversionStatus.Converted, next.Status); Assert.Equal(2, converter.Builds); } [Fact] public void KeepsOnlyTheMostRecentlyUsedParses() { var (pipeline, _, converter) = Alpha(); for (var key = 0; key <= Kept; key++) Item(pipeline, 0, $"box{key}"); Item(pipeline, 1, $"box{Kept}"); Item(pipeline, 1, "box1"); Item(pipeline, 1, "box0"); Assert.Equal(Kept + 2, converter.Builds); } private sealed record Parsed(byte[] Bytes); private sealed class ParseConverter : IConverter { private int _builds; public bool Fail { get; set; } public int Builds => Volatile.Read(ref _builds); public string Id => "test.parse"; public int Version => 1; public ContentKind Produces => ContentKind.Record; public bool Accepts(ConversionContext context) { return context.Id.Name.StartsWith("box", StringComparison.Ordinal); } public void Convert(ConversionContext context, Stream output) { var key = context.Id.Name[..context.Id.Name.IndexOf('/')]; var index = int.Parse(context.Id.Name[(key.Length + 1)..]); var parsed = context.Shared($"test.parse:{key}", shared => { Interlocked.Increment(ref _builds); var bytes = shared.Read(Box).ToArray(); shared.Warn("box parsed"); if (Fail) { Fail = false; throw new InvalidDataException("box is broken."); } if (shared.Exists(Lit)) { shared.Read(Lit); shared.Warn("box parsed with its lit"); } shared.Reference(ContentKind.Texture, "box/palette"); return new Parsed(bytes); }); output.Write(parsed.Bytes.AsSpan(index * 4, 4)); } } }