Path: redb-route/tests/redb.Route.Tests.RabbitMQ/RabbitMQBatchConsumerTests.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.RabbitMQ/RabbitMQBatchConsumerTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using RabbitMQ.Client;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.RabbitMQ;
namespace redb.Route.Tests.RabbitMQ;
///
/// The batch contract on the RabbitMQ consumer against the broker: collection by size and by idle timeout, the body
/// shape, Split, settlement after the route, a delivery with a reply-to refused from a batch (batched with
/// disableReplyTo), a stop during the pause between attempts, and concurrency bounded by concurrentConsumers; a failed
/// batch dead-lettered and a stop with a half-collected batch are cases of RabbitMQConformanceTests. Queues are
/// durable (RabbitMQ 4.3 refuses transient non-exclusive ones), with a real dead letter exchange and queue.
///
[Trait("Category", "Integration")]
public sealed class RabbitMQBatchConsumerTests
{
private const string Connection = "host=localhost&port=5672&username=admin&password=admin";
private static async Task ConnectAsync()
=> await new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = "admin", Password = "admin" }.CreateConnectionAsync();
private sealed class Topology : IAsyncDisposable
{
public string Queue { get; } = $"batch-in-{Guid.NewGuid():N}";
public string DeadLetterExchange { get; } = $"batch-dlx-{Guid.NewGuid():N}";
public string DeadLetterQueue { get; } = $"batch-dlq-{Guid.NewGuid():N}";
private IConnection? _connection;
public IChannel Channel { get; private set; } = null!;
public static async Task CreateAsync()
{
var t = new Topology();
t._connection = await ConnectAsync();
t.Channel = await t._connection.CreateChannelAsync();
await t.Channel.ExchangeDeclareAsync(t.DeadLetterExchange, ExchangeType.Direct, durable: true, autoDelete: false);
await t.Channel.QueueDeclareAsync(t.DeadLetterQueue, durable: true, exclusive: false, autoDelete: false);
await t.Channel.QueueBindAsync(t.DeadLetterQueue, t.DeadLetterExchange, "failed");
await t.Channel.QueueDeclareAsync(t.Queue, durable: true, exclusive: false, autoDelete: false,
arguments: new Dictionary
{
["x-dead-letter-exchange"] = t.DeadLetterExchange,
["x-dead-letter-routing-key"] = "failed",
});
return t;
}
public async Task PublishAsync(params string[] bodies)
{
foreach (var body in bodies)
{
var properties = new BasicProperties { Headers = new Dictionary { ["X-Record"] = "rec-" + body } };
await Channel.BasicPublishAsync(string.Empty, Queue, mandatory: false, properties, Encoding.UTF8.GetBytes(body));
}
}
public async Task PublishWithReplyToAsync(string body, string replyTo)
=> await Channel.BasicPublishAsync(string.Empty, Queue, mandatory: false,
new BasicProperties { ReplyTo = replyTo }, Encoding.UTF8.GetBytes(body));
public async Task ReadyAsync(string queue) => await Channel.MessageCountAsync(queue);
public async Task> DeadLettersAsync(int expected, TimeSpan within)
{
var got = new List();
var deadline = DateTime.UtcNow + within;
while (got.Count < expected && DateTime.UtcNow < deadline)
{
var item = await Channel.BasicGetAsync(DeadLetterQueue, autoAck: true);
if (item is null) { await Task.Delay(100); continue; }
got.Add(Encoding.UTF8.GetString(item.Body.Span));
}
return got;
}
public async ValueTask DisposeAsync()
{
await Channel.QueueDeleteAsync(Queue);
await Channel.QueueDeleteAsync(DeadLetterQueue);
await Channel.ExchangeDeleteAsync(DeadLetterExchange);
await Channel.DisposeAsync();
await _connection!.DisposeAsync();
}
}
private static async Task Start(string queue, string options, Action? extra,
Func route)
{
var context = new RouteContext();
context.AddComponent(new RabbitMQComponent());
context.AddRoutes(r =>
{
r.From($"rabbitmq://{queue}?{Connection}&batching=true&{options}").Process(async (ex, _) => await route(ex));
extra?.Invoke(r);
});
await context.Start();
return context;
}
private static List Records(IExchange exchange) => (List)exchange.In.Body!;
private static string Text(IMessage message) => Encoding.UTF8.GetString((byte[])message.Body!);
private static string? HeaderText(IDictionary headers, string name)
=> headers.TryGetValue(name, out var value) ? value is byte[] bytes ? Encoding.UTF8.GetString(bytes) : value?.ToString() : null;
[Fact]
public async Task A_batch_is_collected_up_to_maxBatchMessages_and_the_rest_by_the_idle_timeout()
{
await using var topology = await Topology.CreateAsync();
await topology.PublishAsync("a", "b", "c", "d", "e", "f", "g");
var batches = new ConcurrentQueue>();
var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (await Start(topology.Queue, "maxBatchMessages=3&pollTimeoutMs=1500", null, ex =>
{
batches.Enqueue(Records(ex).Select(Text).ToList());
if (batches.Sum(b => b.Count) == 7) all.TrySetResult();
return Task.CompletedTask;
}))
{
await all.Task.WaitAsync(TimeSpan.FromSeconds(30));
}
batches.Select(b => b.Count).Should().Equal(3, 3, 1);
batches.SelectMany(b => b).Should().Equal("a", "b", "c", "d", "e", "f", "g");
(await topology.ReadyAsync(topology.Queue)).Should().Be(0, "every delivery was acknowledged after its batch");
}
[Fact]
public async Task One_delivery_is_still_a_list_with_its_own_headers_and_the_routing_key_on_the_batch()
{
await using var topology = await Topology.CreateAsync();
await topology.PublishAsync("only");
var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (await Start(topology.Queue, "pollTimeoutMs=500", null, ex => { seen.TrySetResult(ex); return Task.CompletedTask; }))
{
var batch = await seen.Task.WaitAsync(TimeSpan.FromSeconds(30));
batch.Pattern.Should().Be(ExchangePattern.InOnly);
var record = Records(batch).Should().ContainSingle().Subject;
Text(record).Should().Be("only");
record.Headers.Should().ContainKey(RmqHeaders.DeliveryTag);
batch.In.Headers[RmqHeaders.RoutingKey].Should().Be(topology.Queue);
}
}
[Fact]
public async Task A_split_part_gets_its_deliverys_body_and_headers_and_the_split_metadata_as_properties()
{
await using var topology = await Topology.CreateAsync();
await topology.PublishAsync("a", "b");
var parts = new ConcurrentQueue<(string Body, string? Header, int Index)>();
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var context = new RouteContext();
context.AddComponent(new RabbitMQComponent());
context.AddRoutes(r => r
.From($"rabbitmq://{topology.Queue}?{Connection}&batching=true&maxBatchMessages=2&pollTimeoutMs=2000")
.Split(ex => (IEnumerable