Path: redb-route/tests/redb.Route.Tests.GenericFile/FakeFileOperations.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.GenericFile/FakeFileOperations.cs ---- using System.Text; using redb.Route.GenericFile; namespace redb.Route.Tests.GenericFile; /// /// In-memory for testing the shared consumer/producer /// pipeline of redb.Route.GenericFile without a real file system or server. /// /// Paths are POSIX-style ("/in/order.csv"). Directories are implicit: a directory /// exists when it was explicitly created or when it is a prefix of an existing file. /// /// Fault injection: assign , or /// to make the corresponding operation throw for a given path. /// public sealed class FakeFileOperations : IFileOperations { private readonly Dictionary _files = new(StringComparer.Ordinal); private readonly HashSet _dirs = new(StringComparer.Ordinal) { "/" }; private sealed class Entry { public required byte[] Data { get; set; } public required DateTimeOffset LastModified { get; set; } } /// Return a non-null exception to make ReadAllBytes/OpenRead fail for that path. public Func? FailRead { get; set; } /// Return a non-null exception to make Delete fail for that path. public Func? FailDelete { get; set; } /// Return a non-null exception to make Move fail for that source path. public Func? FailMove { get; set; } // ── Test helpers ──────────────────────────────────────────────── /// Adds a file, creating its parent directories. public void AddFile(string path, string content, DateTimeOffset? lastModified = null) => AddFile(path, Encoding.UTF8.GetBytes(content), lastModified); /// Adds a file, creating its parent directories. public void AddFile(string path, byte[] content, DateTimeOffset? lastModified = null) { EnsureDir(GetParentPath(path)); _files[path] = new Entry { Data = content, LastModified = lastModified ?? DateTimeOffset.UtcNow }; } /// Adds a directory. public void AddDirectory(string path) => EnsureDir(path); /// True when a file exists at the path. public bool HasFile(string path) => _files.ContainsKey(path); /// Content of an existing file as UTF-8 text. public string TextAt(string path) => Encoding.UTF8.GetString(_files[path].Data); /// All file paths currently present, sorted. public IReadOnlyList AllFiles() => _files.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(); /// All directory paths currently present, sorted. public IReadOnlyList AllDirectories() => _dirs.OrderBy(k => k, StringComparer.Ordinal).ToList(); private void EnsureDir(string path) { if (string.IsNullOrEmpty(path)) return; var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries); var current = ""; _dirs.Add("/"); foreach (var p in parts) { current += "/" + p; _dirs.Add(current); } } // ── Enumeration ───────────────────────────────────────────────── public Task> ListFilesAsync( string directory, bool recursive, int maxDepth, int minDepth, Func? directoryFilter = null, CancellationToken ct = default) { var basePath = directory.TrimEnd('/'); if (basePath.Length == 0) basePath = "/"; var result = new List(); Walk(basePath, basePath, 0); return Task.FromResult(result); // Walks directory by directory, the way a real transport does, so a directory the filter // rejects is never listed — which is the whole point of filterDirectory, and what // ListedDirectories lets a test observe. void Walk(string dir, string root, int depth) { ListedDirectories.Add(dir); var prefix = dir == "/" ? "/" : dir + "/"; foreach (var (path, entry) in _files) { if (!path.StartsWith(prefix, StringComparison.Ordinal)) continue; if (path[prefix.Length..].Contains('/', StringComparison.Ordinal)) continue; // deeper: its own walk if (minDepth > 0 && depth < minDepth) continue; result.Add(new GenericFileInfo { Name = GetFileName(path), FullPath = path, BasePath = root, Length = entry.Data.Length, LastModified = entry.LastModified, Depth = depth }); } if (!recursive || (maxDepth > 0 && depth >= maxDepth)) return; foreach (var sub in _dirs.Where(d => d.StartsWith(prefix, StringComparison.Ordinal) && !d[prefix.Length..].Contains('/', StringComparison.Ordinal)) .OrderBy(d => d, StringComparer.Ordinal) .ToList()) { var relative = sub[(root == "/" ? 1 : root.Length + 1)..]; if (directoryFilter != null && !directoryFilter(sub, relative)) continue; Walk(sub, root, depth + 1); } } } /// Every directory a listing actually walked into, in order — for filterDirectory tests. public List ListedDirectories { get; } = []; // ── Read ──────────────────────────────────────────────────────── public Task ReadAllBytesAsync(string path, CancellationToken ct = default) { var injected = FailRead?.Invoke(path); if (injected != null) throw injected; if (!_files.TryGetValue(path, out var e)) throw new FileNotFoundException($"No such file: {path}", path); return Task.FromResult(e.Data.ToArray()); } public Task OpenReadAsync(string path, CancellationToken ct = default) { var injected = FailRead?.Invoke(path); if (injected != null) throw injected; if (!_files.TryGetValue(path, out var e)) throw new FileNotFoundException($"No such file: {path}", path); return Task.FromResult(new MemoryStream(e.Data.ToArray(), writable: false)); } // ── Write ─────────────────────────────────────────────────────── public Task WriteAsync(string path, byte[] data, CancellationToken ct = default) { AddFile(path, data.ToArray()); return Task.CompletedTask; } public async Task WriteAsync(string path, Stream data, CancellationToken ct = default) { using var ms = new MemoryStream(); await data.CopyToAsync(ms, ct).ConfigureAwait(false); AddFile(path, ms.ToArray()); } public Task AppendAsync(string path, byte[] data, CancellationToken ct = default) { if (_files.TryGetValue(path, out var e)) e.Data = [.. e.Data, .. data]; else AddFile(path, data.ToArray()); return Task.CompletedTask; } public Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct = default) => AppendAsync(path, encoding.GetBytes(text), ct); // ── File operations ───────────────────────────────────────────── public Task ExistsAsync(string path, CancellationToken ct = default) => Task.FromResult(_files.ContainsKey(path)); public Task DeleteAsync(string path, CancellationToken ct = default) { var injected = FailDelete?.Invoke(path); if (injected != null) throw injected; _files.Remove(path); return Task.CompletedTask; } public Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default) { var injected = FailMove?.Invoke(source); if (injected != null) throw injected; if (!_files.TryGetValue(source, out var e)) throw new FileNotFoundException($"No such file: {source}", source); if (_files.ContainsKey(destination) && !overwrite) throw new IOException($"Destination already exists: {destination}"); _files.Remove(source); EnsureDir(GetParentPath(destination)); _files[destination] = e; return Task.CompletedTask; } // ── Directory operations ──────────────────────────────────────── public Task CreateDirectoryAsync(string path, CancellationToken ct = default) { EnsureDir(path); return Task.CompletedTask; } public Task DirectoryExistsAsync(string path, CancellationToken ct = default) { var normalized = path.TrimEnd('/'); if (normalized.Length == 0) normalized = "/"; return Task.FromResult(_dirs.Contains(normalized)); } // ── Path helpers ──────────────────────────────────────────────── public string CombinePath(string basePath, string relativePath) { if (string.IsNullOrEmpty(basePath)) return "/" + relativePath.TrimStart('/'); if (string.IsNullOrEmpty(relativePath)) return basePath; return basePath.TrimEnd('/') + "/" + relativePath.TrimStart('/'); } public string GetParentPath(string path) { var i = path.LastIndexOf('/'); return i <= 0 ? "/" : path[..i]; } public string GetFileName(string path) { var i = path.LastIndexOf('/'); return i < 0 ? path : path[(i + 1)..]; } public string GetFileNameWithoutExtension(string name) { var file = GetFileName(name); var dot = file.LastIndexOf('.'); return dot <= 0 ? file : file[..dot]; } public string GetExtension(string name) { var file = GetFileName(name); var dot = file.LastIndexOf('.'); return dot <= 0 ? "" : file[dot..]; } public string GetRelativePath(string basePath, string fullPath) { var prefix = basePath.TrimEnd('/') + "/"; return fullPath.StartsWith(prefix, StringComparison.Ordinal) ? fullPath[prefix.Length..] : fullPath; } public bool IsAbsolutePath(string path) => path.StartsWith('/'); }