using System.Text; using dy.net.storage; using dy.net.Tests.TestInfrastructure; namespace dy.net.Tests; public class LocalMediaStorageTests { [Fact] public async Task WriteAsync_CreatesAndAtomicallyOverwritesFile() { using var temporaryDirectory = new TemporaryDirectory(); var storage = new LocalMediaStorage(); var path = Path.Combine(temporaryDirectory.Path, "nested", "video.mp4"); await WriteAsync(storage, path, "first"); await WriteAsync(storage, path, "replacement"); Assert.Equal("replacement", await File.ReadAllTextAsync(path)); Assert.Empty(Directory.GetFiles(Path.GetDirectoryName(path), "*.part-*")); } [Fact] public async Task ExistsLengthRangeAndDelete_FollowStorageContract() { using var temporaryDirectory = new TemporaryDirectory(); var storage = new LocalMediaStorage(); var path = Path.Combine(temporaryDirectory.Path, "sample.mp4"); await WriteAsync(storage, path, "0123456789"); Assert.True(await storage.ExistsAsync(path)); Assert.Equal(10, await storage.GetLengthAsync(path)); await using (var range = await storage.OpenReadAsync(path, 2, 5)) { Assert.Equal(206, range.StatusCode); Assert.Equal(4, range.ContentLength); Assert.Equal("bytes 2-5/10", range.ContentRange); var bytes = new byte[range.ContentLength.Value]; var read = await range.Stream.ReadAsync(bytes); Assert.Equal(bytes.Length, read); Assert.Equal("2345", Encoding.UTF8.GetString(bytes)); } await storage.DeleteAsync(path); Assert.False(await storage.ExistsAsync(path)); Assert.Null(await storage.GetLengthAsync(path)); } [Fact] public async Task WriteAsync_RejectsEmptyAndLengthMismatchWithoutReplacingExistingFile() { using var temporaryDirectory = new TemporaryDirectory(); var storage = new LocalMediaStorage(); var path = Path.Combine(temporaryDirectory.Path, "video.mp4"); await WriteAsync(storage, path, "original"); await using (var empty = new MemoryStream(Array.Empty(), false)) await Assert.ThrowsAsync(() => storage.WriteAsync(path, empty, 0, "video/mp4")); await using (var shortSource = new MemoryStream(Encoding.UTF8.GetBytes("short"), false)) await Assert.ThrowsAsync(() => storage.WriteAsync(path, shortSource, 99, "video/mp4")); Assert.Equal("original", await File.ReadAllTextAsync(path)); Assert.Empty(Directory.GetFiles(temporaryDirectory.Path, "*.part-*")); } private static async Task WriteAsync(LocalMediaStorage storage, string path, string content) { var bytes = Encoding.UTF8.GetBytes(content); await using var source = new MemoryStream(bytes, false); await storage.WriteAsync(path, source, bytes.Length, "video/mp4"); } }