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;
}
}