using System; using System.IO; using System.IO.Compression; using System.Text; using System.Threading; using UnitTestSharp; namespace Amphora.UnitTests { public class AssetArchiveTests : TestFixture { public static byte[] Bytes(string text) { return Encoding.ASCII.GetBytes(text); } public static byte[] Zip(CompressionLevel level, params (string Name, byte[] Content)[] files) { using (var memory = new MemoryStream()) { using (var zip = new ZipArchive(memory, ZipArchiveMode.Create, leaveOpen: true)) { foreach ((string name, byte[] content) in files) { using (Stream stream = zip.CreateEntry(name, level).Open()) { stream.Write(content, 0, content.Length); } } } return memory.ToArray(); } } public static AssetArchive OpenZip(byte[] zip, int maxFileBytes = AssetArchive.DefaultMaxFileBytes) { return AssetArchive.Open(new MemoryStream(zip), maxFileBytes).Value; } public static AssetArchive Sample() { return OpenZip(Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha")), ("sub/b.txt", Bytes("bravo")), ("empty.bin", new byte[0]))); } public static string TextOf(ByteView view) { var bytes = new byte[view.Length]; view.CopyTo(bytes, 0); return Encoding.ASCII.GetString(bytes); } public class OpenTests : TestFixture { public void NullStream_Throws() { CheckThrow(typeof(ArgumentNullException)); AssetArchive.Open(null); } public void NegativeMaxFileBytes_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); AssetArchive.Open(new MemoryStream(Zip(CompressionLevel.NoCompression)), maxFileBytes: -1); } public void ANonZip_FailsAsUnreadable() { StatusOr opened = AssetArchive.Open(new MemoryStream(Bytes("this is not a zip file"))); CheckTrue(ReferenceEquals(AssetArchive.Unreadable, opened.Kind)); } public void ANonZip_ClosesTheStream() { var stream = new MemoryStream(Bytes("this is not a zip file")); AssetArchive.Open(stream); CheckFalse(stream.CanRead); } public void AZipWithTheSameNameTwice_FailsAsUnreadable() { byte[] zip = Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("one")), ("a.txt", Bytes("two"))); StatusOr opened = AssetArchive.Open(new MemoryStream(zip)); CheckTrue(ReferenceEquals(AssetArchive.Unreadable, opened.Kind)); } public void AZipWithTheSameNameTwice_ClosesTheStream() { byte[] zip = Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("one")), ("a.txt", Bytes("two"))); var stream = new MemoryStream(zip); AssetArchive.Open(stream); CheckFalse(stream.CanRead); } public void AValidZip_Opens() { CheckTrue(AssetArchive.Open(new MemoryStream(Zip(CompressionLevel.NoCompression))).IsOk); } public void AValidZip_KeepsTheStreamOpenUntilDisposed() { var stream = new MemoryStream(Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha")))); using (AssetArchive.Open(stream).Value) { CheckTrue(stream.CanRead); } CheckFalse(stream.CanRead); } public void KeepsTheMaxFileBytes() { using (AssetArchive archive = OpenZip(Zip(CompressionLevel.NoCompression), maxFileBytes: 77)) { CheckEqual(77, archive.MaxFileBytes); } } public void ByDefault_AllowsTheDefaultMaxFileBytes() { using (AssetArchive archive = Sample()) { CheckEqual(AssetArchive.DefaultMaxFileBytes, archive.MaxFileBytes); } } } public class OpenFileTests : TestFixture { public void NullPath_Throws() { CheckThrow(typeof(ArgumentException)); AssetArchive.OpenFile(null); } public void EmptyPath_Throws() { CheckThrow(typeof(ArgumentException)); AssetArchive.OpenFile(""); } public void AMissingFile_FailsAsUnreadable() { string path = Path.Combine(Path.GetTempPath(), "AmphoraTests-" + Guid.NewGuid() + ".zip"); CheckTrue(ReferenceEquals(AssetArchive.Unreadable, AssetArchive.OpenFile(path).Kind)); } public void ADirectory_FailsAsUnreadable() { CheckTrue(ReferenceEquals(AssetArchive.Unreadable, AssetArchive.OpenFile(Path.GetTempPath()).Kind)); } public void AZipFile_ReadsItsFiles() { string path = Path.Combine(Path.GetTempPath(), "AmphoraTests-" + Guid.NewGuid() + ".zip"); File.WriteAllBytes(path, Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha")))); try { using (AssetArchive archive = AssetArchive.OpenFile(path).Value) { CheckEqual("alpha", TextOf(archive.Read("a.txt").Value)); } } finally { File.Delete(path); } } public void DisposingReleasesTheFile() { string path = Path.Combine(Path.GetTempPath(), "AmphoraTests-" + Guid.NewGuid() + ".zip"); File.WriteAllBytes(path, Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha")))); AssetArchive.OpenFile(path).Value.Dispose(); File.Delete(path); CheckFalse(File.Exists(path)); } public void ANonZipFile_FailsAsUnreadableAndReleasesTheFile() { string path = Path.Combine(Path.GetTempPath(), "AmphoraTests-" + Guid.NewGuid() + ".zip"); File.WriteAllBytes(path, Bytes("this is not a zip file")); CheckTrue(ReferenceEquals(AssetArchive.Unreadable, AssetArchive.OpenFile(path).Kind)); File.Delete(path); CheckFalse(File.Exists(path)); } } public class PathsTests : TestFixture { public void ListsEveryFileInTheOrderTheArchiveHoldsThem() { using (AssetArchive archive = Sample()) { CheckEqual(3, archive.Paths.Count); CheckEqual("a.txt", archive.Paths[0]); CheckEqual("sub/b.txt", archive.Paths[1]); CheckEqual("empty.bin", archive.Paths[2]); } } public void LeavesOutFolderEntries() { byte[] zip = Zip(CompressionLevel.NoCompression, ("sub/", new byte[0]), ("sub/b.txt", Bytes("bravo"))); using (AssetArchive archive = OpenZip(zip)) { CheckEqual(1, archive.Paths.Count); CheckEqual("sub/b.txt", archive.Paths[0]); } } public void AnEmptyArchive_HasNoPaths() { using (AssetArchive archive = OpenZip(Zip(CompressionLevel.NoCompression))) { CheckEqual(0, archive.Paths.Count); } } } public class ContainsTests : TestFixture { public void NullPath_Throws() { using (AssetArchive archive = Sample()) { CheckThrow(typeof(ArgumentNullException)); archive.Contains(null); } } public void AFile_IsContained() { using (AssetArchive archive = Sample()) { CheckTrue(archive.Contains("sub/b.txt")); } } public void ADifferentCase_IsNotContained() { using (AssetArchive archive = Sample()) { CheckFalse(archive.Contains("SUB/b.txt")); } } public void ABackslashPath_IsNotContained() { using (AssetArchive archive = Sample()) { CheckFalse(archive.Contains("sub\\b.txt")); } } public void AFolder_IsNotContained() { byte[] zip = Zip(CompressionLevel.NoCompression, ("sub/", new byte[0]), ("sub/b.txt", Bytes("bravo"))); using (AssetArchive archive = OpenZip(zip)) { CheckFalse(archive.Contains("sub/")); } } public void ANameThatIsNotThere_IsNotContained() { using (AssetArchive archive = Sample()) { CheckFalse(archive.Contains("nope.txt")); } } } public class SizeOfTests : TestFixture { public void NullPath_Throws() { using (AssetArchive archive = Sample()) { CheckThrow(typeof(ArgumentNullException)); archive.SizeOf(null); } } public void AFile_IsItsLengthWhenRead() { using (AssetArchive archive = Sample()) { CheckEqual(5L, archive.SizeOf("sub/b.txt").Value); } } public void AnEmptyFile_IsZero() { using (AssetArchive archive = Sample()) { CheckEqual(0L, archive.SizeOf("empty.bin").Value); } } public void ANameThatIsNotThere_FailsAsMissing() { using (AssetArchive archive = Sample()) { CheckTrue(ReferenceEquals(AssetArchive.Missing, archive.SizeOf("nope.txt").Kind)); } } } public class ReadTests : TestFixture { public void NullPath_Throws() { using (AssetArchive archive = Sample()) { CheckThrow(typeof(ArgumentNullException)); archive.Read(null); } } public void AStoredFile_ReturnsItsBytes() { using (AssetArchive archive = Sample()) { CheckEqual("alpha", TextOf(archive.Read("a.txt").Value)); } } public void AFileInAFolder_ReturnsItsBytes() { using (AssetArchive archive = Sample()) { CheckEqual("bravo", TextOf(archive.Read("sub/b.txt").Value)); } } public void ACompressedFile_ReturnsItsBytes() { byte[] zip = Zip(CompressionLevel.Optimal, ("a.txt", Bytes(new string('x', 1000)))); using (AssetArchive archive = OpenZip(zip)) { CheckEqual(new string('x', 1000), TextOf(archive.Read("a.txt").Value)); } } public void AnEmptyFile_ReturnsAnEmptyView() { using (AssetArchive archive = Sample()) { CheckEqual(0, archive.Read("empty.bin").Value.Length); } } public void TheSameFileTwice_ReturnsTheSameBytes() { using (AssetArchive archive = Sample()) { archive.Read("a.txt"); CheckEqual("alpha", TextOf(archive.Read("a.txt").Value)); } } public void ANameThatIsNotThere_FailsAsMissing() { using (AssetArchive archive = Sample()) { StatusOr read = archive.Read("nope.txt"); CheckTrue(ReferenceEquals(AssetArchive.Missing, read.Kind)); CheckEqual("The archive holds no 'nope.txt'.", read.Status.Describe()); } } public void AFolder_FailsAsMissing() { byte[] zip = Zip(CompressionLevel.NoCompression, ("sub/", new byte[0])); using (AssetArchive archive = OpenZip(zip)) { CheckTrue(ReferenceEquals(AssetArchive.Missing, archive.Read("sub/").Kind)); } } public void AFileOverTheLimit_FailsAsTooLarge() { using (AssetArchive archive = OpenZip( Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha"))), maxFileBytes: 4)) { StatusOr read = archive.Read("a.txt"); CheckTrue(ReferenceEquals(AssetArchive.TooLarge, read.Kind)); CheckEqual("'a.txt' is 5 bytes, and the limit is 4.", read.Status.Describe()); } } public void AFileExactlyAtTheLimit_Reads() { using (AssetArchive archive = OpenZip( Zip(CompressionLevel.NoCompression, ("a.txt", Bytes("alpha"))), maxFileBytes: 5)) { CheckEqual("alpha", TextOf(archive.Read("a.txt").Value)); } } public void ACorruptCompressedFile_FailsAsUnreadable() { byte[] zip = Zip(CompressionLevel.Optimal, ("a.txt", Bytes(new string('x', 1000)))); // The entry's data sits right after its 30 byte header and 5 byte name. for (int i = 35; i < 41; i++) { zip[i] = 0xFF; } using (AssetArchive archive = OpenZip(zip)) { CheckTrue(ReferenceEquals(AssetArchive.Unreadable, archive.Read("a.txt").Kind)); } } public void AFileShorterThanItsHeaderClaims_FailsAsUnreadable() { byte[] zip = Zip(CompressionLevel.Optimal, ("a.txt", Bytes(new string('x', 1000)))); int central = IndexOf(zip, 0x50, 0x4B, 0x01, 0x02); // The central directory's uncompressed size, which Length reports, sits 24 bytes into its record. zip[central + 24] = 0xFF; zip[central + 25] = 0x0F; using (AssetArchive archive = OpenZip(zip)) { CheckTrue(ReferenceEquals(AssetArchive.Unreadable, archive.Read("a.txt").Kind)); } } public void ConcurrentReads_EachGetTheirOwnFilesBytes() { using (AssetArchive archive = Sample()) { string[] results = new string[4]; var threads = new Thread[results.Length]; for (int i = 0; i < threads.Length; i++) { int index = i; string path = index % 2 == 0 ? "a.txt" : "sub/b.txt"; threads[i] = new Thread(() => { string last = null; for (int count = 0; count < 200; count++) { last = TextOf(archive.Read(path).Value); } results[index] = last; }); threads[i].Start(); } for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } CheckEqual("alpha", results[0]); CheckEqual("bravo", results[1]); CheckEqual("alpha", results[2]); CheckEqual("bravo", results[3]); } } } public static int IndexOf(byte[] bytes, params byte[] pattern) { for (int i = 0; i + pattern.Length <= bytes.Length; i++) { int j = 0; while (j < pattern.Length && bytes[i + j] == pattern[j]) { j++; } if (j == pattern.Length) { return i; } } return -1; } } }