Bundle: redb-route / tests/redb.Route.Tests.Core (tests.redb.Route.Tests.Core.txt), 29 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.Core/CreateRedbScopeTests.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.Core/CreateRedbScopeTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core; /// /// : a scope of its own per call for code without an exchange. /// The published factory first, then a scope opened from the registered service, otherwise a refusal. /// public sealed class CreateRedbScopeTests { private sealed class TrackingScope : IServiceScope, IAsyncDisposable { public TrackingScope(IServiceProvider provider) => ServiceProvider = provider; public int DisposeCount; public IServiceProvider ServiceProvider { get; } public void Dispose() => Interlocked.Increment(ref DisposeCount); public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); return ValueTask.CompletedTask; } } private static IServiceScopeFactory ScopedRedbFactory() => new ServiceCollection() .AddScoped(_ => Substitute.For()) .BuildServiceProvider() .GetRequiredService(); private static IRedbService ScopeSource() { var instance = Substitute.For(); instance.CanCreateScope.Returns(true); instance.CreateScope().Returns(_ => new RedbScope(Substitute.For(), null)); return instance; } // ── Named ──────────────────────────────────────────────────────── [Fact] public async Task Named_PublishedFactory_Wins_AndEachCallGetsItsOwnService() { var instance = ScopeSource(); var context = Substitute.For(); context.GetFromRegistry("redb-factory:orders").Returns(ScopedRedbFactory()); context.GetFromRegistry("redb:orders").Returns(instance); await using var first = context.CreateRedbScope("orders"); await using var second = context.CreateRedbScope("orders"); first.Service.Should().NotBeSameAs(second.Service, "parallel callers must never share a connection"); first.Service.Should().NotBeSameAs(instance); instance.DidNotReceive().CreateScope(); } [Fact] public async Task Named_Factory_DisposingTheScope_DisposesTheContainerScope() { var provider = Substitute.For(); provider.GetService(typeof(IRedbService)).Returns(Substitute.For()); var tracking = new TrackingScope(provider); var factory = Substitute.For(); factory.CreateScope().Returns(tracking); var context = Substitute.For(); context.GetFromRegistry("redb-factory:orders").Returns(factory); var scope = context.CreateRedbScope("#orders"); tracking.DisposeCount.Should().Be(0); await scope.DisposeAsync(); tracking.DisposeCount.Should().Be(1); } [Fact] public void Named_FactoryWithoutRedb_Throws_AndReleasesTheScope() { var tracking = new TrackingScope(Substitute.For()); var factory = Substitute.For(); factory.CreateScope().Returns(tracking); var context = Substitute.For(); context.GetFromRegistry("redb-factory:orders").Returns(factory); var act = () => context.CreateRedbScope("orders"); act.Should().Throw().WithMessage("*does not provide IRedbService*"); tracking.DisposeCount.Should().Be(1, "a failed resolution must not strand the scope it opened"); } [Fact] public async Task Named_NoFactory_OpensScopeFromTheRegisteredInstance() { var instance = ScopeSource(); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders").Returns(instance); await using var first = context.CreateRedbScope("orders"); await using var second = context.CreateRedbScope("orders"); instance.Received(2).CreateScope(); first.Service.Should().NotBeSameAs(second.Service); first.Service.Should().NotBeSameAs(instance); } [Fact] public void Named_InstanceBuiltWithoutContainer_Throws() { var instance = Substitute.For(); instance.CanCreateScope.Returns(false); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders").Returns(instance); var act = () => context.CreateRedbScope("orders"); act.Should().Throw().WithMessage("*orders*without a DI container*"); instance.DidNotReceive().CreateScope(); } [Fact] public void Named_NotRegistered_Throws() { var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry(Arg.Any()).Returns((IRedbService?)null); var act = () => context.CreateRedbScope("orders"); act.Should().Throw().WithMessage("*orders*is not found*"); } // ── Default ────────────────────────────────────────────────────── [Fact] public async Task Default_ServiceRegisteredOnContext_OpensScopeFromIt() { var registered = ScopeSource(); var context = Substitute.For(); context.GetService().Returns(registered); context.GetServiceProvider().Returns(new ServiceCollection() .AddScoped(_ => Substitute.For()).BuildServiceProvider()); await using var scope = context.CreateRedbScope(); registered.Received(1).CreateScope(); } [Fact] public void Default_ServiceRegisteredOnContext_WithoutContainer_Throws() { var registered = Substitute.For(); registered.CanCreateScope.Returns(false); var context = Substitute.For(); context.GetService().Returns(registered); var act = () => context.CreateRedbScope(string.Empty); act.Should().Throw().WithMessage("*without a DI container*"); } [Fact] public async Task Default_OnlyServiceProvider_EachCallGetsItsOwnScopedService() { var provider = new ServiceCollection() .AddScoped(_ => Substitute.For()) .BuildServiceProvider(); var context = Substitute.For(); context.GetService().Returns((IRedbService?)null); context.GetServiceProvider().Returns(provider); await using var first = context.CreateRedbScope(); await using var second = context.CreateRedbScope(); first.Service.Should().NotBeSameAs(second.Service); } [Fact] public void Default_NothingRegistered_Throws() { var context = Substitute.For(); context.GetService().Returns((IRedbService?)null); context.GetServiceProvider().Returns((IServiceProvider?)null); var act = () => context.CreateRedbScope(); act.Should().Throw().WithMessage("*not registered*"); } [Fact] public void NullContext_Throws() { var act = () => RedbRouteExtensions.CreateRedbScope(null!, "orders"); act.Should().Throw().WithParameterName("context"); } } Path: redb-route/tests/redb.Route.Tests.Core/GetRedbServiceExchangeScopeTests.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.Core/GetRedbServiceExchangeScopeTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core; /// /// A host outside Tsak registers its named database with RegisterRedbService and publishes no scope factory. /// With an exchange, handed every /// exchange that one instance: one connection for all parallel exchanges. An instance built through a container now /// opens a scope of the same database per exchange, as the published factory does in Tsak. /// public sealed class GetRedbServiceExchangeScopeTests { private sealed class TrackingScope : IServiceScope, IAsyncDisposable { public int DisposeCount; public IServiceProvider ServiceProvider { get; } = Substitute.For(); public void Dispose() => Interlocked.Increment(ref DisposeCount); public ValueTask DisposeAsync() { Interlocked.Increment(ref DisposeCount); return ValueTask.CompletedTask; } } private static (IRedbService Instance, List Opened) ScopeSource() { var opened = new List(); var instance = Substitute.For(); instance.CanCreateScope.Returns(true); instance.CreateScope().Returns(_ => { var tracking = new TrackingScope(); opened.Add(tracking); return new RedbScope(Substitute.For(), tracking); }); return (instance, opened); } private static IRouteContext NamedWithoutFactory(IRedbService instance) { var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders").Returns(instance); return context; } [Fact] public async Task Named_NoFactory_InstanceFromContainer_EachExchangeGetsItsOwnScope() { var (instance, opened) = ScopeSource(); var context = NamedWithoutFactory(instance); var first = new Exchange(); var second = new Exchange(); var a1 = context.GetRedbService("orders", first); var a2 = context.GetRedbService("orders", first); var b = context.GetRedbService("orders", second); a1.Should().NotBeSameAs(instance, "parallel exchanges must not share the registered instance's connection"); a2.Should().BeSameAs(a1, "one exchange keeps its scope for every step"); b.Should().NotBeSameAs(a1); opened.Should().HaveCount(2); await first.DisposeAsync(); opened[0].DisposeCount.Should().Be(1, "the scope ends with its exchange"); opened[1].DisposeCount.Should().Be(0); await second.DisposeAsync(); opened[1].DisposeCount.Should().Be(1); } [Fact] public void Named_NoFactory_InstanceWithoutContainer_KeepsTheSharedInstance() { var instance = Substitute.For(); instance.CanCreateScope.Returns(false); var context = NamedWithoutFactory(instance); context.GetRedbService("orders", new Exchange()).Should().BeSameAs(instance); instance.DidNotReceive().CreateScope(); } [Fact] public void Named_PublishedFactory_Wins_InstanceIsNotAsked() { var (instance, opened) = ScopeSource(); var context = Substitute.For(); context.GetFromRegistry("redb-factory:orders").Returns(new ServiceCollection() .AddScoped(_ => Substitute.For()) .BuildServiceProvider() .GetRequiredService()); context.GetFromRegistry("redb:orders").Returns(instance); context.GetRedbService("orders", new Exchange()).Should().NotBeSameAs(instance); opened.Should().BeEmpty(); } [Fact] public void Named_WithoutExchange_KeepsTheInstance_ForStartUpCode() { var (instance, opened) = ScopeSource(); var context = NamedWithoutFactory(instance); context.GetRedbService("orders", exchange: null).Should().BeSameAs(instance); opened.Should().BeEmpty(); } [Fact] public async Task Default_ServiceRegisteredOnContext_NoProvider_EachExchangeGetsItsOwnScope() { var (registered, opened) = ScopeSource(); var context = Substitute.For(); context.GetService().Returns(registered); context.GetServiceProvider().Returns((IServiceProvider?)null); var first = new Exchange(); var second = new Exchange(); var a1 = context.GetRedbService(string.Empty, first); var a2 = context.GetRedbService(string.Empty, first); var b = context.GetRedbService(string.Empty, second); a1.Should().NotBeSameAs(registered); a2.Should().BeSameAs(a1); b.Should().NotBeSameAs(a1); await first.DisposeAsync(); opened[0].DisposeCount.Should().Be(1); } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/MsSqlFixture.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.Core/Integration/MsSqlFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Route.RedbCore.Models; namespace redb.Route.Tests.Core.Integration; /// /// Shared xUnit fixture that boots a real MSSql-backed , /// creates the database schema and syncs the scheme. /// public sealed class MsSqlFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var connectionString = global::redb.Route.Tests.Shared.TestDatabases.MsSql(config.GetConnectionString("MSSql")!); var license = config["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(); services.AddRedbPro(options => { options.UseMsSql(connectionString) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { // Schema may already exist from a parallel TFM run or previous session await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync(); else ServiceProvider?.Dispose(); } } [CollectionDefinition("MsSql")] public class MsSqlCollection : ICollectionFixture; Path: redb-route/tests/redb.Route.Tests.Core/Integration/MsSqlIdempotentRepositoryTests.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.Core/Integration/MsSqlIdempotentRepositoryTests.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Route.Tests.Core.Integration; [Collection("MsSql")] public sealed class MsSqlIdempotentRepositoryTests : RedbIdempotentRepositoryIntegrationTests { public MsSqlIdempotentRepositoryTests(MsSqlFixture fixture) : base(fixture.Redb, fixture.ServiceProvider.GetRequiredService()) { } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/PostgresDiagnosticTests.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.Core/Integration/PostgresDiagnosticTests.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Route.RedbCore.Models; namespace redb.Route.Tests.Core.Integration; /// Quick diagnostic: verify Postgres DB has the scheme and can round-trip objects. public sealed class PostgresDiagnosticTests { [Fact] public async Task Postgres_SchemeExists_And_CanSaveQuery() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = global::redb.Route.Tests.Shared.TestDatabases.Postgres(config.GetConnectionString("Postgres")!); var license = config["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(); services.AddRedbPro(o => { o.UsePostgres(cs) .Configure(c => c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert); if (!string.IsNullOrWhiteSpace(license)) o.WithLicense(license); }); await using var sp = services.BuildServiceProvider(); var redb = sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch { await redb.InitializeAsync(); } var scheme = await redb.SyncSchemeAsync(); scheme.Should().NotBeNull(); // Unique key per test run to avoid collisions between parallel TFM runners var uid = Guid.NewGuid().ToString("N")[..8]; var procName = $"diag-{uid}"; // Save one object var obj = new redb.Core.Models.Entities.RedbObject { name = $"{procName}:key1", Props = new IdempotentEntryProps { ProcessorName = procName, MessageKey = "key1", CreatedAt = DateTimeOffset.UtcNow, Confirmed = false } }; await redb.SaveAsync(obj); // Query it back var items = await redb.Query() .Where(e => e.ProcessorName == procName && e.MessageKey == "key1") .ToListAsync(); items.Should().ContainSingle(); items[0].Props.MessageKey.Should().Be("key1"); // Cleanup await redb.DeleteAsync(items[0]); // Verify deleted var after = await redb.Query() .Where(e => e.ProcessorName == procName) .ToListAsync(); after.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/PostgresFixture.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.Core/Integration/PostgresFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Route.RedbCore.Models; namespace redb.Route.Tests.Core.Integration; /// /// Shared xUnit fixture that boots a real Postgres-backed , /// creates the database schema and syncs the scheme. /// public sealed class PostgresFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var connectionString = global::redb.Route.Tests.Shared.TestDatabases.Postgres(config.GetConnectionString("Postgres")!); var license = config["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(); services.AddRedbPro(options => { options.UsePostgres(connectionString) .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; }); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { // Schema may already exist from a parallel TFM run or previous session await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync(); else ServiceProvider?.Dispose(); } } [CollectionDefinition("Postgres")] public class PostgresCollection : ICollectionFixture; Path: redb-route/tests/redb.Route.Tests.Core/Integration/PostgresFreeFixture.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.Core/Integration/PostgresFreeFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Postgres.Extensions; using redb.Route.RedbCore.Models; namespace redb.Route.Tests.Core.Integration; /// /// The Free counterpart of : the same Postgres database through AddRedb and the Free /// provider, so the redb idempotent repository is shown to hold without Pro. /// public sealed class PostgresFreeFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider ServiceProvider { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var connectionString = global::redb.Route.Tests.Shared.TestDatabases.Postgres(config.GetConnectionString("Postgres")!); var services = new ServiceCollection(); services.AddLogging(); services.AddRedb(options => options .UsePostgres(connectionString) .Configure(c => c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert)); ServiceProvider = services.BuildServiceProvider(); Redb = ServiceProvider.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { // Schema may already exist from the Pro fixture, a parallel TFM run or a previous session await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); } public async Task DisposeAsync() { if (ServiceProvider is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync(); else ServiceProvider?.Dispose(); } } [CollectionDefinition("PostgresFree")] public class PostgresFreeCollection : ICollectionFixture; Path: redb-route/tests/redb.Route.Tests.Core/Integration/PostgresFreeIdempotentRepositoryTests.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.Core/Integration/PostgresFreeIdempotentRepositoryTests.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Route.Tests.Core.Integration; /// The redb idempotent repository on the Free Postgres provider: the same cases as on Pro. [Collection("PostgresFree")] public sealed class PostgresFreeIdempotentRepositoryTests : RedbIdempotentRepositoryIntegrationTests { public PostgresFreeIdempotentRepositoryTests(PostgresFreeFixture fixture) : base(fixture.Redb, fixture.ServiceProvider.GetRequiredService()) { } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/PostgresIdempotentRepositoryTests.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.Core/Integration/PostgresIdempotentRepositoryTests.cs ---- using Microsoft.Extensions.DependencyInjection; namespace redb.Route.Tests.Core.Integration; [Collection("Postgres")] public sealed class PostgresIdempotentRepositoryTests : RedbIdempotentRepositoryIntegrationTests { public PostgresIdempotentRepositoryTests(PostgresFixture fixture) : base(fixture.Redb, fixture.ServiceProvider.GetRequiredService()) { } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/RedbIdempotentRepositoryIntegrationTests.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.Core/Integration/RedbIdempotentRepositoryIntegrationTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.RedbCore.Models; using redb.Route.RedbCore.Repositories; namespace redb.Route.Tests.Core.Integration; /// /// Integration tests for running against a real database. /// Subclassed per provider (Postgres, MsSql). /// Each test instance uses a unique prefix so multiple TFM runners can execute in parallel /// without interfering (no global cleanup required). /// public abstract class RedbIdempotentRepositoryIntegrationTests : IAsyncLifetime { private readonly IRedbService _redb; private readonly IServiceScopeFactory _scopeFactory; /// Unique prefix for this test instance — isolates data across parallel runs. private readonly string _id = Guid.NewGuid().ToString("N")[..8]; protected RedbIdempotentRepositoryIntegrationTests(IRedbService redb, IServiceScopeFactory scopeFactory) { _redb = redb; _scopeFactory = scopeFactory; } private string P(string name) => $"{_id}-{name}"; private RedbIdempotentRepository CreateRepository(string processor = "test-proc", TimeSpan? ttl = null) { var options = new RedbIdempotentOptions { ProcessorName = P(processor), Ttl = ttl }; return new RedbIdempotentRepository(_scopeFactory, options); } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { // Clean up only entries created by this test instance (matching our unique prefix). // StartsWith is supported by redb Pro LINQ provider → translates to LIKE 'prefix%'. try { var all = await _redb.Query() .Where(e => e.ProcessorName!.StartsWith(_id)) .ToListAsync(); if (all.Count > 0) await _redb.DeleteAsync((IEnumerable)all); } catch { // Parallel TFM runs may cause deadlocks during cleanup — safe to ignore } } // ─── Add ─────────────────────────────────────────────── [Fact] public async Task Add_NewKey_ReturnsTrue() { var repo = CreateRepository(); var result = await repo.Add("msg-1"); result.Should().BeTrue(); } [Fact] public async Task Add_DuplicateKey_ReturnsFalse() { var repo = CreateRepository(); await repo.Add("msg-dup"); var result = await repo.Add("msg-dup"); result.Should().BeFalse(); } [Fact] public async Task Add_SameKeyDifferentProcessor_ReturnsTrue() { var repo1 = CreateRepository("proc-A"); var repo2 = CreateRepository("proc-B"); await repo1.Add("shared-key"); var result = await repo2.Add("shared-key"); result.Should().BeTrue(); } // ─── Contains ────────────────────────────────────────── [Fact] public async Task Contains_AfterAdd_ReturnsTrue() { var repo = CreateRepository(); await repo.Add("msg-exists"); (await repo.Contains("msg-exists")).Should().BeTrue(); } [Fact] public async Task Contains_NonExistentKey_ReturnsFalse() { var repo = CreateRepository(); (await repo.Contains("never-added")).Should().BeFalse(); } // ─── Confirm ────────────────────────────────────────── [Fact] public async Task Confirm_SetsConfirmedFlag() { var repo = CreateRepository(); await repo.Add("msg-confirm"); await repo.Confirm("msg-confirm"); // Verify via direct query — match by processor prefix to isolate var procName = P("test-proc"); var items = await _redb.Query() .Where(e => e.MessageKey == "msg-confirm" && e.ProcessorName == procName) .ToListAsync(); items.Should().ContainSingle() .Which.Props.Confirmed.Should().BeTrue(); } // ─── Remove ────────────────────────────────────────── [Fact] public async Task Remove_DeletesEntry() { var repo = CreateRepository(); await repo.Add("msg-remove"); await repo.Remove("msg-remove"); (await repo.Contains("msg-remove")).Should().BeFalse(); } [Fact] public async Task Remove_NonExistentKey_DoesNotThrow() { var repo = CreateRepository(); var act = () => repo.Remove("ghost"); await act.Should().NotThrowAsync(); } // ─── Clear ────────────────────────────────────────── [Fact] public async Task Clear_RemovesAllEntriesForProcessor() { var repo = CreateRepository("clear-proc"); await repo.Add("c1"); await repo.Add("c2"); await repo.Add("c3"); await repo.Clear(); (await repo.Contains("c1")).Should().BeFalse(); (await repo.Contains("c2")).Should().BeFalse(); (await repo.Contains("c3")).Should().BeFalse(); } [Fact] public async Task Clear_DoesNotAffectOtherProcessors() { var repo1 = CreateRepository("isolate-A"); var repo2 = CreateRepository("isolate-B"); await repo1.Add("x"); await repo2.Add("y"); await repo1.Clear(); (await repo2.Contains("y")).Should().BeTrue(); } // ─── Concurrency: one key, one winner ───────────────── [Fact] public async Task Add_ParallelSameKey_ExactlyOneWins_SingleRowStored() { var repo = CreateRepository("race-proc"); // Prime the scheme outside the measured races so scheme sync doesn't add noise. await repo.Add("race-warmup"); for (var i = 0; i < 10; i++) { var key = $"race-key-{i}"; var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => repo.Add(key))); results.Count(r => r).Should().Be(1, $"exactly one of the concurrent Add('{key}') calls may claim the key"); var entryName = RedbIdempotentRepository.ComposeEntryName(P("race-proc"), key); var rows = await _redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync(); rows.Should().ContainSingle( $"the unique index must let exactly one row through for '{key}'"); } } [Fact] public async Task Add_UniqueKeyAlreadyCommittedByRaceWinner_ReturnsFalse() { // Deterministic replay of the TOCTOU window: the winner's row is already committed // with our unique key, but under a name the Add lookup does not see. The insert must // hit UIX__objects__scheme_unique and come back as a calm "duplicate" — no exception. var repo = CreateRepository("toctou-proc"); await repo.Add("toctou-warmup"); const string key = "toctou-key"; var procName = P("toctou-proc"); var entryName = RedbIdempotentRepository.ComposeEntryName(procName, key); var winner = new RedbObject { name = P("toctou-winner-row"), ValueUnique = entryName, Props = new IdempotentEntryProps { ProcessorName = procName, MessageKey = key, CreatedAt = DateTimeOffset.UtcNow, Confirmed = false } }; await _redb.SaveAsync(winner); var result = await repo.Add(key); result.Should().BeFalse("the key is already claimed by the committed row"); } // ─── Long client keys ───────────────────────────────── [Fact] public async Task Add_LongKey_NormalizedAndStillIdempotent() { var repo = CreateRepository("long-proc"); var prefix = new string('k', 600); var key1 = prefix + "-first"; var key2 = prefix + "-second"; (await repo.Add(key1)).Should().BeTrue(); (await repo.Add(key1)).Should().BeFalse("the same long key must be recognized as a duplicate"); (await repo.Add(key2)).Should().BeTrue("a long key differing only past the readable prefix is distinct"); (await repo.Contains(key1)).Should().BeTrue(); await repo.Remove(key1); (await repo.Contains(key1)).Should().BeFalse(); (await repo.Contains(key2)).Should().BeTrue(); } // ─── TTL cleanup ─────────────────────────────────────── [Fact] public async Task Add_WithTtl_CleansUpExpiredEntries() { // Create repo with short TTL var repo = CreateRepository("ttl-proc", ttl: TimeSpan.FromSeconds(2)); // Add an entry that will become "old" after TTL elapses await repo.Add("old-msg"); (await repo.Contains("old-msg")).Should().BeTrue(); // Wait for TTL to expire await Task.Delay(TimeSpan.FromSeconds(3)); // Add a new key — this triggers cleanup of expired entries await repo.Add("new-msg"); // Old entry should be cleaned up by TTL (await repo.Contains("old-msg")).Should().BeFalse(); // New entry should exist (await repo.Contains("new-msg")).Should().BeTrue(); } // ─── End-to-end workflow ────────────────────────────── [Fact] public async Task FullWorkflow_AddContainConfirmRemove() { var repo = CreateRepository("e2e-proc"); // Add (await repo.Add("wf-1")).Should().BeTrue(); // Contains (await repo.Contains("wf-1")).Should().BeTrue(); // Duplicate (await repo.Add("wf-1")).Should().BeFalse(); // Confirm await repo.Confirm("wf-1"); var procName = P("e2e-proc"); var items = await _redb.Query() .Where(e => e.MessageKey == "wf-1" && e.ProcessorName == procName) .ToListAsync(); items.Should().ContainSingle().Which.Props.Confirmed.Should().BeTrue(); // Remove await repo.Remove("wf-1"); (await repo.Contains("wf-1")).Should().BeFalse(); } [Fact] public async Task MultipleKeys_IndependentLifecycle() { var repo = CreateRepository("multi-proc"); await repo.Add("k1"); await repo.Add("k2"); await repo.Add("k3"); await repo.Remove("k2"); (await repo.Contains("k1")).Should().BeTrue(); (await repo.Contains("k2")).Should().BeFalse(); (await repo.Contains("k3")).Should().BeTrue(); } // ─── Claim ───────────────────────────────────────────── [Fact] public async Task Claim_TellsAClaimInFlightFromAConfirmedOne() { var repo = CreateRepository("claim-proc"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.InFlight); await repo.Confirm("c1"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Confirmed); await repo.Remove("c1"); (await repo.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); } [Fact] public async Task Claim_AnAbandonedClaim_IsTakenOver_AConfirmedOneNever() { var repo = CreateRepository("takeover-proc"); await repo.Add("orphan"); await repo.Add("done"); await repo.Confirm("done"); await Task.Delay(TimeSpan.FromSeconds(1.5)); (await repo.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.TakenOver); (await repo.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "the takeover is a fresh claim"); (await repo.Claim("done", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_OneWins_OneEntryStays() { // Two repositories over one database, as two nodes are: both read the same stale entry. It is written long // abandoned and the timeout is a minute, so however long the callers wait on each other's locks, the winner's fresh // claim stays inside it. var nodeA = CreateRepository("race-proc"); var nodeB = CreateRepository("race-proc"); await SeedAbandonedAsync(nodeA, "race-proc", "stale"); var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim("stale", TimeSpan.FromMinutes(1))))); // One caller holds the claim: the one that took the stale entry over, or one that found it gone and claimed it anew. outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed).Should().Be(1); outcomes.Count(o => o == IdempotentClaim.InFlight).Should().Be(outcomes.Length - 1); var procName = P("race-proc"); var entries = await _redb.Query() .Where(e => e.MessageKey == "stale" && e.ProcessorName == procName) .ToListAsync(); entries.Should().ContainSingle().Which.Props.Confirmed.Should().BeFalse(); } [Fact] public async Task Claim_AnInsertThatWaitedPastTheTimeout_BecomesVisibleAsAFreshClaim() { // Another session holds the entry's unique key (under another name, so node A's lookup by name does not wait on // it): node A's insert waits for longer than the timeout. The claim it then commits is new, and node B must find it // in flight, not abandoned. var nodeA = CreateRepository("slow-insert"); var nodeB = CreateRepository("slow-insert"); await nodeA.Contains("slow"); // syncs the scheme using var scope = _scopeFactory.CreateScope(); var blocker = scope.ServiceProvider.GetRequiredService(); var hold = await blocker.Context.BeginTransactionAsync(); await blocker.SaveAsync(new RedbObject { name = $"blocker-{_id}", ValueUnique = RedbIdempotentRepository.ComposeEntryName(P("slow-insert"), "slow"), Props = new IdempotentEntryProps { ProcessorName = P("blocker"), MessageKey = "slow", CreatedAt = DateTimeOffset.UtcNow }, }); var claimA = Task.Run(() => nodeA.Claim("slow", TimeSpan.FromSeconds(1))); await Task.Delay(TimeSpan.FromSeconds(1.5)); claimA.IsCompleted.Should().BeFalse("node A's insert waits on the key the other session holds"); await hold.RollbackAsync(); await hold.DisposeAsync(); (await claimA).Should().Be(IdempotentClaim.Claimed); (await nodeB.Claim("slow", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "node A's claim became visible a moment ago, however long its insert waited"); } [ClaimRaceLoopFact] public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_200Times_OneWinsEachTime() { for (var iteration = 0; iteration < 200; iteration++) { var proc = $"race-loop-{iteration}"; var nodeA = CreateRepository(proc); var nodeB = CreateRepository(proc); await SeedAbandonedAsync(nodeA, proc, "stale"); var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i => Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim("stale", TimeSpan.FromMinutes(1))))); outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed) .Should().Be(1, $"iteration {iteration}: {string.Join(",", outcomes)}"); } } // ─── Lease: the claim id ─────────────────────────────── [Fact] public async Task Lease_StaleHolderAfterATakeover_ConfirmsNothing_TheNewHolderConfirms() { var nodeA = CreateRepository("lease-confirm"); var nodeB = CreateRepository("lease-confirm"); var first = await nodeA.Lease("m1", TimeSpan.FromMinutes(1)); first.Outcome.Should().Be(IdempotentClaim.Claimed); first.Token.Should().NotBeNullOrEmpty(); await AgeAsync("lease-confirm", "m1"); var second = await nodeB.Lease("m1", TimeSpan.FromMinutes(1)); second.Outcome.Should().Be(IdempotentClaim.TakenOver); second.Token.Should().NotBe(first.Token); (await nodeA.Confirm("m1", first.Token, default)).Should().BeFalse("node A's claim was taken over"); (await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.InFlight, "node B's claim is still unconfirmed"); (await nodeB.Confirm("m1", second.Token, default)).Should().BeTrue(); (await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task Lease_StaleHolderAfterATakeover_ReleasesNothing_TheNewHolderReleases() { var nodeA = CreateRepository("lease-release"); var nodeB = CreateRepository("lease-release"); var first = await nodeA.Lease("m2", TimeSpan.FromMinutes(1)); await AgeAsync("lease-release", "m2"); var second = await nodeB.Lease("m2", TimeSpan.FromMinutes(1)); second.Outcome.Should().Be(IdempotentClaim.TakenOver); (await nodeA.Release("m2", first.Token, default)).Should().BeFalse("node A's claim was taken over"); (await EntryAsync("lease-release", "m2"))!.Props.ClaimId.Should().Be(second.Token, "node B's claim stays"); (await nodeB.Release("m2", second.Token, default)).Should().BeTrue(); (await nodeA.Contains("m2")).Should().BeFalse(); } [Fact] public async Task Lease_EntryWithoutClaimId_IsClaimedAsBefore_AndNoTokenSettlesIt() { // An entry as a 4.7 node, or Add, writes it: no claim id. var repo = CreateRepository("lease-legacy"); (await repo.Add("legacy")).Should().BeTrue(); (await repo.Lease("legacy", TimeSpan.FromMinutes(1))).Should().Be(new IdempotentLease(IdempotentClaim.InFlight, null)); (await repo.Confirm("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse(); (await repo.Release("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse(); (await repo.Contains("legacy")).Should().BeTrue(); await AgeAsync("lease-legacy", "legacy"); var takeover = await repo.Lease("legacy", TimeSpan.FromMinutes(1)); takeover.Outcome.Should().Be(IdempotentClaim.TakenOver, "an abandoned entry without a claim id is taken over as before"); (await EntryAsync("lease-legacy", "legacy"))!.Props.ClaimId.Should().Be(takeover.Token); } [Fact] public async Task Lease_OldNode_UnconditionalConfirmAndRemove_StillWorkOnAClaimWithAnId() { // The rolling upgrade: a 4.8 node holds a claim with an id; a 4.7 node settles the key with the calls it has. var newNode = CreateRepository("lease-rolling"); var oldNode = CreateRepository("lease-rolling"); var held = await newNode.Lease("r1", TimeSpan.FromMinutes(1)); await oldNode.Confirm("r1"); (await newNode.Lease("r1", TimeSpan.FromMinutes(1))).Outcome.Should().Be(IdempotentClaim.Confirmed); (await newNode.Confirm("r1", held.Token, default)).Should().BeTrue("the entry still carries node A's claim id"); var again = await newNode.Lease("r2", TimeSpan.FromMinutes(1)); await oldNode.Remove("r2"); (await newNode.Release("r2", again.Token, default)).Should().BeFalse("the old node removed it already"); } /// Makes the entry of look abandoned: its stamp moves an hour back. private async Task AgeAsync(string processor, string key) { var entry = await EntryAsync(processor, key); entry.Should().NotBeNull(); entry!.Props.CreatedAt = DateTimeOffset.UtcNow.AddHours(-1); await _redb.SaveAsync(entry); } private async Task?> EntryAsync(string processor, string key) { var procName = P(processor); var entries = await _redb.Query() .Where(e => e.MessageKey == key && e.ProcessorName == procName) .ToListAsync(); return entries.SingleOrDefault(); } /// A claim of left unconfirmed an hour ago, as a stopped node leaves it. private async Task SeedAbandonedAsync(RedbIdempotentRepository repository, string processor, string key) { await repository.Contains(key); // syncs the scheme var name = RedbIdempotentRepository.ComposeEntryName(P(processor), key); await _redb.SaveAsync(new RedbObject { name = name, ValueUnique = name, Props = new IdempotentEntryProps { ProcessorName = P(processor), MessageKey = key, CreatedAt = DateTimeOffset.UtcNow.AddHours(-1) }, }); } } /// /// The claim race in a loop of 200: minutes per database, so it runs only with REDB_CLAIM_RACE_LOOP=1 and is /// skipped, visibly, otherwise. /// public sealed class ClaimRaceLoopFactAttribute : FactAttribute { public ClaimRaceLoopFactAttribute() { if (Environment.GetEnvironmentVariable("REDB_CLAIM_RACE_LOOP") != "1") Skip = "The 200-iteration claim race runs with REDB_CLAIM_RACE_LOOP=1."; } } Path: redb-route/tests/redb.Route.Tests.Core/Integration/RedbQueryBaseFieldsIntegrationTests.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.Core/Integration/RedbQueryBaseFieldsIntegrationTests.cs ---- using redb.Core; using redb.Core.Attributes; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core.Integration; /// A props type for the query probes: a run tag and a rank. [RedbScheme("Route Query Probe")] public sealed class QueryProbeProps { public string? Tag { get; set; } public int Rank { get; set; } } /// /// RedbQuery(whereRedb:, orderByRedb:) against a real database: the base-field condition /// reaches the provider's SQL and filters there, combined with a props condition. Subclassed per /// provider. Every object carries this instance's tag and hangs under its own parent, so /// parallel runs over the shared test database never see each other's rows. /// public abstract class RedbQueryBaseFieldsIntegrationTests : IAsyncLifetime { private readonly IRedbService _redb; private readonly string _tag = Guid.NewGuid().ToString("N"); private readonly Guid _key = Guid.NewGuid(); private readonly List _created = []; private long _parent; private long _first; private long _second; protected RedbQueryBaseFieldsIntegrationTests(IRedbService redb) => _redb = redb; public async Task InitializeAsync() { await _redb.SyncSchemeAsync(); _parent = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 0 })); _first = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 1 }) { ParentId = _parent, ValueGuid = _key, ValueString = "A-" + _tag }); _second = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 2 }) { ParentId = _parent, ValueGuid = Guid.NewGuid(), ValueString = "B-" + _tag }); } public async Task DisposeAsync() { // Children first, then the parent. foreach (var id in Enumerable.Reverse(_created)) await _redb.DeleteAsync(id); } private async Task Save(RedbObject entity) { var id = await _redb.SaveAsync(entity); _created.Add(id); return id; } private async Task>> Run(Action query, params (string Key, object? Value)[] headers) => (await RunRaw(query, headers)).Should().BeOfType>>().Subject; private async Task RunRaw(Action query, params (string Key, object? Value)[] headers) { await using var context = new RouteContext(); context.AddService(typeof(IRedbService), _redb); context.AddRoutes(r => query(r.From("direct://probe"))); await context.Start(); var producer = context.GetEndpoint("direct://probe").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; exchange.In.Headers["parent"] = _parent; await producer.Process(exchange); exchange.Exception.Should().BeNull(); return exchange.In.Body; } [Fact] public async Task OutputFirst_FollowsTheOrdering_AndIsNullWhenNothingMatches() { var latest = await RunRaw(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", orderByRedb: "Id", descending: true, outputType: RedbQueryOutput.First)); var none = await RunRaw(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent AND ValueString == 'nothing'", outputType: RedbQueryOutput.First)); latest.Should().BeOfType>().Which.Id.Should().Be(Math.Max(_first, _second)); none.Should().BeNull(); } [Fact] public async Task OutputCountAndAny_AnswerInTheDatabase() { var count = await RunRaw(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", outputType: RedbQueryOutput.Count)); var any = await RunRaw(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", where: "Rank > 5", outputType: RedbQueryOutput.Any)); count.Should().Be(2); any.Should().Be(false); } [Fact] public async Task WhereRedb_OnValueGuidAndParent_FiltersInTheDatabase() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent AND ValueGuid == header.key"), ("key", _key.ToString())); found.Select(o => o.Id).Should().Equal(_first); } [Fact] public async Task WhereRedb_ValueStringIn_AListFromAHeader_FiltersInTheDatabase() { // One query for a list of keys: the IN goes to the provider's SQL, not to a loop. var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent AND ValueString in header.codes"), ("codes", new List { "A-" + _tag, "missing" })); found.Select(o => o.Id).Should().Equal(_first); } [Fact] public async Task WhereRedb_IdNotIn_ALiteralList() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: $"ParentId == header.parent AND Id not in ({_first})")); found.Select(o => o.Id).Should().Equal(_second); } [Fact] public async Task Where_PropsIn_ConvertsTheElementsToTheMembersType() { // Rank is an int props field; the header carries strings. Each element converts as a single // comparison converts its value, and the storage runs the IN on the props column. var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", where: "Rank in header.ranks"), ("ranks", new List { "2", "9" })); found.Select(o => o.Id).Should().Equal(_second); } [Fact] public async Task An_empty_list_finds_nothing_in_the_database() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent AND ValueString in header.codes"), ("codes", new List())); found.Should().BeEmpty("an empty IN means nothing matches, not everything and not an error"); } [Fact] public async Task WhereRedb_AndWhere_Combine() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", where: "Rank >= 2")); found.Select(o => o.Id).Should().Equal(_second); } [Fact] public async Task WhereRedb_ValueStringFromAHeader_AndDateCreateFromText() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ValueString == header.code AND DateCreate >= header.since AND ParentId == header.parent"), ("code", "B-" + _tag), ("since", DateTimeOffset.UtcNow.AddDays(-1).ToString("O"))); found.Select(o => o.Id).Should().Equal(_second); } [Fact] public async Task OrderByRedb_Id_Descending_TakesTheLatestChild() { var found = await Run(r => r.RedbQuery(typeof(QueryProbeProps), whereRedb: "ParentId == header.parent", orderByRedb: "Id", descending: true, take: 1)); found.Select(o => o.Id).Should().Equal(Math.Max(_first, _second)); } } [Collection("Postgres")] public sealed class PostgresRedbQueryBaseFieldsTests(PostgresFixture fixture) : RedbQueryBaseFieldsIntegrationTests(fixture.Redb); [Collection("MsSql")] public sealed class MsSqlRedbQueryBaseFieldsTests(MsSqlFixture fixture) : RedbQueryBaseFieldsIntegrationTests(fixture.Redb); Path: redb-route/tests/redb.Route.Tests.Core/Integration/RedbQueryConstantInsideOrIntegrationTests.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.Core/Integration/RedbQueryConstantInsideOrIntegrationTests.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core.Integration; /// /// An empty list in a redbQuery where-string against a real Pro database. The translator decides /// x in <empty> as the constant false and x not in <empty> as the constant true, so /// next to OR and AND the storage receives a constant inside a logical node. The rows must be those LINQ gives: /// in <empty> OR cond is the rows of cond, not in <empty> OR cond is every row, /// in <empty> AND cond is none, not in <empty> AND cond is the rows of cond. /// Both sides of the operator are tried, for props (where) and base fields (whereRedb). /// Every object hangs under this instance's own parent, so parallel runs never see each other's rows. /// public abstract class RedbQueryConstantInsideOrIntegrationTests : IAsyncLifetime { private readonly IRedbService _redb; private readonly string _tag = Guid.NewGuid().ToString("N"); private readonly List _created = []; private long _parent; private long _first; private long _second; protected RedbQueryConstantInsideOrIntegrationTests(IRedbService redb) => _redb = redb; public async Task InitializeAsync() { await _redb.SyncSchemeAsync(); _parent = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 0 })); _first = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 1 }) { ParentId = _parent, ValueString = "A-" + _tag }); _second = await Save(new RedbObject(new QueryProbeProps { Tag = _tag, Rank = 2 }) { ParentId = _parent, ValueString = "B-" + _tag }); } public async Task DisposeAsync() { // Children first, then the parent. foreach (var id in Enumerable.Reverse(_created)) await _redb.DeleteAsync(id); } private async Task Save(RedbObject entity) { var id = await _redb.SaveAsync(entity); _created.Add(id); return id; } private async Task> Ranks(string? where, string whereRedb) { await using var context = new RouteContext(); context.AddService(typeof(IRedbService), _redb); context.AddRoutes(r => r.From("direct://probe") .RedbQuery(typeof(QueryProbeProps), where: where, whereRedb: whereRedb)); await context.Start(); var producer = context.GetEndpoint("direct://probe").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); exchange.In.Headers["parent"] = _parent; exchange.In.Headers["second"] = _second; exchange.In.Headers["none"] = new List(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); return exchange.In.Body.Should().BeOfType>>().Subject .Select(o => o.Props.Rank).OrderBy(r => r).ToList(); } [Theory] [InlineData("Tag in header.none OR Rank >= 2", new[] { 2 })] [InlineData("Rank >= 2 OR Tag in header.none", new[] { 2 })] [InlineData("Tag not in header.none OR Rank >= 2", new[] { 1, 2 })] [InlineData("Rank >= 2 OR Tag not in header.none", new[] { 1, 2 })] [InlineData("Tag in header.none AND Rank >= 2", new int[0])] [InlineData("Rank >= 2 AND Tag in header.none", new int[0])] [InlineData("Tag not in header.none AND Rank >= 2", new[] { 2 })] [InlineData("Rank >= 2 AND Tag not in header.none", new[] { 2 })] public async Task Props_empty_list_beside_a_condition_returns_the_rows_linq_gives(string where, int[] expected) { var ranks = await Ranks(where, "ParentId == header.parent"); ranks.Should().Equal(expected, $"where: {where}"); } [Theory] [InlineData("ValueString in header.none OR Id == header.second", new[] { 2 })] [InlineData("Id == header.second OR ValueString in header.none", new[] { 2 })] [InlineData("ValueString not in header.none OR Id == header.second", new[] { 1, 2 })] [InlineData("Id == header.second OR ValueString not in header.none", new[] { 1, 2 })] [InlineData("ValueString in header.none AND Id == header.second", new int[0])] [InlineData("Id == header.second AND ValueString in header.none", new int[0])] [InlineData("ValueString not in header.none AND Id == header.second", new[] { 2 })] [InlineData("Id == header.second AND ValueString not in header.none", new[] { 2 })] public async Task Base_field_empty_list_beside_a_condition_returns_the_rows_linq_gives(string condition, int[] expected) { var whereRedb = $"ParentId == header.parent AND ({condition})"; var ranks = await Ranks(null, whereRedb); ranks.Should().Equal(expected, $"whereRedb: {whereRedb}"); } } [Collection("Postgres")] public sealed class PostgresRedbQueryConstantInsideOrTests(PostgresFixture fixture) : RedbQueryConstantInsideOrIntegrationTests(fixture.Redb); [Collection("MsSql")] public sealed class MsSqlRedbQueryConstantInsideOrTests(MsSqlFixture fixture) : RedbQueryConstantInsideOrIntegrationTests(fixture.Redb); Path: redb-route/tests/redb.Route.Tests.Core/Integration/RedbQueryFieldAgainstFieldIntegrationTests.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.Core/Integration/RedbQueryFieldAgainstFieldIntegrationTests.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core.Integration; /// Props with two numeric fields for a field-against-field redbQuery. public sealed class FieldPairProbeProps { public string? Tag { get; set; } public int Price { get; set; } public int Cost { get; set; } } /// /// A redbQuery where-string that compares a field with another field (Price > Cost) against a real /// database: the storage filters on both columns and returns the rows LINQ gives, in either order of the operands. /// Every object hangs under this instance's own parent, so parallel runs never see each other's rows. /// public abstract class RedbQueryFieldAgainstFieldIntegrationTests : IAsyncLifetime { private readonly IRedbService _redb; private readonly string _tag = Guid.NewGuid().ToString("N"); private readonly List _created = []; private long _parent; protected RedbQueryFieldAgainstFieldIntegrationTests(IRedbService redb) => _redb = redb; public async Task InitializeAsync() { await _redb.SyncSchemeAsync(); _parent = await Save(new RedbObject(new FieldPairProbeProps { Tag = _tag })); foreach (var (price, cost) in new[] { (5, 3), (3, 5), (4, 4) }) await Save(new RedbObject(new FieldPairProbeProps { Tag = _tag, Price = price, Cost = cost }) { ParentId = _parent }); } public async Task DisposeAsync() { // Children first, then the parent. foreach (var id in Enumerable.Reverse(_created)) await _redb.DeleteAsync(id); } private async Task Save(RedbObject entity) { var id = await _redb.SaveAsync(entity); _created.Add(id); return id; } [Theory] [InlineData("Price > Cost", new[] { 5 })] [InlineData("Cost < Price", new[] { 5 })] [InlineData("Price == Cost", new[] { 4 })] [InlineData("Cost == Price", new[] { 4 })] [InlineData("Price <= Cost", new[] { 3, 4 })] [InlineData("Price != Cost", new[] { 3, 5 })] public async Task A_field_against_another_field_returns_the_rows_linq_gives(string where, int[] expectedPrices) { await using var context = new RouteContext(); context.AddService(typeof(IRedbService), _redb); context.AddRoutes(r => r.From("direct://pair") .RedbQuery(typeof(FieldPairProbeProps), where: where, whereRedb: "ParentId == header.parent")); await context.Start(); var producer = context.GetEndpoint("direct://pair").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); exchange.In.Headers["parent"] = _parent; await producer.Process(exchange); exchange.Exception.Should().BeNull(); exchange.In.Body.Should().BeOfType>>().Subject .Select(o => o.Props.Price).OrderBy(p => p).Should().Equal(expectedPrices, $"where: {where}"); } } [Collection("Postgres")] public sealed class PostgresRedbQueryFieldAgainstFieldTests(PostgresFixture fixture) : RedbQueryFieldAgainstFieldIntegrationTests(fixture.Redb); [Collection("MsSql")] public sealed class MsSqlRedbQueryFieldAgainstFieldTests(MsSqlFixture fixture) : RedbQueryFieldAgainstFieldIntegrationTests(fixture.Redb); Path: redb-route/tests/redb.Route.Tests.Core/Integration/ServerRedbSqlDataSourceTests.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.Core/Integration/ServerRedbSqlDataSourceTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Npgsql; using redb.Core; using redb.Core.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Route.Tests.Core.Sql; namespace redb.Route.Tests.Core.Integration; /// /// The two redb services of on a database server: the default one on the test /// database, the one named orders on that database's name with , created when missing. /// public abstract class ServerRedbSqlFixture : IAsyncLifetime { /// Appended to the test database's name for the named service's database. public const string Suffix = "_route_sql_orders"; public ServiceProvider Services { get; private set; } = null!; public ServiceProvider NamedServices { get; private set; } = null!; protected abstract string ProbeTableSql { get; } /// Registers redb Pro on the test database, or on its named twin when . protected abstract Task RegisterAsync(IServiceCollection services, string connectionString, bool named); protected abstract string ConnectionStringName { get; } public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetConnectionString(ConnectionStringName)!; Services = await BuildAsync(cs, named: false); NamedServices = await BuildAsync(cs, named: true); } private async Task BuildAsync(string connectionString, bool named) { var services = new ServiceCollection(); services.AddLogging(); await RegisterAsync(services, connectionString, named); var provider = services.BuildServiceProvider(); var redb = provider.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch { await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.Context.ExecuteAsync(ProbeTableSql); return provider; } public async Task DisposeAsync() { await Services.DisposeAsync(); await NamedServices.DisposeAsync(); } } public sealed class PostgresRedbSqlFixture : ServerRedbSqlFixture { protected override string ConnectionStringName => "Postgres"; protected override string ProbeTableSql => "CREATE TABLE IF NOT EXISTS route_sql_lease_rows (tag text NOT NULL)"; protected override async Task RegisterAsync(IServiceCollection services, string connectionString, bool named) { var cs = new NpgsqlConnectionStringBuilder(global::redb.Route.Tests.Shared.TestDatabases.Postgres(connectionString)); if (named) { cs.Database += Suffix; var admin = new NpgsqlConnectionStringBuilder(cs.ConnectionString) { Database = "postgres" }; await using var connection = new NpgsqlConnection(admin.ConnectionString); await connection.OpenAsync(); await using var exists = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @n", connection); exists.Parameters.AddWithValue("n", cs.Database!); if (await exists.ExecuteScalarAsync() is null) { await using var create = new NpgsqlCommand($"CREATE DATABASE \"{cs.Database}\"", connection); await create.ExecuteNonQueryAsync(); } } services.AddRedbPro(o => o.UsePostgres(cs.ConnectionString)); } } public sealed class MsSqlRedbSqlFixture : ServerRedbSqlFixture { protected override string ConnectionStringName => "MSSql"; protected override string ProbeTableSql => "IF OBJECT_ID(N'route_sql_lease_rows') IS NULL CREATE TABLE route_sql_lease_rows (tag nvarchar(64) NOT NULL)"; protected override async Task RegisterAsync(IServiceCollection services, string connectionString, bool named) { var cs = new SqlConnectionStringBuilder(global::redb.Route.Tests.Shared.TestDatabases.MsSql(connectionString)); if (named) { cs.InitialCatalog += Suffix; var admin = new SqlConnectionStringBuilder(cs.ConnectionString) { InitialCatalog = "master" }; await using var connection = new SqlConnection(admin.ConnectionString); await connection.OpenAsync(); await using var create = new SqlCommand( $"IF DB_ID(N'{cs.InitialCatalog}') IS NULL CREATE DATABASE [{cs.InitialCatalog}]", connection); await create.ExecuteNonQueryAsync(); } services.AddRedbPro(o => o.UseMsSql(cs.ConnectionString)); } } [Collection("Postgres")] public sealed class PostgresRedbSqlDataSourceTests(PostgresRedbSqlFixture fixture) : RedbSqlDataSourceTestsBase, IClassFixture { protected override IServiceProvider Services => fixture.Services; protected override IServiceProvider NamedServices => fixture.NamedServices; protected override bool ChecksDistributedTransaction => true; } [Collection("MsSql")] public sealed class MsSqlRedbSqlDataSourceTests(MsSqlRedbSqlFixture fixture) : RedbSqlDataSourceTestsBase, IClassFixture { protected override IServiceProvider Services => fixture.Services; protected override IServiceProvider NamedServices => fixture.NamedServices; protected override bool ChecksDistributedTransaction => true; } Path: redb-route/tests/redb.Route.Tests.Core/RedbIdempotentRepositoryStorageTests.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.Core/RedbIdempotentRepositoryStorageTests.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Models; using System.Linq.Expressions; namespace redb.Route.Tests.Core; /// /// with a storage: the entries go to the named /// redb instance of the context, through a scope of it per operation, and a context without a host redb works. /// public sealed class RedbIdempotentRepositoryStorageTests : IAsyncLifetime { private readonly RouteContext _context = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() => await _context.DisposeAsync(); private static IRedbService ScopedService(List> stored) { var service = Substitute.For(); var queryable = Substitute.For>(); queryable.Where(Arg.Any>>()).Returns(queryable); queryable.WhereRedb(Arg.Any>>()).Returns(queryable); queryable.ToListAsync().Returns(_ => Task.FromResult(stored)); service.Query().Returns(queryable); return service; } [Fact] public async Task Named_storage_keeps_the_entries_in_that_instance_without_a_host_redb() { var scoped = ScopedService([]); var instance = Substitute.For(); instance.CanCreateScope.Returns(true); instance.CreateScope().Returns(_ => new RedbScope(scoped, null)); _context.RegisterRedbService("local", instance); _context.AddRedbIdempotentRepository("dedup", storage: "local"); await _context.Start(); var repository = _context.GetIdempotentRepositoryProvider().Get("dedup"); var found = await repository.Contains("order-1"); found.Should().BeFalse(); instance.Received().CreateScope(); _ = scoped.Received(1).SyncSchemeAsync(); scoped.Received(1).Query(); instance.DidNotReceive().Query(); } [Fact] public async Task Unknown_storage_fails_the_start_and_registers_nothing() { _context.AddRedbIdempotentRepository("dedup", storage: "ghost"); var start = () => _context.Start(); var thrown = await start.Should().ThrowAsync(); thrown.Which.ToString().Should().Contain("ghost"); _context.GetIdempotentRepositoryProvider().TryGet("dedup", out _).Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbIdempotentRepositoryTests.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.Core/RedbIdempotentRepositoryTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Route.Abstractions; using redb.Route.RedbCore.Models; using redb.Route.RedbCore.Repositories; using System.Linq.Expressions; namespace redb.Route.Tests.Core; /// /// Unit tests for . /// Uses NSubstitute to mock behind . /// public sealed class RedbIdempotentRepositoryTests { private readonly IRedbService _redb = Substitute.For(); private readonly IServiceScopeFactory _scopeFactory; private readonly RedbIdempotentOptions _defaultOptions = new() { ProcessorName = "test-route" }; public RedbIdempotentRepositoryTests() { var scope = Substitute.For(); var sp = Substitute.For(); sp.GetService(typeof(IRedbService)).Returns(_redb); scope.ServiceProvider.Returns(sp); _scopeFactory = Substitute.For(); _scopeFactory.CreateScope().Returns(scope); } private IServiceScopeFactory CreateScopeFactory(IRedbService redb) { var scope = Substitute.For(); var sp = Substitute.For(); sp.GetService(typeof(IRedbService)).Returns(redb); scope.ServiceProvider.Returns(sp); var factory = Substitute.For(); factory.CreateScope().Returns(scope); return factory; } private RedbIdempotentRepository CreateSut(RedbIdempotentOptions? options = null) => new(_scopeFactory, options ?? _defaultOptions); private void SetupQuery(List> results) { var queryable = Substitute.For>(); queryable.Where(Arg.Any>>()).Returns(queryable); queryable.WhereRedb(Arg.Any>>()).Returns(queryable); queryable.ToListAsync().Returns(Task.FromResult(results)); _redb.Query().Returns(queryable); } // ── Constructor ───────────────────────────────────────────────── [Fact] public void Ctor_NullScopeFactory_Throws() { var act = () => new RedbIdempotentRepository((IServiceScopeFactory)null!, _defaultOptions); act.Should().Throw().WithParameterName("scopeFactory"); } [Fact] public void Ctor_NullOpenScope_Throws() { var act = () => new RedbIdempotentRepository((Func)null!, _defaultOptions); act.Should().Throw().WithParameterName("openScope"); } [Fact] public void Ctor_NullOptions_Throws() { var act = () => new RedbIdempotentRepository(_scopeFactory, null!); act.Should().Throw().WithParameterName("options"); } // ── Add ───────────────────────────────────────────────────────── [Fact] public async Task Add_NullKey_Throws() { var sut = CreateSut(); var act = () => sut.Add(null!); await act.Should().ThrowAsync().WithParameterName("key"); } [Fact] public async Task Add_NewKey_SyncsScheme_SavesEntry_ReturnsTrue() { SetupQuery([]); _redb.SaveAsync(Arg.Any>()).Returns(1L); var sut = CreateSut(); var result = await sut.Add("msg-001"); result.Should().BeTrue(); await _redb.Received(1).SyncSchemeAsync(); await _redb.Received(1).SaveAsync(Arg.Is>(o => o.Props.ProcessorName == "test-route" && o.Props.MessageKey == "msg-001" && o.Props.Confirmed == false)); } [Fact] public async Task Add_DuplicateKey_ReturnsFalse() { var existing = new RedbObject { id = 42, Props = new IdempotentEntryProps { ProcessorName = "test-route", MessageKey = "msg-001", CreatedAt = DateTimeOffset.UtcNow, Confirmed = false } }; SetupQuery([existing]); var sut = CreateSut(); var result = await sut.Add("msg-001"); result.Should().BeFalse(); await _redb.DidNotReceive().SaveAsync(Arg.Any>()); } [Fact] public async Task Add_SyncSchemeCalledOnlyOnce() { SetupQuery([]); _redb.SaveAsync(Arg.Any>()).Returns(1L); var sut = CreateSut(); await sut.Add("msg-001"); await sut.Add("msg-002"); await _redb.Received(1).SyncSchemeAsync(); } // ── Add: unique-key race barrier ──────────────────────────────── [Fact] public async Task Add_SaveHitsUniqueViolation_ReturnsFalseInsteadOfThrowing() { // The lookup saw nothing, but a concurrent Add committed the key before our insert: // the per-scheme unique index rejects the row and the loser must report "duplicate". SetupQuery([]); _redb.SaveAsync(Arg.Any>()) .Returns(Task.FromException(new redb.Core.Exceptions.RedbUniqueViolationException( null, null, null, null, "UIX__objects__scheme_unique", null, new InvalidOperationException("23505")))); var sut = CreateSut(); var result = await sut.Add("msg-race"); result.Should().BeFalse(); } [Fact] public async Task Add_StampsValueUnique_WithCompositeName() { SetupQuery([]); RedbObject? saved = null; _redb.SaveAsync(Arg.Do>(o => saved = (RedbObject)o)) .Returns(1L); var sut = CreateSut(); await sut.Add("msg-001"); saved.Should().NotBeNull(); saved!.ValueUnique.Should().Be("test-route:msg-001"); saved.name.Should().Be(saved.ValueUnique); } // ── ComposeEntryName normalization ────────────────────────────── [Fact] public void ComposeEntryName_ShortComposite_IsRawAndReadable() { RedbIdempotentRepository.ComposeEntryName("proc", "key-1") .Should().Be("proc:key-1"); } [Fact] public void ComposeEntryName_LongComposite_FitsLimitAndStaysDistinct() { var prefix = new string('a', 500); var name1 = RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-1"); var name2 = RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-2"); // Fits _objects._value_unique (varchar(440)) and MSSQL _objects._name (nvarchar(450)). name1.Length.Should().Be(440); name1.Should().StartWith("proc:aaaa"); // Keys differing only past the readable prefix still map to distinct identities. name1.Should().NotBe(name2); name1[..375].Should().Be(name2[..375]); // Deterministic: the same composite always maps to the same identity. RedbIdempotentRepository.ComposeEntryName("proc", prefix + "-tail-1").Should().Be(name1); } // ── Add with TTL cleanup ──────────────────────────────────────── [Fact] public async Task Add_WithTtl_CleansExpired() { var options = new RedbIdempotentOptions { ProcessorName = "test-route", Ttl = TimeSpan.FromMinutes(30) }; // Setup two separate query chains: one for cleanup, one for add-check var cleanupQuery = Substitute.For>(); cleanupQuery.Where(Arg.Any>>()).Returns(cleanupQuery); cleanupQuery.WhereRedb(Arg.Any>>()).Returns(cleanupQuery); cleanupQuery.ToListAsync().Returns(Task.FromResult(new List>())); _redb.Query().Returns(cleanupQuery); _redb.SaveAsync(Arg.Any>()).Returns(1L); var sut = CreateSut(options); await sut.Add("msg-001"); // Query called at least twice: once for cleanup, once for duplicate check _redb.Received(2).Query(); } // ── Confirm ───────────────────────────────────────────────────── [Fact] public async Task Confirm_NullKey_Throws() { var sut = CreateSut(); var act = () => sut.Confirm(null!); await act.Should().ThrowAsync().WithParameterName("key"); } [Fact] public async Task Confirm_ExistingEntry_SetsConfirmedTrue() { var entry = new RedbObject { id = 42, Props = new IdempotentEntryProps { ProcessorName = "test-route", MessageKey = "msg-001", CreatedAt = DateTimeOffset.UtcNow, Confirmed = false } }; SetupQuery([entry]); _redb.SaveAsync(Arg.Any()).Returns(42L); var sut = CreateSut(); await sut.Confirm("msg-001"); entry.Props.Confirmed.Should().BeTrue(); await _redb.Received(1).SaveAsync(Arg.Is>(o => o.Props.Confirmed == true)); } [Fact] public async Task Confirm_NoEntry_DoesNothing() { SetupQuery([]); var sut = CreateSut(); await sut.Confirm("msg-missing"); await _redb.DidNotReceive().SaveAsync(Arg.Any()); } // ── Remove ────────────────────────────────────────────────────── [Fact] public async Task Remove_NullKey_Throws() { var sut = CreateSut(); var act = () => sut.Remove(null!); await act.Should().ThrowAsync().WithParameterName("key"); } [Fact] public async Task Remove_ExistingEntry_DeletesIt() { var entry = new RedbObject { id = 42, Props = new IdempotentEntryProps { ProcessorName = "test-route", MessageKey = "msg-001", CreatedAt = DateTimeOffset.UtcNow } }; SetupQuery([entry]); _redb.DeleteAsync(Arg.Any()).Returns(true); var sut = CreateSut(); await sut.Remove("msg-001"); await _redb.Received(1).DeleteAsync(Arg.Is>(o => o.id == 42)); } [Fact] public async Task Remove_NoEntry_DoesNothing() { SetupQuery([]); var sut = CreateSut(); await sut.Remove("msg-missing"); await _redb.DidNotReceive().DeleteAsync(Arg.Any()); } // ── Contains ──────────────────────────────────────────────────── [Fact] public async Task Contains_NullKey_Throws() { var sut = CreateSut(); var act = () => sut.Contains(null!); await act.Should().ThrowAsync().WithParameterName("key"); } [Fact] public async Task Contains_ExistingEntry_ReturnsTrue() { var entry = new RedbObject { id = 42, Props = new IdempotentEntryProps { ProcessorName = "test-route", MessageKey = "msg-001", CreatedAt = DateTimeOffset.UtcNow } }; SetupQuery([entry]); var sut = CreateSut(); var result = await sut.Contains("msg-001"); result.Should().BeTrue(); } [Fact] public async Task Contains_MissingEntry_ReturnsFalse() { SetupQuery([]); var sut = CreateSut(); var result = await sut.Contains("msg-missing"); result.Should().BeFalse(); } // ── Clear ─────────────────────────────────────────────────────── [Fact] public async Task Clear_EntriesExist_DeletesAll() { var entries = new List> { new() { id = 1, Props = new() { ProcessorName = "test-route", MessageKey = "a" } }, new() { id = 2, Props = new() { ProcessorName = "test-route", MessageKey = "b" } }, new() { id = 3, Props = new() { ProcessorName = "test-route", MessageKey = "c" } } }; SetupQuery(entries); _redb.DeleteAsync(Arg.Any>()).Returns(3); var sut = CreateSut(); await sut.Clear(); await _redb.Received(1).DeleteAsync(Arg.Any>()); } [Fact] public async Task Clear_NoEntries_SkipsDelete() { SetupQuery([]); var sut = CreateSut(); await sut.Clear(); await _redb.DidNotReceive().DeleteAsync(Arg.Any>()); } // ── Processor isolation ───────────────────────────────────────── [Fact] public async Task Add_DifferentProcessors_AreIsolated() { // Processor A has "msg-001" var aQuery = Substitute.For>(); aQuery.Where(Arg.Any>>()).Returns(aQuery); aQuery.WhereRedb(Arg.Any>>()).Returns(aQuery); aQuery.ToListAsync().Returns(Task.FromResult(new List> { new() { id = 1, Props = new() { ProcessorName = "route-A", MessageKey = "msg-001" } } })); // Processor B does not have "msg-001" var bRedb = Substitute.For(); var bQuery = Substitute.For>(); bQuery.Where(Arg.Any>>()).Returns(bQuery); bQuery.WhereRedb(Arg.Any>>()).Returns(bQuery); bQuery.ToListAsync().Returns(Task.FromResult(new List>())); bRedb.Query().Returns(bQuery); bRedb.SaveAsync(Arg.Any>()).Returns(2L); _redb.Query().Returns(aQuery); var sutA = new RedbIdempotentRepository(_scopeFactory, new RedbIdempotentOptions { ProcessorName = "route-A" }); var sutB = new RedbIdempotentRepository(CreateScopeFactory(bRedb), new RedbIdempotentOptions { ProcessorName = "route-B" }); var resultA = await sutA.Add("msg-001"); // already exists var resultB = await sutB.Add("msg-001"); // new for route-B resultA.Should().BeFalse(); resultB.Should().BeTrue(); } // ── IdempotentEntryProps model ────────────────────────────────── [Fact] public void IdempotentEntryProps_Defaults() { var props = new IdempotentEntryProps(); props.ProcessorName.Should().BeEmpty(); props.MessageKey.Should().BeEmpty(); props.CreatedAt.Should().Be(default); props.Confirmed.Should().BeFalse(); } // ── Interface compliance ──────────────────────────────────────── [Fact] public void Implements_IIdempotentRepository() { var sut = CreateSut(); sut.Should().BeAssignableTo(); } // ── An entry read while another caller deletes it ─────────────── /// /// The entry of a key that another node is deleting at that moment: the lookup by name still finds its object, and /// its props are gone (PostgreSQL, two nodes on one key). Each operation passes it over instead of failing. /// private static RedbObject EntryBeingDeleted() => new() { id = 42, Props = null! }; [Fact] public async Task Add_WhileTheEntryIsBeingDeleted_ClaimsTheKey_InsteadOfThrowing() { SetupQuery([EntryBeingDeleted()]); _redb.SaveAsync(Arg.Any>()).Returns(1L); var result = await CreateSut().Add("msg-001"); result.Should().BeTrue("the entry found is on its way out; uniqueness decides if it is not gone yet"); } [Fact] public async Task Contains_WhileTheEntryIsBeingDeleted_IsFalse_InsteadOfThrowing() { SetupQuery([EntryBeingDeleted()]); (await CreateSut().Contains("msg-001")).Should().BeFalse(); } [Fact] public async Task Confirm_WhileTheEntryIsBeingDeleted_SavesNothing_InsteadOfThrowing() { SetupQuery([EntryBeingDeleted()]); await CreateSut().Confirm("msg-001"); await _redb.DidNotReceive().SaveAsync(Arg.Any>()); } [Fact] public async Task Remove_WhileTheEntryIsBeingDeleted_DeletesNothing_InsteadOfThrowing() { SetupQuery([EntryBeingDeleted()]); await CreateSut().Remove("msg-001"); await _redb.DidNotReceive().DeleteAsync(Arg.Any()); } [Fact] public async Task Claim_WhileTheEntryIsBeingDeleted_DoesNotThrow() { SetupQuery([EntryBeingDeleted()]); _redb.SaveAsync(Arg.Any>()).Returns(1L); (await CreateSut().Claim("msg-001", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbObjectBodyExpressionTests.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.Core/RedbObjectBodyExpressionTests.cs ---- using redb.Core.Models.Entities; using redb.Route.Core; using redb.Route.Expressions; namespace redb.Route.Tests.Core; /// /// A body carries both Id and the JSON-named id: ${body.Id} used to /// fail with "Ambiguous match found" because the member lookup ignored case. /// public sealed class RedbObjectBodyExpressionTests { public sealed class SensorProps { public string Room { get; set; } = ""; } private static object? Evaluate(string expression) { var body = new RedbObject { Props = new SensorProps { Room = "kitchen" } }; body.Id = 1021; return new StringExpression(expression).Evaluate(new Exchange(new Message(body))); } [Theory] [InlineData("${body.Id}")] [InlineData("${body.id}")] public void The_id_reads_in_either_spelling(string expression) => Evaluate(expression).Should().Be(1021L); [Fact] public void The_props_read_through_the_body() => Evaluate("${body.Props.Room}").Should().Be("kitchen"); } Path: redb-route/tests/redb.Route.Tests.Core/RedbQueryDslTests.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.Core/RedbQueryDslTests.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Query; namespace redb.Route.Tests.Core; /// /// The RedbQuery verb (step 2): the where-string rides the engine's ONE /// expression AST into redb LINQ. The queryable is substituted and the predicate that reaches /// Where is COMPILED and probed against sample props — semantic checks, no database. /// public sealed class RedbQueryDslTests { public sealed class CustomerProps { public string? Name { get; set; } } public sealed class OrderProps { public string? Status { get; set; } public int Total { get; set; } public int Limit { get; set; } public string? Note { get; set; } public bool Urgent { get; set; } public CustomerProps? Customer { get; set; } } private readonly IRedbService _redb = Substitute.For(); private readonly IRouteContext _context = Substitute.For(); private readonly IOrderedRedbQueryable _query = Substitute.For>(); private Expression>? _captured; private Expression>? _capturedRedb; public RedbQueryDslTests() { _context.GetService().Returns(_redb); _redb.Query().Returns(_query); _query.Where(Arg.Do>>(e => _captured = e)).Returns(_query); _query.WhereRedb(Arg.Do>>(e => _capturedRedb = e)).Returns(_query); _query.OrderBy(Arg.Any>>()).Returns(_query); _query.OrderByDescending(Arg.Any>>()).Returns(_query); _query.Skip(Arg.Any()).Returns(_query); _query.Take(Arg.Any()).Returns(_query); _query.ToListAsync().Returns([]); } private RouteDefinition NewRoute() { var route = new RouteDefinition(); route._context = _context; return route; } private async Task> PredicateFor(string where, params (string Key, object? Value)[] headers) { var route = NewRoute(); route.RedbQuery(typeof(OrderProps), where: where); var exchange = new Exchange(); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; await route.Outputs[0].CreateProcessor(_context).Process(exchange, CancellationToken.None); _captured.Should().NotBeNull(); return _captured!.Compile(); } // ── translation semantics (predicate probed on samples) ────────── [Fact] public async Task Comparison_OnAStringProp() { var predicate = await PredicateFor("Status == 'open'"); predicate(new OrderProps { Status = "open" }).Should().BeTrue(); predicate(new OrderProps { Status = "closed" }).Should().BeFalse(); } [Fact] public async Task ValueSide_FoldsPerMessage_FromTheHeader() { var predicate = await PredicateFor("Total > header.min", ("min", 10)); predicate(new OrderProps { Total = 11 }).Should().BeTrue(); predicate(new OrderProps { Total = 10 }).Should().BeFalse(); } [Fact] public async Task AndOrNot_Combine() { var predicate = await PredicateFor("(Status == 'open' OR Urgent == true) AND NOT (Total < 5)"); predicate(new OrderProps { Status = "open", Total = 5 }).Should().BeTrue(); predicate(new OrderProps { Status = "closed", Urgent = true, Total = 7 }).Should().BeTrue(); predicate(new OrderProps { Status = "closed", Total = 7 }).Should().BeFalse(); predicate(new OrderProps { Status = "open", Total = 4 }).Should().BeFalse(); } [Fact] public async Task Contains_TranslatesOntoTheStringProp() { var predicate = await PredicateFor("contains(Note, header.q)", ("q", "url")); predicate(new OrderProps { Note = "urgently" }).Should().BeFalse(); predicate(new OrderProps { Note = "curl it" }).Should().BeTrue(); } [Fact] public async Task NestedPath_WalksTheClrProperties() { var predicate = await PredicateFor("Customer.Name == 'acme'"); predicate(new OrderProps { Customer = new CustomerProps { Name = "acme" } }).Should().BeTrue(); predicate(new OrderProps { Customer = new CustomerProps { Name = "other" } }).Should().BeFalse(); } [Fact] public async Task MirroredComparison_ValueOnTheLeft() { var predicate = await PredicateFor("50 <= Total"); predicate(new OrderProps { Total = 50 }).Should().BeTrue(); predicate(new OrderProps { Total = 49 }).Should().BeFalse(); } [Fact] public async Task NullComparison_OnANullableProp() { var predicate = await PredicateFor("Note == null"); predicate(new OrderProps()).Should().BeTrue(); predicate(new OrderProps { Note = "x" }).Should().BeFalse(); } [Fact] public async Task ValueOnlyGate_FoldsToABooleanConstant() { var open = await PredicateFor("header.enabled == true AND Status == 'open'", ("enabled", true)); open(new OrderProps { Status = "open" }).Should().BeTrue(); var gated = await PredicateFor("header.enabled == true AND Status == 'open'", ("enabled", false)); gated(new OrderProps { Status = "open" }).Should().BeFalse("the gate folded to false for THIS message"); } [Theory] [InlineData("Total > Limit", 5, 3, true)] [InlineData("Total > Limit", 3, 5, false)] [InlineData("Limit < Total", 5, 3, true)] [InlineData("Limit < Total", 3, 5, false)] [InlineData("Total == Limit", 4, 4, true)] [InlineData("Limit == Total", 4, 5, false)] public async Task AFieldAgainstAnotherField_ComparesTheTwoFields(string where, int total, int limit, bool expected) { var predicate = await PredicateFor(where); predicate(new OrderProps { Total = total, Limit = limit }).Should().Be(expected); } // ── loud refusals at route build ───────────────────────────────── [Fact] public void AFieldAgainstAComputedField_RefusesWithTheSpecHint() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), where: "Total > Limit * 2"); act.Should().Throw().WithMessage("*#spec*"); } [Fact] public void ArithmeticOnProps_RefusesWithTheSpecHint() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), where: "Total % 2 == 0"); act.Should().Throw().WithMessage("*#spec*"); } [Fact] public void UnknownIdentifier_RefusesNamingTheCandidates() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), where: "Statuss == 'open'"); act.Should().Throw() .WithMessage("*Statuss*").WithMessage("*Status*", "the property list helps fix the typo"); } [Fact] public void OrderingComparisonOnAString_RefusesWithTheHint() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), where: "Status > 'a'"); act.Should().Throw() .WithMessage("*string props property*").WithMessage("*#spec*"); } [Fact] public void UnboundedScan_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps)); act.Should().Throw().WithMessage("*unbounded*"); } [Fact] public void OrderByANonPropsPath_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), orderBy: "header.x"); act.Should().Throw().WithMessage("*props property path*"); } // ── query assembly ─────────────────────────────────────────────── [Fact] public async Task OrderBySkipTake_ReachTheQueryable() { var route = NewRoute(); route.RedbQuery(typeof(OrderProps), where: "Status == 'open'", orderBy: "Total", descending: true, skip: 20, take: 10); await route.Outputs[0].CreateProcessor(_context).Process(new Exchange(), CancellationToken.None); _query.Received(1).OrderByDescending(Arg.Any>>()); _query.Received(1).Skip(20); _query.Received(1).Take(10); await _query.Received(1).ToListAsync(); } [Fact] public async Task FilterSpec_AppliesFromTheRegistry() { var spec = Substitute.For>(); spec.Apply(_query).Returns(_query); _context.GetFromRegistry("#active").Returns(spec); var route = NewRoute(); route.RedbQuery(typeof(OrderProps), filter: "#active"); await route.Outputs[0].CreateProcessor(_context).Process(new Exchange(), CancellationToken.None); spec.Received(1).Apply(_query); } [Fact] public async Task TheListLandsInTheTarget() { List> stored = [new()]; _query.ToListAsync().Returns(stored); var route = NewRoute(); route.RedbQuery(typeof(OrderProps), take: 5, target: "header:orders"); var exchange = new Exchange(); exchange.In.Body = "kept"; await route.Outputs[0].CreateProcessor(_context).Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("kept"); exchange.In.Headers["orders"].Should().BeSameAs(stored); } // ── whereRedb / orderByRedb: the base fields of the stored object ─ private async Task>> BasePredicateFor(string whereRedb, params (string Key, object? Value)[] headers) { var route = NewRoute(); route.RedbQuery(typeof(OrderProps), whereRedb: whereRedb); var exchange = new Exchange(); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; await route.Outputs[0].CreateProcessor(_context).Process(exchange, CancellationToken.None); _capturedRedb.Should().NotBeNull("whereRedb goes to WhereRedb, not to Where"); _captured.Should().BeNull(); // The core's own parser must accept what the markup produced — the provider runs it next. var parse = () => new redb.Core.Query.Parsing.FilterExpressionParser().ParseRedbFilter(_capturedRedb!); parse.Should().NotThrow(); return _capturedRedb!; } [Fact] public async Task WhereRedb_ValueGuidFromAHeader() { var key = Guid.NewGuid(); var predicate = (await BasePredicateFor("ValueGuid == header.key", ("key", key.ToString()))).Compile(); predicate(new RedbObject { ValueGuid = key }).Should().BeTrue(); predicate(new RedbObject { ValueGuid = Guid.NewGuid() }).Should().BeFalse(); } [Fact] public async Task WhereRedb_IdParentIdAndValueString_Combine() { var predicate = (await BasePredicateFor("ParentId == 7 AND ValueString == 'A-1' AND Id > 100")).Compile(); predicate(new RedbObject { ParentId = 7, ValueString = "A-1", Id = 101 }).Should().BeTrue(); predicate(new RedbObject { ParentId = 7, ValueString = "A-1", Id = 100 }).Should().BeFalse(); predicate(new RedbObject { ParentId = 8, ValueString = "A-1", Id = 101 }).Should().BeFalse(); } [Fact] public async Task WhereRedb_NullParent_AndStartsWithOnName() { var predicate = (await BasePredicateFor("ParentId == null AND startsWith(Name, 'INC-')")).Compile(); predicate(new RedbObject { Name = "INC-1" }).Should().BeTrue(); predicate(new RedbObject { Name = "INC-1", ParentId = 3 }).Should().BeFalse(); } [Fact] public async Task WhereRedb_DateCreate_TakesATextDate() { var predicate = (await BasePredicateFor("DateCreate >= header.since", ("since", "2026-09-01T00:00:00+00:00"))).Compile(); predicate(new RedbObject { DateCreate = new DateTimeOffset(2026, 9, 2, 0, 0, 0, TimeSpan.Zero) }).Should().BeTrue(); predicate(new RedbObject { DateCreate = new DateTimeOffset(2026, 8, 31, 0, 0, 0, TimeSpan.Zero) }).Should().BeFalse(); } [Fact] public async Task WhereAndWhereRedb_BothReachTheQueryable() { var route = NewRoute(); route.RedbQuery(typeof(OrderProps), where: "Status == 'open'", whereRedb: "ValueLong == 5"); await route.Outputs[0].CreateProcessor(_context).Process(new Exchange(), CancellationToken.None); _captured.Should().NotBeNull(); _capturedRedb.Should().NotBeNull(); } [Fact] public void WhereRedb_APropsName_RefusesNamingTheBaseFields() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "Status == 'open'"); act.Should().Throw() .WithMessage("whereRedb 'Status == 'open'': 'Status' is neither a base field*") .WithMessage("*ValueGuid*", "the base-field list helps fix it"); } [Fact] public void WhereRedb_AComputedMemberOfIRedbObject_IsNotABaseField() { // HasParent is on IRedbObject but has no column; the core would map it to _id silently. var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "HasParent == true"); act.Should().Throw().WithMessage("*'HasParent' is neither a base field*"); } [Fact] public void WhereRedb_ValueBytes_IsRefused() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "ValueBytes == null"); act.Should().Throw().WithMessage("*'ValueBytes' is neither a base field*"); } [Fact] public void WhereRedb_ANestedPath_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "Name.Length == 3"); act.Should().Throw().WithMessage("*base fields are flat*"); } [Fact] public async Task OrderByRedb_ReachesOrderByDescendingRedb_WithTheFieldType() { _query.OrderByDescendingRedb(Arg.Any>>()).Returns(_query); var route = NewRoute(); route.RedbQuery(typeof(OrderProps), whereRedb: "ParentId == 1", orderByRedb: "DateCreate", descending: true); await route.Outputs[0].CreateProcessor(_context).Process(new Exchange(), CancellationToken.None); _query.Received(1).OrderByDescendingRedb( Arg.Is>>(e => new redb.Core.Query.OrderingExpressionParser().ParseRedbOrdering(e, redb.Core.Query.QueryExpressions.SortDirection.Descending) != null)); } [Fact] public void OrderByAndOrderByRedb_Together_Refuse() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), orderBy: "Total", orderByRedb: "Id"); act.Should().Throw().WithMessage("*orders by one key*"); } [Fact] public void OrderByRedb_AnUnknownField_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), orderByRedb: "Total"); act.Should().Throw().WithMessage("*not a base field path of IRedbObject*"); } // ── outputType: the terminal operation ─────────────────────────── private async Task RunOutput(RedbQueryOutput output, string? whereRedb = "Id > 0") { var route = NewRoute(); route.RedbQuery(typeof(OrderProps), whereRedb: whereRedb, outputType: output); var exchange = new Exchange(); await route.Outputs[0].CreateProcessor(_context).Process(exchange, CancellationToken.None); return exchange; } [Fact] public async Task OutputFirst_IsFirstOrDefault_AndLandsTheObjectOrNull() { var found = new RedbObject(); _query.FirstOrDefaultAsync().Returns(found, (RedbObject?)null); (await RunOutput(RedbQueryOutput.First)).In.Body.Should().BeSameAs(found); (await RunOutput(RedbQueryOutput.First)).In.Body.Should().BeNull("nothing matched is null, the markup decides"); await _query.DidNotReceive().ToListAsync(); } [Fact] public async Task OutputCountAndAny_AreCountAsyncAndAnyAsync() { _query.CountAsync().Returns(3); _query.AnyAsync().Returns(true); (await RunOutput(RedbQueryOutput.Count)).In.Body.Should().Be(3); (await RunOutput(RedbQueryOutput.Any)).In.Body.Should().Be(true); await _query.DidNotReceive().ToListAsync(); } [Fact] public async Task OutputCount_WithoutACondition_IsNoUnboundedScan() { // The guard is about pulling every row into memory; a count reads one number. _query.CountAsync().Returns(7); (await RunOutput(RedbQueryOutput.Count, whereRedb: null)).In.Body.Should().Be(7); } [Fact] public void OutputFirst_WithTake_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "Id > 0", take: 1, outputType: RedbQueryOutput.First); act.Should().Throw().WithMessage("*First reads one object*take does not apply*"); } [Fact] public void OutputCount_WithOrdering_Refuses() { var act = () => NewRoute().RedbQuery(typeof(OrderProps), whereRedb: "Id > 0", orderByRedb: "Id", outputType: RedbQueryOutput.Count); act.Should().Throw().WithMessage("*Count answers for all the matches*"); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbQueryInOperatorTests.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.Core/RedbQueryInOperatorTests.cs ---- using System.Linq.Expressions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Parsing; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core; /// /// in / not in in a redbQuery where-string: a search by a list of keys in one /// query (ValueString in header.codes, Id in body.ids). The storage already turns /// Enumerable.Contains over a list into an SQL IN, for props and for base fields alike, /// so the translator emits exactly that — over an array typed as the member, each element converted /// the way a single comparison converts its value. /// /// An empty list never reaches the storage: it becomes a constant "nothing found" (or "everything" /// for not in) in the translator. What the storage does with {"$in": []} is decided in /// SQL we do not see from here, and "nothing found" must not depend on it. /// /// public sealed class RedbQueryInOperatorTests { public sealed class OrderProps { public string? Status { get; set; } public int Total { get; set; } } private readonly IRedbService _redb = Substitute.For(); private readonly IRouteContext _context = Substitute.For(); private readonly IOrderedRedbQueryable _query = Substitute.For>(); private Expression>? _captured; private Expression>? _capturedRedb; public RedbQueryInOperatorTests() { _context.GetService().Returns(_redb); _redb.Query().Returns(_query); _query.Where(Arg.Do>>(e => _captured = e)).Returns(_query); _query.WhereRedb(Arg.Do>>(e => _capturedRedb = e)).Returns(_query); _query.ToListAsync().Returns([]); } private async Task Run(Action configure, params (string Key, object? Value)[] headers) { var route = new RouteDefinition { _context = _context }; configure(route); var exchange = new Exchange(); foreach (var (key, value) in headers) exchange.In.Headers[key] = value; await route.Outputs[0].CreateProcessor(_context).Process(exchange, CancellationToken.None); } private async Task> Props(string where, params (string Key, object? Value)[] headers) { await Run(r => r.RedbQuery(typeof(OrderProps), where: where), headers); _captured.Should().NotBeNull(); // The storage's own parser must accept what we produced — the provider runs it next. var parse = () => new FilterExpressionParser().ParseFilter(_captured!); parse.Should().NotThrow(); return _captured!.Compile(); } private async Task> Base(string whereRedb, params (string Key, object? Value)[] headers) { await Run(r => r.RedbQuery(typeof(OrderProps), whereRedb: whereRedb), headers); _capturedRedb.Should().NotBeNull(); var parse = () => new FilterExpressionParser().ParseRedbFilter(_capturedRedb!); parse.Should().NotThrow(); return _capturedRedb!.Compile(); } [Fact] public async Task A_props_member_in_a_collection_from_a_header() { var predicate = await Props("Status in header.statuses", ("statuses", new List { "open", "held" })); predicate(new OrderProps { Status = "open" }).Should().BeTrue(); predicate(new OrderProps { Status = "held" }).Should().BeTrue(); predicate(new OrderProps { Status = "closed" }).Should().BeFalse(); } [Fact] public async Task Not_in_negates() { var predicate = await Props("Status not in ('closed','void')"); predicate(new OrderProps { Status = "open" }).Should().BeTrue(); predicate(new OrderProps { Status = "void" }).Should().BeFalse(); } [Fact] public async Task Elements_are_converted_to_the_members_type() { // Strings from a header, an int member: each element is converted as a single comparison // converts its value, so the storage gets an int[] and not a list of strings it cannot match. var predicate = await Props("Total in header.totals", ("totals", new List { "10", "20" })); predicate(new OrderProps { Total = 20 }).Should().BeTrue(); predicate(new OrderProps { Total = 30 }).Should().BeFalse(); } [Fact] public async Task A_base_field_in_a_list_of_ids() { var predicate = await Base("Id in header.ids", ("ids", new List { 7, 9 })); predicate(new RedbObject { Id = 9 }).Should().BeTrue(); predicate(new RedbObject { Id = 8 }).Should().BeFalse(); } [Fact] public async Task A_base_string_field_in_a_literal_list() { var predicate = await Base("ValueString in ('A-1','A-2')"); predicate(new RedbObject { ValueString = "A-2" }).Should().BeTrue(); predicate(new RedbObject { ValueString = "B-1" }).Should().BeFalse(); } [Fact] public async Task An_empty_list_finds_nothing_and_never_reaches_the_storage_as_an_empty_in() { var predicate = await Props("Status in header.statuses", ("statuses", new List())); predicate(new OrderProps { Status = "open" }).Should().BeFalse(); _captured!.ToString().Should().NotContain("Contains", "an empty IN is decided here, not in SQL we do not see"); } [Fact] public async Task An_empty_list_under_not_in_keeps_everything() { var predicate = await Props("Status not in header.statuses", ("statuses", new List())); predicate(new OrderProps { Status = "open" }).Should().BeTrue(); } [Fact] public async Task A_member_on_the_right_of_in_is_refused() { var act = () => Props("'open' in Status"); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("in"); } [Fact] public async Task A_header_only_membership_is_a_per_message_gate() { // No member on either side: decided once per message, like any other header condition // inside a where-string. var open = await Props("header.tier in ('gold') AND Status == 'open'", ("tier", "gold")); open(new OrderProps { Status = "open" }).Should().BeTrue(); _captured = null; var shut = await Props("header.tier in ('gold') AND Status == 'open'", ("tier", "bronze")); shut(new OrderProps { Status = "open" }).Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbRouteExtensionsTests.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.Core/RedbRouteExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core; /// /// Tests for . /// public sealed class RedbRouteExtensionsTests { // ── GetRedbService (from IRouteContext) ────────────────────────── [Fact] public void GetRedbService_RegisteredViaAddService_ReturnsIt() { var redb = Substitute.For(); var context = Substitute.For(); context.GetService().Returns(redb); var result = context.GetRedbService(); result.Should().BeSameAs(redb); } [Fact] public void GetRedbService_RegisteredViaServiceProvider_ReturnsIt() { var redb = Substitute.For(); var sp = Substitute.For(); sp.GetService(typeof(IRedbService)).Returns(redb); var context = Substitute.For(); context.GetService().Returns((IRedbService?)null); context.GetServiceProvider().Returns(sp); var result = context.GetRedbService(); result.Should().BeSameAs(redb); } [Fact] public void GetRedbService_NotRegistered_Throws() { var context = Substitute.For(); context.GetService().Returns((IRedbService?)null); context.GetServiceProvider().Returns((IServiceProvider?)null); var act = () => context.GetRedbService(); act.Should().Throw() .WithMessage("*IRedbService*not registered*"); } [Fact] public void GetRedbService_NullContext_Throws() { IRouteContext? context = null; var act = () => RedbRouteExtensions.GetRedbService(context!); act.Should().Throw().WithParameterName("context"); } // ── ProcessWithRedb (async) ───────────────────────────────────── [Fact] public void ProcessWithRedb_Async_NullAction_Throws() { var route = Substitute.For(); var act = () => route.ProcessWithRedb((Func)null!); act.Should().Throw().WithParameterName("action"); } [Fact] public void ProcessWithRedb_Async_ChainsToRoute() { var route = Substitute.For(); route.Process(Arg.Any>()).Returns(route); var result = route.ProcessWithRedb(async (redb, exchange, ct) => { await Task.CompletedTask; }); result.Should().BeSameAs(route); route.Received(1).Process(Arg.Any>()); } // ── ProcessWithRedb (sync) ────────────────────────────────────── [Fact] public void ProcessWithRedb_Sync_NullAction_Throws() { var route = Substitute.For(); var act = () => route.ProcessWithRedb((Action)null!); act.Should().Throw().WithParameterName("action"); } [Fact] public void ProcessWithRedb_Sync_ChainsToRoute() { var route = Substitute.For(); route.Process(Arg.Any>()).Returns(route); var result = route.ProcessWithRedb((redb, exchange) => { }); result.Should().BeSameAs(route); route.Received(1).Process(Arg.Any>()); } // ── SetBodyFromRedb ───────────────────────────────────────────── [Fact] public void SetBodyFromRedb_NullFactory_Throws() { var route = Substitute.For(); var act = () => route.SetBodyFromRedb(null!); act.Should().Throw().WithParameterName("factory"); } [Fact] public void SetBodyFromRedb_ChainsToRoute() { var route = Substitute.For(); route.SetBody(Arg.Any>()).Returns(route); var result = route.SetBodyFromRedb((redb, exchange) => "value"); result.Should().BeSameAs(route); route.Received(1).SetBody(Arg.Any>()); } // ── SetHeaderFromRedb ─────────────────────────────────────────── [Fact] public void SetHeaderFromRedb_NullFactory_Throws() { var route = Substitute.For(); var act = () => route.SetHeaderFromRedb("X-Key", null!); act.Should().Throw().WithParameterName("factory"); } [Fact] public void SetHeaderFromRedb_ChainsToRoute() { var route = Substitute.For(); route.SetHeader(Arg.Any(), Arg.Any>()).Returns(route); var result = route.SetHeaderFromRedb("X-Count", (redb, exchange) => 42); result.Should().BeSameAs(route); route.Received(1).SetHeader("X-Count", Arg.Any>()); } // ── Scoped resolution via exchange.ServiceProvider ─────────────── [Fact] public async Task ProcessWithRedb_Async_ResolvesFromExchangeScope() { var scopedRedb = Substitute.For(); var exchange = CreateExchangeWithScope(scopedRedb); Func? captured = null; var route = Substitute.For(); route.Process(Arg.Any>()) .Returns(ci => { captured = ci.Arg>(); return route; }); route.ProcessWithRedb(async (redb, ex, ct) => { redb.Should().BeSameAs(scopedRedb); await Task.CompletedTask; }); captured.Should().NotBeNull(); await captured!(exchange, CancellationToken.None); } [Fact] public void ProcessWithRedb_Sync_ResolvesFromExchangeScope() { var scopedRedb = Substitute.For(); var exchange = CreateExchangeWithScope(scopedRedb); Action? captured = null; var route = Substitute.For(); route.Process(Arg.Any>()) .Returns(ci => { captured = ci.Arg>(); return route; }); route.ProcessWithRedb((redb, ex) => { redb.Should().BeSameAs(scopedRedb); }); captured.Should().NotBeNull(); captured!(exchange); } [Fact] public void SetBodyFromRedb_ResolvesFromExchangeScope() { var scopedRedb = Substitute.For(); var exchange = CreateExchangeWithScope(scopedRedb); Func? captured = null; var route = Substitute.For(); route.SetBody(Arg.Any>()) .Returns(ci => { captured = ci.Arg>(); return route; }); route.SetBodyFromRedb((redb, ex) => { redb.Should().BeSameAs(scopedRedb); return "ok"; }); captured.Should().NotBeNull(); captured!(exchange).Should().Be("ok"); } [Fact] public void SetHeaderFromRedb_ResolvesFromExchangeScope() { var scopedRedb = Substitute.For(); var exchange = CreateExchangeWithScope(scopedRedb); Func? captured = null; var route = Substitute.For(); route.SetHeader(Arg.Is("X-Key"), Arg.Any>()) .Returns(ci => { captured = ci.Arg>(); return route; }); route.SetHeaderFromRedb("X-Key", (redb, ex) => { redb.Should().BeSameAs(scopedRedb); return 42; }); captured.Should().NotBeNull(); captured!(exchange).Should().Be(42); } [Fact] public async Task ProcessWithRedb_Async_FallsBackToRouteContext_WhenNoScope() { var routeRedb = Substitute.For(); var context = Substitute.For(); context.GetService().Returns(routeRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.ProcessWithRedb(async (redb, ex, ct) => { observed = redb; await Task.CompletedTask; }); await InvokeAsync(route, context, new Exchange()); observed.Should().BeSameAs(routeRedb); } [Fact] public async Task ProcessWithRedb_Async_EachExchange_GetsScopedService() { // Build a real DI container with a scoped service var services = new ServiceCollection(); services.AddScoped(_ => Substitute.For()); var rootProvider = services.BuildServiceProvider(); var scopeFactory = rootProvider.GetRequiredService(); Func? captured = null; var route = Substitute.For(); route.Process(Arg.Any>()) .Returns(ci => { captured = ci.Arg>(); return route; }); IRedbService? first = null; IRedbService? second = null; route.ProcessWithRedb(async (redb, ex, ct) => { if (first == null) first = redb; else second = redb; await Task.CompletedTask; }); captured.Should().NotBeNull(); // Two exchanges with DIFFERENT scopes var scope1 = scopeFactory.CreateScope(); var ex1 = Substitute.For(); ex1.ServiceProvider.Returns(scope1.ServiceProvider); var scope2 = scopeFactory.CreateScope(); var ex2 = Substitute.For(); ex2.ServiceProvider.Returns(scope2.ServiceProvider); await captured!(ex1, CancellationToken.None); await captured!(ex2, CancellationToken.None); first.Should().NotBeNull(); second.Should().NotBeNull(); first.Should().NotBeSameAs(second, "each exchange should get its own scoped IRedbService"); scope1.Dispose(); scope2.Dispose(); } // ── Helper ─────────────────────────────────────────────────────── private static IExchange CreateExchangeWithScope(IRedbService scopedRedb) { var sp = Substitute.For(); sp.GetService(typeof(IRedbService)).Returns(scopedRedb); var exchange = Substitute.For(); exchange.ServiceProvider.Returns(sp); return exchange; } // ── Named ProcessWithRedb (async) ─────────────────────────────── [Fact] public async Task ProcessWithRedb_Named_Async_ResolvesFromRegistry() { var namedRedb = Substitute.For(); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders-db").Returns(namedRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.ProcessWithRedb("orders-db", async (redb, ex, ct) => { observed = redb; await Task.CompletedTask; }); await InvokeAsync(route, context, new Exchange()); observed.Should().BeSameAs(namedRedb); } // ── Named ProcessWithRedb (sync) ──────────────────────────────── [Fact] public async Task ProcessWithRedb_Named_Sync_ResolvesFromRegistry() { var namedRedb = Substitute.For(); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders-db").Returns(namedRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.ProcessWithRedb("orders-db", (redb, ex) => { observed = redb; }); await InvokeAsync(route, context, new Exchange()); observed.Should().BeSameAs(namedRedb); } // ── Named SetBodyFromRedb ─────────────────────────────────────── [Fact] public async Task SetBodyFromRedb_Named_ResolvesFromRegistry() { var namedRedb = Substitute.For(); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:analytics").Returns(namedRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.SetBodyFromRedb("analytics", (redb, ex) => { observed = redb; return "data"; }); var exchange = new Exchange(); await InvokeAsync(route, context, exchange); observed.Should().BeSameAs(namedRedb); exchange.In.Body.Should().Be("data"); } // ── Named SetHeaderFromRedb ───────────────────────────────────── [Fact] public async Task SetHeaderFromRedb_Named_ResolvesFromRegistry() { var namedRedb = Substitute.For(); var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:orders-db").Returns(namedRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.SetHeaderFromRedb("orders-db", "X-Count", (redb, ex) => { observed = redb; return 99; }); var exchange = new Exchange(); await InvokeAsync(route, context, exchange); observed.Should().BeSameAs(namedRedb); exchange.In.Headers["X-Count"].Should().Be(99); } // ── Named: empty name falls back to default ───────────────────── [Fact] public async Task ProcessWithRedb_Named_EmptyName_FallsBackToDefault() { var defaultRedb = Substitute.For(); var context = Substitute.For(); context.GetService().Returns(defaultRedb); var route = new RouteDefinition(); route._context = context; IRedbService? observed = null; route.ProcessWithRedb("", async (redb, ex, ct) => { observed = redb; await Task.CompletedTask; }); await InvokeAsync(route, context, new Exchange()); observed.Should().BeSameAs(defaultRedb); } // ── Named: not found throws ───────────────────────────────────── [Fact] public async Task ProcessWithRedb_Named_NotFound_Throws() { var context = Substitute.For(); context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); context.GetFromRegistry("redb:missing").Returns((IRedbService?)null); var route = new RouteDefinition(); route._context = context; route.ProcessWithRedb("missing", (redb, ex) => { }); var act = async () => await InvokeAsync(route, context, new Exchange()); await act.Should().ThrowAsync() .WithMessage("*Named IRedbService 'missing'*not found*"); } // ── Named + IServiceScopeFactory: per-exchange scoping ─────────── /// /// When a named is registered (as TsakContextManager /// does under "redb-factory:{name}"), each exchange gets its own scoped /// ; repeat calls within the same exchange return the cached scope. /// [Fact] public async Task ProcessWithRedb_Named_WithFactory_PerExchangeScope_AndCacheReuse() { // Real DI container with scoped IRedbService. var services = new ServiceCollection(); services.AddScoped(_ => Substitute.For()); var rootProvider = services.BuildServiceProvider(); var scopeFactory = rootProvider.GetRequiredService(); // Mocked context: factory present at "redb-factory:orders-db". var context = Substitute.For(); context.GetFromRegistry("redb-factory:orders-db").Returns(scopeFactory); var route = new RouteDefinition(); route._context = context; var resolved = new List(); route.ProcessWithRedb("orders-db", async (redb, ex, ct) => { resolved.Add(redb); await Task.CompletedTask; }); var processor = route.Outputs[0].CreateProcessor(context); var ex1 = new Exchange(); var ex2 = new Exchange(); // First exchange — invoke twice to exercise cache reuse. await processor.Process(ex1, CancellationToken.None); await processor.Process(ex1, CancellationToken.None); // Second exchange — must get its own scoped instance. await processor.Process(ex2, CancellationToken.None); resolved.Should().HaveCount(3); resolved[0].Should().BeSameAs(resolved[1], "second call within same exchange must reuse the cached scope"); resolved[0].Should().NotBeSameAs(resolved[2], "different exchanges must get different scoped IRedbService"); } // ── Helper to invoke a real RouteDefinition's first output processor ───── private static async Task InvokeAsync(RouteDefinition route, IRouteContext context, IExchange exchange) { var processor = route.Outputs[0].CreateProcessor(context); await processor.Process(exchange, CancellationToken.None); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbStorageDslTests.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.Core/RedbStorageDslTests.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.RedbCore.Extensions; namespace redb.Route.Tests.Core; /// /// The declarative storage verbs (step 1): string/Type forms of get/save/delete over /// a substituted — no database, pure verb semantics. /// public sealed class RedbStorageDslTests { public sealed class OrderProps { public string? Value { get; set; } } private readonly IRedbService _redb = Substitute.For(); private readonly IRouteContext _context = Substitute.For(); public RedbStorageDslTests() => _context.GetService().Returns(_redb); private RouteDefinition NewRoute() { var route = new RouteDefinition(); route._context = _context; return route; } private async Task RunAsync(RouteDefinition route, object? body = null, params (string Key, object? Value)[] headers) { var exchange = new Exchange(); exchange.In.Body = body; foreach (var (key, value) in headers) exchange.In.Headers[key] = value; var processor = route.Outputs[0].CreateProcessor(_context); await processor.Process(exchange, CancellationToken.None); return exchange; } // ── RedbGet (typed) ────────────────────────────────────────────── [Fact] public async Task RedbGet_LoadsById_IntoTheBody() { var stored = new RedbObject { Props = new OrderProps { Value = "42" } }; _redb.LoadAsync(42L, 10).Returns(stored); var route = NewRoute(); route.RedbGet(typeof(OrderProps), "${header.orderId}"); var exchange = await RunAsync(route, headers: ("orderId", 42L)); exchange.In.Body.Should().BeSameAs(stored); } [Fact] public async Task RedbGet_TargetHeader_LeavesTheBodyAlone() { var stored = new RedbObject(); _redb.LoadAsync(7L, 3).Returns(stored); var route = NewRoute(); route.RedbGet(typeof(OrderProps), "${header.id}", depth: 3, target: "header:order"); var exchange = await RunAsync(route, body: "untouched", headers: ("id", 7L)); exchange.In.Body.Should().Be("untouched"); exchange.In.Headers["order"].Should().BeSameAs(stored); } [Fact] public void RedbGet_UnknownTarget_FailsAtDefinitionTime() { var act = () => NewRoute().RedbGet(typeof(OrderProps), "${header.id}", target: "cookie:x"); act.Should().Throw().WithMessage("*'cookie:x'*"); } // ── RedbGetJson ────────────────────────────────────────────────── [Fact] public async Task RedbGetJson_LoadsRawJson_NoClrTypeInvolved() { _redb.LoadJsonAsync(11L, 2).Returns("{\"id\":11}"); var route = NewRoute(); route.RedbGetJson("${header.id}", depth: 2); var exchange = await RunAsync(route, headers: ("id", 11L)); exchange.In.Body.Should().Be("{\"id\":11}"); } // ── RedbSave ───────────────────────────────────────────────────── [Fact] public async Task RedbSave_RedbObjectBody_SavedAsIs() { var obj = new RedbObject(); var route = NewRoute(); route.RedbSave(); var exchange = await RunAsync(route, body: obj); await _redb.Received(1).SaveAsync((IRedbObject)obj); exchange.In.Body.Should().BeSameAs(obj); } [Fact] public async Task RedbSave_JsonBody_MaterializedThroughTheType() { var route = NewRoute(); route.RedbSave(typeof(OrderProps)); var exchange = await RunAsync(route, body: "{\"properties\":{\"Value\":\"hello\"}}"); await _redb.Received(1).SaveAsync(Arg.Is(o => o is RedbObject && ((RedbObject)o).Props.Value == "hello")); exchange.In.Body.Should().BeOfType>(); } [Fact] public async Task RedbSave_JsonBodyWithoutType_FailsNamingTheAttribute() { var route = NewRoute(); route.RedbSave(); var act = () => RunAsync(route, body: "{\"properties\":{}}"); await act.Should().ThrowAsync().WithMessage("*type*"); await _redb.DidNotReceive().SaveAsync(Arg.Any()); } [Fact] public async Task RedbSave_ByUnique_GoesThroughSaveByUniqueAsync() { var obj = new RedbObject(); var route = NewRoute(); route.RedbSave(typeof(OrderProps), byUnique: true); await RunAsync(route, body: obj); await _redb.Received(1).SaveByUniqueAsync(obj); await _redb.DidNotReceive().SaveAsync(Arg.Any()); } [Fact] public void RedbSave_ByUniqueWithoutType_FailsAtDefinitionTime() { var act = () => NewRoute().RedbSave(byUnique: true); act.Should().Throw().WithMessage("*props type*"); } // ── RedbDelete ─────────────────────────────────────────────────── [Fact] public async Task RedbDelete_DeletesById_AndReportsTheOutcome() { _redb.DeleteAsync(13L).Returns(true); var route = NewRoute(); route.RedbDelete("${header.id}"); var exchange = await RunAsync(route, body: "kept", headers: ("id", 13L)); exchange.In.Body.Should().Be("kept"); exchange.In.Headers["redbDeleted"].Should().Be(true); } // ── storage= resolves the NAMED service ────────────────────────── [Fact] public async Task NamedStorage_ResolvesFromTheRegistry() { var named = Substitute.For(); named.DeleteAsync(5L).Returns(true); _context.GetFromRegistry(Arg.Any()) .Returns((Microsoft.Extensions.DependencyInjection.IServiceScopeFactory?)null); _context.GetFromRegistry("redb:archive").Returns(named); var route = NewRoute(); route.RedbDelete("${header.id}", storage: "archive"); await RunAsync(route, headers: ("id", 5L)); await named.Received(1).DeleteAsync(5L); await _redb.DidNotReceive().DeleteAsync(Arg.Any()); } } Path: redb-route/tests/redb.Route.Tests.Core/RedbTransactedActionTests.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.Core/RedbTransactedActionTests.cs ---- using System.Collections.Concurrent; using NSubstitute; using redb.Core; using redb.Core.Data; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Definitions; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Transactions; using redb.Route.Transactions; namespace redb.Route.Tests.Core; // BeginRedbTransaction is [Obsolete] (use .Transacted()); these tests exercise it deliberately. #pragma warning disable CS0618 /// /// Tests for and the /// BeginRedbTransaction DSL extensions (S3.1 R-17). /// public sealed class RedbTransactedActionTests { // ── RedbTransactedAction adapter ──────────────────────────────── [Fact] public void Constructor_NullTx_Throws() { var act = () => new RedbTransactedAction(null!); act.Should().Throw().WithParameterName("tx"); } [Fact] public async Task Commit_CommitsAndDisposesUnderlyingTx() { var tx = Substitute.For(); tx.IsActive.Returns(true); var action = new RedbTransactedAction(tx); await action.Commit(); await tx.Received(1).CommitAsync(); await tx.Received(1).DisposeAsync(); } [Fact] public async Task Rollback_RollsBackAndDisposesUnderlyingTx() { var tx = Substitute.For(); tx.IsActive.Returns(true); var action = new RedbTransactedAction(tx); await action.Rollback(); await tx.Received(1).RollbackAsync(); await tx.Received(1).DisposeAsync(); } [Fact] public async Task Commit_InactiveTx_OnlyDisposes() { var tx = Substitute.For(); tx.IsActive.Returns(false); var action = new RedbTransactedAction(tx); await action.Commit(); await tx.DidNotReceive().CommitAsync(); await tx.Received(1).DisposeAsync(); } [Fact] public async Task DoubleCommit_SecondCallIsNoOp() { var tx = Substitute.For(); tx.IsActive.Returns(true); var action = new RedbTransactedAction(tx); await action.Commit(); await action.Commit(); await tx.Received(1).CommitAsync(); await tx.Received(1).DisposeAsync(); } [Fact] public async Task Rollback_AfterCommit_IsNoOp() { var tx = Substitute.For(); tx.IsActive.Returns(true); var action = new RedbTransactedAction(tx); await action.Commit(); await action.Rollback(); await tx.Received(1).CommitAsync(); await tx.DidNotReceive().RollbackAsync(); await tx.Received(1).DisposeAsync(); } // ── BeginRedbTransaction DSL ───────────────────────────────────── [Fact] public void BeginRedbTransaction_NullRoute_Throws() { IRouteDefinition? route = null; var act = () => route!.BeginRedbTransaction(); act.Should().Throw().WithParameterName("route"); } [Fact] public void BeginRedbTransaction_Named_NullName_Throws() { var route = Substitute.For(); var act = () => route.BeginRedbTransaction(null!); act.Should().Throw(); } [Fact] public void BeginRedbTransaction_Named_EmptyName_Throws() { var route = Substitute.For(); var act = () => route.BeginRedbTransaction(string.Empty); act.Should().Throw(); } [Fact] public async Task BeginRedbTransaction_Default_OpensTxAndEnrollsInTransactActions() { var (route, context, tx) = SetupRouteWithRedb(name: null); var exchange = new Exchange(); route.BeginRedbTransaction(); await InvokeFirstOutputAsync(route, context, exchange); await context.GetRedbService().Context.Received(1).BeginTransactionAsync(); var actions = GetActionsBag(exchange); actions.Should().ContainKey("redb:"); actions["redb:"].Should().BeOfType() .Which.Transaction.Should().BeSameAs(tx); } [Fact] public async Task BeginRedbTransaction_Named_OpensTxUnderNamedKey() { var (route, context, tx) = SetupRouteWithRedb(name: "orders-db"); var exchange = new Exchange(); route.BeginRedbTransaction("orders-db"); await InvokeFirstOutputAsync(route, context, exchange); var actions = GetActionsBag(exchange); actions.Should().ContainKey("redb:orders-db"); actions["redb:orders-db"].Should().BeOfType() .Which.Transaction.Should().BeSameAs(tx); } [Fact] public async Task BeginRedbTransaction_Idempotent_DoesNotOpenSecondTxForSameKey() { var (route, context, _) = SetupRouteWithRedb(name: null); var exchange = new Exchange(); route.BeginRedbTransaction(); var processor = route.Outputs[0].CreateProcessor(context); await processor.Process(exchange, CancellationToken.None); await processor.Process(exchange, CancellationToken.None); await context.GetRedbService().Context.Received(1).BeginTransactionAsync(); GetActionsBag(exchange).Should().HaveCount(1); } [Fact] public async Task BeginRedbTransaction_UnderAmbientScope_DoesNotOpenRedbTx() { // Under core 5dc3741e, inside an ambient TransactionScope (.Transacted()) redb already writes // into that transaction via AmbientConnectionRegistry, and BeginTransactionAsync is rejected. // BeginRedbTransaction must be a no-op here — not open a second redb tx, not enroll an action. var (route, context, _) = SetupRouteWithRedb(name: null); var exchange = new Exchange(); route.BeginRedbTransaction(); using (var scope = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeAsyncFlowOption.Enabled)) { await InvokeFirstOutputAsync(route, context, exchange); scope.Complete(); } await context.GetRedbService().Context.DidNotReceive().BeginTransactionAsync(); exchange.Properties.ContainsKey(TransactedProcessor.TransactActionPropertyKey) .Should().BeFalse("under an ambient scope nothing is enrolled — the scope owns the redb transaction"); } [Fact] public async Task BeginRedbTransaction_NullContext_Throws() { // Real RouteDefinition with no context attached. var route = new RouteDefinition(); route.BeginRedbTransaction(); var processor = route.Outputs[0].CreateProcessor(context: null!); var act = async () => await processor.Process(new Exchange(), CancellationToken.None); await act.Should().ThrowAsync() .WithMessage("*RouteContext is not available*"); } // ── Helpers ────────────────────────────────────────────────────── private static (RouteDefinition route, IRouteContext context, IRedbTransaction tx) SetupRouteWithRedb(string? name) { var redb = Substitute.For(); var ctx = Substitute.For(); var tx = Substitute.For(); tx.IsActive.Returns(true); ctx.BeginTransactionAsync().Returns(Task.FromResult(tx)); redb.Context.Returns(ctx); var context = Substitute.For(); if (string.IsNullOrEmpty(name)) { context.GetService().Returns(redb); } else { // Singleton fallback path (no factory). context.GetFromRegistry(Arg.Any()) .Returns((Microsoft.Extensions.DependencyInjection.IServiceScopeFactory?)null); context.GetFromRegistry("redb:" + name).Returns(redb); } var route = new RouteDefinition(); route._context = context; return (route, context, tx); } private static async Task InvokeFirstOutputAsync(RouteDefinition route, IRouteContext context, IExchange exchange) { var processor = route.Outputs[0].CreateProcessor(context); await processor.Process(exchange, CancellationToken.None); } private static ConcurrentDictionary GetActionsBag(IExchange exchange) { exchange.Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out var raw) .Should().BeTrue("TRANSACT_ACTION dictionary should be initialized by BeginRedbTransaction"); return raw.Should().BeOfType>().Which; } } Path: redb-route/tests/redb.Route.Tests.Core/RedbUniqueKeyTests.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.Core/RedbUniqueKeyTests.cs ---- using System.Text; using redb.Route.RedbCore; namespace redb.Route.Tests.Core; /// Unit tests for — the shared 440-safe key normalizer. public sealed class RedbUniqueKeyTests { [Fact] public void Normalize_ShortKey_PassesThroughVerbatim() { RedbUniqueKey.Normalize("proc:key-1").Should().Be("proc:key-1"); } [Fact] public void Normalize_SurrogatePairAtCutPoint_NeverSplitsThePair() { // Index 374 holds the high half of an emoji: a naive raw[..375] slice would end // the prefix with a lone high surrogate — not encodable to UTF-8, so the // provider would reject the row instead of saving the key. var raw = new string('a', 374) + "\U0001F600" + new string('b', 100); var normalized = RedbUniqueKey.Normalize(raw); normalized.Length.Should().BeLessThanOrEqualTo(RedbUniqueKey.MaxLength); var strictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); var encode = () => strictUtf8.GetBytes(normalized); encode.Should().NotThrow("the stored key must be valid UTF-16 with no lone surrogates"); // Deterministic and still collision-resistant past the readable prefix. RedbUniqueKey.Normalize(raw).Should().Be(normalized); RedbUniqueKey.Normalize(raw + "x").Should().NotBe(normalized); } [Fact] public void Normalize_SurrogatePairBeforeCutPoint_KeepsFullLength() { // The pair sits fully inside the prefix — nothing to trim, exact 440 shape. var raw = "\U0001F600" + new string('a', 500); var normalized = RedbUniqueKey.Normalize(raw); normalized.Length.Should().Be(RedbUniqueKey.MaxLength); normalized.Should().Contain("#"); } } Path: redb-route/tests/redb.Route.Tests.Core/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.Core/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.RedbCore; using redb.Route.RedbCore.Repositories; namespace redb.Route.Tests.Core; /// /// Tests for . /// public sealed class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteCore_NoConfigure_DoesNotThrow() { var services = new ServiceCollection(); var act = () => services.AddRedbRouteCore(); act.Should().NotThrow(); } [Fact] public void UseIdempotentRepository_RegistersOptions() { var services = new ServiceCollection(); services.AddScoped(_ => Substitute.For()); services.AddRedbRouteCore(core => { core.UseIdempotentRepository(o => { o.ProcessorName = "my-route"; o.Ttl = TimeSpan.FromDays(7); }); }); var sp = services.BuildServiceProvider(); var options = sp.GetRequiredService(); options.ProcessorName.Should().Be("my-route"); options.Ttl.Should().Be(TimeSpan.FromDays(7)); } [Fact] public void UseIdempotentRepository_RegistersIIdempotentRepository() { var services = new ServiceCollection(); services.AddScoped(_ => Substitute.For()); services.AddRedbRouteCore(core => { core.UseIdempotentRepository(o => o.ProcessorName = "test"); }); var sp = services.BuildServiceProvider(); var repo = sp.GetRequiredService(); repo.Should().BeOfType(); } [Fact] public void UseIdempotentRepository_DefaultOptions() { var services = new ServiceCollection(); services.AddScoped(_ => Substitute.For()); services.AddRedbRouteCore(core => { core.UseIdempotentRepository(); }); var sp = services.BuildServiceProvider(); var options = sp.GetRequiredService(); options.ProcessorName.Should().BeEmpty(); options.Ttl.Should().BeNull(); } [Fact] public void AddRedbRouteCore_Builder_ExposesServices() { var services = new ServiceCollection(); RedbCoreConfigurationBuilder? capturedBuilder = null; services.AddRedbRouteCore(core => { capturedBuilder = core; }); capturedBuilder.Should().NotBeNull(); capturedBuilder!.Services.Should().BeSameAs(services); } } Path: redb-route/tests/redb.Route.Tests.Core/Sql/RedbSqlDataSourceTestsBase.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.Core/Sql/RedbSqlDataSourceTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Sql; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Sql.Repositories; namespace redb.Route.Tests.Core.Sql; /// /// dataSource=redb: a sql: step runs on the connection the exchange's redb service works on. Inside /// .Transacted() the statement and a .RedbSave() into the same database commit or roll back together on one /// connection; outside a transaction the statement commits on its own. Every count is read through a fresh scope outside /// any transaction. /// public abstract class RedbSqlDataSourceTestsBase { /// The probe table every engine creates: route_sql_lease_rows (tag). protected const string Table = "route_sql_lease_rows"; /// The name the second instance is registered under. protected const string NamedService = "orders"; /// The provider of the default redb service. protected abstract IServiceProvider Services { get; } /// The provider of the instance registered under , in a database of its own. protected abstract IServiceProvider NamedServices { get; } /// /// Whether the transaction may be checked for staying local. PostgreSQL and SQL Server enlist and would promote a /// second connection to a distributed transaction; SQLite never enlists. /// protected abstract bool ChecksDistributedTransaction { get; } private static string NewTag() => "rsl-" + Guid.NewGuid().ToString("N")[..12]; private static string Insert(string dataSource, string extra = "") => $"sql:INSERT INTO {Table} (tag) VALUES (:#tag)?dataSource={dataSource}&outputType=None{extra}"; private static void SetObject(IExchange exchange, string tag) => exchange.In.Body = new RedbObject { name = tag, Props = new RedbSqlLeaseProps { Tag = tag } }; private RouteContext NewContext(bool withNamed = true) { var context = new RouteContext(Services); context.AddComponent(new SqlComponent()); context.AddRedbSqlDataSource(); if (withNamed) context.RegisterRedbService(NamedService, NamedServices.GetRequiredService()); return context; } private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } private static Exchange Delivery(string tag) { var exchange = new Exchange(new Message(null)); exchange.In.Headers["tag"] = tag; return exchange; } /// Rows of the probe table and redb objects carrying , committed in ' database. protected static async Task<(long Rows, long Objects)> CountAsync(IServiceProvider services, string tag) { await using var scope = services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var rows = await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM {Table} WHERE tag = '{tag}'"); var objects = await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = '{tag}'"); return (rows, objects); } [Fact] public async Task A_transacted_block_commits_the_statement_and_the_redb_save_together() { var tag = NewTag(); var distributed = Guid.Empty; await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-commit") .Transacted() .To(Insert("redb")) .Process(e => SetObject(e, tag)) .RedbSave() .Process(_ => distributed = Transaction.Current!.TransactionInformation.DistributedIdentifier) .End()); var producer = await Start(context, "direct://rsl-commit"); await producer.Process(Delivery(tag)); (await CountAsync(Services, tag)).Should().Be((1L, 1L), "the statement and the save commit with the block"); if (ChecksDistributedTransaction) distributed.Should().Be(Guid.Empty, "the statement and the save share one connection, so the transaction stays local"); } [Fact] public async Task A_failure_after_the_statement_rolls_back_the_statement_and_the_redb_save() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-rollback") .Transacted() .To(Insert("redb")) .Process(e => SetObject(e, tag)) .RedbSave() .Process(_ => throw new InvalidOperationException("the block fails after the statement and the save")) .End()); var producer = await Start(context, "direct://rsl-rollback"); var send = () => producer.Process(Delivery(tag)); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Should().Be((0L, 0L), "the block's rollback takes back the statement's row and the object"); } [Fact] public async Task A_batch_runs_in_the_block_transaction() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-batch") .Transacted() .To(Insert("redb", "&batchSize=10")) .Process(_ => throw new InvalidOperationException("the block fails after the batch")) .End()); var producer = await Start(context, "direct://rsl-batch"); var items = new List> { new() { ["tag"] = tag }, new() { ["tag"] = tag } }; var send = () => producer.Process(new Exchange(new Message(items))); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Rows.Should().Be(0, "the batch wrote in the block's transaction, which rolled back"); } [Fact] public async Task A_function_call_runs_inside_the_block() { await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-function") .Transacted() .To("sql:abs?mode=Procedure&asFunction=true&procedureParams=IN:x:Int64&dataSource=redb") .End()); var producer = await Start(context, "direct://rsl-function"); var exchange = new Exchange(new Message(null)); exchange.In.Headers["x"] = -42L; await producer.Process(exchange); Convert.ToInt64(exchange.In.Body).Should().Be(42L); } [Fact] public async Task The_named_service_runs_the_statement_in_its_own_database() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-named") .Transacted() .To(Insert("redb:" + NamedService)) .Process(e => SetObject(e, tag)) .RedbSave(storage: NamedService) .End()); var producer = await Start(context, "direct://rsl-named"); await producer.Process(Delivery(tag)); (await CountAsync(NamedServices, tag)).Should().Be((1L, 1L), "redb:orders writes where the orders service works"); (await CountAsync(Services, tag)).Should().Be((0L, 0L), "nothing lands in the default service's database"); } /// /// The context starts every endpoint and goes on in degraded mode past one that fails (it logs the failure), so the /// refusal is read from the endpoint's own start; the first exchange is refused with the same message. /// private static async Task<(Exception? AtStart, Exception? AtFirstExchange)> StartFailures( RouteContext context, string from, string sqlUri) { var producer = await Start(context, from); var atStart = await Record.ExceptionAsync(() => context.GetEndpoint(sqlUri).Start()); var atFirstExchange = await Record.ExceptionAsync(() => producer.Process(Delivery(NewTag()))); return (atStart, atFirstExchange); } [Fact] public async Task A_route_naming_an_unregistered_service_fails_at_start() { await using var context = NewContext(withNamed: false); context.AddRoutes(r => r.From("direct://rsl-missing").To(Insert("redb:missing"))); var (atStart, atFirstExchange) = await StartFailures(context, "direct://rsl-missing", Insert("redb:missing")); atStart.Should().BeOfType().Which.Message.Should().Contain("redb:missing"); atFirstExchange.Should().BeOfType().Which.Message.Should().Contain("redb:missing"); } [Fact] public async Task A_route_on_a_context_without_redb_fails_at_start() { await using var context = new RouteContext(new ServiceCollection().BuildServiceProvider()); context.AddComponent(new SqlComponent()); context.AddRedbSqlDataSource(); context.AddRoutes(r => r.From("direct://rsl-no-redb").To(Insert("redb"))); var (atStart, atFirstExchange) = await StartFailures(context, "direct://rsl-no-redb", Insert("redb")); atStart.Should().BeOfType().Which.Message.Should().Contain("no IRedbService"); atFirstExchange.Should().BeOfType().Which.Message.Should().Contain("no IRedbService"); } [Fact] public async Task Outside_a_transaction_the_statement_commits_on_its_own() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-autocommit") .To(Insert("redb")) .Process(_ => throw new InvalidOperationException("a failure after the statement, no transaction"))); var producer = await Start(context, "direct://rsl-autocommit"); var send = () => producer.Process(Delivery(tag)); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Rows.Should().Be(1, "without a transaction the statement commits as it runs"); } [Fact] public async Task A_streamed_result_is_refused() { await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-stream") .To($"sql:SELECT tag FROM {Table}?dataSource=redb&outputType=StreamList")); var producer = await Start(context, "direct://rsl-stream"); var send = () => producer.Process(new Exchange(new Message(null))); (await send.Should().ThrowAsync()).Which.Message.Should().Contain("StreamList"); } [Fact] public async Task A_batch_that_continues_past_errors_is_refused() { await using var context = NewContext(); context.AddRoutes(r => r.From("direct://rsl-savepoints").To(Insert("redb", "&batchSize=10&breakBatchOnError=false"))); var producer = await Start(context, "direct://rsl-savepoints"); var items = new List> { new() { ["tag"] = NewTag() } }; var send = () => producer.Process(new Exchange(new Message(items))); (await send.Should().ThrowAsync()).Which.Message.Should().Contain("breakBatchOnError"); } [Fact] public async Task The_polling_consumer_is_refused_at_start() { var uri = $"sql:SELECT tag FROM {Table}?mode=Poll&dataSource=redb"; await using var context = NewContext(); context.AddRoutes(r => r.From(uri).RouteId("rsl-poll").Process(_ => { })); await context.Start(); var consumerStart = () => context.GetEndpoint(uri).CreateConsumer(Substitute.For()).Start(); context.GetRoute("rsl-poll")!.Status.Should().Be(RouteStatus.Errored, "the route's consumer refused to start"); (await consumerStart.Should().ThrowAsync()).Which.Message.Should().Contain("dataSource=redb"); } [Fact] public void The_repositories_refuse_the_lending_data_source() { var factory = new RedbSqlConnectionFactory(new RouteContext(Services)); var idempotent = () => new SqlIdempotentRepository(factory, new SqlIdempotentOptions()); var claimCheck = () => new SqlClaimCheckRepository(factory, new SqlClaimCheckOptions()); idempotent.Should().Throw().Which.Message.Should().Contain("lends"); claimCheck.Should().Throw().Which.Message.Should().Contain("lends"); } [Fact] public void A_factory_that_implements_only_CreateConnectionAsync_keeps_its_defaults() { ISqlConnectionFactory plain = new PlainFactory(); plain.LendsConnection.Should().BeFalse(); plain.ForQualifier(null).Should().BeSameAs(plain); var qualified = () => plain.ForQualifier("x"); qualified.Should().Throw(); } /// A factory written before the lease: it implements only . private sealed class PlainFactory : ISqlConnectionFactory { public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) => throw new NotSupportedException("never opened by this test"); } } Path: redb-route/tests/redb.Route.Tests.Core/Sql/RedbSqlLeaseProps.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.Core/Sql/RedbSqlLeaseProps.cs ---- using redb.Core.Attributes; namespace redb.Route.Tests.Core.Sql; /// The object a .RedbSave() step writes next to the sql: step's row. [RedbScheme("route_sql_lease_probe")] public sealed class RedbSqlLeaseProps { public string Tag { get; set; } = string.Empty; } Path: redb-route/tests/redb.Route.Tests.Core/Sql/SqliteRedbSqlDataSourceTests.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.Core/Sql/SqliteRedbSqlDataSourceTests.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Extensions; using redb.SQLite.Extensions; namespace redb.Route.Tests.Core.Sql; /// Two redb (Free) services on SQLite files of their own: the default one and the one named orders. public sealed class SqliteRedbSqlFixture : IAsyncLifetime { private readonly string _directory = Path.Combine(Path.GetTempPath(), "redb-route-sql-lease-" + Guid.NewGuid().ToString("N")[..8]); public ServiceProvider Services { get; private set; } = null!; public ServiceProvider NamedServices { get; private set; } = null!; public async Task InitializeAsync() { Directory.CreateDirectory(_directory); Services = await BuildAsync(Path.Combine(_directory, "default.db")); NamedServices = await BuildAsync(Path.Combine(_directory, "orders.db")); } private static async Task BuildAsync(string file) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(o => o.UseSqlite($"Data Source={file}")); var provider = services.BuildServiceProvider(); var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.Context.ExecuteAsync("CREATE TABLE IF NOT EXISTS route_sql_lease_rows (tag TEXT NOT NULL)"); return provider; } public async Task DisposeAsync() { await Services.DisposeAsync(); await NamedServices.DisposeAsync(); Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); try { Directory.Delete(_directory, recursive: true); } catch (IOException) { /* a file still mapped by the native extension: the temp folder keeps it */ } } } public sealed class SqliteRedbSqlDataSourceTests(SqliteRedbSqlFixture fixture) : RedbSqlDataSourceTestsBase, IClassFixture { protected override IServiceProvider Services => fixture.Services; protected override IServiceProvider NamedServices => fixture.NamedServices; protected override bool ChecksDistributedTransaction => false; } Path: redb-route/tests/redb.Route.Tests.Core/appsettings.json 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.Core/appsettings.json ---- { "ConnectionStrings": { "Postgres": "Host=pgdb;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Include Error Detail=true;Timeout=600;Command Timeout=600;Options=-c jit=off", "MSSql": "Server=msdb;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;" } } Path: redb-route/tests/redb.Route.Tests.Core/redb.Route.Tests.Core.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.Core/redb.Route.Tests.Core.csproj ----