Bundle: redb-route / tests/redb.Route.Tests.Sftp (tests.redb.Route.Tests.Sftp.txt), 12 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.Sftp/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.Sftp/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteSftp_RegistersSftpComponent() { var services = new ServiceCollection(); services.AddRedbRouteSftp(); var descriptors = services.Where(d => d.ServiceType == typeof(SftpComponent)).ToList(); descriptors.Should().HaveCount(1); descriptors[0].Lifetime.Should().Be(ServiceLifetime.Singleton); } [Fact] public async Task AddRedbRouteSftp_ConfiguratorRegistersComponentInContext() { var services = new ServiceCollection(); services.AddRedbRouteSftp(); services.Where(d => d.ServiceType == typeof(IRouteContextConfigurator)) .Should().ContainSingle() .Which.Lifetime.Should().Be(ServiceLifetime.Singleton); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.HasComponent("sftp").Should().BeTrue(); } [Fact] public void AddRedbRouteSftp_ReturnsServices() { var services = new ServiceCollection(); var result = services.AddRedbRouteSftp(); result.Should().BeSameAs(services); } [Fact] public void AddRedbRouteSftp_ResolvesComponent() { var services = new ServiceCollection(); services.AddRedbRouteSftp(); // Add a mock IRouteContext var routeContext = Substitute.For(); services.AddSingleton(routeContext); var provider = services.BuildServiceProvider(); var component = provider.GetRequiredService(); component.Should().NotBeNull(); component.Scheme.Should().Be("sftp"); } [Fact] public void AddRedbRouteSftp_IdempotentMultipleCalls() { var services = new ServiceCollection(); services.AddRedbRouteSftp(); services.AddRedbRouteSftp(); var descriptors = services.Where(d => d.ServiceType == typeof(SftpComponent)).ToList(); // ServiceCollection allows duplicates (by design), but the component still works descriptors.Should().HaveCountGreaterThanOrEqualTo(1); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpBuilderTests.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.Sftp/SftpBuilderTests.cs ---- using redb.Route.Core; using redb.Route.Expressions; using SftpDsl = redb.Route.Sftp.Sftp; namespace redb.Route.Tests.Sftp; public class SftpBuilderTests { private static ConstantExpression C(string s) => new(s); // ── Factory ───────────────────────────────────────────────────── [Fact] public void Directory_StartsWithSftpScheme() { var uri = SftpDsl.Directory("/incoming").Build(); uri.Should().StartWith("sftp:///incoming"); } [Fact] public void NullPath_Throws() { var act = () => SftpDsl.Directory(null!); act.Should().Throw(); } [Fact] public void EmptyPath_Throws() { var act = () => SftpDsl.Directory(""); act.Should().Throw(); } // ── Connection ────────────────────────────────────────────────── [Fact] public void Host_SetsParam() { var uri = SftpDsl.Directory("/d").Host(C("sftp.example.com")).Build(); uri.Should().Contain("host=sftp.example.com"); } [Fact] public void Port_SetsParam() { var uri = SftpDsl.Directory("/d").Port(2222).Build(); uri.Should().Contain("port=2222"); } [Fact] public void Username_SetsParam() { var uri = SftpDsl.Directory("/d").Username(C("admin")).Build(); uri.Should().Contain("username=admin"); } [Fact] public void Password_SetsParam() { var uri = SftpDsl.Directory("/d").Password(C("secret")).Build(); uri.Should().Contain("password=secret"); } [Fact] public void PrivateKey_SetsParam() { var uri = SftpDsl.Directory("/d").PrivateKey(C("/keys/id_rsa")).Build(); uri.Should().Contain("privateKeyPath="); } [Fact] public void PrivateKey_WithPassphrase_SetsBothParams() { var uri = SftpDsl.Directory("/d").PrivateKey(C("/keys/id_rsa"), C("pp")).Build(); uri.Should().Contain("privateKeyPath="); uri.Should().Contain("privateKeyPassphrase=pp"); } [Fact] public void ServerFingerprint_SetsParam() { var uri = SftpDsl.Directory("/d").ServerFingerprint(C("SHA256:abc")).Build(); uri.Should().Contain("serverFingerprint="); } [Fact] public void StrictHostKeyChecking_SetsParam() { var uri = SftpDsl.Directory("/d").StrictHostKeyChecking().Build(); uri.Should().Contain("strictHostKeyChecking=true"); } [Fact] public void Compression_SetsParam() { var uri = SftpDsl.Directory("/d").Compression().Build(); uri.Should().Contain("compression=true"); } // ── Consumer ──────────────────────────────────────────────────── [Fact] public void Include_SetsParam() { var uri = SftpDsl.Directory("/d").Include("*.csv").Build(); uri.Should().Contain("include=%2A.csv"); } [Fact] public void PathFilters_SetTheirParams() { var uri = SftpDsl.Directory("/d") .Recursive() .AntInclude("TYPE_A/outbox/*.csv") .AntExclude("archive/**") .AntFilterCaseSensitive(false) .FilterDirectory("header.redbSftp.Name != 'tmp'") .FilterFile("header.redbSftp.Length > 0") .Filter("#partnerFilter") .Build(); var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["antInclude"].Should().Be("TYPE_A/outbox/*.csv"); parsed.RawParameters["antExclude"].Should().Be("archive/**"); parsed.RawParameters["antFilterCaseSensitive"].Should().Be("false"); parsed.RawParameters["filterDirectory"].Should().Be("header.redbSftp.Name != 'tmp'"); parsed.RawParameters["filterFile"].Should().Be("header.redbSftp.Length > 0"); parsed.RawParameters["filter"].Should().Be("#partnerFilter"); } [Fact] public void Exclude_SetsParam() { var uri = SftpDsl.Directory("/d").Exclude("*.tmp").Build(); uri.Should().Contain("exclude=%2A.tmp"); } [Fact] public void Recursive_SetsParam() { var uri = SftpDsl.Directory("/d").Recursive().Build(); uri.Should().Contain("recursive=true"); } [Fact] public void Delay_SetsParam() { var uri = SftpDsl.Directory("/d").Delay(5000).Build(); uri.Should().Contain("delay=5000"); } [Fact] public void SortBy_SetsParam() { var uri = SftpDsl.Directory("/d").SortBy("name").Build(); uri.Should().Contain("sortBy=name"); } [Fact] public void MaxMessagesPerPoll_SetsParam() { var uri = SftpDsl.Directory("/d").MaxMessagesPerPoll(10).Build(); uri.Should().Contain("maxMessagesPerPoll=10"); } // ── Post-processing ───────────────────────────────────────────── [Fact] public void Noop_SetsParam() { var uri = SftpDsl.Directory("/d").Noop().Build(); uri.Should().Contain("noop=true"); } [Fact] public void Delete_SetsParam() { var uri = SftpDsl.Directory("/d").Delete().Build(); uri.Should().Contain("delete=true"); } [Fact] public void MoveTo_SetsParam() { var uri = SftpDsl.Directory("/d").MoveTo(C("/done")).Build(); uri.Should().Contain("moveTo="); } [Fact] public void Idempotent_SetsParam() { var uri = SftpDsl.Directory("/d").Idempotent().Build(); uri.Should().Contain("idempotent=true"); } // ── Producer ──────────────────────────────────────────────────── [Fact] public void AutoCreate_SetsParam() { var uri = SftpDsl.Directory("/d").AutoCreate().Build(); uri.Should().Contain("autoCreate=true"); } [Fact] public void TempPrefix_SetsParam() { var uri = SftpDsl.Directory("/d").TempPrefix(C(".tmp")).Build(); uri.Should().Contain("tempPrefix=.tmp"); } [Fact] public void Chmod_SetsParam() { var uri = SftpDsl.Directory("/d").Chmod("644").Build(); uri.Should().Contain("chmod=644"); } [Fact] public void Flatten_SetsParam() { var uri = SftpDsl.Directory("/d").Flatten().Build(); uri.Should().Contain("flatten=true"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = SftpDsl.Directory("/incoming").Host(C("sftp.example.com")).Username(C("admin")); uri.Should().StartWith("sftp:///incoming?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = SftpDsl.Directory("/d").Host(C("h")).Include("*.csv"); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_Consumer_BuildsCorrectUri() { var uri = SftpDsl.Directory("/incoming") .Host(C("sftp.example.com")) .Port(22) .Username(C("admin")) .Password(C("secret")) .Include("*.csv") .Recursive() .Delete() .Delay(5000) .Build(); uri.Should().StartWith("sftp:///incoming?"); uri.Should().Contain("host=sftp.example.com"); uri.Should().Contain("include=%2A.csv"); uri.Should().Contain("recursive=true"); uri.Should().Contain("delete=true"); } [Fact] public void FullChain_Producer_BuildsCorrectUri() { var uri = SftpDsl.Directory("/outgoing") .Host(C("sftp.example.com")) .Username(C("admin")) .Password(C("secret")) .AutoCreate() .TempPrefix(C(".uploading-")) .Chmod("644") .Build(); uri.Should().StartWith("sftp:///outgoing?"); uri.Should().Contain("autoCreate=true"); uri.Should().Contain("chmod=644"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = SftpDsl.Directory("/data").Host(C("sftp.example.com")).Include("*.csv").Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("sftp"); parsed.RawParameters["host"].Should().Be("sftp.example.com"); parsed.RawParameters["include"].Should().Be("*.csv"); } // ── StreamBody ────────────────────────────────────────────────── [Fact] public void StreamBody_SetsParam() { var uri = SftpDsl.Directory("/data").StreamBody().Build(); uri.Should().Contain("streamBody=true"); } [Fact] public void StreamBody_RoundTrip() { var uri = SftpDsl.Directory("/data").StreamBody().Build(); var parsed = EndpointUriParser.Parse(uri); parsed.RawParameters["streamBody"].Should().Be("true"); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpClientFactoryTests.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.Sftp/SftpClientFactoryTests.cs ---- using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpClientFactoryTests { [Fact] public void Create_NullOptions_Throws() { var act = () => SftpClientFactory.Create(null!); act.Should().Throw(); } [Fact] public void Create_PasswordAuth_ReturnsClient() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret" }; using var client = SftpClientFactory.Create(options); client.Should().NotBeNull(); client.OperationTimeout.Should().Be(TimeSpan.FromMilliseconds(60_000)); client.BufferSize.Should().Be(32_768u); } [Fact] public void Create_CustomTimeouts_Applied() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", OperationTimeout = 5000, BufferSize = 65536 }; using var client = SftpClientFactory.Create(options); client.OperationTimeout.Should().Be(TimeSpan.FromMilliseconds(5000)); client.BufferSize.Should().Be(65536u); } [Fact] public void Create_KeepAlive_Applied() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", KeepAliveInterval = 10000 }; using var client = SftpClientFactory.Create(options); client.KeepAliveInterval.Should().Be(TimeSpan.FromMilliseconds(10000)); } [Fact] public void Create_NoAuthMethods_Throws() { var options = new SftpEndpointOptions { Host = "localhost", Username = "testuser", Password = "", PrivateKeyPath = "" }; var act = () => SftpClientFactory.Create(options); act.Should().Throw().WithMessage("*authentication*"); } [Fact] public void Create_InvalidPrivateKeyPath_Throws() { var options = new SftpEndpointOptions { Host = "localhost", Username = "testuser", PrivateKeyPath = "/nonexistent/path/key" }; // SSH.NET will throw when trying to load the key file var act = () => SftpClientFactory.Create(options); act.Should().Throw(); } [Fact] public void Create_StrictHostKeyWithFingerprint_NoThrow() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", StrictHostKeyChecking = true, ServerFingerprint = "AA:BB:CC:DD" }; // Should create client (fingerprint validated on connect, not create) using var client = SftpClientFactory.Create(options); client.Should().NotBeNull(); } [Fact] public void Create_NonStrictHostKey_NoThrow() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", StrictHostKeyChecking = false }; using var client = SftpClientFactory.Create(options); client.Should().NotBeNull(); } [Fact] public void Create_WithProxy_ReturnsClient() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", ProxyType = SftpProxyType.Socks5, ProxyHost = "proxy.local", ProxyPort = 1080, ProxyUsername = "proxyuser", ProxyPassword = "proxypass" }; using var client = SftpClientFactory.Create(options); client.Should().NotBeNull(); } [Fact] public void Create_WithKeyboardInteractive_ReturnsClient() { var options = new SftpEndpointOptions { Host = "localhost", Port = 2222, Username = "testuser", Password = "secret", UseKeyboardInteractive = true }; using var client = SftpClientFactory.Create(options); client.Should().NotBeNull(); } // ── The options sweep: separator ── [Fact] public void Compression_PrefersZlibInTheNegotiationList() { // The option was declared ("Enable zlib compression on the SSH channel") and read by // nothing: SSH.NET negotiated its default list regardless. var options = new SftpEndpointOptions { Host = "localhost", Username = "u", Password = "p", Compression = true, }; using var client = SftpClientFactory.Create(options); client.ConnectionInfo.CompressionAlgorithms.Keys.First().Should().Be("zlib@openssh.com", "compression=true must put zlib first in the negotiation list"); client.ConnectionInfo.CompressionAlgorithms.Keys.Should().Contain("none", "a server without compression must still negotiate"); } [Fact] public void NoCompression_KeepsTheLibraryDefault() { var options = new SftpEndpointOptions { Host = "localhost", Username = "u", Password = "p" }; using var client = SftpClientFactory.Create(options); client.ConnectionInfo.CompressionAlgorithms.Keys.First().Should().Be("none"); } } /// The separator option shapes remote path building; Auto also normalizes. public sealed class SftpSeparatorTests { private static SftpFileOperations Ops(SftpSeparator separator) => new(new SftpEndpointOptions { Host = "h", Username = "u", Password = "p", Separator = separator }); [Fact] public void Auto_NormalizesBackslashesAndJoinsWithForwardSlash() { var ops = Ops(SftpSeparator.Auto); ops.CombinePath(@"upload\in", @"sub\file.txt").Should().Be("upload/in/sub/file.txt", "Auto must handle Windows separators in the input"); } [Fact] public void Unix_JoinsStrictlyWithForwardSlash() { var ops = Ops(SftpSeparator.Unix); ops.CombinePath("upload/in", "file.txt").Should().Be("upload/in/file.txt"); } [Fact] public void Unix_TakesBackslashesLiterally() { // Unix mode is the byte-for-byte contract: a backslash is a legal character in a UNIX // file name, so it must NOT be treated as a separator (that was the removed Windows // mode's job, and it could never be honest - SFTP's wire separator is always "/"). var ops = Ops(SftpSeparator.Unix); var combined = ops.CombinePath("upload/in", @"weird\name.txt"); combined.Should().Be(@"upload/in/weird\name.txt"); ops.GetFileName(combined).Should().Be(@"weird\name.txt"); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpComponentTests.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.Sftp/SftpComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpComponentTests { [Fact] public void Scheme_IsSftp() { var component = new SftpComponent(); component.Scheme.Should().Be("sftp"); } [Fact] public void CreateEndpoint_ReturnsCorrectType() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new SftpComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_ParsesRemotePath() { var component = new SftpComponent(); var uri = CreateUri("/upload/data", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); endpoint.RemotePath.Should().Be("/upload/data"); } [Fact] public void CreateEndpoint_EmptyPath_DefaultsToRoot() { var component = new SftpComponent(); var uri = CreateUri("", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); endpoint.RemotePath.Should().Be("/"); } [Fact] public void CreateEndpoint_NormalizesDoubleSlashes() { var component = new SftpComponent(); var uri = CreateUri("/upload//data//", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); endpoint.RemotePath.Should().Be("/upload/data"); } [Fact] public void CreateEndpoint_BindsOptionsFromUri() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { ["host"] = "sftp.company.com", ["port"] = "2222", ["username"] = "admin", ["password"] = "secret", ["delay"] = "5000", ["include"] = "*.csv", ["noop"] = "true" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); var opts = endpoint.EndpointOptions; opts.Host.Should().Be("sftp.company.com"); opts.Port.Should().Be(2222); opts.Username.Should().Be("admin"); opts.Password.Should().Be("secret"); opts.Delay.Should().Be(5000); opts.Include.Should().Be("*.csv"); opts.Noop.Should().BeTrue(); } [Fact] public void CreateEndpoint_InvalidOptions_Throws() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { // Missing username and auth ["host"] = "myserver" }); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } [Fact] public void CreateEndpoint_CreatesProducer() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } [Fact] public void CreateEndpoint_CreatesConsumer() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } [Fact] public void CreateEndpoint_NullProcessor_Throws() { var component = new SftpComponent(); var uri = CreateUri("/upload", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_PathWithoutLeadingSlash_Normalized() { var component = new SftpComponent(); var uri = CreateUri("upload", new Dictionary { ["host"] = "myserver", ["username"] = "admin", ["password"] = "secret" }); var endpoint = (SftpEndpoint)component.CreateEndpoint(uri); endpoint.RemotePath.Should().Be("/upload"); } private static EndpointUri CreateUri(string path, Dictionary parameters) { return new EndpointUri("sftp", path, $"sftp://{path}", parameters); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpConnectionFactoryTests.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.Sftp/SftpConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; /// /// SFTP password, private-key passphrase and proxy password must be able to live in the registry /// instead of the endpoint URI, so they never reach logs, telemetry, or the dashboard. /// public sealed class SftpConnectionFactoryTests { private const string Passphrase = "keyPassphr4se"; private const string ProxyPw = "proxyP4ss"; private static SftpComponent Wire(string name, SftpConnectionFactory factory) { var context = new RouteContext(); var component = new SftpComponent(); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesSecrets_WhenUriCarriesNone() { var component = Wire("partner-sftp", new SftpConnectionFactory { Host = "sftp.partner.com", Port = 2222, Username = "svc-drop", PrivateKeyPath = "/etc/redb/keys/partner.pem", PrivateKeyPassphrase = Passphrase, ProxyPassword = ProxyPw }); var uri = EndpointUriParser.Parse("sftp://inbox?connectionFactory=partner-sftp"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Passphrase).And.NotContain(ProxyPw); uri.ToString().Should().NotContain(Passphrase).And.NotContain(ProxyPw); } [Fact] public void ExplicitUriValue_WinsOverFactory() { // Validate() demands a username and at least one auth method — supplied by the factory. var component = Wire("f", new SftpConnectionFactory { Host = "from-factory", Username = "factory-user", Port = 2222, PrivateKeyPath = "/etc/redb/keys/partner.pem" }); var uri = EndpointUriParser.Parse( "sftp://inbox?connectionFactory=f&host=from-uri&username=uri-user"); component.CreateEndpoint(uri).Should().NotBeNull(); uri.RawParameters["host"].Should().Be("from-uri"); uri.RawParameters["username"].Should().Be("uri-user"); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new SftpComponent(); context.AddComponent(component); // Falls back to URI parameters, which must therefore satisfy Validate() on their own. var uri = EndpointUriParser.Parse( "sftp://inbox?connectionFactory=absent&host=direct&username=u&password=p"); var act = () => component.CreateEndpoint(uri); // A typo in connectionFactory must fail loud, not fall back silently act.Should().Throw() .Which.Message.Should().Contain("absent"); } [Fact] public void Dsl_EmitsConnectionFactory() { var uri = redb.Route.Sftp.Sftp.Directory("/inbox").ConnectionFactory("partner-sftp").Build(); uri.Should().Contain("connectionFactory=partner-sftp"); uri.Should().NotContain("privateKeyPassphrase="); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpConsumerHelperTests.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.Sftp/SftpConsumerHelperTests.cs ---- using redb.Route.GenericFile; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpConsumerHelperTests { // ── GlobMatch ─────────────────────────────────────────────────── [Theory] [InlineData("report.csv", "*.csv", true)] [InlineData("report.csv", "*.json", false)] [InlineData("report.csv", "*", true)] [InlineData("report.csv", "report.*", true)] [InlineData("report.csv", "report.csv", true)] [InlineData("REPORT.CSV", "*.csv", true)] // case-insensitive [InlineData("data.json", "*.csv,*.json", true)] // comma-separated [InlineData("readme.txt", "*.csv,*.json", false)] [InlineData("file1.txt", "file?.txt", true)] // ? wildcard [InlineData("file10.txt", "file?.txt", false)] [InlineData(".hidden", ".*", true)] [InlineData("test.backup.csv", "*.csv", true)] [InlineData("test.backup.csv", "test.*.csv", true)] public void GlobMatch_ReturnsExpected(string input, string pattern, bool expected) { GenericFileUtils.GlobMatch(input, pattern).Should().Be(expected); } [Fact] public void GlobMatch_EmptyPattern_MatchesNothing() { // Empty after split gives no patterns GenericFileUtils.GlobMatch("test.csv", "").Should().BeFalse(); } // ── CombinePath ───────────────────────────────────────────────── private readonly SftpFileOperations _ops = new(new SftpEndpointOptions { Host = "test", Username = "test", Password = "test" }); [Theory] [InlineData("/upload", "report.csv", "/upload/report.csv")] [InlineData("/upload/", "report.csv", "/upload/report.csv")] [InlineData("/upload", "/report.csv", "/upload/report.csv")] [InlineData("/", "report.csv", "/report.csv")] [InlineData("", "report.csv", "/report.csv")] [InlineData("/upload", "", "/upload")] [InlineData("/upload/data", "sub/file.txt", "/upload/data/sub/file.txt")] public void CombinePath_ReturnsExpected(string basePath, string relativePath, string expected) { _ops.CombinePath(basePath, relativePath).Should().Be(expected); } // ── EnsureRemoteDirectoryExists ───────────────────────────────── [Fact] public void EnsureRemoteDirectoryExists_CalledWithNullClient_Throws() { var act = () => SftpFileOperations.EnsureRemoteDirectoryExists(null!, "/test"); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpEndpointOptionsTests.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.Sftp/SftpEndpointOptionsTests.cs ---- using redb.Route.GenericFile; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpEndpointOptionsTests { // ── Defaults ──────────────────────────────────────────────────── [Fact] public void Defaults_Connection_AreCorrect() { var opts = new SftpEndpointOptions(); opts.Host.Should().Be("localhost"); opts.Port.Should().Be(22); opts.Username.Should().BeEmpty(); opts.Password.Should().BeEmpty(); opts.PrivateKeyPath.Should().BeEmpty(); opts.PrivateKeyPassphrase.Should().BeEmpty(); opts.UseKeyboardInteractive.Should().BeFalse(); opts.PreferredAuthentications.Should().BeEmpty(); opts.ServerFingerprint.Should().BeEmpty(); opts.StrictHostKeyChecking.Should().BeFalse(); opts.KnownHostsFile.Should().BeEmpty(); opts.ConnectionTimeout.Should().Be(30_000); opts.OperationTimeout.Should().Be(60_000); opts.KeepAliveInterval.Should().Be(0); opts.BufferSize.Should().Be(32_768); opts.Compression.Should().BeFalse(); } [Fact] public void Defaults_Proxy_AreCorrect() { var opts = new SftpEndpointOptions(); opts.ProxyType.Should().Be(SftpProxyType.None); opts.ProxyHost.Should().BeEmpty(); opts.ProxyPort.Should().Be(1080); opts.ProxyUsername.Should().BeEmpty(); opts.ProxyPassword.Should().BeEmpty(); } [Fact] public void Defaults_Reconnection_AreCorrect() { var opts = new SftpEndpointOptions(); opts.MaximumReconnectAttempts.Should().Be(3); opts.ReconnectDelay.Should().Be(1000); opts.Disconnect.Should().BeFalse(); } [Fact] public void Defaults_Consumer_AreCorrect() { var opts = new SftpEndpointOptions(); opts.Delay.Should().Be(60_000); opts.InitialDelay.Should().Be(1000); opts.Include.Should().BeEmpty(); opts.Exclude.Should().BeEmpty(); opts.Recursive.Should().BeFalse(); opts.MaxDepth.Should().Be(0); opts.MinDepth.Should().Be(0); opts.SortBy.Should().Be(GenericFileSortBy.None); opts.MaxMessagesPerPoll.Should().Be(0); opts.MinAge.Should().Be(0); opts.MaxAge.Should().Be(0); opts.Noop.Should().BeFalse(); opts.Delete.Should().BeFalse(); opts.MoveTo.Should().BeEmpty(); opts.MoveExisting.Should().Be(GenericFileExistStrategy.Override); opts.PreMove.Should().BeEmpty(); opts.MoveFailed.Should().BeEmpty(); opts.Idempotent.Should().BeFalse(); opts.IdempotentKey.Should().BeEmpty(); opts.DoneFileName.Should().BeEmpty(); // Binary and StepWise removed in the options sweep: SFTP has no text mode and no cd opts.Charset.Should().Be("utf-8"); opts.Separator.Should().Be(SftpSeparator.Auto); opts.IgnoreFileNotFoundOrPermissionError.Should().BeFalse(); opts.StartingDirectoryMustExist.Should().BeTrue(); opts.DirectoryMustExist.Should().BeFalse(); opts.SendEmptyMessageWhenIdle.Should().BeFalse(); } [Fact] public void Defaults_Producer_AreCorrect() { var opts = new SftpEndpointOptions(); opts.FileName.Should().BeNull(); opts.FileExist.Should().Be(GenericFileExistStrategy.Override); opts.MoveExistingFileStrategy.Should().Be(SftpMoveExistingStrategy.Timestamp); opts.TempPrefix.Should().BeEmpty(); opts.TempFileName.Should().BeEmpty(); opts.Chmod.Should().BeEmpty(); opts.ChmodDirectory.Should().BeEmpty(); opts.AutoCreate.Should().BeTrue(); opts.AllowNullBody.Should().BeFalse(); opts.EagerDeleteTargetFile.Should().BeTrue(); opts.KeepLastModified.Should().BeFalse(); opts.Flatten.Should().BeFalse(); opts.JailStartingDirectory.Should().BeTrue(); opts.AppendChars.Should().BeEmpty(); } // ── Validation passes ─────────────────────────────────────────── [Fact] public void Validate_MinimalValidOptions_Succeeds() { var opts = new SftpEndpointOptions { Host = "myserver", Username = "admin", Password = "secret" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_PrivateKeyAuth_Succeeds() { var opts = new SftpEndpointOptions { Host = "myserver", Username = "admin", PrivateKeyPath = "/home/user/.ssh/id_rsa" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_BothAuthMethods_Succeeds() { var opts = new SftpEndpointOptions { Host = "myserver", Username = "admin", Password = "pass", PrivateKeyPath = "/key" }; var act = () => opts.Validate(); act.Should().NotThrow(); } // ── Connection validation ─────────────────────────────────────── [Fact] public void Validate_EmptyHost_Throws() { var opts = new SftpEndpointOptions { Host = "", Username = "u", Password = "p" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Host*"); } [Fact] public void Validate_WhitespaceHost_Throws() { var opts = new SftpEndpointOptions { Host = " ", Username = "u", Password = "p" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Host*"); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(65536)] [InlineData(100000)] public void Validate_InvalidPort_Throws(int port) { var opts = new SftpEndpointOptions { Host = "h", Port = port, Username = "u", Password = "p" }; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("Port"); } [Theory] [InlineData(1)] [InlineData(22)] [InlineData(2222)] [InlineData(65535)] public void Validate_ValidPort_Succeeds(int port) { var opts = new SftpEndpointOptions { Host = "h", Port = port, Username = "u", Password = "p" }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_EmptyUsername_Throws() { var opts = new SftpEndpointOptions { Host = "h", Username = "", Password = "p" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Username*"); } [Fact] public void Validate_NoAuthMethod_Throws() { var opts = new SftpEndpointOptions { Host = "h", Username = "u", Password = "", PrivateKeyPath = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*authentication*"); } // ── Consumer validation ───────────────────────────────────────── [Fact] public void Validate_NegativeDelay_Throws() { var opts = ValidOptions(); opts.Delay = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("Delay"); } [Fact] public void Validate_NegativeInitialDelay_Throws() { var opts = ValidOptions(); opts.InitialDelay = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("InitialDelay"); } [Fact] public void Validate_NoopAndDelete_Throws() { var opts = ValidOptions(); opts.Noop = true; opts.Delete = true; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Noop*Delete*"); } [Fact] public void Validate_NoopAndMoveTo_Throws() { var opts = ValidOptions(); opts.Noop = true; opts.MoveTo = ".done"; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Noop*MoveTo*"); } [Fact] public void Validate_DeleteAndMoveTo_Throws() { var opts = ValidOptions(); opts.Delete = true; opts.MoveTo = ".done"; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Delete*MoveTo*"); } [Fact] public void Validate_NegativeMaxMessagesPerPoll_Throws() { var opts = ValidOptions(); opts.MaxMessagesPerPoll = -5; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MaxMessagesPerPoll"); } [Fact] public void Validate_NegativeMaxDepth_Throws() { var opts = ValidOptions(); opts.MaxDepth = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MaxDepth"); } [Fact] public void Validate_NegativeMinDepth_Throws() { var opts = ValidOptions(); opts.MinDepth = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MinDepth"); } [Fact] public void Validate_NegativeMinAge_Throws() { var opts = ValidOptions(); opts.MinAge = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MinAge"); } [Fact] public void Validate_NegativeMaxAge_Throws() { var opts = ValidOptions(); opts.MaxAge = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MaxAge"); } // ── Timeout validation ────────────────────────────────────────── [Fact] public void Validate_NegativeConnectionTimeout_Throws() { var opts = ValidOptions(); opts.ConnectionTimeout = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("ConnectionTimeout"); } [Fact] public void Validate_NegativeOperationTimeout_Throws() { var opts = ValidOptions(); opts.OperationTimeout = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("OperationTimeout"); } // ── Buffer validation ─────────────────────────────────────────── [Theory] [InlineData(0)] [InlineData(512)] [InlineData(1023)] public void Validate_BufferSizeTooSmall_Throws(int size) { var opts = ValidOptions(); opts.BufferSize = size; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("BufferSize"); } [Fact] public void Validate_BufferSizeMinimum_Succeeds() { var opts = ValidOptions(); opts.BufferSize = 1024; var act = () => opts.Validate(); act.Should().NotThrow(); } // ── Reconnection validation ───────────────────────────────────── [Fact] public void Validate_NegativeMaxReconnectAttempts_Throws() { var opts = ValidOptions(); opts.MaximumReconnectAttempts = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("MaximumReconnectAttempts"); } [Fact] public void Validate_NegativeReconnectDelay_Throws() { var opts = ValidOptions(); opts.ReconnectDelay = -1; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("ReconnectDelay"); } // ── Proxy validation ──────────────────────────────────────────── [Theory] [InlineData(SftpProxyType.Socks4)] [InlineData(SftpProxyType.Socks5)] [InlineData(SftpProxyType.Http)] public void Validate_ProxyTypeWithoutHost_Throws(SftpProxyType proxyType) { var opts = ValidOptions(); opts.ProxyType = proxyType; opts.ProxyHost = ""; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*ProxyHost*"); } [Fact] public void Validate_ProxyNoneWithoutHost_Succeeds() { var opts = ValidOptions(); opts.ProxyType = SftpProxyType.None; opts.ProxyHost = ""; var act = () => opts.Validate(); act.Should().NotThrow(); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(65536)] public void Validate_InvalidProxyPort_Throws(int port) { var opts = ValidOptions(); opts.ProxyPort = port; var act = () => opts.Validate(); act.Should().Throw().Which.ParamName.Should().Be("ProxyPort"); } // ── Chmod validation ──────────────────────────────────────────── [Theory] [InlineData("0644")] [InlineData("0755")] [InlineData("0777")] [InlineData("0600")] [InlineData("0000")] public void Validate_ValidChmod_Succeeds(string chmod) { var opts = ValidOptions(); opts.Chmod = chmod; var act = () => opts.Validate(); act.Should().NotThrow(); } [Theory] [InlineData("abc")] [InlineData("9999")] [InlineData("0888")] [InlineData("rwxr-xr-x")] public void Validate_InvalidChmod_Throws(string chmod) { var opts = ValidOptions(); opts.Chmod = chmod; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Chmod*"); } [Theory] [InlineData("0755")] [InlineData("0700")] public void Validate_ValidChmodDirectory_Succeeds(string chmod) { var opts = ValidOptions(); opts.ChmodDirectory = chmod; var act = () => opts.Validate(); act.Should().NotThrow(); } [Theory] [InlineData("xyz")] [InlineData("0888")] public void Validate_InvalidChmodDirectory_Throws(string chmod) { var opts = ValidOptions(); opts.ChmodDirectory = chmod; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*ChmodDirectory*"); } // ── ParseOctalPermissions ─────────────────────────────────────── [Theory] [InlineData("0644", 0x1A4)] // 420 decimal [InlineData("0755", 0x1ED)] // 493 decimal [InlineData("0777", 0x1FF)] // 511 decimal [InlineData("0600", 0x180)] // 384 decimal public void ParseOctalPermissions_ReturnsCorrectValue(string octal, short expected) { SftpEndpointOptions.ParseOctalPermissions(octal).Should().Be(expected); } // ── Post-processing combinations ──────────────────────────────── [Fact] public void Validate_NoopOnly_Succeeds() { var opts = ValidOptions(); opts.Noop = true; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_DeleteOnly_Succeeds() { var opts = ValidOptions(); opts.Delete = true; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_MoveToOnly_Succeeds() { var opts = ValidOptions(); opts.MoveTo = ".done"; var act = () => opts.Validate(); act.Should().NotThrow(); } // ── BindFromUri ───────────────────────────────────────────────── [Fact] public void BindFromUri_SetsConnectionOptions() { var opts = new SftpEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "myserver.com", ["port"] = "2222", ["username"] = "admin", ["password"] = "secret123", ["connectionTimeout"] = "5000", ["operationTimeout"] = "10000", ["keepAliveInterval"] = "3000", ["bufferSize"] = "65536", ["strictHostKeyChecking"] = "true", ["serverFingerprint"] = "AA:BB:CC" }); opts.Host.Should().Be("myserver.com"); opts.Port.Should().Be(2222); opts.Username.Should().Be("admin"); opts.Password.Should().Be("secret123"); opts.ConnectionTimeout.Should().Be(5000); opts.OperationTimeout.Should().Be(10000); opts.KeepAliveInterval.Should().Be(3000); opts.BufferSize.Should().Be(65536); opts.StrictHostKeyChecking.Should().BeTrue(); opts.ServerFingerprint.Should().Be("AA:BB:CC"); } [Fact] public void BindFromUri_SetsConsumerOptions() { var opts = new SftpEndpointOptions(); opts.BindFromUri(new Dictionary { ["delay"] = "5000", ["initialDelay"] = "2000", ["include"] = "*.csv", ["exclude"] = "*.tmp", ["recursive"] = "true", ["maxDepth"] = "3", ["sortBy"] = "Name", ["maxMessagesPerPoll"] = "10", ["minAge"] = "5000", ["maxAge"] = "60000", ["noop"] = "true", ["idempotent"] = "true", ["doneFileName"] = "${file:name}.done", ["sendEmptyMessageWhenIdle"] = "true" }); opts.Delay.Should().Be(5000); opts.InitialDelay.Should().Be(2000); opts.Include.Should().Be("*.csv"); opts.Exclude.Should().Be("*.tmp"); opts.Recursive.Should().BeTrue(); opts.MaxDepth.Should().Be(3); opts.SortBy.Should().Be(GenericFileSortBy.Name); opts.MaxMessagesPerPoll.Should().Be(10); opts.MinAge.Should().Be(5000); opts.MaxAge.Should().Be(60000); opts.Noop.Should().BeTrue(); opts.Idempotent.Should().BeTrue(); opts.DoneFileName.Should().Be("${file:name}.done"); opts.SendEmptyMessageWhenIdle.Should().BeTrue(); } [Fact] public void BindFromUri_SetsProducerOptions() { var opts = new SftpEndpointOptions(); opts.BindFromUri(new Dictionary { ["fileExist"] = "Fail", ["tempPrefix"] = ".redb_", ["chmod"] = "0644", ["chmodDirectory"] = "0755", ["autoCreate"] = "true", ["allowNullBody"] = "true", ["eagerDeleteTargetFile"] = "false", ["keepLastModified"] = "true", ["flatten"] = "true", ["jailStartingDirectory"] = "false" }); opts.FileExist.Should().Be(GenericFileExistStrategy.Fail); opts.TempPrefix.Should().Be(".redb_"); opts.Chmod.Should().Be("0644"); opts.ChmodDirectory.Should().Be("0755"); opts.AutoCreate.Should().BeTrue(); opts.AllowNullBody.Should().BeTrue(); opts.EagerDeleteTargetFile.Should().BeFalse(); opts.KeepLastModified.Should().BeTrue(); opts.Flatten.Should().BeTrue(); opts.JailStartingDirectory.Should().BeFalse(); } [Fact] public void BindFromUri_SetsProxyOptions() { var opts = new SftpEndpointOptions(); opts.BindFromUri(new Dictionary { ["proxyType"] = "Socks5", ["proxyHost"] = "proxy.corp.com", ["proxyPort"] = "8080", ["proxyUsername"] = "proxy_user", ["proxyPassword"] = "proxy_pass" }); opts.ProxyType.Should().Be(SftpProxyType.Socks5); opts.ProxyHost.Should().Be("proxy.corp.com"); opts.ProxyPort.Should().Be(8080); opts.ProxyUsername.Should().Be("proxy_user"); opts.ProxyPassword.Should().Be("proxy_pass"); } [Fact] public void BindFromUri_SetsReconnectionOptions() { var opts = new SftpEndpointOptions(); opts.BindFromUri(new Dictionary { ["maximumReconnectAttempts"] = "5", ["reconnectDelay"] = "2000", ["disconnect"] = "true" }); opts.MaximumReconnectAttempts.Should().Be(5); opts.ReconnectDelay.Should().Be(2000); opts.Disconnect.Should().BeTrue(); } // ── Helper ────────────────────────────────────────────────────── private static SftpEndpointOptions ValidOptions() => new() { Host = "myserver", Username = "admin", Password = "secret" }; } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpEnumsTests.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.Sftp/SftpEnumsTests.cs ---- using redb.Route.GenericFile; using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpEnumsTests { [Fact] public void GenericFileExistStrategy_HasExpectedValues() { Enum.GetNames().Should() .BeEquivalentTo("Override", "Append", "Fail", "Ignore", "Move", "TryRename"); } [Fact] public void GenericFileSortBy_HasExpectedValues() { Enum.GetNames().Should() .BeEquivalentTo("None", "Name", "NameDesc", "Modified", "ModifiedDesc", "Size", "SizeDesc"); } [Fact] public void SftpProxyType_HasExpectedValues() { Enum.GetNames().Should() .BeEquivalentTo("None", "Socks4", "Socks5", "Http"); } [Fact] public void SftpMoveExistingStrategy_HasExpectedValues() { Enum.GetNames().Should() .BeEquivalentTo("Backup", "Timestamp", "Guid"); } [Fact] public void SftpSeparator_HasExpectedValues() { // No Windows: SFTP's wire separator is always "/" (removed like Binary/StepWise). Enum.GetNames().Should() .BeEquivalentTo("Auto", "Unix"); } [Theory] [InlineData(GenericFileExistStrategy.Override, 0)] [InlineData(GenericFileExistStrategy.Append, 1)] [InlineData(GenericFileExistStrategy.Fail, 2)] [InlineData(GenericFileExistStrategy.Ignore, 3)] [InlineData(GenericFileExistStrategy.Move, 4)] [InlineData(GenericFileExistStrategy.TryRename, 5)] public void GenericFileExistStrategy_IntValues_AreStable(GenericFileExistStrategy strategy, int expected) { ((int)strategy).Should().Be(expected); } [Theory] [InlineData(GenericFileSortBy.None, 0)] [InlineData(GenericFileSortBy.Name, 1)] [InlineData(GenericFileSortBy.NameDesc, 2)] [InlineData(GenericFileSortBy.Modified, 3)] [InlineData(GenericFileSortBy.ModifiedDesc, 4)] [InlineData(GenericFileSortBy.Size, 5)] [InlineData(GenericFileSortBy.SizeDesc, 6)] public void GenericFileSortBy_IntValues_AreStable(GenericFileSortBy sort, int expected) { ((int)sort).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpHeadersTests.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.Sftp/SftpHeadersTests.cs ---- using redb.Route.Sftp; namespace redb.Route.Tests.Sftp; public sealed class SftpHeadersTests { [Fact] public void AllHeaders_HaveCorrectPrefix() { var headerFields = typeof(SftpHeaders) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(f => f.FieldType == typeof(string) && f.Name != nameof(SftpHeaders.Prefix)) .ToList(); headerFields.Should().NotBeEmpty(); foreach (var field in headerFields) { var val = (string)field.GetValue(null)!; val.Should().StartWith(SftpHeaders.Prefix, $"header {field.Name} should start with '{SftpHeaders.Prefix}'"); } } [Fact] public void Prefix_IsCorrect() { SftpHeaders.Prefix.Should().Be("redbSftp."); } [Fact] public void AllHeaders_AreUnique() { var headerFields = typeof(SftpHeaders) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(f => f.FieldType == typeof(string)) .Select(f => (string)f.GetValue(null)!) .ToList(); headerFields.Should().OnlyHaveUniqueItems(); } [Fact] public void KnownConsumerHeaders_ExistAndCorrect() { SftpHeaders.FileName.Should().Be("redbSftp.Name"); SftpHeaders.FileNameOnly.Should().Be("redbSftp.NameOnly"); SftpHeaders.FileExtension.Should().Be("redbSftp.Extension"); SftpHeaders.RemotePath.Should().Be("redbSftp.RemotePath"); SftpHeaders.RelativePath.Should().Be("redbSftp.RelativePath"); SftpHeaders.RemoteParent.Should().Be("redbSftp.RemoteParent"); SftpHeaders.FileLength.Should().Be("redbSftp.Length"); SftpHeaders.FileLastModified.Should().Be("redbSftp.LastModified"); SftpHeaders.FilePermissions.Should().Be("redbSftp.Permissions"); SftpHeaders.FileOwner.Should().Be("redbSftp.Owner"); SftpHeaders.FileGroup.Should().Be("redbSftp.Group"); SftpHeaders.Host.Should().Be("redbSftp.Host"); SftpHeaders.Port.Should().Be("redbSftp.Port"); SftpHeaders.Username.Should().Be("redbSftp.Username"); } [Fact] public void KnownProducerHeaders_ExistAndCorrect() { SftpHeaders.FileNameProduced.Should().Be("redbSftp.NameProduced"); } [Fact] public void HeaderCount_IsExpected() { var count = typeof(SftpHeaders) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Count(f => f.FieldType == typeof(string)); // Prefix + 15 consumer/producer headers = 16 count.Should().Be(16); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpIntegrationTests.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.Sftp/SftpIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sftp; using Xunit.Abstractions; namespace redb.Route.Tests.Sftp; /// /// Integration tests against atmoz/sftp docker container. /// Expects SFTP at localhost:2222 (testuser/secret, writable dir: /upload). /// Start with: docker compose -f docker-compose.tests.yml up sftp -d /// [Trait("Category", "Integration")] public sealed class SftpIntegrationTests { private const string Host = "localhost"; private const int Port = 2222; private const string Username = "testuser"; private const string Password = "secret"; private const string BaseDir = "upload"; private readonly ITestOutputHelper _output; public SftpIntegrationTests(ITestOutputHelper output) => _output = output; // ───── Helpers ───── private static string UniqueDir() => $"test-{Guid.NewGuid():N}"; private static string UniqueFile() => $"{Guid.NewGuid():N}.txt"; private SftpEndpoint CreateEndpoint(string remotePath, string? extraParams = null) { var qs = $"host={Host}&port={Port}&username={Username}&password={Password}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"sftp:///{remotePath}?{qs}"); return (SftpEndpoint)new SftpComponent().CreateEndpoint(uri); } private Renci.SshNet.SftpClient CreateRawClient() { var client = new Renci.SshNet.SftpClient(Host, Port, Username, Password); client.HostKeyReceived += (_, e) => e.CanTrust = true; client.Connect(); return client; } private void CleanupDir(Renci.SshNet.SftpClient client, string path) { if (!client.Exists(path)) return; foreach (var entry in client.ListDirectory(path)) { if (entry.Name is "." or "..") continue; if (entry.IsDirectory) CleanupDir(client, entry.FullName); else client.DeleteFile(entry.FullName); } client.DeleteDirectory(path); } // ───── Producer Tests ───── [Fact] public async Task Producer_UploadsTextFile() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; _output.WriteLine($"Remote: {remotePath}"); var ep = CreateEndpoint(remotePath, "autoCreate=true"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("Hello SFTP!")); exchange.In.Headers[SftpHeaders.FileName] = "hello.txt"; await producer.Process(exchange); await producer.Stop(); exchange.In.Headers[SftpHeaders.FileNameProduced].Should().NotBeNull(); // Verify via raw client using var client = CreateRawClient(); var filePath = $"/{remotePath}/hello.txt"; client.Exists(filePath).Should().BeTrue(); var content = Encoding.UTF8.GetString(client.ReadAllBytes(filePath)); content.Should().Be("Hello SFTP!"); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_UploadsBinaryFile() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var data = new byte[] { 0x00, 0x01, 0xFF, 0xFE, 0x42, 0x43 }; var exchange = new Exchange(new Message { Body = data }); exchange.In.Headers[SftpHeaders.FileName] = "binary.bin"; await producer.Process(exchange); await producer.Stop(); using var client = CreateRawClient(); var filePath = $"/{remotePath}/binary.bin"; var downloaded = client.ReadAllBytes(filePath); downloaded.Should().BeEquivalentTo(data); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_WithTempPrefix_AtomicUpload() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&tempPrefix=.tmp."); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("atomic content")); exchange.In.Headers[SftpHeaders.FileName] = "atomic.txt"; await producer.Process(exchange); await producer.Stop(); // Verify final file exists, temp file does not using var client = CreateRawClient(); var fullDir = $"/{remotePath}"; client.Exists($"{fullDir}/atomic.txt").Should().BeTrue(); client.Exists($"{fullDir}/.tmp.atomic.txt").Should().BeFalse(); var content = Encoding.UTF8.GetString(client.ReadAllBytes($"{fullDir}/atomic.txt")); content.Should().Be("atomic content"); CleanupDir(client, fullDir); } [Fact] public async Task Producer_FileExistFail_Throws() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&fileExist=Fail"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); // Upload first time var exchange1 = new Exchange(new Message("first")); exchange1.In.Headers[SftpHeaders.FileName] = "fail-test.txt"; await producer.Process(exchange1); // Upload same file again — should fail var exchange2 = new Exchange(new Message("second")); exchange2.In.Headers[SftpHeaders.FileName] = "fail-test.txt"; var act = () => producer.Process(exchange2); await act.Should().ThrowAsync(); await producer.Stop(); using var client = CreateRawClient(); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_FileExistIgnore_Skips() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&fileExist=Ignore"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange1 = new Exchange(new Message("original")); exchange1.In.Headers[SftpHeaders.FileName] = "ignore-test.txt"; await producer.Process(exchange1); // Upload again with different content — should be ignored var exchange2 = new Exchange(new Message("updated")); exchange2.In.Headers[SftpHeaders.FileName] = "ignore-test.txt"; await producer.Process(exchange2); await producer.Stop(); // Content should still be original using var client = CreateRawClient(); var content = Encoding.UTF8.GetString( client.ReadAllBytes($"/{remotePath}/ignore-test.txt")); content.Should().Be("original"); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_FileExistOverride_Overwrites() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&fileExist=Override"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange1 = new Exchange(new Message("original")); exchange1.In.Headers[SftpHeaders.FileName] = "override-test.txt"; await producer.Process(exchange1); var exchange2 = new Exchange(new Message("updated")); exchange2.In.Headers[SftpHeaders.FileName] = "override-test.txt"; await producer.Process(exchange2); await producer.Stop(); using var client = CreateRawClient(); var content = Encoding.UTF8.GetString( client.ReadAllBytes($"/{remotePath}/override-test.txt")); content.Should().Be("updated"); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_AutoCreate_CreatesNestedDirs() { var dir = $"{UniqueDir()}/nested/deep"; var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("nested file")); exchange.In.Headers[SftpHeaders.FileName] = "deep.txt"; await producer.Process(exchange); await producer.Stop(); using var client = CreateRawClient(); client.Exists($"/{remotePath}/deep.txt").Should().BeTrue(); // Cleanup from the root test dir CleanupDir(client, $"/{BaseDir}/{dir.Split('/')[0]}"); } // ───── Consumer Tests ───── [Fact] public async Task Consumer_ReceivesUploadedFile() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; _output.WriteLine($"Remote: {remotePath}"); // Seed a file via raw client using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("consumer test"))) rawClient.UploadFile(ms, $"{fullDir}/data.txt"); // Consume via SftpConsumer var ep = CreateEndpoint(remotePath, "noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); var rx = received.First(); rx.In.Headers[SftpHeaders.FileName].Should().Be("data.txt"); rx.In.Headers[SftpHeaders.FileNameOnly].Should().Be("data"); rx.In.Headers[SftpHeaders.FileExtension].Should().Be(".txt"); rx.In.Headers[SftpHeaders.Host].Should().Be(Host); rx.In.Headers[SftpHeaders.Port].Should().Be(Port); rx.In.Headers[SftpHeaders.Username].Should().Be(Username); ((long)rx.In.Headers[SftpHeaders.FileLength]!).Should().BeGreaterThan(0); var body = (byte[])rx.In.Body!; Encoding.UTF8.GetString(body).Should().Be("consumer test"); consumer.ProcessedCount.Should().Be(1); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_Delete_RemovesFileAfterProcessing() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("delete me"))) rawClient.UploadFile(ms, $"{fullDir}/deletable.txt"); var ep = CreateEndpoint(remotePath, "delete=true&delay=500&initialDelay=100"); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); // File should be deleted rawClient.Exists($"{fullDir}/deletable.txt").Should().BeFalse(); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_MoveTo_MovesFileAfterProcessing() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("move me"))) rawClient.UploadFile(ms, $"{fullDir}/movable.txt"); var ep = CreateEndpoint(remotePath, "moveTo=.done&delay=500&initialDelay=100"); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); // File should be in .done subdirectory rawClient.Exists($"{fullDir}/movable.txt").Should().BeFalse(); rawClient.Exists($"{fullDir}/.done/movable.txt").Should().BeTrue(); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_IncludeFilter_OnlyMatchingFiles() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("csv"))) rawClient.UploadFile(ms, $"{fullDir}/report.csv"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("txt"))) rawClient.UploadFile(ms, $"{fullDir}/readme.txt"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("csv2"))) rawClient.UploadFile(ms, $"{fullDir}/data.csv"); var ep = CreateEndpoint(remotePath, "include=*.csv&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(2); received.Select(r => (string)r.In.Headers[SftpHeaders.FileName]!) .Should().BeEquivalentTo(["report.csv", "data.csv"]); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_ExcludeFilter_SkipsMatchingFiles() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("keep"))) rawClient.UploadFile(ms, $"{fullDir}/keep.txt"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("skip"))) rawClient.UploadFile(ms, $"{fullDir}/skip.log"); var ep = CreateEndpoint(remotePath, "exclude=*.log&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); ((string)received.First().In.Headers[SftpHeaders.FileName]!).Should().Be("keep.txt"); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_Recursive_ReadsSubdirectories() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); rawClient.CreateDirectory($"{fullDir}/sub"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("root"))) rawClient.UploadFile(ms, $"{fullDir}/root.txt"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("child"))) rawClient.UploadFile(ms, $"{fullDir}/sub/child.txt"); var ep = CreateEndpoint(remotePath, "recursive=true&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(2); received.Select(r => (string)r.In.Headers[SftpHeaders.FileName]!) .Should().BeEquivalentTo(["root.txt", "child.txt"]); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_MaxMessagesPerPoll_LimitsFiles() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); for (int i = 0; i < 5; i++) using (var ms = new MemoryStream(Encoding.UTF8.GetBytes($"file-{i}"))) rawClient.UploadFile(ms, $"{fullDir}/file-{i}.txt"); var ep = CreateEndpoint(remotePath, "maxMessagesPerPoll=2&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(10_000)); // Stop quickly after first poll await Task.Delay(200); await consumer.Stop(); // First poll should have exactly 2 // (noop=true, so next poll would pick same files) received.Count.Should().BeGreaterThanOrEqualTo(2); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_Idempotent_NoReprocessing() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("idempotent data"))) rawClient.UploadFile(ms, $"{fullDir}/stable.txt"); var ep = CreateEndpoint(remotePath, "idempotent=true&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(10_000)); // Wait for a couple more poll cycles await Task.Delay(2000); await consumer.Stop(); // Should still be only 1 — idempotent prevents reprocessing received.Should().HaveCount(1); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_EmptyDirectory_NoMessages() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); rawClient.CreateDirectory($"/{remotePath}"); var ep = CreateEndpoint(remotePath, "noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.Delay(2000); await consumer.Stop(); received.Should().BeEmpty(); CleanupDir(rawClient, $"/{remotePath}"); } [Fact] public async Task Consumer_SortByName_OrderedOutput() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); // Upload in random order foreach (var name in new[] { "charlie.txt", "alpha.txt", "bravo.txt" }) using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(name))) rawClient.UploadFile(ms, $"{fullDir}/{name}"); var ep = CreateEndpoint(remotePath, "sortBy=Name&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 3) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(3); // Files processed in name order var names = received.Select(r => (string)r.In.Headers[SftpHeaders.FileName]!) .ToList(); names.Should().BeEquivalentTo(["alpha.txt", "bravo.txt", "charlie.txt"]); CleanupDir(rawClient, fullDir); } // ───── Roundtrip Tests ───── [Fact] public async Task Producer_To_Consumer_FullRoundtrip() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; _output.WriteLine($"Roundtrip dir: {remotePath}"); // Upload via producer var prodEp = CreateEndpoint(remotePath, "autoCreate=true"); var producer = (SftpProducer)prodEp.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("roundtrip content")); exchange.In.Headers[SftpHeaders.FileName] = "roundtrip.txt"; await producer.Process(exchange); await producer.Stop(); // Consume via consumer var consEp = CreateEndpoint(remotePath, "delete=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)consEp.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); var rx = received.First(); rx.In.Headers[SftpHeaders.FileName].Should().Be("roundtrip.txt"); var body = Encoding.UTF8.GetString((byte[])rx.In.Body!); body.Should().Be("roundtrip content"); // File deleted after processing using var rawClient = CreateRawClient(); rawClient.Exists($"/{remotePath}/roundtrip.txt").Should().BeFalse(); CleanupDir(rawClient, $"/{remotePath}"); } [Fact] public async Task Producer_To_Consumer_MultipleFiles() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; const int fileCount = 5; // Upload multiple files via producer var prodEp = CreateEndpoint(remotePath, "autoCreate=true"); var producer = (SftpProducer)prodEp.CreateProducer(); await producer.Start(); for (int i = 0; i < fileCount; i++) { var ex = new Exchange(new Message($"content-{i}")); ex.In.Headers[SftpHeaders.FileName] = $"file-{i}.txt"; await producer.Process(ex); } await producer.Stop(); // Consume all files var consEp = CreateEndpoint(remotePath, "noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var allDone = new TaskCompletionSource(); var counter = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= fileCount) allDone.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)consEp.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allDone.Task, Task.Delay(15_000)); await consumer.Stop(); received.Count.Should().BeGreaterThanOrEqualTo(fileCount); using var rawClient = CreateRawClient(); CleanupDir(rawClient, $"/{remotePath}"); } [Fact] public async Task Producer_NullBody_WithAllowNullBody_UploadsEmptyFile() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&allowNullBody=true"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = null }); exchange.In.Headers[SftpHeaders.FileName] = "empty.txt"; await producer.Process(exchange); await producer.Stop(); using var client = CreateRawClient(); var filePath = $"/{remotePath}/empty.txt"; client.Exists(filePath).Should().BeTrue(); client.ReadAllBytes(filePath).Length.Should().Be(0); CleanupDir(client, $"/{remotePath}"); } [Fact] public async Task Producer_NullBody_WithoutAllowNullBody_Throws() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&allowNullBody=false"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message { Body = null }); exchange.In.Headers[SftpHeaders.FileName] = "null.txt"; var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*AllowNullBody*"); await producer.Stop(); } [Fact] public async Task Producer_FileExistMove_BacksUpExisting() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var ep = CreateEndpoint(remotePath, "autoCreate=true&fileExist=Move&moveExistingFileStrategy=Backup"); var producer = (SftpProducer)ep.CreateProducer(); await producer.Start(); // Upload first time var ex1 = new Exchange(new Message("v1")); ex1.In.Headers[SftpHeaders.FileName] = "versioned.txt"; await producer.Process(ex1); // Upload again — should move existing to .bak var ex2 = new Exchange(new Message("v2")); ex2.In.Headers[SftpHeaders.FileName] = "versioned.txt"; await producer.Process(ex2); await producer.Stop(); using var client = CreateRawClient(); var fullDir = $"/{remotePath}"; client.Exists($"{fullDir}/versioned.txt").Should().BeTrue(); var content = Encoding.UTF8.GetString(client.ReadAllBytes($"{fullDir}/versioned.txt")); content.Should().Be("v2"); // Backup should exist var files = client.ListDirectory(fullDir) .Where(f => f.Name.StartsWith("versioned.txt.bak")).ToList(); files.Should().HaveCount(1); CleanupDir(client, fullDir); } [Fact] public async Task Consumer_PreMove_MovesBeforeProcessing() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("pre-move data"))) rawClient.UploadFile(ms, $"{fullDir}/source.txt"); // preMove=.inprogress will move file to .inprogress dir before processing var ep = CreateEndpoint(remotePath, "preMove=.inprogress&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); // Original file should not be in source location rawClient.Exists($"{fullDir}/source.txt").Should().BeFalse(); // Should be in .inprogress (noop = leave file after processing at its current location) rawClient.Exists($"{fullDir}/.inprogress/source.txt").Should().BeTrue(); CleanupDir(rawClient, fullDir); } // ───── StreamBody Tests ───── [Fact] public async Task Consumer_StreamBody_ReceivesStream() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("stream content"))) rawClient.UploadFile(ms, $"{fullDir}/streamed.txt"); var ep = CreateEndpoint(remotePath, "streamBody=true&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); var rx = received.First(); rx.In.Body.Should().BeAssignableTo(); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_StreamBody_DataCorrect() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; var expectedContent = "hello from sftp stream"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(expectedContent))) rawClient.UploadFile(ms, $"{fullDir}/readable.txt"); var ep = CreateEndpoint(remotePath, "streamBody=true&noop=true&delay=500&initialDelay=100"); string? readContent = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var exchange = ci.ArgAt(0); var stream = (Stream)exchange.In.Body!; using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); readContent = await reader.ReadToEndAsync(); tcs.TrySetResult(); }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); readContent.Should().Be(expectedContent); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_StreamBody_HeadersPopulated() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("headers test"))) rawClient.UploadFile(ms, $"{fullDir}/meta.txt"); var ep = CreateEndpoint(remotePath, "streamBody=true&noop=true&delay=500&initialDelay=100"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); received.Should().HaveCount(1); var rx = received.First(); rx.In.Headers[SftpHeaders.FileName].Should().Be("meta.txt"); rx.In.Headers[SftpHeaders.FileNameOnly].Should().Be("meta"); rx.In.Headers[SftpHeaders.FileExtension].Should().Be(".txt"); rx.In.Headers[SftpHeaders.Host].Should().Be(Host); rx.In.Headers[SftpHeaders.Port].Should().Be(Port); rx.In.Headers[SftpHeaders.Username].Should().Be(Username); ((long)rx.In.Headers[SftpHeaders.FileLength]!).Should().BeGreaterThan(0); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_StreamBody_DeleteAfterRead() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("delete after stream"))) rawClient.UploadFile(ms, $"{fullDir}/deletable.txt"); var ep = CreateEndpoint(remotePath, "streamBody=true&delete=true&delay=500&initialDelay=100"); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(15_000)); await consumer.Stop(); rawClient.Exists($"{fullDir}/deletable.txt").Should().BeFalse(); CleanupDir(rawClient, fullDir); } // ───── Path filters (Camel parity) ───── [Fact] public async Task Consumer_AntInclude_TakesOnlyTheNamedDirectories() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); foreach (var type in new[] { "TYPE_A", "TYPE_B", "TYPE_C" }) { rawClient.CreateDirectory($"{fullDir}/{type}"); rawClient.CreateDirectory($"{fullDir}/{type}/outbox"); using var ms = new MemoryStream(Encoding.UTF8.GetBytes(type)); rawClient.UploadFile(ms, $"{fullDir}/{type}/outbox/data.csv"); } // The partner allows one session: one consumer over the parent, the wanted directories // named by path, and the rest is neither downloaded nor deleted. var ep = CreateEndpoint(remotePath, "recursive=true&delete=true&delay=5000&initialDelay=100&antInclude=TYPE_A/outbox/*.csv,TYPE_B/outbox/*.csv"); var received = new ConcurrentBag(); var counter = 0; var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); if (Interlocked.Increment(ref counter) >= 2) done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); await consumer.Stop(); received.Select(r => r.In.Headers[SftpHeaders.RelativePath]!.ToString()!) .Should().BeEquivalentTo(["TYPE_A/outbox/data.csv", "TYPE_B/outbox/data.csv"]); rawClient.Exists($"{fullDir}/TYPE_C/outbox/data.csv").Should().BeTrue("a file no filter took is left alone"); rawClient.Exists($"{fullDir}/TYPE_A/outbox/data.csv").Should().BeFalse(); CleanupDir(rawClient, fullDir); } [Fact] public async Task Consumer_FilterDirectory_LeavesTheRejectedDirectoryAlone() { var dir = UniqueDir(); var remotePath = $"{BaseDir}/{dir}"; using var rawClient = CreateRawClient(); var fullDir = $"/{remotePath}"; rawClient.CreateDirectory(fullDir); rawClient.CreateDirectory($"{fullDir}/wanted"); rawClient.CreateDirectory($"{fullDir}/skipped"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("in"))) rawClient.UploadFile(ms, $"{fullDir}/wanted/a.csv"); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("out"))) rawClient.UploadFile(ms, $"{fullDir}/skipped/b.csv"); var ep = CreateEndpoint(remotePath, "recursive=true&noop=true&delay=5000&initialDelay=100&filterDirectory=header.redbSftp.Name != 'skipped'"); var received = new ConcurrentBag(); var done = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.ArgAt(0)); done.TrySetResult(); return Task.CompletedTask; }); var consumer = (SftpConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(done.Task, Task.Delay(15_000)); await Task.Delay(500); await consumer.Stop(); received.Select(r => (string)r.In.Headers[SftpHeaders.FileName]!) .Should().BeEquivalentTo(["a.csv"]); CleanupDir(rawClient, fullDir); } } Path: redb-route/tests/redb.Route.Tests.Sftp/SftpTraceTests.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.Sftp/SftpTraceTests.cs ---- using System.Diagnostics; using System.Text; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Sftp; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Sftp; /// /// A polled remote 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. /// EnableTelemetry=false opens none. Each test polls a directory of its own and reads only the spans of that /// endpoint. Expects SFTP at localhost:2222 (testuser/secret, writable upload/). /// [Trait("Category", "Integration")] public sealed class SftpTraceTests : IDisposable { private const string Host = "localhost"; private const int Port = 2222; private const string Username = "testuser"; private const string Password = "secret"; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15); private readonly string _dir = $"upload/trace-{Guid.NewGuid():N}"; private readonly Renci.SshNet.SftpClient _client; public SftpTraceTests() { _client = new Renci.SshNet.SftpClient(Host, Port, Username, Password); _client.HostKeyReceived += (_, e) => e.CanTrust = true; _client.Connect(); _client.CreateDirectory(_dir); } public void Dispose() { if (_client.Exists(_dir)) { foreach (var entry in _client.ListDirectory(_dir)) if (entry is { IsDirectory: false }) _client.DeleteFile(entry.FullName); _client.DeleteDirectory(_dir); } _client.Dispose(); } private string Uri => $"sftp:///{_dir}?host={Host}&port={Port}&username={Username}&password={Password}" + "&delay=200&initialDelay=10&delete=true"; private RouteTelemetryProbe Spans() => new(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_dir, StringComparison.Ordinal) == true); private void Seed(string name) { using var content = new MemoryStream(Encoding.UTF8.GetBytes("payload")); _client.UploadFile(content, $"{_dir}/{name}"); } private async Task StartConsumer(Action step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new SftpComponent()); ctx.AddRoutes(r => r.From(Uri).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(100); } [Fact] public async Task Each_file_opens_a_root_span_even_under_an_ambient_activity() { Seed("a.txt"); Seed("b.txt"); using var probe = Spans(); await using (await StartConsumer(_ => { })) await Until(() => probe.Activities.Count(a => a.Kind == ActivityKind.Consumer) >= 2); var receives = probe.Activities.Where(a => a.Kind == ActivityKind.Consumer).ToList(); receives.Should().HaveCount(2, "one span per routed file"); receives.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a file carries no context, so its span starts a trace rather than joining the host's"); receives[0].GetTagItem("redb.system").Should().Be("sftp"); } [Fact] public async Task An_empty_poll_opens_no_span() { using var probe = Spans(); await using (await StartConsumer(_ => { })) await Task.Delay(1500); // several polls of an empty directory probe.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_route_marks_the_span_red() { Seed("fail.txt"); using var probe = Spans(); await using (await StartConsumer(_ => throw new InvalidOperationException("route failed"))) await Until(() => probe.Activities.Any(a => a.Kind == ActivityKind.Consumer)); probe.Activities.Where(a => a.Kind == ActivityKind.Consumer).Should().NotBeEmpty() .And.OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span() { Seed("off.txt"); using var probe = Spans(); 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(); } } Path: redb-route/tests/redb.Route.Tests.Sftp/redb.Route.Tests.Sftp.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.Sftp/redb.Route.Tests.Sftp.csproj ----