Bundle: redb-route / tests/redb.Route.Tests.GenericFile (tests.redb.Route.Tests.GenericFile.txt), 9 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
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('/');
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/FileFilterParityTests.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/FileFilterParityTests.cs
----
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
///
/// Apache Camel parity for the file consumer's filters. include/exclude only ever see
/// the file name, so "take these three directories out of two hundred" had no answer: the route had
/// to poll the parent recursively and throw away what it did not want — after downloading it, and
/// after delete/move had already touched it. Camel answers with filters that see the
/// path: antInclude/antExclude over the path relative to the polled directory,
/// filterDirectory deciding before a directory is listed at all, filterFile over the
/// file, and filter naming a bean in the registry.
///
public class FileFilterParityTests : GenericFileTestBase
{
private static Dictionary Params(params (string Key, string Value)[] pairs)
=> pairs.ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase);
private async Task> PolledNames(Dictionary parameters)
{
var (processor, _, exchanges) = Collector();
var consumer = (TestFileConsumer)Endpoint(parameters).CreateConsumer(processor);
await consumer.PollOnceAsync();
return exchanges.Select(e => (string)e.In.Headers["testFile.AbsolutePath"]!).OrderBy(p => p).ToList();
}
private void ThreePartnerDirectories()
{
Ops.AddFile("/in/TYPE_A/outbox/a.csv", "a");
Ops.AddFile("/in/TYPE_B/outbox/b.csv", "b");
Ops.AddFile("/in/TYPE_C/outbox/c.csv", "c");
}
[Fact]
public async Task AntInclude_picks_directories_out_of_the_tree()
{
ThreePartnerDirectories();
var polled = await PolledNames(Params(
("recursive", "true"),
("antInclude", "TYPE_A/outbox/*,TYPE_B/outbox/*")));
polled.Should().Equal("/in/TYPE_A/outbox/a.csv", "/in/TYPE_B/outbox/b.csv");
}
[Fact]
public async Task AntExclude_drops_what_it_matches()
{
ThreePartnerDirectories();
var polled = await PolledNames(Params(
("recursive", "true"),
("antExclude", "TYPE_C/**")));
polled.Should().Equal("/in/TYPE_A/outbox/a.csv", "/in/TYPE_B/outbox/b.csv");
}
[Fact]
public async Task A_single_star_stops_at_a_slash_and_a_double_star_does_not()
{
Ops.AddFile("/in/one/x.csv", "1");
Ops.AddFile("/in/one/two/x.csv", "2");
var single = await PolledNames(Params(("recursive", "true"), ("antInclude", "*/x.csv")));
var doubled = await PolledNames(Params(("recursive", "true"), ("antInclude", "**/x.csv")));
// This is exactly what the name-based glob could not express: its '*' became ".*" and
// crossed the separator, so the two patterns meant the same thing.
single.Should().Equal("/in/one/x.csv");
doubled.Should().Equal("/in/one/two/x.csv", "/in/one/x.csv");
}
[Fact]
public async Task Ant_patterns_are_case_sensitive_unless_told_otherwise()
{
Ops.AddFile("/in/Type_A/a.csv", "a");
var sensitive = await PolledNames(Params(("recursive", "true"), ("antInclude", "type_a/*")));
var insensitive = await PolledNames(Params(
("recursive", "true"), ("antInclude", "type_a/*"), ("antFilterCaseSensitive", "false")));
sensitive.Should().BeEmpty();
insensitive.Should().Equal("/in/Type_A/a.csv");
}
[Fact]
public async Task FilterDirectory_decides_before_the_directory_is_listed()
{
ThreePartnerDirectories();
var polled = await PolledNames(Params(
("recursive", "true"),
("filterDirectory", "header.testFile.Name == 'TYPE_A' or header.testFile.Name == 'outbox'")));
polled.Should().Equal("/in/TYPE_A/outbox/a.csv");
// The point of the option: two hundred directories are not two hundred listings.
Ops.ListedDirectories.Should().NotContain("/in/TYPE_B").And.NotContain("/in/TYPE_C");
}
[Fact]
public async Task FilterFile_is_a_condition_over_the_file()
{
Ops.AddFile("/in/small.csv", "1");
Ops.AddFile("/in/big.csv", new string('x', 100));
var polled = await PolledNames(Params(("filterFile", "header.testFile.Length > 10")));
polled.Should().Equal("/in/big.csv");
}
[Fact]
public async Task A_filter_bean_from_the_registry_decides_for_files_and_directories()
{
ThreePartnerDirectories();
var filter = new OnlyTypeA();
var (processor, _, exchanges) = Collector();
var endpoint = Endpoint(Params(("recursive", "true")), filter: filter);
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
exchanges.Select(e => (string)e.In.Headers["testFile.AbsolutePath"]!)
.Should().Equal("/in/TYPE_A/outbox/a.csv");
Ops.ListedDirectories.Should().NotContain("/in/TYPE_B");
}
[Fact]
public async Task What_a_filter_rejected_is_never_deleted()
{
ThreePartnerDirectories();
await PolledNames(Params(
("recursive", "true"),
("antInclude", "TYPE_A/**"),
("delete", "true")));
// The reason this work exists: polling the parent and sorting it out in the route deleted
// the partner's files from the directories the route was never meant to read.
Ops.HasFile("/in/TYPE_A/outbox/a.csv").Should().BeFalse("it was polled and consumed");
Ops.HasFile("/in/TYPE_B/outbox/b.csv").Should().BeTrue();
Ops.HasFile("/in/TYPE_C/outbox/c.csv").Should().BeTrue();
}
/// Registry bean: takes TYPE_A only, and says so for the directory as well.
private sealed class OnlyTypeA : IGenericFileFilter
{
public bool Accept(GenericFileInfo file) => file.FullPath.Contains("/TYPE_A/", StringComparison.Ordinal);
public bool AcceptDirectory(string fullPath, string relativePath)
=> relativePath.StartsWith("TYPE_A", StringComparison.Ordinal) || relativePath.Contains("outbox", StringComparison.Ordinal);
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/FileKeysInOptionsTests.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/FileKeysInOptionsTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Expressions;
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
///
/// The file keys in the consumer's own options (findings register row 34 point 5): every key of
/// resolves against the file being handled, ignoring case as these options always
/// have; an unknown key fails when the endpoint is created. Before 4.7.0 only name and name.noext
/// resolved, and any other key stayed in the path as written.
///
public class FileKeysInOptionsTests : GenericFileTestBase
{
private static readonly DateTimeOffset Modified = new(2026, 11, 5, 10, 30, 0, TimeSpan.Zero);
[Theory]
[InlineData("done-${file:name}", "/in/done-order.CSV/order.CSV")]
[InlineData("done-${file:onlyname.noext}", "/in/done-order/order.CSV")]
[InlineData("done-${file:ext}", "/in/done-csv/order.CSV")]
[InlineData("done-${file:name.ext}", "/in/done-csv/order.CSV")]
[InlineData("done-${file:size}", "/in/done-7/order.CSV")]
[InlineData("done-${FILE:EXT}", "/in/done-csv/order.CSV")]
[InlineData("done-${file:Name.NoExt}", "/in/done-order/order.CSV")]
public async Task MoveTo_ResolvesEveryKey(string moveTo, string expected)
{
Ops.AddFile("/in/order.CSV", "PAYLOAD", Modified);
var consumer = (TestFileConsumer)Endpoint(new() { ["moveTo"] = moveTo }).CreateConsumer(Collector().Processor);
await consumer.PollOnceAsync();
Ops.HasFile(expected).Should().BeTrue();
Ops.AllDirectories().Should().NotContain(d => d.Contains("${"));
}
[Fact]
public async Task MoveTo_ModifiedIsTheFileTime()
{
Ops.AddFile("/in/order.csv", "PAYLOAD", Modified);
var consumer = (TestFileConsumer)Endpoint(new() { ["moveTo"] = "m-${file:modified}" }).CreateConsumer(Collector().Processor);
await consumer.PollOnceAsync();
Ops.HasFile("/in/m-2026-11-05T10:30:00.0000000+00:00/order.csv").Should().BeTrue();
}
[Fact]
public async Task DoneFileName_ResolvesTheExtension()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
Ops.AddFile("/in/order.csv-ready", "");
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)Endpoint(new() { ["doneFileName"] = "${file:name.noext}.${file:ext}-ready", ["include"] = "*.csv", ["noop"] = "true" })
.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().ContainSingle().Which.Should().Be("PAYLOAD");
}
[Theory]
[InlineData("moveTo")]
[InlineData("preMove")]
[InlineData("doneFileName")]
[InlineData("idempotentKey")]
[InlineData("tempFileName")]
public void AnUnknownKey_FailsWhenTheEndpointIsCreated(string option)
{
var act = () => Endpoint(new() { [option] = "x-${file:nosuch}" });
act.Should().Throw()
.WithMessage($"{option}='x-${{file:nosuch}}': 'nosuch' is not a file key; the keys are name, onlyname, name.noext, *");
}
[Theory]
[InlineData(".writing.tmp", "/in/.writing.tmp")]
[InlineData("${file:name}.part", "/in/order.xml.part")]
[InlineData("${File:Name.NoExt}.tmp", "/in/order.tmp")]
public async Task TempFileName_IsTheTempFileTheWriteRenamesFrom(string tempFileName, string expected)
{
// Row 46: the shared write flow of every file producer (File, FTP, SFTP); the keys read the target file.
string? renamedFrom = null;
Ops.FailMove = source => { renamedFrom = source; return null; };
var producer = Endpoint(new() { ["tempFileName"] = tempFileName }).CreateProducer();
var message = new redb.Route.Core.Message { Body = System.Text.Encoding.UTF8.GetBytes("PAYLOAD") };
message.Headers["testFile.Name"] = "order.xml";
await producer.Process(new redb.Route.Core.Exchange(message) { Pattern = ExchangePattern.InOnly });
renamedFrom.Should().Be(expected);
Ops.TextAt("/in/order.xml").Should().Be("PAYLOAD");
Ops.AllFiles().Should().NotContain(expected);
}
[Fact]
public void SubstituteFileTokens_ByNameAlone_KnowsTheNameKeys()
{
GenericFileUtils.SubstituteFileTokens("order.csv", "${file:name.noext}.${file:ext}|${file:size}", Ops)
.Should().Be("order.csv|", "the name form knows no size");
}
[Fact]
public void Facts_AreTheValuesTheFileHeadersCarry()
{
var file = new GenericFileInfo { Name = "a.XML", FullPath = "/in/sub/a.XML", BasePath = "/in", Length = 42, LastModified = Modified };
var facts = new GenericFileFacts(file, "/in/sub/a.XML", Ops);
facts.Name.Should().Be("a.XML");
facts.NameOnly.Should().Be("a");
facts.Extension.Should().Be("xml", "the header holds '.xml', the key is without the dot");
facts.Parent.Should().Be("/in/sub");
facts.AbsolutePath.Should().Be("/in/sub/a.XML");
facts.RelativePath.Should().Be(Ops.GetRelativePath("/in", "/in/sub/a.XML"));
facts.Length.Should().Be(42);
facts.LastModified.Should().Be(Modified);
}
// ── The compatibility form of the hooks ─────────────────────────
[Fact]
public async Task ASubclassOverridingThePathForm_IsStillCalled()
{
Ops.AddFile("/in/ok.csv", "OK");
Ops.AddFile("/in/bad.csv", "BAD");
var endpoint = Endpoint(new() { ["noop"] = "true" });
var (processor, _, _) = Collector(exchange =>
{
if (exchange.In.Headers["testFile.Name"] as string == "bad.csv")
exchange.Exception = new FormatException("bad");
});
var consumer = new PathFormConsumer(endpoint, processor, new TestFileEndpointOptions { Noop = true }, Ops);
await consumer.PollOnceAsync();
consumer.Calls.Should().BeEquivalentTo(["post /in/ok.csv ok.csv /in", "failed /in/bad.csv bad.csv /in"]);
}
[Fact]
public async Task ASubclassOverridingBothForms_GetsTheFileForm()
{
Ops.AddFile("/in/ok.csv", "OK");
var endpoint = Endpoint(new() { ["noop"] = "true" });
var consumer = new BothFormsConsumer(endpoint, Collector().Processor, new TestFileEndpointOptions { Noop = true }, Ops);
await consumer.PollOnceAsync();
consumer.Calls.Should().Equal("post-file ok.csv 2");
}
private class PathFormConsumer(TestFileEndpoint endpoint, IProcessor processor, TestFileEndpointOptions options, FakeFileOperations ops)
: GenericFileConsumer(endpoint, processor, options, ops)
{
public List Calls { get; } = [];
protected override string ConsumerName => "path-form";
protected override string BasePath => endpoint.DirectoryPath;
public Task PollOnceAsync() => PollDirectory(CancellationToken.None);
protected override void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath)
=> message.Headers["testFile.Name"] = file.Name;
protected override Task AcquireReadLockAsync(GenericFileInfo file, CancellationToken ct) => Task.FromResult(true);
protected override Task PostProcessAsync(string filePath, string fileName, string basePath, CancellationToken ct)
{
Calls.Add($"post {filePath} {fileName} {basePath}");
return Task.CompletedTask;
}
protected override Task OnProcessingFailedAsync(string filePath, string fileName, string basePath, CancellationToken ct)
{
Calls.Add($"failed {filePath} {fileName} {basePath}");
return Task.CompletedTask;
}
}
private sealed class BothFormsConsumer(TestFileEndpoint endpoint, IProcessor processor, TestFileEndpointOptions options, FakeFileOperations ops)
: PathFormConsumer(endpoint, processor, options, ops)
{
protected override Task PostProcessAsync(GenericFileInfo file, string workPath, CancellationToken ct)
{
Calls.Add($"post-file {file.Name} {file.Length}");
return Task.CompletedTask;
}
protected override Task PostProcessAsync(string filePath, string fileName, string basePath, CancellationToken ct)
{
Calls.Add("post-path");
return Task.CompletedTask;
}
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/GenericFileConsumerTests.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/GenericFileConsumerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
///
/// Behaviour tests for the shared poll loop in GenericFileConsumer.
/// These run against , so they cover the code path
/// used by the File, FTP and SFTP transports without touching a disk or a server.
///
public class GenericFileConsumerTests : GenericFileTestBase
{
// ── Baseline: the pipeline works ────────────────────────────────
[Fact]
public async Task Poll_ReadsBody_SetsHeaders_AndDeletes()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["delete"] = "true" });
var (processor, bodies, exchanges) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().ContainSingle().Which.Should().Be("PAYLOAD");
exchanges[0].In.Headers["testFile.Name"].Should().Be("order.csv");
Ops.HasFile("/in/order.csv").Should().BeFalse();
}
[Fact]
public async Task Poll_AppliesIncludeExcludeSortAndLimit()
{
var t0 = DateTimeOffset.UtcNow.AddMinutes(-10);
Ops.AddFile("/in/c.csv", "3", t0.AddMinutes(3));
Ops.AddFile("/in/a.csv", "1", t0.AddMinutes(1));
Ops.AddFile("/in/b.csv", "2", t0.AddMinutes(2));
Ops.AddFile("/in/skip.tmp", "x", t0);
var endpoint = Endpoint(new()
{
["include"] = "*.csv",
["exclude"] = "*.tmp",
["sortBy"] = "Modified",
["maxMessagesPerPoll"] = "2",
["noop"] = "true"
});
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().Equal("1", "2");
}
[Fact]
public async Task Poll_SkipsInternalTempFiles()
{
Ops.AddFile("/in/.redb_staging.csv", "internal");
Ops.AddFile("/in/.tmp-partial.csv", "partial");
Ops.AddFile("/in/real.csv", "real");
var endpoint = Endpoint(new() { ["tempPrefix"] = ".tmp-", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().ContainSingle().Which.Should().Be("real");
}
// ── Failure contract ────────────────────────────────────────────
[Fact]
public async Task ProcessingFailure_KeepsFile_AndReleasesIdempotentKey()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["delete"] = "true", ["idempotent"] = "true" });
var (processor, _, _) = Collector(exchange => exchange.Exception = new FormatException("bad row"));
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
Ops.HasFile("/in/order.csv").Should().BeTrue("a file that failed processing must not be deleted");
// Second poll must retry it: the idempotent key was released on failure.
var (retryProcessor, retryBodies, _) = Collector();
var retryConsumer = (TestFileConsumer)endpoint.CreateConsumer(retryProcessor);
await retryConsumer.PollOnceAsync();
retryBodies.Should().ContainSingle();
}
[Fact]
public async Task UnreadableFile_IsNotDeliveredAsEmptyBody()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
Ops.FailRead = path => path == "/in/order.csv"
? new IOException("The process cannot access the file because it is being used by another process.")
: null;
var endpoint = Endpoint(new() { ["delete"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().NotContain("", "an unreadable file must never arrive as a successfully processed empty body");
Ops.HasFile("/in/order.csv").Should().BeTrue("an unreadable file must not be treated as processed");
}
[Fact]
public async Task UnreadableFile_DoesNotAbortTheRestOfTheBatch()
{
Ops.AddFile("/in/a.csv", "A");
Ops.AddFile("/in/b.csv", "B");
Ops.FailRead = path => path == "/in/a.csv" ? new IOException("locked") : null;
var endpoint = Endpoint(new() { ["sortBy"] = "Name", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().Contain("B", "one unreadable file must not block the files after it");
}
// ── Idempotency ─────────────────────────────────────────────────
[Fact]
public async Task Idempotent_DefaultKey_SkipsAlreadyProcessedFile()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["idempotent"] = "true", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
await consumer.PollOnceAsync();
bodies.Should().ContainSingle();
}
[Fact]
public async Task Idempotent_LostReadLock_ProcessesFileOnceLockIsAvailable()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["idempotent"] = "true", ["noop"] = "true" });
var locked = true;
endpoint.ReadLockGate = _ => !locked;
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync(); // another consumer holds the lock
bodies.Should().BeEmpty();
locked = false; // the other consumer is done
await consumer.PollOnceAsync();
bodies.Should().ContainSingle("claiming the idempotent key must not consume the file when the read lock was refused");
}
[Fact]
public async Task Idempotent_TreatsNamesDifferingOnlyInCaseAsDistinctFiles()
{
// Every SFTP/FTP server and every non-Windows file system treats these as two files.
// Same timestamp and same length on purpose: the path case must be what separates the keys.
var stamp = new DateTimeOffset(2026, 8, 25, 10, 0, 0, TimeSpan.Zero);
Ops.AddFile("/in/order.csv", "lower", stamp);
Ops.AddFile("/in/Order.csv", "upper", stamp);
var endpoint = Endpoint(new() { ["idempotent"] = "true", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().HaveCount(2, "case-insensitive keys collapse two real files into one");
bodies.Should().BeEquivalentTo(["lower", "upper"]);
}
[Fact]
public async Task Idempotent_CustomKey_ProcessesDistinctFiles()
{
Ops.AddFile("/in/one.csv", "1");
Ops.AddFile("/in/two.csv", "2");
var endpoint = Endpoint(new()
{
["idempotent"] = "true",
["idempotentKey"] = "${file:name}",
["noop"] = "true"
});
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().HaveCount(2, "a per-file key expression must produce a distinct key per file");
bodies.Should().BeEquivalentTo(["1", "2"]);
}
[Fact]
public async Task Idempotent_CustomKey_StillSkipsRepeats()
{
Ops.AddFile("/in/one.csv", "1");
var endpoint = Endpoint(new()
{
["idempotent"] = "true",
["idempotentKey"] = "${file:name}",
["noop"] = "true"
});
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
await consumer.PollOnceAsync();
bodies.Should().ContainSingle();
}
// ── Post-processing ─────────────────────────────────────────────
[Fact]
public async Task MoveTo_MovesFileToDirectory()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["moveTo"] = "archive" });
var (processor, _, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
Ops.HasFile("/in/archive/order.csv").Should().BeTrue();
Ops.HasFile("/in/order.csv").Should().BeFalse();
}
[Fact]
public async Task MoveTo_ResolvesFileNameSubstitutions()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["moveTo"] = "archive-${file:name.noext}" });
var (processor, _, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
Ops.HasFile("/in/archive-order/order.csv").Should()
.BeTrue("moveTo must resolve the same file substitutions as doneFileName");
Ops.AllDirectories().Should().NotContain(d => d.Contains("${"),
"an unresolved template must never become a directory name");
}
[Fact]
public async Task PreMove_MovesBeforeProcessing_AndResolvesSubstitutions()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["preMove"] = "work-${file:name.noext}", ["delete"] = "true" });
var (processor, _, exchanges) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
exchanges[0].In.Headers["testFile.AbsolutePath"].Should().Be("/in/work-order/order.csv");
Ops.AllDirectories().Should().NotContain(d => d.Contains("${"));
}
[Fact]
public async Task DoneFile_GatesProcessing_AndIsRemovedAfterwards()
{
Ops.AddFile("/in/order.csv", "PAYLOAD");
var endpoint = Endpoint(new() { ["doneFileName"] = "${file:name}.done", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().BeEmpty("no done file yet");
Ops.AddFile("/in/order.csv.done", "");
await consumer.PollOnceAsync();
bodies.Should().ContainSingle();
Ops.HasFile("/in/order.csv.done").Should().BeFalse("the done file is consumed with the payload");
}
[Fact]
public async Task MinAge_DefersYoungFiles()
{
Ops.AddFile("/in/fresh.csv", "new", DateTimeOffset.UtcNow);
Ops.AddFile("/in/settled.csv", "old", DateTimeOffset.UtcNow.AddMinutes(-5));
var endpoint = Endpoint(new() { ["minAge"] = "60000", ["noop"] = "true" });
var (processor, bodies, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
await consumer.PollOnceAsync();
bodies.Should().ContainSingle().Which.Should().Be("old");
}
// ── Poll backoff: exchange count feeds idle/success classification ──
[Fact]
public async Task PollCount_EmptyDirectory_IsZero()
{
var endpoint = Endpoint();
var (processor, _, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
(await consumer.PollOnceAsync()).Created.Should().Be(0, "no files → idle poll");
}
[Fact]
public async Task PollCount_OneFile_IsOne()
{
Ops.AddFile("/in/a.csv", "x");
var endpoint = Endpoint(new() { ["noop"] = "true" });
var (processor, _, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
(await consumer.PollOnceAsync()).Created.Should().Be(1);
}
[Fact]
public async Task PollCount_IdempotentDuplicate_IsZeroOnSecondPoll()
{
Ops.AddFile("/in/a.csv", "x");
var endpoint = Endpoint(new() { ["idempotent"] = "true", ["noop"] = "true" });
var (processor, _, _) = Collector();
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
(await consumer.PollOnceAsync()).Created.Should().Be(1, "first sighting creates an exchange");
(await consumer.PollOnceAsync()).Created.Should().Be(0, "the duplicate is filtered → idle");
}
[Fact]
public async Task PollTally_AllExchangesFail_CountsCreatedAndFailed()
{
Ops.AddFile("/in/a.csv", "x");
Ops.AddFile("/in/b.csv", "y");
var endpoint = Endpoint(new() { ["noop"] = "true" });
// Processor that fails every exchange the way an unhandled route error does.
var (processor, _, _) = Collector(onProcess: ex => ex.Exception = new InvalidOperationException("down"));
var consumer = (TestFileConsumer)endpoint.CreateConsumer(processor);
var tally = await consumer.PollOnceAsync();
tally.Created.Should().Be(2);
tally.Failed.Should().Be(2, "both exchanges failed unhandled");
// With BackoffOnFailedExchanges on, this tally classifies as Error; off (default) it is Success.
PollBackoff.Classify(tally, backoffOnFailedExchanges: true).Should().Be(PollOutcome.Error);
PollBackoff.Classify(tally, backoffOnFailedExchanges: false).Should().Be(PollOutcome.Success);
}
// ── Poll backoff: option validation and URI binding ──
[Fact]
public void Backoff_MultiplierWithoutThreshold_ThrowsAtCreation()
{
var act = () => Endpoint(new() { ["backoffMultiplier"] = "3" });
act.Should().Throw();
}
[Fact]
public void Backoff_ThresholdWithoutMultiplier_ThrowsAtCreation()
{
var act = () => Endpoint(new() { ["backoffErrorThreshold"] = "2" });
act.Should().Throw();
}
[Fact]
public void Backoff_NegativeMultiplier_ThrowsAtCreation()
{
var act = () => Endpoint(new() { ["backoffMultiplier"] = "-1", ["backoffErrorThreshold"] = "1" });
act.Should().Throw();
}
[Fact]
public void Backoff_UriKeys_BindToOptions()
{
var options = new TestFileEndpointOptions();
options.BindFromUri(new Dictionary
{
["backoffMultiplier"] = "3",
["backoffIdleThreshold"] = "2",
["backoffErrorThreshold"] = "1",
});
options.BackoffMultiplier.Should().Be(3);
options.BackoffIdleThreshold.Should().Be(2);
options.BackoffErrorThreshold.Should().Be(1);
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/GenericFileUtilsTests.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/GenericFileUtilsTests.cs
----
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
/// Unit tests for the shared helpers used by every file transport.
public class GenericFileUtilsTests
{
private readonly FakeFileOperations _ops = new();
// ── IsWithinDirectory ───────────────────────────────────────────
[Theory]
[InlineData("/data/out", "/data/out", true)]
[InlineData("/data/out", "/data/out/report.csv", true)]
[InlineData("/data/out", "/data/out/sub/report.csv", true)]
[InlineData("/data/out/", "/data/out/report.csv", true)]
[InlineData("/data/out", "/data/outside/report.csv", false)]
[InlineData("/data/out", "/data/out2/report.csv", false)]
[InlineData("/data/out", "/data/report.csv", false)]
[InlineData("/data/out", "/etc/passwd", false)]
public void IsWithinDirectory_RespectsTheDirectoryBoundary(string basePath, string candidate, bool expected)
=> GenericFileUtils.IsWithinDirectory(basePath, candidate, '/', StringComparison.Ordinal)
.Should().Be(expected);
[Fact]
public void IsWithinDirectory_HonoursTheRequestedCaseSensitivity()
{
GenericFileUtils.IsWithinDirectory("/data/out", "/DATA/OUT/x", '/', StringComparison.Ordinal)
.Should().BeFalse();
GenericFileUtils.IsWithinDirectory("/data/out", "/DATA/OUT/x", '/', StringComparison.OrdinalIgnoreCase)
.Should().BeTrue();
}
// ── SubstituteFileTokens ────────────────────────────────────────
[Theory]
[InlineData("${file:name}.done", "order.csv.done")]
[InlineData("${file:name.noext}.done", "order.done")]
[InlineData("archive-${file:name.noext}", "archive-order")]
[InlineData("${FILE:NAME}", "order.csv")]
[InlineData("plain", "plain")]
[InlineData("", "")]
public void SubstituteFileTokens_ReplacesFileVariables(string pattern, string expected)
=> GenericFileUtils.SubstituteFileTokens("order.csv", pattern, _ops).Should().Be(expected);
[Fact]
public void SubstituteFileTokens_LeavesUnknownVariablesAlone()
=> GenericFileUtils.SubstituteFileTokens("order.csv", "${header.x}", _ops).Should().Be("${header.x}");
// ── GlobMatch ───────────────────────────────────────────────────
[Theory]
[InlineData("order.csv", "*.csv", true)]
[InlineData("ORDER.CSV", "*.csv", true)]
[InlineData("order.xml", "*.csv,*.xml", true)]
[InlineData("order.txt", "*.csv,*.xml", false)]
[InlineData("data1.txt", "data?.txt", true)]
[InlineData("data12.txt", "data?.txt", false)]
public void GlobMatch_HandlesWildcardsAndLists(string input, string pattern, bool expected)
=> GenericFileUtils.GlobMatch(input, pattern).Should().Be(expected);
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/InMemoryGenericFileIdempotentRepositoryTests.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/InMemoryGenericFileIdempotentRepositoryTests.cs
----
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
///
/// Tests for the idempotent repository shared by the File, FTP and SFTP transports.
/// Consolidated here from the per-connector copies that tested the now-removed
/// InMemoryFileIdempotentRepository / InMemorySftpIdempotentRepository.
///
public class InMemoryGenericFileIdempotentRepositoryTests
{
private static GenericFileInfo FileInfo(
string path = "/in/order.csv", long length = 100, DateTimeOffset? lastModified = null)
=> new()
{
Name = path[(path.LastIndexOf('/') + 1)..],
FullPath = path,
BasePath = "/in",
Length = length,
LastModified = lastModified ?? new DateTimeOffset(2026, 8, 25, 10, 0, 0, TimeSpan.Zero)
};
// ── Add / Contains / Remove ─────────────────────────────────────
[Fact]
public async Task Add_NewKey_ReturnsTrue()
=> (await new InMemoryGenericFileIdempotentRepository().Add("key1")).Should().BeTrue();
[Fact]
public async Task Add_DuplicateKey_ReturnsFalse()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
(await repo.Add("key1")).Should().BeFalse();
}
[Fact]
public async Task Contains_TracksWhatWasAdded()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
(await repo.Contains("key1")).Should().BeTrue();
(await repo.Contains("key2")).Should().BeFalse();
}
[Fact]
public async Task Remove_MakesTheKeyAddableAgain()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
await repo.Remove("key1");
(await repo.Contains("key1")).Should().BeFalse();
(await repo.Add("key1")).Should().BeTrue();
}
[Fact]
public async Task Remove_UnknownKey_DoesNotThrow()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
var act = () => repo.Remove("missing");
await act.Should().NotThrowAsync();
repo.Count.Should().Be(1);
}
[Fact]
public async Task Clear_EmptiesTheRepository()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
await repo.Add("key2");
await repo.Clear();
repo.Count.Should().Be(0);
}
[Fact]
public async Task Count_ReflectsDistinctKeys()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
await repo.Add("key2");
await repo.Add("key1");
repo.Count.Should().Be(2);
}
[Fact]
public async Task Confirm_DoesNotThrow()
{
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("key1");
var act = () => repo.Confirm("key1");
await act.Should().NotThrowAsync();
}
// ── Case sensitivity ────────────────────────────────────────────
[Fact]
public async Task Keys_AreCaseSensitive()
{
// The key embeds the file path. Every SFTP/FTP server and every non-Windows file
// system is case-sensitive, so folding case here would hide a real second file.
var repo = new InMemoryGenericFileIdempotentRepository();
await repo.Add("/upload/File.TXT");
(await repo.Add("/upload/file.txt")).Should().BeTrue();
}
// ── DefaultKey ──────────────────────────────────────────────────
[Fact]
public void DefaultKey_CombinesPathTimestampAndLength()
{
var file = FileInfo("/upload/order.csv", length: 4096);
var key = InMemoryGenericFileIdempotentRepository.DefaultKey(file);
key.Should().Contain("/upload/order.csv");
key.Should().Contain("|");
key.Should().Contain("4096");
}
[Fact]
public void DefaultKey_DiffersByPath_Timestamp_AndLength()
{
var stamp = new DateTimeOffset(2026, 8, 25, 10, 0, 0, TimeSpan.Zero);
var baseline = InMemoryGenericFileIdempotentRepository.DefaultKey(FileInfo("/upload/a.csv", 100, stamp));
var otherPath = InMemoryGenericFileIdempotentRepository.DefaultKey(FileInfo("/upload/b.csv", 100, stamp));
var otherSize = InMemoryGenericFileIdempotentRepository.DefaultKey(FileInfo("/upload/a.csv", 200, stamp));
var otherStamp = InMemoryGenericFileIdempotentRepository.DefaultKey(
FileInfo("/upload/a.csv", 100, stamp.AddSeconds(1)));
new[] { baseline, otherPath, otherSize, otherStamp }.Should().OnlyHaveUniqueItems();
}
[Fact]
public void DefaultKey_NullFile_Throws()
{
var act = () => InMemoryGenericFileIdempotentRepository.DefaultKey(null!);
act.Should().Throw();
}
// ── Concurrency ─────────────────────────────────────────────────
[Fact]
public async Task Add_IsSafeUnderConcurrency_AndOnlyOneCallerWins()
{
var repo = new InMemoryGenericFileIdempotentRepository();
var results = await Task.WhenAll(Enumerable.Range(0, 50).Select(_ => repo.Add("same-key")));
results.Count(won => won).Should().Be(1, "the claim must be granted exactly once");
repo.Count.Should().Be(1);
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/PollBackoffTests.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/PollBackoffTests.cs
----
using AwesomeAssertions;
using redb.Route.GenericFile;
using Xunit;
namespace redb.Route.Tests.GenericFile;
///
/// Unit tests for the pure poll-backoff decision (no timers, no I/O): thresholds arm the skip countdown,
/// exactly multiplier polls are skipped, then counters reset. Mirrors Apache Camel semantics.
///
public class PollBackoffTests
{
private static int SkipsFor(PollBackoff b)
{
var skips = 0;
while (b.ShouldSkip()) skips++;
return skips;
}
[Fact]
public void Error_Threshold_Arms_Then_Skips_Exactly_Multiplier_Then_Resets()
{
var b = new PollBackoff(multiplier: 3, idleThreshold: 0, errorThreshold: 2);
b.Record(PollOutcome.Error).Should().BeNull("one error is below the threshold of 2");
SkipsFor(b).Should().Be(0);
b.Record(PollOutcome.Error).Should().NotBeNull("the second error hits the threshold");
SkipsFor(b).Should().Be(3, "the multiplier is 3");
// After the skips the counters reset, so a fresh error is below the threshold again.
b.Record(PollOutcome.Error).Should().BeNull();
SkipsFor(b).Should().Be(0);
}
[Fact]
public void Idle_Threshold_Arms_The_Skip()
{
var b = new PollBackoff(multiplier: 2, idleThreshold: 3, errorThreshold: 0);
b.Record(PollOutcome.Idle).Should().BeNull();
b.Record(PollOutcome.Idle).Should().BeNull();
b.Record(PollOutcome.Idle).Should().NotBeNull("the third idle hits the threshold of 3");
SkipsFor(b).Should().Be(2);
}
[Fact]
public void Success_Resets_The_Error_Count()
{
var b = new PollBackoff(multiplier: 5, idleThreshold: 0, errorThreshold: 2);
b.Record(PollOutcome.Error);
b.Record(PollOutcome.Success).Should().BeNull("success clears the error count");
b.Record(PollOutcome.Error).Should().BeNull("only one error since the reset — below threshold 2");
SkipsFor(b).Should().Be(0);
}
[Fact]
public void Error_Resets_The_Idle_Count()
{
var b = new PollBackoff(multiplier: 2, idleThreshold: 2, errorThreshold: 0);
b.Record(PollOutcome.Idle);
b.Record(PollOutcome.Error).Should().BeNull("error has no error-threshold and clears idle");
b.Record(PollOutcome.Idle).Should().BeNull("idle count restarted — one idle, below threshold 2");
SkipsFor(b).Should().Be(0);
}
[Fact]
public void Trigger_Reports_Reason_And_Skip_Count()
{
var byError = new PollBackoff(1, 0, 1).Record(PollOutcome.Error);
byError!.Value.ByError.Should().BeTrue();
byError.Value.Skips.Should().Be(1);
var byIdle = new PollBackoff(4, 1, 0).Record(PollOutcome.Idle);
byIdle!.Value.ByError.Should().BeFalse();
byIdle.Value.Skips.Should().Be(4);
}
[Fact]
public void Classify_MapsTallyToOutcome()
{
// No exchange → idle, regardless of the flag.
PollBackoff.Classify(new PollTally(0, 0), false).Should().Be(PollOutcome.Idle);
PollBackoff.Classify(new PollTally(0, 0), true).Should().Be(PollOutcome.Idle);
// Some created → success by default (Camel parity), even if all failed.
PollBackoff.Classify(new PollTally(2, 2), false).Should().Be(PollOutcome.Success);
// All created failed + flag → error (the Camel-superset behaviour).
PollBackoff.Classify(new PollTally(2, 2), true).Should().Be(PollOutcome.Error);
// Partial success + flag → success (progress was made, don't back off).
PollBackoff.Classify(new PollTally(2, 1), true).Should().Be(PollOutcome.Success);
}
[Theory]
[InlineData(0, 0, 0)] // nothing configured
[InlineData(0, 2, 3)] // thresholds but no multiplier
[InlineData(3, 0, 0)] // multiplier but no threshold
public void Disabled_Never_Skips_And_Ignores_Outcomes(int mult, int idle, int error)
{
var b = new PollBackoff(mult, idle, error);
b.Enabled.Should().BeFalse();
for (var i = 0; i < 10; i++)
{
b.Record(PollOutcome.Error).Should().BeNull();
b.Record(PollOutcome.Idle).Should().BeNull();
b.ShouldSkip().Should().BeFalse();
}
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/TestFileHarness.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/TestFileHarness.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.GenericFile;
namespace redb.Route.Tests.GenericFile;
/// Options for the in-memory test transport.
public sealed class TestFileEndpointOptions : GenericFileEndpointOptions
{
///
public override void Validate() => ValidateCommon();
}
/// Component for the in-memory test transport. Scheme: "testfile".
public sealed class TestFileComponent : ComponentBase
{
private readonly FakeFileOperations _ops;
/// Filter bean the component hands to the options, the way the real components resolve filter=#name from the registry.
public IGenericFileFilter? Filter { get; set; }
public TestFileComponent(FakeFileOperations ops) => _ops = ops;
///
public override string Scheme => "testfile";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
var options = new TestFileEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.FilterInstance = Filter;
options.Validate();
return new TestFileEndpoint(uri, this, options, _ops);
}
}
/// Endpoint for the in-memory test transport.
public sealed class TestFileEndpoint : EndpointBase
{
private readonly FakeFileOperations _ops;
public TestFileEndpoint(EndpointUri uri, TestFileComponent component, TestFileEndpointOptions options, FakeFileOperations ops)
: base(uri, component, options)
=> _ops = ops;
/// Base directory this endpoint polls or writes to.
public string DirectoryPath => Uri.Path.Length == 0 ? "/" : Uri.Path;
/// Read-lock outcome injected by tests (null = strategy grants the lock).
public Func? ReadLockGate { get; set; }
///
public override IProducer CreateProducer() => new TestFileProducer(this, Options, _ops);
///
public override IConsumer CreateConsumer(IProcessor processor)
=> new TestFileConsumer(this, processor, Options, _ops);
}
/// Consumer over , exercising the shared poll loop.
public sealed class TestFileConsumer : GenericFileConsumer
{
private readonly TestFileEndpoint _endpoint;
///
protected override string ConsumerName => $"testfile:{_endpoint.DirectoryPath}";
///
protected override string BasePath => _endpoint.DirectoryPath;
public TestFileConsumer(TestFileEndpoint endpoint, IProcessor processor, TestFileEndpointOptions options, FakeFileOperations ops)
: base(endpoint, processor, options, ops)
=> _endpoint = endpoint;
/// Runs exactly one poll cycle, returning its tally (created / failed exchanges).
public Task PollOnceAsync(CancellationToken ct = default) => PollDirectory(ct);
///
protected override void SetExchangeHeaders(IMessage message, GenericFileInfo file, string workPath)
{
message.Headers["testFile.Name"] = file.Name;
message.Headers["testFile.AbsolutePath"] = workPath;
message.Headers["testFile.Length"] = file.Length;
}
///
protected override Task AcquireReadLockAsync(GenericFileInfo file, CancellationToken ct)
=> Task.FromResult(_endpoint.ReadLockGate?.Invoke(file) ?? true);
}
/// Producer over , exercising the shared write flow.
public sealed class TestFileProducer : GenericFileProducer
{
private readonly TestFileEndpoint _endpoint;
///
protected override string BasePath => _endpoint.DirectoryPath;
///
protected override string FileNameProducedHeader => "testFile.NameProduced";
public TestFileProducer(TestFileEndpoint endpoint, TestFileEndpointOptions options, FakeFileOperations ops)
: base(endpoint, options, ops)
=> _endpoint = endpoint;
}
/// Shared scaffolding for the tests in this project.
public abstract class GenericFileTestBase
{
protected const string BaseDir = "/in";
protected FakeFileOperations Ops { get; } = new();
protected GenericFileTestBase() => Ops.AddDirectory(BaseDir);
protected TestFileEndpoint Endpoint(Dictionary? parameters = null, string? dir = null, IGenericFileFilter? filter = null)
{
var component = new TestFileComponent(Ops) { Filter = filter };
var path = dir ?? BaseDir;
var uri = new EndpointUri("testfile", path, "testfile://" + path, parameters ?? new Dictionary());
return (TestFileEndpoint)component.CreateEndpoint(uri);
}
/// Collecting processor: records every exchange body as UTF-8 text.
protected static (IProcessor Processor, List Bodies, List Exchanges) Collector(
Action? onProcess = null)
{
var bodies = new List();
var exchanges = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(call =>
{
var exchange = call.Arg();
exchanges.Add(exchange);
bodies.Add(exchange.In.Body switch
{
byte[] b => System.Text.Encoding.UTF8.GetString(b),
null => "",
var other => other.ToString() ?? ""
});
onProcess?.Invoke(exchange);
});
return (processor, bodies, exchanges);
}
}
Path: redb-route/tests/redb.Route.Tests.GenericFile/redb.Route.Tests.GenericFile.csproj
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/redb.Route.Tests.GenericFile.csproj
----