Bundle: redb-route / tests/redb.Route.Tests.File (tests.redb.Route.Tests.File.txt), 19 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.File/ConsumerTemplateFileTests.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.File/ConsumerTemplateFileTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// ConsumerTemplate over a polled directory, as Camel's: a Receive hands over one file and the file
/// stays where it is until the caller says it is done with it (DoneUoW ). Only then is it
/// deleted or moved. Files the caller has not received are never touched, and a template stopped
/// before DoneUoW leaves its file in place.
///
public class ConsumerTemplateFileTests : IAsyncLifetime
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-route-ct-" + Guid.NewGuid().ToString("N")[..8]);
private readonly RouteContext _context = new();
private ConsumerTemplate _template = null!;
public Task InitializeAsync()
{
Directory.CreateDirectory(_root);
_context.AddComponent(new FileComponent());
_template = new ConsumerTemplate(_context);
_template.Start();
return Task.CompletedTask;
}
public async Task DisposeAsync()
{
_template.Dispose();
await _context.DisposeAsync();
try { Directory.Delete(_root, recursive: true); } catch (IOException) { }
}
private string Uri(string options = "delete=true") =>
"file:///" + _root.Replace("\\", "/").TrimStart('/') + "?delay=10&" + options;
private void Write(int count)
{
for (var i = 0; i < count; i++)
System.IO.File.WriteAllText(Path.Combine(_root, $"f{i}.txt"), $"payload {i}");
}
private int FilesLeft() => Directory.GetFiles(_root).Length;
/// For files that must stay: nothing to wait for, so give a wrong delete time to happen.
private async Task SettleAndCount()
{
await Task.Delay(300);
return FilesLeft();
}
/// For files that must go: the commit runs after the call returns, so poll for it.
private async Task WaitUntilAllGone()
{
var deadline = DateTime.UtcNow.AddSeconds(5);
while (FilesLeft() > 0 && DateTime.UtcNow < deadline)
await Task.Delay(50);
return FilesLeft();
}
[Fact]
public async Task One_receive_takes_one_file_and_leaves_the_others()
{
Write(5);
var exchange = await _template.Receive(Uri(), TimeSpan.FromSeconds(5));
await _template.DoneUoW(exchange!);
(await SettleAndCount()).Should().Be(4, "a file the caller never received must not be deleted");
}
[Fact]
public async Task The_file_stays_until_the_caller_is_done()
{
Write(1);
var exchange = await _template.Receive(Uri(), TimeSpan.FromSeconds(5));
exchange!.In.Body.Should().BeOfType();
(await SettleAndCount()).Should().Be(1, "the caller has not said it is done");
await _template.DoneUoW(exchange);
(await WaitUntilAllGone()).Should().Be(0);
}
[Fact]
public async Task Receives_hand_over_every_file_once()
{
Write(3);
var names = new List();
for (var i = 0; i < 3; i++)
{
var exchange = await _template.Receive(Uri(), TimeSpan.FromSeconds(5));
names.Add(exchange!.In.Headers[FileHeaders.FileName]!.ToString()!);
await _template.DoneUoW(exchange);
}
names.Should().BeEquivalentTo(["f0.txt", "f1.txt", "f2.txt"]);
(await WaitUntilAllGone()).Should().Be(0);
}
[Fact]
public async Task A_failure_recorded_by_the_caller_leaves_the_file()
{
Write(1);
var exchange = await _template.Receive(Uri(), TimeSpan.FromSeconds(5));
exchange!.Exception = new InvalidOperationException("the caller could not handle it");
await _template.DoneUoW(exchange);
(await SettleAndCount()).Should().Be(1, "a failed unit of work is rolled back, not committed");
}
[Fact]
public async Task Stopping_before_done_leaves_the_file()
{
Write(1);
var exchange = await _template.Receive(Uri(), TimeSpan.FromSeconds(5));
exchange.Should().NotBeNull();
_template.Stop();
(await SettleAndCount()).Should().Be(1);
var act = () => _template.DoneUoW(exchange!);
await act.Should().ThrowAsync("the unit of work was rolled back by the stop");
}
[Fact]
public async Task ReceiveBody_is_done_by_itself()
{
Write(1);
var body = await _template.ReceiveBody(Uri(), TimeSpan.FromSeconds(5));
System.Text.Encoding.UTF8.GetString(body!).Should().Be("payload 0");
(await WaitUntilAllGone()).Should().Be(0);
}
[Fact]
public async Task ReceiveBody_reads_a_streamed_file_before_it_is_committed()
{
Write(1);
var body = await _template.ReceiveBody(Uri("delete=true&streamBody=true"), TimeSpan.FromSeconds(5));
var stream = body.Should().BeAssignableTo().Subject;
new StreamReader(stream).ReadToEnd().Should().Be("payload 0", "the body outlives the committed file");
}
[Fact]
public async Task Done_on_an_exchange_the_template_did_not_hand_out_is_refused()
{
var act = () => _template.DoneUoW(new Exchange());
await act.Should().ThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileBuilderTests.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.File/FileBuilderTests.cs
----
using redb.Route.Core;
using redb.Route.File;
using redb.Route.Expressions;
namespace redb.Route.Tests.File;
public class FileBuilderTests
{
private static ConstantExpression C(string s) => new(s);
// ── Factory methods ─────────────────────────────────────────────
[Fact]
public void Read_StartsWithFileScheme()
{
var uri = FileDsl.Read("/data/input").Build();
uri.Should().StartWith("file:///");
}
[Fact]
public void Write_StartsWithFileScheme()
{
var uri = FileDsl.Write("/data/output").Build();
uri.Should().StartWith("file:///");
}
[Fact]
public void NullDirectory_Throws()
{
var act = () => FileDsl.Read(null!);
act.Should().Throw();
}
[Fact]
public void PathIsNormalized_NoDoubleSlash()
{
var uri = FileDsl.Read("/incoming").Build();
uri.Should().StartWith("file:///incoming");
}
// ── Consumer params ─────────────────────────────────────────────
[Fact]
public void Delay_SetsParam()
{
var uri = FileDsl.Read("/in").Delay(5000).Build();
uri.Should().Contain("delay=5000");
}
[Fact]
public void Include_SetsParam()
{
var uri = FileDsl.Read("/in").Include("*.csv").Build();
uri.Should().Contain("include=%2A.csv");
}
[Fact]
public void Exclude_SetsParam()
{
var uri = FileDsl.Read("/in").Exclude("*.tmp").Build();
uri.Should().Contain("exclude=%2A.tmp");
}
[Fact]
public void Recursive_SetsParam()
{
var uri = FileDsl.Read("/in").Recursive().Build();
uri.Should().Contain("recursive=true");
}
[Fact]
public void SortBy_SetsParam()
{
var uri = FileDsl.Read("/in").SortBy("Modified").Build();
uri.Should().Contain("sortBy=Modified");
}
[Fact]
public void MaxMessagesPerPoll_SetsParam()
{
var uri = FileDsl.Read("/in").MaxMessagesPerPoll(10).Build();
uri.Should().Contain("maxMessagesPerPoll=10");
}
// ── Post-processing ─────────────────────────────────────────────
[Fact]
public void Noop_SetsParam()
{
var uri = FileDsl.Read("/in").Noop().Build();
uri.Should().Contain("noop=true");
}
[Fact]
public void Delete_SetsParam()
{
var uri = FileDsl.Read("/in").Delete().Build();
uri.Should().Contain("delete=true");
}
[Fact]
public void MoveTo_SetsParam()
{
var uri = FileDsl.Read("/in").MoveTo(C("/archive")).Build();
uri.Should().Contain("moveTo=%2Farchive");
}
// ── Idempotency ─────────────────────────────────────────────────
[Fact]
public void Idempotent_SetsParam()
{
var uri = FileDsl.Read("/in").Idempotent().Build();
uri.Should().Contain("idempotent=true");
}
[Fact]
public void IdempotentWithKey_SetsBothParams()
{
var uri = FileDsl.Read("/in").Idempotent(C("${file:name}")).Build();
uri.Should().Contain("idempotent=true");
uri.Should().Contain("idempotentKey=");
}
// ── Read locking ────────────────────────────────────────────────
[Fact]
public void ReadLock_SetsParam()
{
var uri = FileDsl.Read("/in").ReadLock("Changed").Build();
uri.Should().Contain("readLock=Changed");
}
// ── Producer params ─────────────────────────────────────────────
[Fact]
public void FileExist_SetsParam()
{
var uri = FileDsl.Write("/out").FileExist("Append").Build();
uri.Should().Contain("fileExist=Append");
}
[Fact]
public void Charset_SetsParam()
{
var uri = FileDsl.Write("/out").Charset("windows-1251").Build();
uri.Should().Contain("charset=windows-1251");
}
[Fact]
public void TempPrefix_SetsParam()
{
var uri = FileDsl.Write("/out").TempPrefix(C(".tmp")).Build();
uri.Should().Contain("tempPrefix=.tmp");
}
// ── Conversion ──────────────────────────────────────────────────
[Fact]
public void ImplicitConversion_ReturnsUri()
{
string uri = FileDsl.Read("/data").Include("*.xml").Recursive();
uri.Should().StartWith("file:///data?");
}
[Fact]
public void ToString_ReturnsSameAsBuild()
{
var builder = FileDsl.Write("/out").FileExist("Fail");
builder.ToString().Should().Be(builder.Build());
}
// ── Full chain ──────────────────────────────────────────────────
[Fact]
public void FullConsumerChain_BuildsCorrectUri()
{
var uri = FileDsl.Read("/incoming")
.Include("*.csv")
.Recursive()
.Delay(5000)
.SortBy("Modified")
.Noop()
.Idempotent()
.ReadLock("Changed")
.Build();
uri.Should().StartWith("file:///incoming?");
uri.Should().Contain("include=%2A.csv");
uri.Should().Contain("recursive=true");
uri.Should().Contain("delay=5000");
uri.Should().Contain("noop=true");
uri.Should().Contain("idempotent=true");
uri.Should().Contain("readLock=Changed");
}
// ── StreamBody ────────────────────────────────────────────────
[Fact]
public void StreamBody_SetsParam()
{
var uri = FileDsl.Read("/in").StreamBody().Build();
uri.Should().Contain("streamBody=true");
}
[Fact]
public void StreamBody_RoundTripParseable()
{
var uri = FileDsl.Read("/in").StreamBody().Delete().Build();
var parsed = EndpointUriParser.Parse(uri);
parsed.RawParameters["streamBody"].Should().Be("true");
}
// ── Round-trip ──────────────────────────────────────────────────
[Fact]
public void RoundTrip_ParseAndReconstruct()
{
var original = FileDsl.Read("/data/input").Include("*.csv").Delay(5000).Build();
var parsed = EndpointUriParser.Parse(original);
parsed.Scheme.Should().Be("file");
parsed.RawParameters["include"].Should().Be("*.csv");
parsed.RawParameters["delay"].Should().Be("5000");
}
// ── A string is a string ────────────────────────────────────────
///
/// The string overloads store the string. A dash used to be read as a subtraction and a
/// slash as a division by the expression compiler the value passed through for nothing.
///
[Theory]
[InlineData("my-file.txt")]
[InlineData("archive/2026/data.txt")]
[InlineData("report(1).txt")]
public void StringOverloads_KeepAnyStringLiteral(string value)
{
var act = () => FileDsl.Read("/in").FileName(value).MoveTo(value).Build();
act.Should().NotThrow();
Uri.UnescapeDataString(act()).Should().Contain("fileName=" + value);
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileComponentTests.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.File/FileComponentTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
using redb.Route.GenericFile;
namespace redb.Route.Tests.File;
///
/// Tests for FileComponent, FileEndpoint, and FileEndpointOptions.
///
public class FileComponentTests
{
[Fact]
public void Scheme_ReturnsFile()
{
var component = new FileComponent();
component.Scheme.Should().Be("file");
}
[Fact]
public void CreateEndpoint_ValidUri_ReturnsFileEndpoint()
{
var component = new FileComponent();
var uri = new EndpointUri("file", "/C:/input", "file:///C:/input", new Dictionary());
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().BeOfType();
endpoint.Uri.Should().BeSameAs(uri);
endpoint.Component.Should().BeSameAs(component);
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var component = new FileComponent();
var act = () => component.CreateEndpoint(null!);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_WithOptions_BindsCorrectly()
{
var component = new FileComponent();
var parameters = new Dictionary
{
["delay"] = "2000",
["include"] = "*.csv",
["noop"] = "true",
["recursive"] = "true",
["sortBy"] = "Modified",
["idempotent"] = "true"
};
var uri = new EndpointUri("file", "/C:/input", "file:///C:/input", parameters);
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.Delay.Should().Be(2000);
endpoint.EndpointOptions.Include.Should().Be("*.csv");
endpoint.EndpointOptions.Noop.Should().BeTrue();
endpoint.EndpointOptions.Recursive.Should().BeTrue();
endpoint.EndpointOptions.SortBy.Should().Be(GenericFileSortBy.Modified);
endpoint.EndpointOptions.Idempotent.Should().BeTrue();
}
[Fact]
public void CreateEndpoint_ProducerOptions_BindsCorrectly()
{
var component = new FileComponent();
var parameters = new Dictionary
{
["fileExist"] = "Append",
["tempPrefix"] = ".redb_",
["charset"] = "utf-16",
["autoCreate"] = "true",
["allowNullBody"] = "true",
["appendChars"] = "\n"
};
var uri = new EndpointUri("file", "/C:/output", "file:///C:/output", parameters);
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.FileExist.Should().Be(GenericFileExistStrategy.Append);
endpoint.EndpointOptions.TempPrefix.Should().Be(".redb_");
endpoint.EndpointOptions.Charset.Should().Be("utf-16");
endpoint.EndpointOptions.AutoCreate.Should().BeTrue();
endpoint.EndpointOptions.AllowNullBody.Should().BeTrue();
endpoint.EndpointOptions.AppendChars.Should().Be("\n");
}
[Fact]
public void CreateEndpoint_ReadLockOptions_BindsCorrectly()
{
var component = new FileComponent();
var parameters = new Dictionary
{
["readLock"] = "Changed",
["readLockTimeout"] = "5000",
["readLockCheckInterval"] = "500",
["readLockMinAge"] = "2000"
};
var uri = new EndpointUri("file", "/C:/input", "file:///C:/input", parameters);
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
endpoint.EndpointOptions.ReadLock.Should().Be(ReadLockStrategy.Changed);
endpoint.EndpointOptions.ReadLockTimeout.Should().Be(5000);
endpoint.EndpointOptions.ReadLockCheckInterval.Should().Be(500);
endpoint.EndpointOptions.ReadLockMinAge.Should().Be(2000);
}
[Fact]
public void Endpoint_DirectoryPath_WindowsPath_NormalizesCorrectly()
{
var component = new FileComponent();
var uri = new EndpointUri("file", "/C:/input/data", "file:///C:/input/data", new Dictionary());
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
endpoint.DirectoryPath.Should().Be(Path.GetFullPath("C:/input/data"));
}
[Fact]
public void Endpoint_CreateConsumer_ReturnsFileConsumer()
{
var component = new FileComponent();
var uri = new EndpointUri("file", "/C:/input", "file:///C:/input", new Dictionary());
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
consumer.Should().BeOfType();
}
[Fact]
public void Endpoint_CreateConsumer_NullProcessor_Throws()
{
var component = new FileComponent();
var uri = new EndpointUri("file", "/C:/input", "file:///C:/input", new Dictionary());
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
var act = () => endpoint.CreateConsumer(null!);
act.Should().Throw();
}
[Fact]
public void Endpoint_CreateProducer_ReturnsFileProducer()
{
var component = new FileComponent();
var uri = new EndpointUri("file", "/C:/output", "file:///C:/output", new Dictionary());
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
var producer = endpoint.CreateProducer();
producer.Should().BeOfType();
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileConsumerCancellationTests.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.File/FileConsumerCancellationTests.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// A cancellation coming out of the route that is not the consumer's own stop — an HttpClient timeout comes as a
/// , and an error handler passes a cancellation on rather than swallow it — is a
/// failure of that file, like any other exception: the failure path runs (the idempotent key is released, moveFailed on
/// the remote connectors) and the rest of the poll goes on. It used to escape the per-file handling and fail the whole
/// poll: the files after it waited for the next poll, the failure path did not run, and the poll counted as an error.
///
public sealed class FileConsumerCancellationTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-cancel-" + Guid.NewGuid().ToString("N")[..12]);
public FileConsumerCancellationTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch (IOException) { }
}
[Fact]
public async Task A_cancellation_out_of_the_route_fails_the_file_releases_its_key_and_the_poll_goes_on()
{
System.IO.File.WriteAllText(Path.Combine(_root, "a.txt"), "a");
System.IO.File.WriteAllText(Path.Combine(_root, "b.txt"), "b");
var attempts = new ConcurrentDictionary();
var order = new ConcurrentQueue();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(ci =>
{
var name = ci.Arg().In.Headers[FileHeaders.FileName]!.ToString()!;
order.Enqueue(name);
return attempts.AddOrUpdate(name, 1, (_, n) => n + 1) == 1 && name == "a.txt"
? Task.FromException(new TaskCanceledException("a call inside the route timed out"))
: Task.CompletedTask;
});
var path = "/" + _root.Replace("\\", "/");
var endpoint = (FileEndpoint)new FileComponent().CreateEndpoint(new EndpointUri("file", path, $"file://{path}",
new Dictionary
{
["delay"] = "100", ["initialDelay"] = "10", ["idempotent"] = "true", ["noop"] = "true", ["sortBy"] = "Name",
}));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline && !(attempts.GetValueOrDefault("a.txt") >= 2 && attempts.ContainsKey("b.txt")))
await Task.Delay(50);
await consumer.Stop();
attempts.GetValueOrDefault("a.txt").Should().BeGreaterThanOrEqualTo(2,
"the failed file's idempotent key is released, so a later poll takes it again");
attempts.GetValueOrDefault("b.txt").Should().Be(1, "b keeps its key");
order.Take(3).Should().Equal(["a.txt", "b.txt", "a.txt"],
"b is taken in the same poll as a's failure, not left for the next one: a single failed file does not end the poll");
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileConsumerTests.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.File/FileConsumerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// Tests for FileConsumer — polling, filtering, idempotency, post-processing.
/// Uses real temp directories on the filesystem.
///
public class FileConsumerTests : IDisposable
{
private readonly string _tempDir;
private readonly string _inputDir;
public FileConsumerTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-consumer-tests-" + Guid.NewGuid().ToString("N")[..8]);
_inputDir = Path.Combine(_tempDir, "input");
Directory.CreateDirectory(_inputDir);
}
private FileEndpoint CreateEndpoint(Dictionary? parameters = null)
{
var component = new FileComponent();
var path = "/" + _inputDir.Replace("\\", "/");
var parms = parameters ?? new Dictionary();
var uri = new EndpointUri("file", path, $"file://{path}", parms);
return (FileEndpoint)component.CreateEndpoint(uri);
}
private void CreateFile(string name, string content = "test data")
{
System.IO.File.WriteAllText(Path.Combine(_inputDir, name), content);
}
// ── Basic polling ───────────────────────────────────────────────
[Fact]
public async Task Consumer_PollsAndProcessesFile()
{
CreateFile("order.csv", "data");
var endpoint = CreateEndpoint(new() { ["delete"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(1);
var exchange = processed[0];
exchange.Pattern.Should().Be(ExchangePattern.InOnly);
exchange.In.Headers[FileHeaders.FileName].Should().Be("order.csv");
exchange.In.Headers[FileHeaders.FileNameOnly].Should().Be("order");
exchange.In.Headers[FileHeaders.FileExtension].Should().Be(".csv");
exchange.In.Headers[FileHeaders.FileLength].Should().BeOfType();
exchange.In.Headers[FileHeaders.FileLastModified].Should().BeOfType();
exchange.In.Body.Should().BeOfType();
((byte[])exchange.In.Body!).Length.Should().Be(4); // "data"
}
[Fact]
public async Task Consumer_EmptyDirectory_NoProcessing()
{
var endpoint = CreateEndpoint(new() { ["delay"] = "100" });
var processor = Substitute.For();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(300);
await consumer.Stop();
await processor.DidNotReceive().Process(Arg.Any(), Arg.Any());
}
[Fact]
public async Task Consumer_NonExistentDirectory_NoError()
{
var component = new FileComponent();
var nonExistent = Path.Combine(_tempDir, "nonexistent");
var path = "/" + nonExistent.Replace("\\", "/");
var uri = new EndpointUri("file", path, $"file://{path}", new Dictionary { ["delay"] = "100" });
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(300);
await consumer.Stop();
// No exception thrown, no processing
await processor.DidNotReceive().Process(Arg.Any(), Arg.Any());
}
// ── Include/Exclude filters ─────────────────────────────────────
[Fact]
public async Task Consumer_IncludeFilter_OnlyMatchingFiles()
{
CreateFile("order.csv", "csv data");
CreateFile("readme.txt", "txt data");
CreateFile("data.csv", "more csv");
var endpoint = CreateEndpoint(new() { ["include"] = "*.csv", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 2, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(2);
processed.Should().AllSatisfy(e =>
e.In.Headers[FileHeaders.FileName].ToString()!.EndsWith(".csv").Should().BeTrue());
}
[Fact]
public async Task Consumer_ExcludeFilter_SkipsMatchingFiles()
{
CreateFile("order.csv", "csv data");
CreateFile("readme.tmp", "temp data");
var endpoint = CreateEndpoint(new() { ["exclude"] = "*.tmp", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(1);
processed.Should().AllSatisfy(e =>
e.In.Headers[FileHeaders.FileName].ToString()!.EndsWith(".tmp").Should().BeFalse());
}
[Fact]
public async Task Consumer_CommaIncludeFilter_MultiplePatterns()
{
CreateFile("order.csv", "csv");
CreateFile("data.json", "json");
CreateFile("readme.txt", "txt");
var endpoint = CreateEndpoint(new() { ["include"] = "*.csv,*.json", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 2, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(2);
processed.Should().NotContain(e => e.In.Headers[FileHeaders.FileName].ToString()!.EndsWith(".txt"));
}
// ── Recursive ───────────────────────────────────────────────────
[Fact]
public async Task Consumer_Recursive_FindsSubdirFiles()
{
CreateFile("root.txt", "root");
var subDir = Path.Combine(_inputDir, "sub");
Directory.CreateDirectory(subDir);
System.IO.File.WriteAllText(Path.Combine(subDir, "child.txt"), "child");
var endpoint = CreateEndpoint(new() { ["recursive"] = "true", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 2, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(2);
var names = processed.Select(e => e.In.Headers[FileHeaders.FileName].ToString()).ToList();
names.Should().Contain("root.txt");
names.Should().Contain("child.txt");
}
[Fact]
public async Task Consumer_NotRecursive_SkipsSubdirFiles()
{
CreateFile("root.txt", "root");
var subDir = Path.Combine(_inputDir, "sub");
Directory.CreateDirectory(subDir);
System.IO.File.WriteAllText(Path.Combine(subDir, "child.txt"), "child");
var endpoint = CreateEndpoint(new() { ["recursive"] = "false", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await Task.Delay(200); // Extra time to ensure no more files processed
await consumer.Stop();
var names = processed.Select(e => e.In.Headers[FileHeaders.FileName].ToString()).Distinct().ToList();
names.Should().Contain("root.txt");
names.Should().NotContain("child.txt");
}
// ── Sort ────────────────────────────────────────────────────────
[Fact]
public async Task Consumer_SortByName_ProcessesInOrder()
{
CreateFile("c_file.txt", "c");
await Task.Delay(10);
CreateFile("a_file.txt", "a");
await Task.Delay(10);
CreateFile("b_file.txt", "b");
var endpoint = CreateEndpoint(new()
{
["sortBy"] = "Name",
["noop"] = "true",
["delay"] = "5000", // Long delay so only one poll
["maxMessagesPerPoll"] = "10"
});
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
// Trigger single poll directly
await consumer.Start();
await WaitForCondition(() => processed.Count >= 3, 3000);
await consumer.Stop();
var names = processed.Select(e => e.In.Headers[FileHeaders.FileName].ToString()).ToList();
names.Should().StartWith("a_file.txt");
}
// ── MaxMessagesPerPoll ──────────────────────────────────────────
[Fact]
public async Task Consumer_MaxMessagesPerPoll_LimitsCount()
{
for (int i = 0; i < 5; i++)
CreateFile($"file{i}.txt", $"data{i}");
var endpoint = CreateEndpoint(new()
{
["maxMessagesPerPoll"] = "2",
["noop"] = "true",
["delay"] = "5000" // Long delay - one poll
});
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 2, 3000);
// Give a bit more time to ensure no extra files are processed in this poll
await Task.Delay(100);
await consumer.Stop();
processed.Should().HaveCount(2);
}
// ── Post-processing: Delete ─────────────────────────────────────
[Fact]
public async Task Consumer_Delete_RemovesFileAfterProcessing()
{
CreateFile("deleteme.txt", "bye");
var filePath = Path.Combine(_inputDir, "deleteme.txt");
var endpoint = CreateEndpoint(new() { ["delete"] = "true", ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => !System.IO.File.Exists(filePath), 3000);
await consumer.Stop();
System.IO.File.Exists(filePath).Should().BeFalse();
}
// ── Post-processing: MoveTo ─────────────────────────────────────
[Fact]
public async Task Consumer_MoveTo_MovesFileAfterProcessing()
{
CreateFile("moveme.txt", "content");
var archiveDir = Path.Combine(_tempDir, "archive");
var endpoint = CreateEndpoint(new() { ["moveTo"] = archiveDir, ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => System.IO.File.Exists(Path.Combine(archiveDir, "moveme.txt")), 3000);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(_inputDir, "moveme.txt")).Should().BeFalse();
System.IO.File.Exists(Path.Combine(archiveDir, "moveme.txt")).Should().BeTrue();
System.IO.File.ReadAllText(Path.Combine(archiveDir, "moveme.txt")).Should().Be("content");
}
// ── Failure handling: MoveFailed ────────────────────────────────
[Fact]
public async Task Consumer_RollbackOnlyExchange_IsNotCommitted_TheFileGoesToMoveFailed()
{
CreateFile("rolled-back.txt", "data");
var failedDir = Path.Combine(_tempDir, "failed");
// .RollbackAll() leaves no exception, only the rollback-only mark: the work was rolled back, so the file must
// not be treated as done (Camel's file consumer rolls back on isRollbackOnly as well).
var endpoint = CreateEndpoint(new() { ["moveFailed"] = failedDir, ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => x.Arg().MarkRollbackOnly());
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => System.IO.File.Exists(Path.Combine(failedDir, "rolled-back.txt")), 3000);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(failedDir, "rolled-back.txt"))
.Should().BeTrue("a rolled-back file takes the failure path, not the success path");
}
[Fact]
public async Task Consumer_ProcessingFails_WithMoveFailed_QuarantinesFile()
{
CreateFile("poison.txt", "bad");
var failedDir = Path.Combine(_tempDir, "failed");
// The processor "fails" the way a route with .OnException() (handled:false) does: it leaves an
// exception on the exchange (ExceptionHandled stays false), which the consumer treats as a failure.
var endpoint = CreateEndpoint(new() { ["moveFailed"] = failedDir, ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => x.Arg().Exception = new InvalidOperationException("boom"));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => System.IO.File.Exists(Path.Combine(failedDir, "poison.txt")), 3000);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(failedDir, "poison.txt"))
.Should().BeTrue("a failed file must be quarantined to the MoveFailed directory");
System.IO.File.Exists(Path.Combine(_inputDir, "poison.txt"))
.Should().BeFalse("the poison file must leave the poll directory so it is not re-picked forever");
}
[Fact]
public async Task Consumer_ProcessingFails_WithoutMoveFailed_LeavesFileInPlace()
{
CreateFile("stay.txt", "bad");
var filePath = Path.Combine(_inputDir, "stay.txt");
var calls = 0;
var endpoint = CreateEndpoint(new() { ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x =>
{
Interlocked.Increment(ref calls);
x.Arg().Exception = new InvalidOperationException("boom");
});
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => calls >= 1, 3000);
await consumer.Stop();
System.IO.File.Exists(filePath)
.Should().BeTrue("without MoveFailed a failed file is left in place (the caller opts into quarantine)");
}
[Fact]
public async Task Consumer_PoisonFile_DoesNotBlockLaterFiles_AndIsQuarantined()
{
// The processor THROWS on the first file (as a route with no matching OnException does — the
// exception escapes the pipeline). A single poison file must NOT abort the poll batch and leave
// the files after it unprocessed; it must be quarantined via MoveFailed and the batch must go on.
CreateFile("001-poison.txt", "bad");
CreateFile("002-good.txt", "ok");
var failedDir = Path.Combine(_tempDir, "failed");
var processedNames = new System.Collections.Concurrent.ConcurrentBag();
var endpoint = CreateEndpoint(new() { ["moveFailed"] = failedDir, ["sortBy"] = "Name", ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x =>
{
var e = x.Arg();
var name = e.In.Headers[FileHeaders.FileName]?.ToString() ?? "";
processedNames.Add(name);
if (name.StartsWith("001")) throw new InvalidOperationException("poison");
});
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processedNames.Contains("002-good.txt"), 3000);
await consumer.Stop();
processedNames.Should().Contain("002-good.txt",
"a poison file that throws must not abort the batch — later files still get processed");
System.IO.File.Exists(Path.Combine(failedDir, "001-poison.txt"))
.Should().BeTrue("the file that threw is quarantined via MoveFailed");
System.IO.File.Exists(Path.Combine(_inputDir, "001-poison.txt"))
.Should().BeFalse("the poison file leaves the poll directory");
}
// ── Post-processing: Noop ───────────────────────────────────────
[Fact]
public async Task Consumer_Noop_KeepsFile()
{
CreateFile("keepme.txt", "content");
var filePath = Path.Combine(_inputDir, "keepme.txt");
var endpoint = CreateEndpoint(new() { ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
System.IO.File.Exists(filePath).Should().BeTrue();
}
// ── Idempotency ─────────────────────────────────────────────────
[Fact]
public async Task Consumer_Idempotent_SkipsDuplicates()
{
CreateFile("unique.txt", "data");
var endpoint = CreateEndpoint(new() { ["idempotent"] = "true", ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
// Wait for extra polls — file should not be processed again
await Task.Delay(500);
await consumer.Stop();
processed.Should().HaveCount(1);
}
// ── PreMove ─────────────────────────────────────────────────────
[Fact]
public async Task Consumer_PreMove_MovesBeforeProcessing()
{
CreateFile("premove.txt", "data");
var preMoveDir = Path.Combine(_tempDir, "processing");
var endpoint = CreateEndpoint(new() { ["preMove"] = preMoveDir, ["delete"] = "true", ["delay"] = "100" });
string? processedPath = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processedPath = x.Arg().In.Headers[FileHeaders.FileAbsolutePath]?.ToString());
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processedPath != null, 3000);
await consumer.Stop();
// File should have been moved to preMove dir before processing
processedPath.Should().Contain("processing");
}
// ── DoneFileName ────────────────────────────────────────────────
[Fact]
public async Task Consumer_DoneFileName_WaitsForDoneFile()
{
CreateFile("data.csv", "test");
var endpoint = CreateEndpoint(new()
{
["doneFileName"] = "${file:name}.done",
["noop"] = "true",
["delay"] = "100"
});
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
// Wait — file should NOT be processed (no .done file)
await Task.Delay(400);
processed.Should().BeEmpty();
// Create the done file
CreateFile("data.csv.done", "");
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
processed.Should().HaveCountGreaterThanOrEqualTo(1);
}
// ── Start/Stop lifecycle ────────────────────────────────────────
[Fact]
public async Task Consumer_StopIdempotent()
{
var endpoint = CreateEndpoint(new() { ["delay"] = "100" });
var processor = Substitute.For();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await consumer.Stop();
await consumer.Stop(); // Should not throw
}
[Fact]
public async Task Consumer_ProcessedCount_Increments()
{
CreateFile("file1.txt", "a");
CreateFile("file2.txt", "b");
var endpoint = CreateEndpoint(new() { ["delete"] = "true", ["delay"] = "100" });
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => consumer.ProcessedCount >= 2, 3000);
await consumer.Stop();
consumer.ProcessedCount.Should().BeGreaterThanOrEqualTo(2);
}
// ── GlobMatch tests ─────────────────────────────────────────────
[Theory]
[InlineData("order.csv", "*.csv", true)]
[InlineData("order.CSV", "*.csv", true)]
[InlineData("order.txt", "*.csv", false)]
[InlineData("report.json", "*.json", true)]
[InlineData("test.file", "test.*", true)]
[InlineData("test.file", "test.?ile", true)]
[InlineData("test.file", "t?st.file", true)]
[InlineData("data.csv", "*.csv,*.json", true)]
[InlineData("data.json", "*.csv,*.json", true)]
[InlineData("data.txt", "*.csv,*.json", false)]
public void GlobMatch_VariousPatterns(string input, string pattern, bool expected)
{
FileConsumer.GlobMatch(input, pattern).Should().Be(expected);
}
// ── MinAge ──────────────────────────────────────────────────────
[Fact]
public async Task Consumer_MinAge_SkipsNewFiles()
{
var endpoint = CreateEndpoint(new()
{
["minAge"] = "60000", // 60 seconds
["noop"] = "true",
["delay"] = "100"
});
var processor = Substitute.For();
CreateFile("newfile.txt", "data");
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(400);
await consumer.Stop();
// File is too new — should not be processed
await processor.DidNotReceive().Process(Arg.Any(), Arg.Any());
}
// ── Headers are populated correctly ─────────────────────────────
[Fact]
public async Task Consumer_PopulatesAllHeaders()
{
CreateFile("order.csv", "hello");
var endpoint = CreateEndpoint(new() { ["noop"] = "true", ["delay"] = "100" });
IExchange? captured = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => captured = x.Arg());
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => captured != null, 3000);
await consumer.Stop();
captured.Should().NotBeNull();
captured!.In.Headers.Should().ContainKey(FileHeaders.FileName);
captured.In.Headers.Should().ContainKey(FileHeaders.FileNameOnly);
captured.In.Headers.Should().ContainKey(FileHeaders.FileExtension);
captured.In.Headers.Should().ContainKey(FileHeaders.FileAbsolutePath);
captured.In.Headers.Should().ContainKey(FileHeaders.FileRelativePath);
captured.In.Headers.Should().ContainKey(FileHeaders.FileParent);
captured.In.Headers.Should().ContainKey(FileHeaders.FileLength);
captured.In.Headers.Should().ContainKey(FileHeaders.FileLastModified);
captured.In.Headers[FileHeaders.FileName].Should().Be("order.csv");
captured.In.Headers[FileHeaders.FileNameOnly].Should().Be("order");
captured.In.Headers[FileHeaders.FileExtension].Should().Be(".csv");
((long)captured.In.Headers[FileHeaders.FileLength]!).Should().Be(5);
}
// ── Excludes lock files ─────────────────────────────────────────
[Fact]
public async Task Consumer_ExcludesLockAndTempFiles()
{
CreateFile("data.csv", "data");
CreateFile("data.csv.redbLock", "lock");
CreateFile("data.csv.redbRename", "rename");
CreateFile(".redb_temp", "temp");
var endpoint = CreateEndpoint(new() { ["noop"] = "true", ["delay"] = "100" });
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await Task.Delay(300);
await consumer.Stop();
var names = processed.Select(e => e.In.Headers[FileHeaders.FileName].ToString()).Distinct().ToList();
names.Should().Contain("data.csv");
names.Should().NotContain("data.csv.redbLock");
names.Should().NotContain("data.csv.redbRename");
names.Should().NotContain(".redb_temp");
}
// ── StreamBody ──────────────────────────────────────────────────
[Fact]
public async Task Consumer_StreamBody_ReturnsStream()
{
CreateFile("report.csv", "stream-test-data");
var endpoint = CreateEndpoint(new()
{
["delete"] = "true", ["delay"] = "100", ["streamBody"] = "true"
});
bool? wasStream = null;
bool? canRead = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x =>
{
var body = x.Arg().In.Body;
wasStream = body is Stream;
if (body is Stream s) canRead = s.CanRead;
});
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => wasStream.HasValue, 3000);
await consumer.Stop();
wasStream.Should().BeTrue();
canRead.Should().BeTrue();
}
[Fact]
public async Task Consumer_StreamBody_StreamContainsCorrectData()
{
CreateFile("body.txt", "hello-stream");
var endpoint = CreateEndpoint(new()
{
["noop"] = "true", ["delay"] = "100", ["streamBody"] = "true"
});
string? readContent = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x =>
{
var s = (Stream)x.Arg().In.Body!;
using var reader = new StreamReader(s, leaveOpen: true);
readContent = reader.ReadToEnd();
});
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => readContent != null, 3000);
await consumer.Stop();
readContent.Should().Be("hello-stream");
}
[Fact]
public async Task Consumer_StreamBody_HeadersStillSet()
{
CreateFile("meta.json", "{}");
var endpoint = CreateEndpoint(new()
{
["noop"] = "true", ["delay"] = "100", ["streamBody"] = "true"
});
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
var ex = processed[0];
ex.In.Headers[FileHeaders.FileName].Should().Be("meta.json");
ex.In.Headers[FileHeaders.FileNameOnly].Should().Be("meta");
ex.In.Headers[FileHeaders.FileExtension].Should().Be(".json");
ex.In.Headers[FileHeaders.FileLength].Should().BeOfType();
ex.In.ContentType.Should().Be("application/json");
}
[Fact]
public async Task Consumer_StreamBody_DeleteAfterRead()
{
var filePath = Path.Combine(_inputDir, "todelete.txt");
CreateFile("todelete.txt", "delete-me");
var endpoint = CreateEndpoint(new()
{
["delete"] = "true", ["delay"] = "100", ["streamBody"] = "true"
});
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask);
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => !System.IO.File.Exists(filePath), 3000);
await consumer.Stop();
System.IO.File.Exists(filePath).Should().BeFalse();
}
[Fact]
public async Task Consumer_StreamBody_False_ReturnsBytes()
{
CreateFile("compat.csv", "back-compat");
var endpoint = CreateEndpoint(new()
{
["delete"] = "true", ["delay"] = "100"
});
var processed = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => processed.Add(x.Arg()));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => processed.Count >= 1, 3000);
await consumer.Stop();
processed[0].In.Body.Should().BeOfType();
}
// ── Helpers ──────────────────────────────────────────────────────
private static async Task WaitForCondition(Func condition, int timeoutMs)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (!condition() && sw.ElapsedMilliseconds < timeoutMs)
{
await Task.Delay(50);
}
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { }
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileEndpointOptionsTests.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.File/FileEndpointOptionsTests.cs
----
using redb.Route.File;
using redb.Route.GenericFile;
namespace redb.Route.Tests.File;
///
/// Tests for FileEndpointOptions validation.
///
public class FileEndpointOptionsTests
{
[Fact]
public void Defaults_AreCorrect()
{
var options = new FileEndpointOptions();
options.Delay.Should().Be(500);
options.InitialDelay.Should().Be(0);
options.Include.Should().BeEmpty();
options.Exclude.Should().BeEmpty();
options.Recursive.Should().BeFalse();
options.SortBy.Should().Be(GenericFileSortBy.None);
options.MaxMessagesPerPoll.Should().Be(0);
options.Noop.Should().BeFalse();
options.Delete.Should().BeFalse();
options.MoveTo.Should().BeEmpty();
options.Idempotent.Should().BeFalse();
options.ReadLock.Should().Be(ReadLockStrategy.None);
options.ReadLockTimeout.Should().Be(10000);
options.ReadLockCheckInterval.Should().Be(1000);
options.ReadLockMinAge.Should().Be(1000);
options.ReadLockMarkerFileExtension.Should().Be(".redbLock");
options.DoneFileName.Should().BeEmpty();
options.FileExist.Should().Be(GenericFileExistStrategy.Override);
options.TempPrefix.Should().BeEmpty();
options.Charset.Should().Be("utf-8");
options.AutoCreate.Should().BeTrue();
options.AllowNullBody.Should().BeFalse();
options.AppendChars.Should().BeEmpty();
options.EagerDeleteTargetFile.Should().BeTrue();
}
[Fact]
public void Validate_ValidOptions_NoException()
{
var options = new FileEndpointOptions();
options.Validate(); // Should not throw
}
[Fact]
public void Validate_NegativeDelay_Throws()
{
var options = new FileEndpointOptions { Delay = -1 };
var act = () => options.Validate();
act.Should().Throw().Which.ParamName.Should().Be("Delay");
}
[Fact]
public void Validate_NoopAndDelete_Throws()
{
var options = new FileEndpointOptions { Noop = true, Delete = true };
var act = () => options.Validate();
act.Should().Throw()
.WithMessage("*Noop*Delete*");
}
[Fact]
public void Validate_NoopAndMoveTo_Throws()
{
var options = new FileEndpointOptions { Noop = true, MoveTo = "C:/archive" };
var act = () => options.Validate();
act.Should().Throw()
.WithMessage("*Noop*MoveTo*");
}
[Fact]
public void Validate_DeleteAndMoveTo_Throws()
{
var options = new FileEndpointOptions { Delete = true, MoveTo = "C:/archive" };
var act = () => options.Validate();
act.Should().Throw()
.WithMessage("*Delete*MoveTo*");
}
[Fact]
public void Validate_NegativeReadLockCheckInterval_Throws()
{
var options = new FileEndpointOptions { ReadLockCheckInterval = -1 };
var act = () => options.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_ZeroReadLockCheckInterval_Throws()
{
var options = new FileEndpointOptions { ReadLockCheckInterval = 0 };
var act = () => options.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_NegativeReadLockMinAge_Throws()
{
var options = new FileEndpointOptions { ReadLockMinAge = -1 };
var act = () => options.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_NegativeReadLockTimeout_Throws()
{
var options = new FileEndpointOptions { ReadLockTimeout = -1 };
var act = () => options.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_NegativeMaxMessagesPerPoll_Throws()
{
var options = new FileEndpointOptions { MaxMessagesPerPoll = -1 };
var act = () => options.Validate();
act.Should().Throw();
}
[Fact]
public void Validate_NoopOnly_Valid()
{
var options = new FileEndpointOptions { Noop = true };
options.Validate(); // No exception
}
[Fact]
public void Validate_DeleteOnly_Valid()
{
var options = new FileEndpointOptions { Delete = true };
options.Validate(); // No exception
}
[Fact]
public void Validate_MoveToOnly_Valid()
{
var options = new FileEndpointOptions { MoveTo = "C:/archive" };
options.Validate(); // No exception
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileIntegrationTests.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.File/FileIntegrationTests.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// End-to-end integration tests: FileConsumer → IProcessor → FileProducer.
/// Simulates a file-copy route using real temp directories on disk.
///
public class FileIntegrationTests : IAsyncLifetime
{
private readonly string _tempDir;
private readonly string _inputDir;
private readonly string _outputDir;
private FileConsumer? _consumer;
private FileProducer? _producer;
// Captured exchanges
private readonly List _capturedExchanges = [];
public FileIntegrationTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-file-integ-" + Guid.NewGuid().ToString("N")[..8]);
_inputDir = Path.Combine(_tempDir, "input");
_outputDir = Path.Combine(_tempDir, "output");
Directory.CreateDirectory(_inputDir);
Directory.CreateDirectory(_outputDir);
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
if (_consumer is not null) await _consumer.Stop();
try { Directory.Delete(_tempDir, recursive: true); } catch { }
}
private (FileConsumer consumer, FileProducer producer) CreatePair(
Dictionary? consumerParams = null,
Dictionary? producerParams = null)
{
var component = new FileComponent();
// Consumer endpoint
var cPath = "/" + _inputDir.Replace("\\", "/");
var cParms = consumerParams ?? new Dictionary();
if (!cParms.ContainsKey("delay")) cParms["delay"] = "100";
if (!cParms.ContainsKey("delete")) cParms["delete"] = "true";
var cUri = new EndpointUri("file", cPath, $"file://{cPath}", cParms);
var cEndpoint = (FileEndpoint)component.CreateEndpoint(cUri);
// Producer endpoint
var pPath = "/" + _outputDir.Replace("\\", "/");
var pParms = producerParams ?? new Dictionary();
var pUri = new EndpointUri("file", pPath, $"file://{pPath}", pParms);
var pEndpoint = (FileEndpoint)component.CreateEndpoint(pUri);
_producer = (FileProducer)pEndpoint.CreateProducer();
// Processor bridges consumer→producer
var producer = _producer;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async ci =>
{
var ex = ci.Arg();
lock (_capturedExchanges) _capturedExchanges.Add(ex);
await producer.Process(ex);
});
_consumer = (FileConsumer)cEndpoint.CreateConsumer(processor);
return (_consumer, _producer);
}
private void WriteInputFile(string name, string content = "test data")
{
System.IO.File.WriteAllText(Path.Combine(_inputDir, name), content);
}
private string ReadOutputFile(string name)
{
return System.IO.File.ReadAllText(Path.Combine(_outputDir, name));
}
private bool OutputFileExists(string name)
{
return System.IO.File.Exists(Path.Combine(_outputDir, name));
}
// ── End-to-end copy ─────────────────────────────────────────────
[Fact]
public async Task EndToEnd_SingleFile_CopiedToOutput()
{
WriteInputFile("order.csv", "col1,col2\nA,B");
var (consumer, _) = CreatePair();
await consumer.Start();
await WaitForCondition(() => OutputFileExists("order.csv"), 5000);
await consumer.Stop();
ReadOutputFile("order.csv").Should().Be("col1,col2\nA,B");
// Source removed (delete=true)
System.IO.File.Exists(Path.Combine(_inputDir, "order.csv")).Should().BeFalse();
}
[Fact]
public async Task EndToEnd_MultipleFiles_AllCopied()
{
for (var i = 0; i < 5; i++)
WriteInputFile($"file{i}.txt", $"content-{i}");
var (consumer, _) = CreatePair();
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 5;
}, 5000);
await consumer.Stop();
for (var i = 0; i < 5; i++)
{
OutputFileExists($"file{i}.txt").Should().BeTrue($"file{i}.txt should exist in output");
ReadOutputFile($"file{i}.txt").Should().Be($"content-{i}");
}
}
[Fact]
public async Task EndToEnd_BinaryFile_ContentPreserved()
{
var binaryData = new byte[] { 0x00, 0x01, 0xFF, 0xFE, 0x80, 0x7F };
System.IO.File.WriteAllBytes(Path.Combine(_inputDir, "data.bin"), binaryData);
var (consumer, _) = CreatePair();
await consumer.Start();
await WaitForCondition(() => OutputFileExists("data.bin"), 5000);
await consumer.Stop();
var output = System.IO.File.ReadAllBytes(Path.Combine(_outputDir, "data.bin"));
output.Should().BeEquivalentTo(binaryData);
}
// ── Include filter ──────────────────────────────────────────────
[Fact]
public async Task EndToEnd_IncludeFilter_OnlyMatchingFilesCopied()
{
WriteInputFile("report.csv", "csv data");
WriteInputFile("notes.txt", "text data");
WriteInputFile("summary.csv", "more csv");
var (consumer, _) = CreatePair(new Dictionary { ["include"] = "*.csv" });
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 2;
}, 5000);
await consumer.Stop();
OutputFileExists("report.csv").Should().BeTrue();
OutputFileExists("summary.csv").Should().BeTrue();
OutputFileExists("notes.txt").Should().BeFalse("txt file should not be copied");
}
// ── Noop mode ───────────────────────────────────────────────────
[Fact]
public async Task EndToEnd_Noop_SourceFileNotDeleted()
{
WriteInputFile("keep.txt", "keep me");
var (consumer, _) = CreatePair(new Dictionary
{
["noop"] = "true",
["delete"] = "false",
["idempotent"] = "true" // prevent re-processing
});
await consumer.Start();
await WaitForCondition(() => OutputFileExists("keep.txt"), 5000);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(_inputDir, "keep.txt")).Should().BeTrue("noop should keep source");
ReadOutputFile("keep.txt").Should().Be("keep me");
}
// ── MoveTo ──────────────────────────────────────────────────────
[Fact]
public async Task EndToEnd_MoveTo_SourceMovedToArchive()
{
var archiveDir = Path.Combine(_tempDir, "archive");
WriteInputFile("invoice.pdf", "pdf bytes");
var (consumer, _) = CreatePair(new Dictionary
{
["delete"] = "false",
["moveTo"] = archiveDir
});
await consumer.Start();
await WaitForCondition(() => OutputFileExists("invoice.pdf"), 5000);
await consumer.Stop();
// Source moved to archive
System.IO.File.Exists(Path.Combine(_inputDir, "invoice.pdf")).Should().BeFalse();
System.IO.File.Exists(Path.Combine(archiveDir, "invoice.pdf")).Should().BeTrue();
// Output also written
ReadOutputFile("invoice.pdf").Should().Be("pdf bytes");
}
// ── Headers propagation through the route ───────────────────────
[Fact]
public async Task EndToEnd_ConsumerHeaders_PropagatedThroughRoute()
{
WriteInputFile("report.csv", "col1\nval1");
var (consumer, _) = CreatePair();
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 1;
}, 5000);
await consumer.Stop();
IExchange captured;
lock (_capturedExchanges) captured = _capturedExchanges[0];
captured.In.Headers.Should().ContainKey(FileHeaders.FileName);
captured.In.Headers.Should().ContainKey(FileHeaders.FileNameOnly);
captured.In.Headers.Should().ContainKey(FileHeaders.FileExtension);
captured.In.Headers.Should().ContainKey(FileHeaders.FileAbsolutePath);
captured.In.Headers.Should().ContainKey(FileHeaders.FileLength);
captured.In.Headers.Should().ContainKey(FileHeaders.FileLastModified);
captured.In.Headers[FileHeaders.FileName].Should().Be("report.csv");
captured.In.Headers[FileHeaders.FileNameOnly].Should().Be("report");
captured.In.Headers[FileHeaders.FileExtension].Should().Be(".csv");
((long)captured.In.Headers[FileHeaders.FileLength]!).Should().BeGreaterThan(0);
}
// ── Producer FileExist: Append ──────────────────────────────────
[Fact]
public async Task EndToEnd_ProducerAppend_AccumulatesContent()
{
// Pre-create an existing output file
System.IO.File.WriteAllText(Path.Combine(_outputDir, "log.txt"), "line1\n");
WriteInputFile("log.txt", "line2\n");
var (consumer, _) = CreatePair(
producerParams: new Dictionary { ["fileExist"] = "Append" });
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 1;
}, 5000);
await consumer.Stop();
var content = ReadOutputFile("log.txt");
content.Should().Contain("line1");
content.Should().Contain("line2");
}
// ── Producer with TempPrefix (atomic writes) ────────────────────
[Fact]
public async Task EndToEnd_TempPrefix_AtomicWrite()
{
WriteInputFile("atomic.dat", "important data");
var (consumer, _) = CreatePair(
producerParams: new Dictionary { ["tempPrefix"] = ".tmp_" });
await consumer.Start();
await WaitForCondition(() => OutputFileExists("atomic.dat"), 5000);
await consumer.Stop();
ReadOutputFile("atomic.dat").Should().Be("important data");
// No temp files should remain
Directory.GetFiles(_outputDir, ".tmp_*").Should().BeEmpty();
}
// ── SortBy with multiple files ──────────────────────────────────
[Fact]
public async Task EndToEnd_SortByName_ProcessedInAlphaOrder()
{
WriteInputFile("c_third.txt", "C");
WriteInputFile("a_first.txt", "A");
WriteInputFile("b_second.txt", "B");
var (consumer, _) = CreatePair(new Dictionary { ["sortBy"] = "name" });
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 3;
}, 5000);
await consumer.Stop();
List snapshot;
lock (_capturedExchanges) snapshot = [.. _capturedExchanges];
snapshot.Should().HaveCountGreaterThanOrEqualTo(3);
var names = snapshot.Select(e => (string)e.In.Headers[FileHeaders.FileName]!).ToList();
names.Should().ContainInOrder("a_first.txt", "b_second.txt", "c_third.txt");
}
// ── Large file ──────────────────────────────────────────────────
[Fact]
public async Task EndToEnd_LargeFile_PreservedExactly()
{
var largeContent = new string('X', 1_000_000); // 1MB text
WriteInputFile("large.bin", largeContent);
var (consumer, _) = CreatePair();
await consumer.Start();
await WaitForCondition(() => OutputFileExists("large.bin"), 10000);
await consumer.Stop();
ReadOutputFile("large.bin").Should().Be(largeContent);
}
// ── Files arriving after consumer started ───────────────────────
[Fact]
public async Task EndToEnd_FileArrivesWhileRunning_StillProcessed()
{
var (consumer, _) = CreatePair();
await consumer.Start();
// Wait one poll cycle
await Task.Delay(200);
// File drops in while consumer is running
WriteInputFile("late.txt", "arrived late");
await WaitForCondition(() => OutputFileExists("late.txt"), 5000);
await consumer.Stop();
ReadOutputFile("late.txt").Should().Be("arrived late");
}
// ── ProcessedCount / WriteCount counters ────────────────────────
[Fact]
public async Task EndToEnd_Counters_IncrementCorrectly()
{
for (var i = 0; i < 3; i++)
WriteInputFile($"count{i}.txt", $"data{i}");
var (consumer, producer) = CreatePair();
await consumer.Start();
await WaitForCondition(() => consumer.ProcessedCount >= 3, 5000);
await consumer.Stop();
consumer.ProcessedCount.Should().BeGreaterThanOrEqualTo(3);
}
// ── StreamBody end-to-end ───────────────────────────────────────
[Fact]
public async Task EndToEnd_StreamBody_SingleFile_CopiedToOutput()
{
WriteInputFile("stream-order.csv", "col1,col2\nX,Y");
var (consumer, _) = CreatePair(
consumerParams: new() { ["streamBody"] = "true" });
await consumer.Start();
await WaitForCondition(() => OutputFileExists("stream-order.csv"), 5000);
await consumer.Stop();
ReadOutputFile("stream-order.csv").Should().Be("col1,col2\nX,Y");
System.IO.File.Exists(Path.Combine(_inputDir, "stream-order.csv")).Should().BeFalse();
}
[Fact]
public async Task EndToEnd_StreamBody_BinaryPreserved()
{
var binaryData = new byte[] { 0x00, 0x01, 0xFF, 0xFE, 0x80, 0x7F, 0xAB, 0xCD };
System.IO.File.WriteAllBytes(Path.Combine(_inputDir, "binary.dat"), binaryData);
var (consumer, _) = CreatePair(
consumerParams: new() { ["streamBody"] = "true" });
await consumer.Start();
await WaitForCondition(() => OutputFileExists("binary.dat"), 5000);
await consumer.Stop();
System.IO.File.ReadAllBytes(Path.Combine(_outputDir, "binary.dat"))
.Should().BeEquivalentTo(binaryData);
}
[Fact]
public async Task EndToEnd_StreamBody_LargeFile_NoOOM()
{
// 2MB file — would OOM if we accidentally doubled buffers
var largeContent = new string('Z', 2_000_000);
WriteInputFile("large-stream.bin", largeContent);
var (consumer, _) = CreatePair(
consumerParams: new() { ["streamBody"] = "true" });
await consumer.Start();
await WaitForCondition(() => OutputFileExists("large-stream.bin"), 10000);
await consumer.Stop();
ReadOutputFile("large-stream.bin").Should().Be(largeContent);
}
[Fact]
public async Task EndToEnd_StreamBody_DeleteAfterRead_FileRemoved()
{
WriteInputFile("delete-me.txt", "bye");
var filePath = Path.Combine(_inputDir, "delete-me.txt");
var (consumer, _) = CreatePair(
consumerParams: new() { ["streamBody"] = "true", ["delete"] = "true" });
await consumer.Start();
await WaitForCondition(() => !System.IO.File.Exists(filePath), 5000);
await consumer.Stop();
System.IO.File.Exists(filePath).Should().BeFalse();
OutputFileExists("delete-me.txt").Should().BeTrue();
ReadOutputFile("delete-me.txt").Should().Be("bye");
}
[Fact]
public async Task EndToEnd_StreamBody_MoveTo_SourceMovedToArchive()
{
var archiveDir = Path.Combine(_tempDir, "archive-stream");
WriteInputFile("move-stream.txt", "move me");
var (consumer, _) = CreatePair(
consumerParams: new()
{
["streamBody"] = "true", ["delete"] = "false", ["moveTo"] = archiveDir
});
await consumer.Start();
await WaitForCondition(() => OutputFileExists("move-stream.txt"), 5000);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(_inputDir, "move-stream.txt")).Should().BeFalse();
System.IO.File.Exists(Path.Combine(archiveDir, "move-stream.txt")).Should().BeTrue();
ReadOutputFile("move-stream.txt").Should().Be("move me");
}
[Fact]
public async Task EndToEnd_StreamBody_MultipleFiles_AllCopied()
{
for (var i = 0; i < 5; i++)
WriteInputFile($"stream-f{i}.txt", $"stream-content-{i}");
var (consumer, _) = CreatePair(
consumerParams: new() { ["streamBody"] = "true" });
await consumer.Start();
await WaitForCondition(() =>
{
lock (_capturedExchanges) return _capturedExchanges.Count >= 5;
}, 5000);
await consumer.Stop();
for (var i = 0; i < 5; i++)
{
OutputFileExists($"stream-f{i}.txt").Should().BeTrue();
ReadOutputFile($"stream-f{i}.txt").Should().Be($"stream-content-{i}");
}
}
[Fact]
public async Task EndToEnd_StreamBody_BodyIsStreamDuringProcessing()
{
WriteInputFile("check-type.txt", "type-check");
Type? bodyType = null;
var component = new FileComponent();
var cPath = "/" + _inputDir.Replace("\\", "/");
var cUri = new EndpointUri("file", cPath, $"file://{cPath}",
new Dictionary { ["streamBody"] = "true", ["delay"] = "100", ["noop"] = "true", ["idempotent"] = "true" });
var cEndpoint = (FileEndpoint)component.CreateEndpoint(cUri);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => bodyType = x.Arg().In.Body?.GetType());
_consumer = (FileConsumer)cEndpoint.CreateConsumer(processor);
await _consumer.Start();
await WaitForCondition(() => bodyType != null, 3000);
await _consumer.Stop();
bodyType.Should().BeAssignableTo();
}
// ── Helpers ──────────────────────────────────────────────────────
private static async Task WaitForCondition(Func condition, int timeoutMs)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (!condition() && sw.ElapsedMilliseconds < timeoutMs)
{
await Task.Delay(50);
}
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileKeysInOptionsFileTests.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.File/FileKeysInOptionsFileTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// The file keys in the File consumer's options on a real disk (findings register row 34 point 5): moveTo and
/// moveFailed resolve every key, and a key gives the same value in the option as in a template over the
/// redbFile.* headers of the same file.
///
public sealed class FileKeysInOptionsFileTests : IDisposable
{
private readonly string _tempDir = Path.Combine(Path.GetTempPath(), "redb-route-filekeys-" + Guid.NewGuid().ToString("N")[..8]);
private readonly string _inputDir;
public FileKeysInOptionsFileTests()
{
_inputDir = Path.Combine(_tempDir, "input");
Directory.CreateDirectory(_inputDir);
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch (IOException) { }
}
private FileEndpoint Endpoint(Dictionary parameters)
{
var path = "/" + _inputDir.Replace("\\", "/");
parameters["delay"] = "100";
return (FileEndpoint)new FileComponent().CreateEndpoint(new EndpointUri("file", path, $"file://{path}", parameters));
}
private static async Task Until(Func condition)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (!condition() && sw.ElapsedMilliseconds < 5000)
await Task.Delay(50);
}
[Fact]
public async Task MoveTo_ResolvesTheKeys_AsTheTemplateDoesOverTheHeaders()
{
System.IO.File.WriteAllText(Path.Combine(_inputDir, "order.CSV"), "1234567");
string? fromTemplate = null;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask)
.AndDoes(call => fromTemplate = ExpressionResolver.ProcessTemplate("done-${file:ext}-${file:size}", call.Arg()));
var consumer = (FileConsumer)Endpoint(new() { ["moveTo"] = "done-${file:ext}-${file:size}" }).CreateConsumer(processor);
await consumer.Start();
var target = Path.Combine(_inputDir, "done-csv-7", "order.CSV");
await Until(() => System.IO.File.Exists(target));
await consumer.Stop();
System.IO.File.Exists(target).Should().BeTrue();
fromTemplate.Should().Be("done-csv-7", "the option and the template read the same file");
}
[Fact]
public async Task MoveFailed_ResolvesTheKeys()
{
System.IO.File.WriteAllText(Path.Combine(_inputDir, "bad.xml"), "x");
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask)
.AndDoes(call => call.Arg().Exception = new FormatException("bad"));
var consumer = (FileConsumer)Endpoint(new() { ["moveFailed"] = "failed-${file:ext}-${file:length}" }).CreateConsumer(processor);
await consumer.Start();
var target = Path.Combine(_inputDir, "failed-xml-1", "bad.xml");
await Until(() => System.IO.File.Exists(target));
await consumer.Stop();
System.IO.File.Exists(target).Should().BeTrue();
}
[Fact]
public void MoveFailed_WithAnUnknownKey_FailsWhenTheEndpointIsCreated()
{
var act = () => Endpoint(new() { ["moveFailed"] = "failed/${file:nosuch}" });
act.Should().Throw().WithMessage("moveFailed='failed/${file:nosuch}': 'nosuch' is not a file key*");
}
// Row 46: tempFileName of the producer reads the file keys of the target file, the name being written.
private sealed class TempProbe(FileEndpoint endpoint) : FileProducer(endpoint, endpoint.EndpointOptions)
{
public string Temp(string targetPath) => ResolveTempPath(targetPath);
}
private TempProbe Producer(string tempFileName) => new(Endpoint(new() { ["tempFileName"] = tempFileName }));
[Fact]
public void TempFileName_WithoutKeys_IsThePathAsWritten()
{
var target = Path.Combine(_inputDir, "order.xml");
Producer(".writing.tmp").Temp(target).Should().Be(Path.Combine(_inputDir, ".writing.tmp"));
}
[Theory]
[InlineData("${file:name}.part", "order.xml.part")]
[InlineData("${file:name.noext}.tmp", "order.tmp")]
[InlineData("tmp-${file:ext}-${file:onlyname}", "tmp-xml-order.xml")]
[InlineData("${FILE:NAME.NOEXT}.tmp", "order.tmp")]
public void TempFileName_ResolvesTheKeysOfTheTargetFile(string tempFileName, string expected)
{
var target = Path.Combine(_inputDir, "order.xml");
Producer(tempFileName).Temp(target).Should().Be(Path.Combine(_inputDir, expected));
}
[Fact]
public async Task TempFileName_WithKeys_WritesThroughTheTempFileAndRenames()
{
var producer = Endpoint(new() { ["tempFileName"] = "${file:name.noext}.part" }).CreateProducer();
var message = new Message { Body = System.Text.Encoding.UTF8.GetBytes("data") };
message.Headers[FileHeaders.FileName] = "final.txt";
await producer.Process(new Exchange(message) { Pattern = ExchangePattern.InOnly });
System.IO.File.ReadAllText(Path.Combine(_inputDir, "final.txt")).Should().Be("data");
System.IO.File.Exists(Path.Combine(_inputDir, "final.part")).Should().BeFalse();
}
[Fact]
public void TempFileName_WithAnUnknownKey_FailsWhenTheEndpointIsCreated()
{
var act = () => Endpoint(new() { ["tempFileName"] = "${file:nosuch}.tmp" });
act.Should().Throw().WithMessage("tempFileName='${file:nosuch}.tmp': 'nosuch' is not a file key*");
}
}
Path: redb-route/tests/redb.Route.Tests.File/FilePathFilterTests.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.File/FilePathFilterTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
using redb.Route.GenericFile;
namespace redb.Route.Tests.File;
///
/// The path filters over a real directory tree: antInclude /antExclude on the path
/// relative to the polled directory, filterDirectory deciding before a directory is walked
/// into, and a registry filter bean. The local listing walks the tree itself for this — the
/// framework's all-directories enumeration cannot be told to leave a directory alone.
///
public class FilePathFilterTests : IDisposable
{
private readonly string _root;
public FilePathFilterTests()
{
_root = Path.Combine(Path.GetTempPath(), "redb-route-pathfilter-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_root);
}
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch (IOException) { }
GC.SuppressFinalize(this);
}
private void Write(string relativePath, string content = "x")
{
var full = Path.Combine(_root, relativePath.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(full)!);
System.IO.File.WriteAllText(full, content);
}
private FileEndpoint Endpoint(Dictionary parameters)
{
var component = new FileComponent();
var path = "/" + _root.Replace("\\", "/");
return (FileEndpoint)component.CreateEndpoint(new EndpointUri("file", path, $"file://{path}", parameters));
}
private static async Task> Poll(FileEndpoint endpoint)
{
var seen = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(x => seen.Add(x.Arg().In.Headers[FileHeaders.FileRelativePath]!.ToString()!
.Replace('\\', '/')));
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
var deadline = DateTime.UtcNow.AddSeconds(3);
while (DateTime.UtcNow < deadline && seen.Count == 0)
await Task.Delay(50);
await Task.Delay(200); // let a second file of the same poll arrive
await consumer.Stop();
return seen.OrderBy(s => s, StringComparer.Ordinal).ToList();
}
private void PartnerTree()
{
Write("TYPE_A/outbox/a.csv");
Write("TYPE_B/outbox/b.csv");
Write("TYPE_C/outbox/c.csv");
}
[Fact]
public async Task AntInclude_takes_two_directories_out_of_three()
{
PartnerTree();
var polled = await Poll(Endpoint(new()
{
["recursive"] = "true",
["noop"] = "true",
["delay"] = "5000",
["antInclude"] = "TYPE_A/outbox/*.csv,TYPE_B/outbox/*.csv",
}));
polled.Should().Equal("TYPE_A/outbox/a.csv", "TYPE_B/outbox/b.csv");
}
[Fact]
public async Task FilterDirectory_keeps_the_walk_out_of_a_directory()
{
PartnerTree();
var polled = await Poll(Endpoint(new()
{
["recursive"] = "true",
["noop"] = "true",
["delay"] = "5000",
["filterDirectory"] = "header.redbFile.Name != 'TYPE_C'",
}));
polled.Should().Equal("TYPE_A/outbox/a.csv", "TYPE_B/outbox/b.csv");
}
[Fact]
public async Task A_filter_bean_named_in_the_uri_decides_for_files_and_for_directories()
{
PartnerTree();
// The whole path the option takes in production: a name in the registry, resolved by the
// component when the endpoint is created.
await using var context = new RouteContext();
context.AddToRegistry("onlyTypeA", new OnlyTypeA());
context.AddComponent(new FileComponent());
var path = "/" + _root.Replace("\\", "/");
var endpoint = (FileEndpoint)context.GetEndpoint(
$"file://{path}?recursive=true&noop=true&delay=5000&filter=%23onlyTypeA");
var polled = await Poll(endpoint);
polled.Should().Equal("TYPE_A/outbox/a.csv");
}
[Fact]
public void A_filter_name_the_registry_does_not_hold_fails_when_the_endpoint_is_created()
{
using var context = new RouteContext();
context.AddComponent(new FileComponent());
var path = "/" + _root.Replace("\\", "/");
var act = () => context.GetEndpoint($"file://{path}?filter=%23missing");
act.Should().Throw().WithMessage("*missing*");
}
[Fact]
public async Task MaxDepth_still_stops_at_its_level()
{
Write("top.csv");
Write("one/mid.csv");
Write("one/two/deep.csv");
var polled = await Poll(Endpoint(new()
{
["recursive"] = "true",
["noop"] = "true",
["delay"] = "5000",
["maxDepth"] = "1",
}));
// The rewritten walk stops descending instead of enumerating everything and discarding it;
// what a poll returns must not have changed.
polled.Should().Equal("one/mid.csv", "top.csv");
}
[Fact]
public async Task What_a_path_filter_rejected_is_never_deleted()
{
PartnerTree();
await Poll(Endpoint(new()
{
["recursive"] = "true",
["delete"] = "true",
["delay"] = "5000",
["antInclude"] = "TYPE_A/**",
}));
System.IO.File.Exists(Path.Combine(_root, "TYPE_A", "outbox", "a.csv")).Should().BeFalse();
System.IO.File.Exists(Path.Combine(_root, "TYPE_B", "outbox", "b.csv")).Should().BeTrue();
System.IO.File.Exists(Path.Combine(_root, "TYPE_C", "outbox", "c.csv")).Should().BeTrue();
}
private sealed class OnlyTypeA : IGenericFileFilter
{
public bool Accept(GenericFileInfo file) => file.FullPath.Replace('\\', '/').Contains("/TYPE_A/", StringComparison.Ordinal);
public bool AcceptDirectory(string fullPath, string relativePath)
{
var rel = relativePath.Replace('\\', '/');
return rel.StartsWith("TYPE_A", StringComparison.Ordinal) || rel.Contains("outbox", StringComparison.Ordinal);
}
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileProducerPathSafetyTests.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.File/FileProducerPathSafetyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// The producer's target file name normally arrives from the incoming message, so it is
/// untrusted input. These tests pin the jail: the producer must not write outside its
/// endpoint directory unless that was asked for explicitly.
///
public class FileProducerPathSafetyTests : IDisposable
{
private readonly string _tempDir;
private readonly string _outputDir;
public FileProducerPathSafetyTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-jail-" + Guid.NewGuid().ToString("N")[..8]);
_outputDir = Path.Combine(_tempDir, "out");
Directory.CreateDirectory(_outputDir);
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { /* best effort */ }
GC.SuppressFinalize(this);
}
private FileEndpoint CreateEndpoint(Dictionary? parameters = null)
{
var component = new FileComponent();
var path = "/" + _outputDir.Replace("\\", "/");
var uri = new EndpointUri("file", path, $"file://{path}", parameters ?? new Dictionary());
return (FileEndpoint)component.CreateEndpoint(uri);
}
private static IExchange ExchangeWithFileName(FileEndpoint endpoint, string fileName, string body = "PAYLOAD")
{
var message = new Message { Body = body };
message.Headers[FileHeaders.FileName] = fileName;
return Exchange.Create(message, endpoint.ScopeFactory);
}
[Fact]
public async Task RelativeEscape_FromHeader_IsRejected()
{
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
var act = () => producer.Process(ExchangeWithFileName(endpoint, "../escaped.txt"));
await act.Should().ThrowAsync();
System.IO.File.Exists(Path.Combine(_tempDir, "escaped.txt")).Should().BeFalse();
}
[Fact]
public async Task AbsolutePath_FromHeader_IsRejected()
{
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
var absoluteTarget = Path.Combine(_tempDir, "absolute-escape.txt");
var act = () => producer.Process(ExchangeWithFileName(endpoint, absoluteTarget));
await act.Should().ThrowAsync();
System.IO.File.Exists(absoluteTarget).Should().BeFalse();
}
[Fact]
public async Task SiblingDirectoryWithSharedPrefix_IsRejected()
{
// "out2" starts with "out": a plain prefix comparison would let this through.
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
var act = () => producer.Process(ExchangeWithFileName(endpoint, "../out2/escaped.txt"));
await act.Should().ThrowAsync();
System.IO.File.Exists(Path.Combine(_tempDir, "out2", "escaped.txt")).Should().BeFalse();
}
[Fact]
public async Task RelativeEscape_FromFileNameOption_IsRejected()
{
var endpoint = CreateEndpoint(new() { ["fileName"] = "../escaped-by-option.txt" });
var producer = endpoint.CreateProducer();
var message = new Message { Body = "PAYLOAD" };
var act = () => producer.Process(Exchange.Create(message, endpoint.ScopeFactory));
await act.Should().ThrowAsync();
System.IO.File.Exists(Path.Combine(_tempDir, "escaped-by-option.txt")).Should().BeFalse();
}
[Fact]
public async Task SubdirectoryInsideTheEndpoint_IsAllowed()
{
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
await producer.Process(ExchangeWithFileName(endpoint, "sub/ok.txt"));
System.IO.File.Exists(Path.Combine(_outputDir, "sub", "ok.txt")).Should().BeTrue();
}
[Fact]
public async Task PlainFileName_IsAllowed()
{
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
await producer.Process(ExchangeWithFileName(endpoint, "report.csv"));
System.IO.File.ReadAllText(Path.Combine(_outputDir, "report.csv")).Should().Be("PAYLOAD");
}
[Fact]
public async Task JailCanBeTurnedOffExplicitly()
{
var endpoint = CreateEndpoint(new() { ["jailStartingDirectory"] = "false" });
var producer = endpoint.CreateProducer();
await producer.Process(ExchangeWithFileName(endpoint, "../deliberate.txt"));
System.IO.File.Exists(Path.Combine(_tempDir, "deliberate.txt")).Should()
.BeTrue("writing outside must stay possible when it is asked for explicitly");
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileProducerTests.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.File/FileProducerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// Tests for FileProducer — file writing, temp files, FileExist strategies.
///
public class FileProducerTests : IDisposable
{
private readonly string _tempDir;
private readonly string _outputDir;
public FileProducerTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-producer-tests-" + Guid.NewGuid().ToString("N")[..8]);
_outputDir = Path.Combine(_tempDir, "output");
Directory.CreateDirectory(_outputDir);
}
private FileEndpoint CreateEndpoint(Dictionary? parameters = null)
{
var component = new FileComponent();
var path = "/" + _outputDir.Replace("\\", "/");
var parms = parameters ?? new Dictionary();
var uri = new EndpointUri("file", path, $"file://{path}", parms);
return (FileEndpoint)component.CreateEndpoint(uri);
}
private Exchange CreateExchange(string? body = "test content", string? fileName = null)
{
var message = new Message { Body = body != null ? System.Text.Encoding.UTF8.GetBytes(body) : null };
if (fileName != null)
message.Headers[FileHeaders.FileName] = fileName;
return new Exchange(message) { Pattern = ExchangePattern.InOnly };
}
// ── Basic write ─────────────────────────────────────────────────
[Fact]
public async Task Producer_WritesFileWithHeaderName()
{
var endpoint = CreateEndpoint();
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("hello world", "output.txt");
await producer.Process(exchange);
var path = Path.Combine(_outputDir, "output.txt");
System.IO.File.Exists(path).Should().BeTrue();
System.IO.File.ReadAllBytes(path).Should().Equal(System.Text.Encoding.UTF8.GetBytes("hello world"));
}
[Fact]
public async Task Producer_WritesFile_SetsFileNameProducedHeader()
{
var endpoint = CreateEndpoint();
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("data", "result.txt");
await producer.Process(exchange);
exchange.In.Headers.Should().ContainKey(FileHeaders.FileNameProduced);
exchange.In.Headers[FileHeaders.FileNameProduced]!.ToString().Should().Contain("result.txt");
}
[Fact]
public async Task Producer_WithoutFileName_GeneratesGuid()
{
var endpoint = CreateEndpoint();
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("data");
await producer.Process(exchange);
var files = Directory.GetFiles(_outputDir);
files.Should().HaveCount(1);
Path.GetFileName(files[0]).Should().StartWith("redb-");
}
[Fact]
public async Task Producer_DynamicFileName()
{
var endpoint = CreateEndpoint(new() { ["fileName"] = "report.json" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("{}", null);
await producer.Process(exchange);
System.IO.File.Exists(Path.Combine(_outputDir, "report.json")).Should().BeTrue();
}
// ── FileExist strategies ────────────────────────────────────────
[Fact]
public async Task Producer_FileExist_Override_OverwritesExisting()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "target.txt"), "old");
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Override" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("new content", "target.txt");
await producer.Process(exchange);
System.IO.File.ReadAllText(Path.Combine(_outputDir, "target.txt")).Should().Be("new content");
}
[Fact]
public async Task Producer_FileExist_Append_AppendsToExisting()
{
System.IO.File.WriteAllBytes(Path.Combine(_outputDir, "target.txt"),
System.Text.Encoding.UTF8.GetBytes("old"));
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Append" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("NEW", "target.txt");
await producer.Process(exchange);
var content = System.IO.File.ReadAllBytes(Path.Combine(_outputDir, "target.txt"));
System.Text.Encoding.UTF8.GetString(content).Should().Contain("old");
System.Text.Encoding.UTF8.GetString(content).Should().Contain("NEW");
}
[Fact]
public async Task Producer_FileExist_Append_WithAppendChars()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "lines.txt"), "line1");
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Append", ["appendChars"] = "\n" });
var producer = (FileProducer)endpoint.CreateProducer();
// Write line2
var exchange = CreateExchange("line2", "lines.txt");
await producer.Process(exchange);
var content = System.IO.File.ReadAllText(Path.Combine(_outputDir, "lines.txt"));
content.Should().Contain("line2\n");
}
[Fact]
public async Task Producer_FileExist_Fail_ThrowsWhenExists()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "target.txt"), "existing");
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Fail" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("new", "target.txt");
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*FileExist=Fail*");
}
[Fact]
public async Task Producer_FileExist_Ignore_SkipsWrite()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "target.txt"), "original");
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Ignore" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("new", "target.txt");
await producer.Process(exchange);
System.IO.File.ReadAllText(Path.Combine(_outputDir, "target.txt")).Should().Be("original");
}
[Fact]
public async Task Producer_FileExist_Move_BacksUpExisting()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "target.txt"), "old");
var endpoint = CreateEndpoint(new() { ["fileExist"] = "Move" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("new", "target.txt");
await producer.Process(exchange);
System.IO.File.ReadAllText(Path.Combine(_outputDir, "target.txt")).Should().Be("new");
System.IO.File.Exists(Path.Combine(_outputDir, "target.txt.bak")).Should().BeTrue();
System.IO.File.ReadAllText(Path.Combine(_outputDir, "target.txt.bak")).Should().Be("old");
}
// ── Temp file writing ───────────────────────────────────────────
[Fact]
public async Task Producer_TempPrefix_WritesToTempThenRenames()
{
var endpoint = CreateEndpoint(new() { ["tempPrefix"] = ".redb_" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("atomic data", "result.txt");
await producer.Process(exchange);
var targetPath = Path.Combine(_outputDir, "result.txt");
System.IO.File.Exists(targetPath).Should().BeTrue();
System.IO.File.ReadAllText(targetPath).Should().Be("atomic data");
// Temp file should not remain
var tempPath = Path.Combine(_outputDir, ".redb_result.txt");
System.IO.File.Exists(tempPath).Should().BeFalse();
}
[Fact]
public async Task Producer_TempFileName_WritesToExactTempFile()
{
var endpoint = CreateEndpoint(new() { ["tempFileName"] = ".writing.tmp" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("data", "final.txt");
await producer.Process(exchange);
System.IO.File.Exists(Path.Combine(_outputDir, "final.txt")).Should().BeTrue();
System.IO.File.Exists(Path.Combine(_outputDir, ".writing.tmp")).Should().BeFalse();
}
// ── AutoCreate ──────────────────────────────────────────────────
[Fact]
public async Task Producer_AutoCreate_CreatesDirectory()
{
var subDir = Path.Combine(_outputDir, "nested", "deep");
var component = new FileComponent();
var path = "/" + subDir.Replace("\\", "/");
var uri = new EndpointUri("file", path, $"file://{path}", new Dictionary { ["autoCreate"] = "true" });
var ep = (FileEndpoint)component.CreateEndpoint(uri);
var producer = (FileProducer)ep.CreateProducer();
var exchange = CreateExchange("nested data", "file.txt");
await producer.Process(exchange);
System.IO.File.Exists(Path.Combine(subDir, "file.txt")).Should().BeTrue();
}
// ── AllowNullBody ───────────────────────────────────────────────
[Fact]
public async Task Producer_NullBody_AllowNullBodyFalse_Throws()
{
var endpoint = CreateEndpoint(new() { ["allowNullBody"] = "false" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange(null, "empty.txt");
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync()
.WithMessage("*null*AllowNullBody*");
}
[Fact]
public async Task Producer_NullBody_AllowNullBodyTrue_WritesEmptyFile()
{
var endpoint = CreateEndpoint(new() { ["allowNullBody"] = "true" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange(null, "empty.txt");
await producer.Process(exchange);
var path = Path.Combine(_outputDir, "empty.txt");
System.IO.File.Exists(path).Should().BeTrue();
System.IO.File.ReadAllBytes(path).Should().BeEmpty();
}
// ── String body ─────────────────────────────────────────────────
[Fact]
public async Task Producer_StringBody_WritesAsText()
{
var endpoint = CreateEndpoint();
var producer = (FileProducer)endpoint.CreateProducer();
var message = new Message { Body = "text content" };
message.Headers[FileHeaders.FileName] = "text.txt";
var exchange = new Exchange(message);
await producer.Process(exchange);
System.IO.File.ReadAllText(Path.Combine(_outputDir, "text.txt")).Should().Be("text content");
}
// ── Stream body ─────────────────────────────────────────────────
[Fact]
public async Task Producer_StreamBody_WritesFromStream()
{
var endpoint = CreateEndpoint();
var producer = (FileProducer)endpoint.CreateProducer();
var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("stream data"));
var message = new Message { Body = stream };
message.Headers[FileHeaders.FileName] = "stream.txt";
var exchange = new Exchange(message);
await producer.Process(exchange);
System.IO.File.ReadAllText(Path.Combine(_outputDir, "stream.txt")).Should().Be("stream data");
}
// ── EagerDeleteTargetFile ───────────────────────────────────────
[Fact]
public async Task Producer_EagerDeleteTargetFile_False_DoesNotPreDelete()
{
System.IO.File.WriteAllText(Path.Combine(_outputDir, "target.txt"), "old");
var endpoint = CreateEndpoint(new() { ["eagerDeleteTargetFile"] = "false" });
var producer = (FileProducer)endpoint.CreateProducer();
var exchange = CreateExchange("new", "target.txt");
await producer.Process(exchange);
// File should still be overwritten (WriteAllBytes handles it)
System.IO.File.ReadAllText(Path.Combine(_outputDir, "target.txt")).Should().Be("new");
}
// ── Start/Stop ──────────────────────────────────────────────────
[Fact]
public async Task Producer_StartStop_NoOp()
{
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Stop();
// No exception
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { }
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileRestartTests.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.File/FileRestartTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// A file consumer and producer keep working after Stop() and Start() of the same route context: the stop
/// ends the polling of the cached endpoint, the start polls again, and the producer still writes.
///
public sealed class FileRestartTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "redb-file-restart-" + Guid.NewGuid().ToString("N"));
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch (IOException) { }
}
private string Uri(string directory, string options) =>
"file:///" + Path.Combine(_root, directory).Replace("\\", "/").TrimStart('/') + "?" + options;
private static async Task WaitForAsync(Func condition, string because)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(50);
condition().Should().BeTrue(because);
}
[Fact]
public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again()
{
var inbox = Path.Combine(_root, "in");
var outbox = Path.Combine(_root, "out");
Directory.CreateDirectory(inbox);
Directory.CreateDirectory(outbox);
var read = new List();
await using var ctx = new RouteContext();
ctx.AddComponent(new FileComponent());
ctx.AddRoutes(r => r.From(Uri("in", "delay=100&initialDelay=10&delete=true"))
.Process(e => { lock (read) read.Add(e.ExchangeId); }));
ctx.AddRoutes(r => r.From("direct://write").To(Uri("out", "")));
async Task CheckAsync(string payload, int round)
{
await System.IO.File.WriteAllTextAsync(Path.Combine(inbox, payload + ".txt"), payload);
await WaitForAsync(() => { lock (read) return read.Count == round; }, "the file receiver reads after a restart");
var producer = ctx.GetEndpoint("direct://write").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(payload)));
Directory.GetFiles(outbox).Should().HaveCount(round, "the file send writes after a restart");
}
await ctx.Start();
await CheckAsync("first", 1);
await ctx.Stop();
await ctx.Start();
await CheckAsync("second", 2);
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileTelemetrySmokeTests.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.File/FileTelemetrySmokeTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
using redb.Route.Telemetry;
using redb.Route.Tests.Shared;
namespace redb.Route.Tests.File;
/// Smoke test for the P1 transport span opened by .
public sealed class FileTelemetrySmokeTests : IDisposable
{
private readonly string _tempDir;
public FileTelemetrySmokeTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-tel-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_tempDir);
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { }
}
[Fact]
public async Task FileProducer_EmitsTransportSpanWithFileSystemTag()
{
var component = new FileComponent();
var path = "/" + _tempDir.Replace("\\", "/");
var uri = new EndpointUri("file", path, $"file://{path}", new Dictionary());
var endpoint = (FileEndpoint)component.CreateEndpoint(uri);
var producer = (FileProducer)endpoint.CreateProducer();
using var capture = new SpanCapture(); // this test's spans only
var message = new Message { Body = System.Text.Encoding.UTF8.GetBytes("hi") };
message.Headers[FileHeaders.FileName] = "smoke.txt";
await producer.Process(new Exchange(message) { Pattern = ExchangePattern.InOnly });
var activities = capture.Spans;
activities.Should().NotBeEmpty();
var activity = activities.First();
activity.Source.Name.Should().Be(RouteActivitySource.SourceName);
activity.Kind.Should().Be(ActivityKind.Producer);
activity.GetTagItem("redb.system").Should().Be("file");
activity.GetTagItem("messaging.operation").Should().Be("write");
activity.GetTagItem("redb.route.endpoint").Should().NotBeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.File/FileTraceTests.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.File/FileTraceTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.File;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.File;
///
/// A polled file carries no trace context: the consumer opens a root span per routed file, never a child of the activity
/// the poll loop inherited from whoever started it, and none for an empty poll. A failed route marks it red. The
/// producer marks a failed write red. EnableTelemetry=false opens none of these spans. Each test polls a directory
/// of its own and reads only the spans of that endpoint.
///
public sealed class FileTraceTests : IDisposable
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
private readonly string _root;
private readonly string _marker;
public FileTraceTests()
{
_marker = "redb-trace-" + Guid.NewGuid().ToString("N")[..12];
_root = Path.Combine(Path.GetTempPath(), _marker);
Directory.CreateDirectory(_root);
}
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch (IOException) { }
}
private string Uri(string directory, string options) =>
"file:///" + Path.Combine(_root, directory).Replace("\\", "/").TrimStart('/') + "?" + options;
private string ConsumerUri => Uri("in", "delay=100&initialDelay=10&delete=true");
private RouteTelemetryProbe Spans(ActivityKind kind)
=> new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_marker, StringComparison.Ordinal) == true);
private void Write(string name)
{
Directory.CreateDirectory(Path.Combine(_root, "in"));
System.IO.File.WriteAllText(Path.Combine(_root, "in", name), "payload");
}
private async Task StartConsumer(Action step, bool telemetry = true)
{
Directory.CreateDirectory(Path.Combine(_root, "in"));
var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new FileComponent());
ctx.AddRoutes(r => r.From(ConsumerUri).Process(step));
using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start())
await ctx.Start();
return ctx;
}
private static async Task Until(Func done)
{
var deadline = DateTime.UtcNow + Wait;
while (!done() && DateTime.UtcNow < deadline)
await Task.Delay(50);
}
[Fact]
public async Task Each_file_opens_a_root_span_even_under_an_ambient_activity()
{
Write("a.txt");
Write("b.txt");
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => { }))
await Until(() => probe.Activities.Count >= 2);
probe.Activities.Should().HaveCount(2, "one span per routed file");
probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId),
"a file carries no context, so its span starts a trace rather than joining the host's");
}
[Fact]
public async Task An_empty_poll_opens_no_span()
{
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => { }))
await Task.Delay(800); // several polls of an empty directory
probe.Activities.Should().BeEmpty();
}
[Fact]
public async Task A_failed_route_marks_the_span_red()
{
Write("fail.txt");
using var probe = Spans(ActivityKind.Consumer);
await using (await StartConsumer(_ => throw new InvalidOperationException("route failed")))
await Until(() => probe.Activities.Count >= 1);
probe.Activities.Should().NotBeEmpty();
probe.Activities.Should().OnlyContain(a => a.Status == ActivityStatusCode.Error);
}
[Fact]
public async Task Tracing_off_opens_no_span()
{
Write("off.txt");
using var probe = new RouteTelemetryProbe(a =>
RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_marker, StringComparison.Ordinal) == true);
var routed = new TaskCompletionSource();
await using (await StartConsumer(_ => routed.TrySetResult(), telemetry: false))
(await Task.WhenAny(routed.Task, Task.Delay(Wait))).Should().Be(routed.Task);
probe.Activities.Should().BeEmpty();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task A_failed_write_marks_the_producer_span_red_and_tracing_off_opens_none(bool telemetry)
{
Directory.CreateDirectory(Path.Combine(_root, "out"));
System.IO.File.WriteAllText(Path.Combine(_root, "out", "taken.txt"), "already here");
using var probe = Spans(ActivityKind.Producer);
await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new FileComponent());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var act = () => template.SendAsync(Uri("out", "fileName=taken.txt&fileExist=Fail"), new Exchange(new Message("payload")));
await act.Should().ThrowAsync();
if (telemetry)
probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error);
else
probe.Activities.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.File/ReadLockConsumerTests.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.File/ReadLockConsumerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// End-to-end tests for read-lock strategies driven through the real .
/// The strategies are also covered in isolation by ; these tests exist
/// because a strategy can be correct on its own and still break the consumer that uses it.
///
public class ReadLockConsumerTests : IDisposable
{
private readonly string _tempDir;
private readonly string _inputDir;
public ReadLockConsumerTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-readlock-e2e-" + Guid.NewGuid().ToString("N")[..8]);
_inputDir = Path.Combine(_tempDir, "input");
Directory.CreateDirectory(_inputDir);
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { /* best effort */ }
GC.SuppressFinalize(this);
}
private FileEndpoint CreateEndpoint(Dictionary parameters)
{
var component = new FileComponent();
var path = "/" + _inputDir.Replace("\\", "/");
var uri = new EndpointUri("file", path, $"file://{path}", parameters);
return (FileEndpoint)component.CreateEndpoint(uri);
}
private string CreateFile(string name, string content)
{
var path = Path.Combine(_inputDir, name);
System.IO.File.WriteAllText(path, content);
return path;
}
private static async Task WaitForCondition(Func condition, int timeoutMs)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs && !condition())
await Task.Delay(25);
}
private static (IProcessor Processor, List Bodies) Collector()
{
var bodies = new List();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(call =>
{
var body = call.Arg().In.Body;
bodies.Add(body switch
{
byte[] b => System.Text.Encoding.UTF8.GetString(b),
Stream s => new StreamReader(s).ReadToEnd(),
null => "",
var other => other.ToString() ?? ""
});
});
return (processor, bodies);
}
// ── Rename ──────────────────────────────────────────────────────
[Fact]
public async Task Rename_DeliversFileContent_AndCompletesPostProcessing()
{
CreateFile("order.csv", "PAYLOAD");
var endpoint = CreateEndpoint(new() { ["readLock"] = "Rename", ["delete"] = "true", ["delay"] = "100" });
var (processor, bodies) = Collector();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => bodies.Count >= 1, 3000);
await Task.Delay(400); // let further polls run — a broken lock re-delivers forever
await consumer.Stop();
bodies.Should().ContainSingle().Which.Should().Be("PAYLOAD");
Directory.GetFiles(_inputDir).Should().BeEmpty("the file is consumed and deleted, not renamed back");
}
[Fact]
public async Task Rename_MovesFileToArchiveUnderOriginalName()
{
CreateFile("order.csv", "PAYLOAD");
var archive = Path.Combine(_tempDir, "archive");
var endpoint = CreateEndpoint(new()
{
["readLock"] = "Rename",
["moveTo"] = archive,
["delay"] = "100"
});
var (processor, bodies) = Collector();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => bodies.Count >= 1, 3000);
await Task.Delay(300);
await consumer.Stop();
System.IO.File.Exists(Path.Combine(archive, "order.csv")).Should().BeTrue();
System.IO.File.ReadAllText(Path.Combine(archive, "order.csv")).Should().Be("PAYLOAD");
}
// ── FileLock ────────────────────────────────────────────────────
[Fact]
public async Task FileLock_DeliversFileContent_AndCompletesPostProcessing()
{
CreateFile("order.csv", "PAYLOAD");
var endpoint = CreateEndpoint(new() { ["readLock"] = "FileLock", ["delete"] = "true", ["delay"] = "100" });
var (processor, bodies) = Collector();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => bodies.Count >= 1, 3000);
await Task.Delay(400);
await consumer.Stop();
bodies.Should().ContainSingle().Which.Should().Be("PAYLOAD");
Directory.GetFiles(_inputDir).Should().BeEmpty();
}
[Fact]
public async Task FileLock_StreamBody_DeliversFileContent()
{
CreateFile("order.csv", "STREAMED");
var endpoint = CreateEndpoint(new()
{
["readLock"] = "FileLock",
["streamBody"] = "true",
["delete"] = "true",
["delay"] = "100"
});
var (processor, bodies) = Collector();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await WaitForCondition(() => bodies.Count >= 1, 3000);
await Task.Delay(300);
await consumer.Stop();
bodies.Should().ContainSingle().Which.Should().Be("STREAMED");
}
[WindowsFact("FileLock excludes other readers on Windows only: Linux and macOS have advisory locks, "
+ "a reader that does not ask for a lock opens the file anyway (README, Read Lock Strategies).")]
public async Task FileLock_KeepsOtherReadersOut_WhileHeld()
{
var path = CreateFile("order.csv", "PAYLOAD");
var strategy = new FileLockReadLock();
var options = new FileEndpointOptions();
var acquired = await strategy.AcquireLock(new FileInfo(path), options, CancellationToken.None);
acquired.Should().BeTrue();
// Another process opening the file for reading must be refused: the point of this
// strategy is exclusivity, and it must survive the fix that made our own read work.
var openOther = () => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
openOther.Should().Throw();
strategy.ReleaseLock(new FileInfo(path), options);
using var reopened = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
reopened.Should().NotBeNull();
}
// ── MarkerFile + idempotency ────────────────────────────────────
[Fact]
public async Task MarkerFile_Contended_ProcessesFileOnceTheOtherConsumerReleases()
{
CreateFile("order.csv", "PAYLOAD");
var marker = Path.Combine(_inputDir, "order.csv" + new FileEndpointOptions().ReadLockMarkerFileExtension);
System.IO.File.WriteAllText(marker, "held by another consumer");
var endpoint = CreateEndpoint(new()
{
["readLock"] = "MarkerFile",
["idempotent"] = "true",
["noop"] = "true",
["delay"] = "100"
});
var (processor, bodies) = Collector();
var consumer = (FileConsumer)endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(400);
bodies.Should().BeEmpty("the marker belongs to another consumer");
System.IO.File.Delete(marker); // the other consumer finished
await WaitForCondition(() => bodies.Count >= 1, 3000);
await consumer.Stop();
bodies.Should().ContainSingle("losing the lock race must not consume the idempotent key")
.Which.Should().Be("PAYLOAD");
}
}
Path: redb-route/tests/redb.Route.Tests.File/ReadLockTests.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.File/ReadLockTests.cs
----
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// Tests for read lock strategies.
///
public class ReadLockTests
{
private readonly string _tempDir;
public ReadLockTests()
{
_tempDir = Path.Combine(Path.GetTempPath(), "redb-route-readlock-tests-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(_tempDir);
}
private FileInfo CreateTestFile(string name = "test.txt", string content = "hello")
{
var path = Path.Combine(_tempDir, name);
System.IO.File.WriteAllText(path, content);
return new FileInfo(path);
}
private FileEndpointOptions DefaultOptions() => new();
// ── NoReadLock ───────────────────────────────────────────────────
[Fact]
public async Task NoReadLock_AlwaysAcquires()
{
var file = CreateTestFile();
var strategy = NoReadLock.Instance;
var result = await strategy.AcquireLock(file, DefaultOptions(), CancellationToken.None);
result.Should().BeTrue();
}
[Fact]
public void NoReadLock_ReleaseDoesNothing()
{
var file = CreateTestFile();
var strategy = NoReadLock.Instance;
strategy.ReleaseLock(file, DefaultOptions()); // No exception
}
// ── MarkerFileReadLock ──────────────────────────────────────────
[Fact]
public async Task MarkerFile_AcquiresAndCreatesMarker()
{
var file = CreateTestFile();
var strategy = MarkerFileReadLock.Instance;
var options = DefaultOptions();
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeTrue();
System.IO.File.Exists(file.FullName + ".redbLock").Should().BeTrue();
strategy.ReleaseLock(file, options);
System.IO.File.Exists(file.FullName + ".redbLock").Should().BeFalse();
}
[Fact]
public async Task MarkerFile_LockedByAnother_ReturnsFalse()
{
var file = CreateTestFile();
var strategy = MarkerFileReadLock.Instance;
var options = DefaultOptions();
// Simulate another consumer holding the lock
System.IO.File.WriteAllText(file.FullName + ".redbLock", "locked");
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeFalse();
// Cleanup
System.IO.File.Delete(file.FullName + ".redbLock");
}
[Fact]
public async Task MarkerFile_CustomExtension()
{
var file = CreateTestFile();
var strategy = MarkerFileReadLock.Instance;
var options = new FileEndpointOptions { ReadLockMarkerFileExtension = ".mylock" };
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeTrue();
System.IO.File.Exists(file.FullName + ".mylock").Should().BeTrue();
strategy.ReleaseLock(file, options);
System.IO.File.Exists(file.FullName + ".mylock").Should().BeFalse();
}
// ── ChangedReadLock ─────────────────────────────────────────────
[Fact]
public async Task Changed_StableFile_Acquires()
{
var file = CreateTestFile();
var strategy = ChangedReadLock.Instance;
var options = new FileEndpointOptions
{
ReadLockCheckInterval = 50,
ReadLockMinAge = 100,
ReadLockTimeout = 5000
};
// File is already stable
await Task.Delay(150); // Ensure it's old enough
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeTrue();
}
[Fact]
public async Task Changed_Timeout_ReturnsFalse()
{
var file = CreateTestFile();
var strategy = ChangedReadLock.Instance;
var options = new FileEndpointOptions
{
ReadLockCheckInterval = 50,
ReadLockMinAge = 10000, // File must be stable for 10s
ReadLockTimeout = 200 // But timeout after 200ms
};
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeFalse();
}
// ── FileLockReadLock ────────────────────────────────────────────
[Fact]
public async Task FileLock_AcquiresAndReleases()
{
var file = CreateTestFile();
var strategy = new FileLockReadLock();
var options = DefaultOptions();
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeTrue();
// File should be locked — another attempt should fail
try
{
using var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.None);
// If we get here, the lock wasn't exclusive, which is fine — depends on OS behavior
}
catch (IOException)
{
// Expected — file is locked
}
strategy.ReleaseLock(file, options);
// After release, file should be accessible
using var fs2 = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
fs2.Should().NotBeNull();
}
[Fact]
public async Task FileLock_AlreadyLocked_ReturnsFalse()
{
var file = CreateTestFile();
var strategy = new FileLockReadLock();
var options = DefaultOptions();
// Lock the file from outside
using var externalLock = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.None);
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeFalse();
}
// ── RenameReadLock ──────────────────────────────────────────────
[Fact]
public async Task Rename_AcquiresAndRenames()
{
var file = CreateTestFile();
var strategy = new RenameReadLock();
var options = DefaultOptions();
var originalPath = file.FullName;
var result = await strategy.AcquireLock(file, options, CancellationToken.None);
result.Should().BeTrue();
System.IO.File.Exists(originalPath).Should().BeFalse();
System.IO.File.Exists(originalPath + ".redbRename").Should().BeTrue();
strategy.ReleaseLock(file, options);
System.IO.File.Exists(originalPath).Should().BeTrue();
System.IO.File.Exists(originalPath + ".redbRename").Should().BeFalse();
}
// ── ReadLockFactory ─────────────────────────────────────────────
[Theory]
[InlineData(ReadLockStrategy.None, typeof(NoReadLock))]
[InlineData(ReadLockStrategy.MarkerFile, typeof(MarkerFileReadLock))]
[InlineData(ReadLockStrategy.Changed, typeof(ChangedReadLock))]
[InlineData(ReadLockStrategy.FileLock, typeof(FileLockReadLock))]
[InlineData(ReadLockStrategy.Rename, typeof(RenameReadLock))]
public void Factory_CreatesCorrectStrategy(ReadLockStrategy strategy, Type expectedType)
{
var result = ReadLockFactory.Create(strategy);
result.Should().BeOfType(expectedType);
}
public void Dispose()
{
try { Directory.Delete(_tempDir, recursive: true); } catch { }
}
}
Path: redb-route/tests/redb.Route.Tests.File/ServiceCollectionExtensionsTests.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.File/ServiceCollectionExtensionsTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.File;
namespace redb.Route.Tests.File;
///
/// Tests for DI extension methods.
///
public class ServiceCollectionExtensionsTests
{
[Fact]
public void AddRedbRouteFile_RegistersFileComponent()
{
var services = new ServiceCollection();
services.AddRedbRouteFile();
var sp = services.BuildServiceProvider();
var component = sp.GetService();
component.Should().NotBeNull();
component!.Scheme.Should().Be("file");
}
[Fact]
public void AddRedbRouteFile_Singleton()
{
var services = new ServiceCollection();
services.AddRedbRouteFile();
var sp = services.BuildServiceProvider();
var c1 = sp.GetService();
var c2 = sp.GetService();
c1.Should().BeSameAs(c2);
}
}
Path: redb-route/tests/redb.Route.Tests.File/WindowsFactAttribute.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.File/WindowsFactAttribute.cs
----
namespace redb.Route.Tests.File;
///
/// A fact about behavior only Windows has. Elsewhere it is skipped with the documented reason, never silently passed.
///
public sealed class WindowsFactAttribute : FactAttribute
{
/// Why the behavior is Windows only, as the README documents it.
public WindowsFactAttribute(string reason)
{
if (!OperatingSystem.IsWindows())
Skip = reason;
}
}
Path: redb-route/tests/redb.Route.Tests.File/redb.Route.Tests.File.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.File/redb.Route.Tests.File.csproj
----