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