Bundle: redb-route / tests/redb.Route.Tests.IbmMq (tests.redb.Route.Tests.IbmMq.txt), 34 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.IbmMq/IbmMqBackoutDelayTests.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.IbmMq/IbmMqBackoutDelayTests.cs ---- using System.Diagnostics; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// The consumer's pause after a backout (backoutDelay) against IBM MQ, in poll and batch modes: a message the /// route failed on is backed out and not read again before the delay; with backoutDelay=0 it comes back at once. /// Expects IBM MQ at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqBackoutDelayTests { private const string Queue = "DEV.QUEUE.POISON"; private const string BackoutQueue = "DEV.QUEUE.POISON.BOQ"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private const int Delay = 3000; /// /// Runs a route that fails on the first delivery and succeeds on the second; returns the time between the two. /// private static async Task TimeBetweenDeliveries(string options) { IbmMqPoisonTests.Drain(Queue); IbmMqPoisonTests.Drain(BackoutQueue); IbmMqPoisonTests.Put(Queue, "again"); var runs = new List(); var clock = Stopwatch.StartNew(); var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (var context = new RouteContext()) { context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{Queue}?{Connection}&{options}") .Process(_ => { int run; lock (runs) { runs.Add(clock.Elapsed); run = runs.Count; } if (run == 1) throw new InvalidOperationException("fails the first time"); second.TrySetResult(); })); await context.Start(); await second.Task.WaitAsync(TimeSpan.FromSeconds(30)); } IbmMqPoisonTests.Drain(Queue).Should().BeEmpty("the second delivery committed the message"); IbmMqPoisonTests.Drain(BackoutQueue).Should().BeEmpty(); return runs[1] - runs[0]; } [Fact] public async Task Poll_mode_does_not_read_a_backed_out_message_again_before_the_delay() { var gap = await TimeBetweenDeliveries($"transacted=true&backoutThreshold=5&backoutQueue={BackoutQueue}&backoutDelay={Delay}"); gap.Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(Delay)); } [Fact] public async Task Batch_mode_does_not_read_a_backed_out_batch_again_before_the_delay() { var gap = await TimeBetweenDeliveries( $"batching=true&maxBatchMessages=1&pollTimeoutMs=200&backoutThreshold=5&backoutQueue={BackoutQueue}&backoutDelay={Delay}"); gap.Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(Delay)); } [Fact] public async Task A_delay_of_zero_reads_a_backed_out_message_again_at_once() { var gap = await TimeBetweenDeliveries($"transacted=true&backoutThreshold=5&backoutQueue={BackoutQueue}&backoutDelay=0"); gap.Should().BeLessThan(TimeSpan.FromMilliseconds(Delay), "without the pause nothing holds the next MQGET back"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqBackoutPauseTests.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.IbmMq/IbmMqBackoutPauseTests.cs ---- using Microsoft.Extensions.Time.Testing; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// The consumer's pause after a backout (backoutDelay), on a fake clock: the next read waits until the delay has /// passed, a later backout extends the pause, and zero keeps no pause. /// public sealed class IbmMqBackoutPauseTests { [Fact] public async Task The_next_read_waits_until_the_delay_after_a_backout_has_passed() { var time = new FakeTimeProvider(); var pause = new IbmMqBackoutPause(1000, time); await pause.WaitAsync(CancellationToken.None); // no backout yet: no pause pause.Begin(); var read = pause.WaitAsync(CancellationToken.None); time.Advance(TimeSpan.FromMilliseconds(999)); read.IsCompleted.Should().BeFalse("the backed-out message is not read again before the delay"); time.Advance(TimeSpan.FromMilliseconds(1)); await read.WaitAsync(TimeSpan.FromSeconds(5)); pause.Remaining.Should().Be(TimeSpan.Zero); } [Fact] public async Task A_later_backout_extends_the_pause_and_never_shortens_it() { var time = new FakeTimeProvider(); var pause = new IbmMqBackoutPause(1000, time); pause.Begin(); time.Advance(TimeSpan.FromMilliseconds(600)); pause.Begin(); // now ends at 1600 var read = pause.WaitAsync(CancellationToken.None); time.Advance(TimeSpan.FromMilliseconds(500)); read.IsCompleted.Should().BeFalse("the second backout's pause runs until 1600 ms"); time.Advance(TimeSpan.FromMilliseconds(500)); await read.WaitAsync(TimeSpan.FromSeconds(5)); } [Fact] public void A_delay_of_zero_keeps_no_pause() { var pause = new IbmMqBackoutPause(0, new FakeTimeProvider()); pause.Begin(); pause.Remaining.Should().Be(TimeSpan.Zero); pause.WaitAsync(CancellationToken.None).IsCompleted.Should().BeTrue(); } [Fact] public async Task A_wait_with_a_limit_returns_at_the_limit_while_the_pause_lasts() { var time = new FakeTimeProvider(); var pause = new IbmMqBackoutPause(1000, time); pause.Begin(); var wait = pause.WaitAsync(CancellationToken.None, TimeSpan.FromMilliseconds(300)); time.Advance(TimeSpan.FromMilliseconds(300)); await wait.WaitAsync(TimeSpan.FromSeconds(5)); pause.Remaining.Should().Be(TimeSpan.FromMilliseconds(700)); } [Fact] public async Task A_stop_ends_the_wait() { var pause = new IbmMqBackoutPause(1000, new FakeTimeProvider()); pause.Begin(); using var stop = new CancellationTokenSource(); var wait = pause.WaitAsync(stop.Token); stop.Cancel(); await FluentActions.Awaiting(() => wait).Should().ThrowAsync(); } [Fact] public void BackoutDelay_defaults_to_one_second_binds_from_the_uri_and_rejects_a_negative_value() { new IbmMqEndpointOptions().BackoutDelay.Should().Be(1000); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(EndpointUriParser.Parse("wmq:Q?host=localhost&backoutDelay=0").RawParameters); opts.BackoutDelay.Should().Be(0); var negative = new IbmMqEndpointOptions { BackoutDelay = -1 }; FluentActions.Invoking(negative.Validate).Should().Throw().WithMessage("*backoutDelay*"); } [Fact] public void The_builder_sets_backoutDelay() => Wmq.Queue("Q").BackoutDelay(2500).Build().Should().Contain("backoutDelay=2500"); } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqBatchConsumerTests.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.IbmMq/IbmMqBatchConsumerTests.cs ---- using System.Collections.Concurrent; using System.Text; using IBM.WMQ; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// The batch contract on the IBM MQ consumer against the broker: batches read with MQGET under syncpoint, collected by /// size and idle timeout, the body shape, Split, a request moved to the backout queue (batched with disableReplyTo), /// and concurrency bounded by concurrentConsumers. A batch accepted, rejected to the backout queue and returned at /// stop are cases of . /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqBatchConsumerTests { private const string Queue = "DEV.QUEUE.BATCH"; private const string BackoutQueue = "DEV.QUEUE.BATCH.BOQ"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static void Reset() { IbmMqPoisonTests.Drain(Queue); IbmMqPoisonTests.Drain(BackoutQueue); } private static void PutRequest(string body, string replyTo) { using var qm = IbmMqPoisonTests.Connect(); var q = qm.AccessQueue(Queue, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING); var message = new MQMessage { Format = MQC.MQFMT_STRING, MessageType = MQC.MQMT_REQUEST, ReplyToQueueName = replyTo }; message.WriteString(body); q.Put(message); q.Close(); qm.Disconnect(); } private static async Task Start(string options, Func route) { var context = new RouteContext(); context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{Queue}?{Connection}&batching=true&backoutQueue={BackoutQueue}&{options}") .Process(async (ex, _) => await route(ex))); await context.Start(); return context; } private static List Records(IExchange exchange) => (List)exchange.In.Body!; private static string Text(IMessage message) => message.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : message.Body?.ToString() ?? ""; [Fact] public async Task A_batch_is_collected_up_to_maxBatchMessages_and_the_rest_by_the_idle_timeout() { Reset(); IbmMqPoisonTests.Put(Queue, "a", "b", "c", "d", "e", "f", "g"); var batches = new ConcurrentQueue>(); var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start("maxBatchMessages=3&pollTimeoutMs=1500", 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(60)); } batches.Select(b => b.Count).Should().Equal(3, 3, 1); batches.SelectMany(b => b).Should().Equal("a", "b", "c", "d", "e", "f", "g"); IbmMqPoisonTests.Drain(Queue).Should().BeEmpty("every batch was committed"); } [Fact] public async Task One_message_is_still_a_list_with_its_own_headers_and_the_destination_on_the_batch() { Reset(); IbmMqPoisonTests.Put(Queue, "only"); var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start("pollTimeoutMs=500", 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(IbmMqHeaders.MsgId); batch.In.Headers[IbmMqHeaders.Destination].Should().Be(Queue); } } [Fact] public async Task A_split_part_gets_its_messages_body_and_the_split_metadata_as_properties() { Reset(); IbmMqPoisonTests.Put(Queue, "a", "b"); var parts = new ConcurrentQueue<(string Body, bool HasMsgId, int Index)>(); var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var context = new RouteContext(); context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{Queue}?{Connection}&batching=true&backoutQueue={BackoutQueue}&maxBatchMessages=2&pollTimeoutMs=2000") .Split(ex => (IEnumerable)ex.In.Body!) .Process(ex => { parts.Enqueue((ex.In.Body is byte[] b ? Encoding.UTF8.GetString(b) : ex.In.Body?.ToString() ?? "", ex.In.Headers.ContainsKey(IbmMqHeaders.MsgId), ex.GetProperty(ExchangePropertyKeys.SplitIndex))); if (parts.Count == 2) done.TrySetResult(); }) .EndSplit()); await using (context) { await context.Start(); await done.Task.WaitAsync(TimeSpan.FromSeconds(30)); } parts.Should().Equal(("a", true, 0), ("b", true, 1)); } [Fact] public async Task A_request_goes_to_the_backout_queue_and_the_others_run() { Reset(); IbmMqPoisonTests.Put(Queue, "a"); PutRequest("request", "SOMEBODYS.REPLIES"); IbmMqPoisonTests.Put(Queue, "b"); var batched = new ConcurrentQueue(); var both = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start("pollTimeoutMs=1500", ex => { foreach (var record in Records(ex)) batched.Enqueue(Text(record)); if (batched.Count >= 2) both.TrySetResult(); return Task.CompletedTask; })) { await both.Task.WaitAsync(TimeSpan.FromSeconds(30)); await Task.Delay(500); } batched.Should().BeEquivalentTo(["a", "b"]); IbmMqPoisonTests.Drain(BackoutQueue, waitMs: 2000).Should().Equal("request"); } [Fact] public async Task With_disableReplyTo_a_request_is_batched_and_nobody_replies() { Reset(); PutRequest("request", "SOMEBODYS.REPLIES"); var batched = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start("pollTimeoutMs=500&disableReplyTo=true", ex => { batched.TrySetResult(Text(Records(ex)[0])); return Task.CompletedTask; })) { (await batched.Task.WaitAsync(TimeSpan.FromSeconds(30))).Should().Be("request"); } IbmMqPoisonTests.Drain(BackoutQueue).Should().BeEmpty(); } [Fact] public async Task ConcurrentConsumers_bounds_how_many_batches_run_at_once() { Reset(); IbmMqPoisonTests.Put(Queue, Enumerable.Range(0, 12).Select(i => $"m{i}").ToArray()); var running = 0; var maxRunning = 0; var processed = 0; var all = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using (await Start("maxBatchMessages=3&pollTimeoutMs=500&concurrentConsumers=2", async ex => { var now = Interlocked.Increment(ref running); int seen; while ((seen = Volatile.Read(ref maxRunning)) < now && Interlocked.CompareExchange(ref maxRunning, now, seen) != seen) { } await Task.Delay(300); Interlocked.Decrement(ref running); if (Interlocked.Add(ref processed, Records(ex).Count) == 12) all.TrySetResult(); })) { await all.Task.WaitAsync(TimeSpan.FromSeconds(60)); } maxRunning.Should().BeInRange(1, 2, "two workers run at most two batches at once"); IbmMqPoisonTests.Drain(Queue).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqBatchStartTests.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.IbmMq/IbmMqBatchStartTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// IBM MQ batch options: resolved when the endpoint is created; each configuration that cannot work refused. public sealed class IbmMqBatchStartTests { private const string Base = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1"; private static IbmMqEndpoint Create(string query) => (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(EndpointUriParser.Parse($"wmq:ORDERS?{Base}&{query}")); [Theory] [InlineData("maxBatchMessages=5", "maxBatchMessages")] [InlineData("batchingIntervalMs=1000", "batchingIntervalMs")] public void A_batch_option_without_batching_is_refused(string query, string named) { var act = () => Create(query); act.Should().Throw().WithMessage($"*{named}*batching=true*"); } [Fact] public void Batching_with_the_listener_receive_mode_is_refused() { var act = () => Create("batching=true&backoutQueue=BOQ&receiveMode=listener"); act.Should().Throw().WithMessage("*receiveMode=listener*"); } [Fact] public void Batching_with_request_reply_is_refused() { var act = () => Create("batching=true&backoutQueue=BOQ&replyTo=true"); act.Should().Throw().WithMessage("*replyTo=true*"); } [Theory] [InlineData("maxBatchMessages=0", "maxBatchMessages")] [InlineData("pollTimeoutMs=0", "pollTimeoutMs")] [InlineData("batchingIntervalMs=0", "batchingIntervalMs")] public void A_value_out_of_range_is_refused(string query, string named) { var act = () => Create($"batching=true&backoutQueue=BOQ&{query}"); act.Should().Throw().WithMessage($"*{named}*"); } [Fact] public void BatchSize_is_refused_naming_its_replacement() { var act = () => Create("batchSize=10"); act.Should().Throw().WithMessage("*batchSize*batching=true*maxBatchMessages*"); } [Fact] public void Batching_resolves_with_the_default_size() { var options = new IbmMqEndpointOptions { Batching = true, BackoutQueue = "BOQ" }; options.ResolveBatch("wmq:ORDERS"); options.Batch!.MaxMessages.Should().Be(100); options.Batch.PollTimeout.Should().Be(TimeSpan.FromSeconds(1)); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqBuilderTests.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.IbmMq/IbmMqBuilderTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; using IbmMqDsl = redb.Route.IbmMq.Wmq; namespace redb.Route.Tests.IbmMq; public sealed class IbmMqBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Queue_StartsWithIbmMqScheme() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1").Build(); uri.Should().StartWith("wmq:DEV.QUEUE.1"); } [Fact] public void Topic_SetsDestinationType() { var uri = IbmMqDsl.Topic("EVENTS/ORDER").Build(); uri.Should().StartWith("wmq:EVENTS/ORDER"); uri.Should().Contain("destinationType=Topic"); } [Fact] public void Queue_DoesNotSetDestinationType() { var uri = IbmMqDsl.Queue("Q1").Build(); uri.Should().NotContain("destinationType"); } [Fact] public void NullDestination_Throws() { var act = () => IbmMqDsl.Queue(null!); act.Should().Throw(); } [Fact] public void EmptyDestination_Throws() { var act = () => IbmMqDsl.Queue(""); act.Should().Throw(); } // ── Connection ────────────────────────────────────────────────── [Fact] public void Host_SetsParam() { var uri = IbmMqDsl.Queue("Q").Host("broker1").Build(); uri.Should().Contain("host=broker1"); } [Fact] public void Port_SetsParam() { var uri = IbmMqDsl.Queue("Q").Port(1415).Build(); uri.Should().Contain("port=1415"); } [Fact] public void Channel_SetsParam() { var uri = IbmMqDsl.Queue("Q").Channel("MY.SVRCONN").Build(); uri.Should().Contain("channel=MY.SVRCONN"); } [Fact] public void QueueManager_SetsParam() { var uri = IbmMqDsl.Queue("Q").QueueManager("QM2").Build(); uri.Should().Contain("queueManager=QM2"); } [Fact] public void User_SetsParam() { var uri = IbmMqDsl.Queue("Q").User("admin").Build(); uri.Should().Contain("user=admin"); } [Fact] public void Password_SetsParam() { var uri = IbmMqDsl.Queue("Q").Password("secret").Build(); uri.Should().Contain("password=secret"); } [Fact] public void ClientId_SetsParam() { var uri = IbmMqDsl.Queue("Q").ClientId("app1").Build(); uri.Should().Contain("clientId=app1"); } [Fact] public void ConnectionFactory_SetsParam() { var uri = IbmMqDsl.Queue("Q").ConnectionFactory("myFactory").Build(); uri.Should().Contain("connectionFactory=myFactory"); } // ── Consumer ──────────────────────────────────────────────────── [Fact] public void ConcurrentConsumers_SetsParam() { var uri = IbmMqDsl.Queue("Q").ConcurrentConsumers(4).Build(); uri.Should().Contain("concurrentConsumers=4"); } [Fact] public void WaitInterval_SetsParam() { var uri = IbmMqDsl.Queue("Q").WaitInterval(10000).Build(); uri.Should().Contain("waitInterval=10000"); } [Fact] public void Batching_SetsTheBatchOptions() { var uri = IbmMqDsl.Queue("Q").Batching().MaxBatchMessages(50).PollTimeoutMs(300).BatchingIntervalMs(2000).DisableReplyTo().Build(); uri.Should().Contain("batching=true").And.Contain("maxBatchMessages=50").And.Contain("pollTimeoutMs=300") .And.Contain("batchingIntervalMs=2000").And.Contain("disableReplyTo=true"); } [Fact] public void BackoutThreshold_SetsParam() { var uri = IbmMqDsl.Queue("Q").BackoutThreshold(5).Build(); uri.Should().Contain("backoutThreshold=5"); } [Fact] public void BackoutQueue_SetsParam() { var uri = IbmMqDsl.Queue("Q").BackoutQueue("DLQ").Build(); uri.Should().Contain("backoutQueue=DLQ"); } [Fact] public void Selector_SetsParam() { var uri = IbmMqDsl.Queue("Q").Selector("priority > 5").Build(); uri.Should().Contain("selector="); } [Fact] public void Convert_False_SetsParam() { var uri = IbmMqDsl.Queue("Q").Convert(false).Build(); uri.Should().Contain("convert=false"); } // ── Producer ──────────────────────────────────────────────────── [Fact] public void Persistent_SetsParam() { var uri = IbmMqDsl.Queue("Q").Persistent().Build(); uri.Should().Contain("persistence=Persistent"); } [Fact] public void NonPersistent_SetsParam() { var uri = IbmMqDsl.Queue("Q").NonPersistent().Build(); uri.Should().Contain("persistence=NonPersistent"); } [Fact] public void Priority_SetsParam() { var uri = IbmMqDsl.Queue("Q").Priority(7).Build(); uri.Should().Contain("priority=7"); } [Fact] public void Expiry_SetsParam() { var uri = IbmMqDsl.Queue("Q").Expiry(3000).Build(); uri.Should().Contain("expiry=3000"); } [Fact] public void TargetClient_Mq_SetsParam() { var uri = IbmMqDsl.Queue("Q").TargetClient(IbmMqTargetClient.Mq).Build(); uri.Should().Contain("targetClient=Mq"); } [Fact] public void MessageType_Request_SetsParam() { var uri = IbmMqDsl.Queue("Q").MessageType(IbmMqMessageType.Request).Build(); uri.Should().Contain("messageType=Request"); } // ── Transactions ──────────────────────────────────────────────── [Fact] public void Transacted_SetsParam() { var uri = IbmMqDsl.Queue("Q").Transacted().Build(); uri.Should().Contain("transacted=true"); } [Fact] public void Transacted_false_is_written_out_to_send_at_once_inside_a_block() { var uri = IbmMqDsl.Queue("Q").Transacted(false).Build(); uri.Should().Contain("transacted=false"); } [Fact] public void Transacted_left_unset_is_not_written_so_the_producer_follows_the_block() { var uri = IbmMqDsl.Queue("Q").Build(); uri.Should().NotContain("transacted"); } // DeadLetterQueue/MaxRedeliveries tests removed with the verbs (the options sweep): a second, dead // vocabulary for poison handling - the implemented one is BackoutThreshold/BackoutQueue. // These *_SetsParam tests are exactly the coverage that let dead options survive: they // asserted the URI string and nothing else. // ── RPC ───────────────────────────────────────────────────────── [Fact] public void ReplyTo_SetsParam() { var uri = IbmMqDsl.Queue("Q").ReplyTo().Build(); uri.Should().Contain("replyTo=true"); } [Fact] public void ReplyToQueue_SetsReplyToAndQueue() { var uri = IbmMqDsl.Queue("Q").ReplyToQueue("REPLY.Q").Build(); uri.Should().Contain("replyTo=true"); uri.Should().Contain("replyToQueue=REPLY.Q"); } [Fact] public void ReplyToQueueManager_SetsParam() { var uri = IbmMqDsl.Queue("Q").ReplyToQueueManager("QM2").Build(); uri.Should().Contain("replyToQueueManager=QM2"); } [Fact] public void Timeout_SetsParam() { var uri = IbmMqDsl.Queue("Q").Timeout(60).Build(); uri.Should().Contain("timeout=60"); } [Fact] public void CorrelationPattern_CorrelId_SetsParam() { var uri = IbmMqDsl.Queue("Q").CorrelationPattern(IbmMqCorrelationPattern.CorrelId).Build(); uri.Should().Contain("correlationPattern=CorrelId"); } // ── SSL ───────────────────────────────────────────────────────── [Fact] public void SslCipherSpec_SetsParam() { var uri = IbmMqDsl.Queue("Q").SslCipherSpec("TLS_RSA_WITH_AES_256_CBC_SHA256").Build(); uri.Should().Contain("sslCipherSpec=TLS_RSA_WITH_AES_256_CBC_SHA256"); } [Fact] public void SslCertLabel_SetsParam() { var uri = IbmMqDsl.Queue("Q").SslCertLabel("mycert").Build(); uri.Should().Contain("sslCertLabel=mycert"); } [Fact] public void SslPeerName_SetsParam() { var uri = IbmMqDsl.Queue("Q").SslPeerName("CN=broker1").Build(); uri.Should().Contain("sslPeerName="); } [Fact] public void SslKeyRepository_SetsParam() { var uri = IbmMqDsl.Queue("Q").SslKeyRepository("/opt/keys/key").Build(); uri.Should().Contain("sslKeyRepository="); } [Fact] public void TemporaryModel_SetsParam() { var uri = IbmMqDsl.Queue("Q").TemporaryModel("DEV.APP.MODEL.QUEUE").Build(); uri.Should().Contain("temporaryModel=DEV.APP.MODEL.QUEUE"); } [Fact] public void SslKeyResetCount_SetsParam() { var uri = IbmMqDsl.Queue("Q").SslKeyResetCount(1000000).Build(); uri.Should().Contain("sslKeyResetCount=1000000"); } // ── Advanced ──────────────────────────────────────────────────── [Fact] public void CCSID_SetsParam() { var uri = IbmMqDsl.Queue("Q").CCSID(437).Build(); uri.Should().Contain("cCSID=437"); } [Fact] public void MqmdWriteEnabled_SetsParam() { var uri = IbmMqDsl.Queue("Q").MqmdWriteEnabled().Build(); uri.Should().Contain("mqmdWriteEnabled=true"); } [Fact] public void MqmdReadEnabled_False_SetsParam() { var uri = IbmMqDsl.Queue("Q").MqmdReadEnabled(false).Build(); uri.Should().Contain("mqmdReadEnabled=false"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = IbmMqDsl.Queue("DEV.QUEUE.1").Host("broker1"); uri.Should().StartWith("wmq:DEV.QUEUE.1?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = IbmMqDsl.Queue("Q").Host("broker1").User("admin"); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_BuildsCorrectUri() { var uri = IbmMqDsl.Queue("ORDERS") .Host("mq.example.com") .Port(1414) .Channel("APP.SVRCONN") .QueueManager("QM1") .User("app") .Password("passw0rd") .ConcurrentConsumers(4) .Transacted() .Persistent() .Build(); uri.Should().StartWith("wmq:ORDERS?"); uri.Should().Contain("host=mq.example.com"); uri.Should().Contain("port=1414"); uri.Should().Contain("channel=APP.SVRCONN"); uri.Should().Contain("queueManager=QM1"); uri.Should().Contain("concurrentConsumers=4"); uri.Should().Contain("transacted=true"); uri.Should().Contain("persistence=Persistent"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = IbmMqDsl.Queue("Q1").Host("broker1").Port(1414).Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("wmq"); parsed.Path.Should().Be("Q1"); parsed.RawParameters["host"].Should().Be("broker1"); parsed.RawParameters["port"].Should().Be("1414"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqComponentTests.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.IbmMq/IbmMqComponentTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; public sealed class IbmMqComponentTests { private readonly IbmMqComponent _sut = new(); [Fact] public void Scheme_ReturnsIbmMq() { _sut.Scheme.Should().Be("wmq"); } [Fact] public void CreateEndpoint_ValidUri_ReturnsIbmMqEndpoint() { var uri = EndpointUriParser.Parse("wmq:DEV.QUEUE.1?host=localhost&queueManager=QM1&channel=DEV.APP.SVRCONN"); var endpoint = _sut.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_NullUri_Throws() { var act = () => _sut.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_WithConnectionParams_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:ORDERS?host=broker1&port=1415&channel=APP.SVRCONN&queueManager=QM2&user=admin&password=secret"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("ORDERS"); } [Fact] public void CreateEndpoint_WithConsumerOptions_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:Q1?host=localhost&concurrentConsumers=4&waitInterval=10000&backoutThreshold=5"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("Q1"); } [Fact] public void CreateEndpoint_WithProducerOptions_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:OUT.Q?host=localhost&persistence=Persistent&priority=7&expiry=3000&targetClient=Mq"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("OUT.Q"); } [Fact] public void CreateEndpoint_WithTopicDestination_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:EVENTS/ORDER?host=localhost&destinationType=Topic"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("EVENTS/ORDER"); } [Fact] public void CreateEndpoint_WithTransactedMode_ParsesCorrectly() { var uri = EndpointUriParser.Parse("wmq:TX.Q?host=localhost&transacted=true"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("TX.Q"); } [Fact] public void CreateEndpoint_WithRpcOptions_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:RPC.Q?host=localhost&replyTo=true&timeout=60&correlationPattern=CorrelId"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("RPC.Q"); } [Fact] public void CreateEndpoint_WithSslOptions_ParsesCorrectly() { var uri = EndpointUriParser.Parse( "wmq:SECURE.Q?host=localhost&sslCipherSpec=TLS_RSA_WITH_AES_256_CBC_SHA256&sslPeerName=CN%3Dbroker1"); var endpoint = (IbmMqEndpoint)_sut.CreateEndpoint(uri); endpoint.Destination.Should().Be("SECURE.Q"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConcurrencyTests.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.IbmMq/IbmMqConcurrencyTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; using Xunit.Abstractions; namespace redb.Route.Tests.IbmMq; /// /// End-to-end regression tests for the consumer-concurrency fix: ConcurrentConsumers(N) must /// actually process up to N messages in parallel (it used to be a dead semaphore on a serial MQGET /// loop). Each worker runs its own dedicated MQQueueManager, so N workers on a queue opened /// INPUT_SHARED are real competing consumers. The bound itself (two at a time under a slow route) is a case of /// ; here every message is processed exactly once. Expects IBM MQ at /// localhost:1414 (QM1, DEV.APP.SVRCONN, app/admin). /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqConcurrencyTests { private const string Host = "localhost"; private const int Port = 1414; private const string Channel = "DEV.APP.SVRCONN"; private const string QueueManager = "QM1"; private const string User = "app"; private const string Password = "admin"; private readonly ITestOutputHelper _output; public IbmMqConcurrencyTests(ITestOutputHelper output) => _output = output; private static IbmMqEndpoint CreateEndpoint(string destination, string? extraParams = null) { var qs = $"host={Host}&port={Port}&channel={Channel}&queueManager={QueueManager}&user={User}&password={Password}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"wmq:{destination}?{qs}"); var component = new IbmMqComponent(); return (IbmMqEndpoint)component.CreateEndpoint(uri); } private static async Task PublishAsync(string queue, IEnumerable bodies) { var ep = CreateEndpoint(queue); var producer = (IbmMqProducer)ep.CreateProducer(); await producer.Start(); foreach (var b in bodies) await producer.Process(new Exchange(new Message(b))); await producer.Stop(); await ep.Stop(); } /// Drains any leftover messages from the shared dev queue so the test starts clean. private static async Task DrainAsync(string queue) { var ep = CreateEndpoint(queue, "waitInterval=1500"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var consumer = (IbmMqConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.Delay(2500); await consumer.Stop(); await ep.Stop(); } [Fact] public async Task ConcurrentConsumers_AllMessagesProcessedExactlyOnce() { // Competing consumers must SHARE the queue: every message processed once, no duplication/loss. const int concurrency = 4; const int messageCount = 24; const string queue = "DEV.QUEUE.2"; await DrainAsync(queue); await PublishAsync(queue, Enumerable.Range(0, messageCount).Select(i => $"m-{i}")); var epCons = CreateEndpoint(queue, $"concurrentConsumers={concurrency}&waitInterval=2000"); var received = new ConcurrentBag(); var allDone = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(ci.Arg().In.Body?.ToString() ?? ""); if (received.Count >= messageCount) allDone.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allDone.Task, Task.Delay(40_000)); await consumer.Stop(); await epCons.Stop(); var distinct = received.Distinct().ToList(); _output.WriteLine($"received={received.Count}, distinct={distinct.Count}"); distinct.Count.Should().Be(messageCount, "every message delivered exactly once across competing consumers"); received.Count.Should().Be(messageCount, "competing consumers share the queue — no duplicate delivery"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConformanceTests.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.IbmMq/IbmMqConformanceTests.cs ---- using redb.Route.Abstractions; using redb.Route.IbmMq; using redb.Route.Tests.Conformance; namespace redb.Route.Tests.IbmMq; /// /// The IBM MQ connector against , in poll receive mode. The queues of a queue /// manager are fixed objects: every case reads DEV.QUEUE.CONFORMANCE of tests/docker/ibmmq/redb-tests.mqsc, /// emptied before and after it, and its backout queue DEV.QUEUE.CONFORMANCE.BOQ is the dead letter queue. /// /// How the cases map onto IBM MQ: attempts are the broker's own redelivery, transacted=true with /// backoutThreshold set to the attempts (a message runs on backout counts 0 to attempts-1, then goes to the /// backout queue); acknowledgement on receipt is the default consumer, whose MQGET takes the message outside a unit of /// work; a batch always reads under syncpoint, so it takes only the threshold. backoutDelay=0 keeps the /// redelivery quick. Runs in the IBM MQ collection, which runs alone: the restart case breaks the queue manager for /// every connection of the suite. Expects IBM MQ at localhost:1414. /// /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqConformanceTests : ConnectorConformance { private const string Queue = "DEV.QUEUE.CONFORMANCE"; private const string BackoutQueue = "DEV.QUEUE.CONFORMANCE.BOQ"; private const string Login = "channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; protected override IbmMqStand Stand => IbmMqStand.Instance; protected override ConnectorTraits Traits { get; } = new() { AckOnReceipt = true, Transactions = true, DeadLetter = true, Concurrency = true, Batch = true, }; protected override int BrokerPort => 1414; protected override IComponent CreateComponent() => new IbmMqComponent(); protected override async Task CreateQueueAsync(bool deadLetter) { await EmptyAsync(); return new ConformanceQueue(Queue, deadLetter ? BackoutQueue : null); } protected override Task DeleteQueueAsync(ConformanceQueue queue) => EmptyAsync(); protected override string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings) { // A batch starts only with a backout or dead letter queue to divert to, so the backout queue is always named; // with no threshold it is not used outside a batch. var uri = $"wmq:{queue.Name}?host=localhost&port={settings.Port ?? BrokerPort}&{Login}" + $"&waitInterval=500&backoutDelay=0&backoutQueue={BackoutQueue}"; if (settings.Attempts is { } attempts && !settings.AckOnReceipt) uri += (settings.BatchSize is null ? "&transacted=true" : "") + $"&backoutThreshold={attempts}"; if (settings.Concurrency is { } concurrency) uri += $"&concurrentConsumers={concurrency}"; if (settings.BatchSize is { } size) uri += $"&batching=true&maxBatchMessages={size}&pollTimeoutMs={(int)settings.BatchWait.TotalMilliseconds}"; return uri; } // Left unset the producer follows a block too; that rule is IbmMqIntegrationTests' own. protected override string ProducerUri(ConformanceQueue queue, bool transacted) => $"wmq:{queue.Name}?host=localhost&port={BrokerPort}&{Login}" + (transacted ? "&transacted=true" : ""); private async Task EmptyAsync() { await Stand.DrainAsync(Queue, TimeSpan.Zero); await Stand.DrainAsync(BackoutQueue, TimeSpan.Zero); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConnectionFactoryTests.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.IbmMq/IbmMqConnectionFactoryTests.cs ---- using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; public sealed class IbmMqConnectionFactoryTests { [Fact] public void Defaults_AreCorrect() { var factory = new IbmMqConnectionFactory(); factory.Host.Should().Be("localhost"); factory.Port.Should().Be(1414); factory.Channel.Should().Be("DEV.APP.SVRCONN"); factory.QueueManager.Should().Be("QM1"); factory.CCSID.Should().Be(1208); factory.User.Should().BeNull(); factory.Password.Should().BeNull(); factory.SslCipherSpec.Should().BeNull(); } [Fact] public void BuildConnectionProperties_ContainsRequiredKeys() { var factory = new IbmMqConnectionFactory { Host = "broker1", Port = 1415, Channel = "MY.SVRCONN", QueueManager = "QM2", CCSID = 437 }; var props = factory.BuildConnectionProperties(); props.Should().NotBeNull(); props.Count.Should().BeGreaterThanOrEqualTo(5); } [Fact] public void BuildConnectionProperties_WithAuth_IncludesCredentials() { var factory = new IbmMqConnectionFactory { User = "admin", Password = "secret" }; var props = factory.BuildConnectionProperties(); // Should have more entries than the base set (transport, host, port, channel, ccsid) props.Count.Should().BeGreaterThanOrEqualTo(7); } [Fact] public void BuildConnectionProperties_WithoutAuth_ExcludesCredentials() { var factory = new IbmMqConnectionFactory(); var props = factory.BuildConnectionProperties(); // Base set: transport, host, port, channel, ccsid = 5 props.Count.Should().Be(5); } [Fact] public void BuildConnectionProperties_WithClientName_IncludesAppName() { var factory = new IbmMqConnectionFactory { ClientName = "myApp" }; var props = factory.BuildConnectionProperties(); props.Count.Should().BeGreaterThanOrEqualTo(6); } [Fact] public void BuildConnectionProperties_WithSslCipherSpec_IncludesSsl() { var factory = new IbmMqConnectionFactory { SslCipherSpec = "TLS_RSA_WITH_AES_256_CBC_SHA256" }; var props = factory.BuildConnectionProperties(); props.Count.Should().BeGreaterThanOrEqualTo(6); } [Fact] public void BuildConnectionProperties_WithSslPeerName_IncludesSsl() { var factory = new IbmMqConnectionFactory { SslPeerName = "CN=broker1" }; var props = factory.BuildConnectionProperties(); props.Count.Should().BeGreaterThanOrEqualTo(6); } [Fact] public void BuildConnectionProperties_WithSslCertLabel_IncludesSsl() { var factory = new IbmMqConnectionFactory { SslCertLabel = "mycert" }; var props = factory.BuildConnectionProperties(); props.Count.Should().BeGreaterThanOrEqualTo(6); } [Fact] public void BuildConnectionProperties_ReturnsNewInstanceEachTime() { var factory = new IbmMqConnectionFactory(); var props1 = factory.BuildConnectionProperties(); var props2 = factory.BuildConnectionProperties(); props1.Should().NotBeSameAs(props2); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConnectionPoolIntegrationTests.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.IbmMq/IbmMqConnectionPoolIntegrationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; using Xunit.Abstractions; namespace redb.Route.Tests.IbmMq; /// /// Integration tests for the connection pool against a live broker /// (IBM MQ Developer Edition). Validates the new shared-connection model: identical inline /// parameters share one underlying MQQueueManager, named factories partition by name, /// endpoint Stop does not affect the pool, and component DisposeAsync drains the pool. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqConnectionPoolIntegrationTests { private const string Host = "localhost"; private const int Port = 1414; private const string Channel = "DEV.APP.SVRCONN"; private const string QueueManager = "QM1"; private const string User = "app"; private const string Password = "admin"; private const string Queue = "DEV.QUEUE.1"; private readonly ITestOutputHelper _output; public IbmMqConnectionPoolIntegrationTests(ITestOutputHelper output) => _output = output; private static IbmMqEndpoint CreateEndpoint(IbmMqComponent component, string destination, string? extraParams = null) { var qs = $"host={Host}&port={Port}&channel={Channel}&queueManager={QueueManager}&user={User}&password={Password}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"wmq:{destination}?{qs}"); return (IbmMqEndpoint)component.CreateEndpoint(uri); } /// /// Drain all messages currently sitting on the given queues so that pool tests do not /// leave residue that pollutes other integration tests sharing the same DEV queues. /// private static async Task DrainAsync(params string[] queues) { var component = new IbmMqComponent(); try { foreach (var q in queues) { var ep = CreateEndpoint(component, q, "waitInterval=200"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (IbmMqConsumer)ep.CreateConsumer(processor); await consumer.Start(); // Give the consumer enough cycles to drain whatever is queued. await Task.Delay(1_500); await consumer.Stop(); await ep.Stop(); } } finally { await component.DisposeAsync(); } } // NOTE: As of the dynamic-endpoints / dedicated-connections refactor (commit aa33e1a1) // each IbmMqProducer / IbmMqConsumer opens its own dedicated MQQueueManager via // IbmMqEndpoint.CreateDedicatedQueueManagerAsync to avoid MQI-call serialisation // deadlocks. The shared component pool (IbmMqComponent._connections) is still used // for endpoint-scoped MQI work (OpenQueueAsync / OpenTopicAsync / OpenTopicForPublishAsync) // and is exercised here directly via IbmMqEndpoint.GetQueueManagerAsync, NOT via // producer.Start (which goes to the dedicated path). [Fact] public async Task Pool_TwoEndpointsIdenticalParams_ShareSingleQueueManager() { var component = new IbmMqComponent(); // Two endpoints on different queues but same connection identity \u2192 1 MQQueueManager var epA = CreateEndpoint(component, Queue); var epB = CreateEndpoint(component, "DEV.QUEUE.2"); var qmA = await epA.GetQueueManagerAsync(); var qmB = await epB.GetQueueManagerAsync(); component.PooledConnectionCount.Should().Be(1, "both endpoints have identical inline params"); var conns = await component.GetPooledConnectionsAsync(); conns.Should().HaveCount(1); conns[0].IsConnected.Should().BeTrue(); ReferenceEquals(qmA, qmB).Should().BeTrue("identical inline params share one pooled MQQueueManager"); await epA.Stop(); await epB.Stop(); await component.DisposeAsync(); _output.WriteLine("IBM MQ shared QM: 2 endpoints, 1 MQQueueManager."); } [Fact] public async Task Pool_DifferentFactoryNames_ProduceDistinctQueueManagers() { var component = new IbmMqComponent(); var ctx = new RouteContext(); ctx.AddComponent(component); var f1 = new IbmMqConnectionFactory { Host = Host, Port = Port, Channel = Channel, QueueManager = QueueManager, User = User, Password = Password }; var f2 = new IbmMqConnectionFactory { Host = Host, Port = Port, Channel = Channel, QueueManager = QueueManager, User = User, Password = Password }; ctx.AddToRegistry("mq-1", f1); ctx.AddToRegistry("mq-2", f2); // Row 54: the inline coordinates point nowhere, so only a factory that is actually read can connect. Before, // the names only split the pool key and the inline values (equal to the factories') made the connection. static IbmMqEndpoint ThroughFactory(IbmMqComponent component, string factory) => (IbmMqEndpoint)component.CreateEndpoint(EndpointUriParser.Parse( $"wmq:{Queue}?connectionFactory={factory}&host=inline.invalid&port=1&channel=NO.SUCH.SVRCONN&queueManager=NOQM")); var epA = ThroughFactory(component, "mq-1"); var epB = ThroughFactory(component, "mq-2"); var qmA = await epA.GetQueueManagerAsync(); var qmB = await epB.GetQueueManagerAsync(); component.PooledConnectionCount.Should().Be(2, "two named factories produce two distinct MQQueueManager instances even when params match"); var conns = await component.GetPooledConnectionsAsync(); conns.Should().HaveCount(2); conns.Should().OnlyContain(c => c.IsConnected); ReferenceEquals(qmA, qmB).Should().BeFalse(); await epA.Stop(); await epB.Stop(); await ctx.DisposeAsync(); } [Fact] public async Task Pool_StopOneEndpoint_PooledQueueManagerRemains_OtherEndpointStillWorks() { var component = new IbmMqComponent(); var epA = CreateEndpoint(component, Queue); var epB = CreateEndpoint(component, "DEV.QUEUE.2"); await epA.GetQueueManagerAsync(); await epB.GetQueueManagerAsync(); component.PooledConnectionCount.Should().Be(1); await epA.Stop(); var conns = await component.GetPooledConnectionsAsync(); conns.Should().HaveCount(1); conns[0].IsConnected.Should().BeTrue("pooled MQQueueManager survives endpoint Stop"); // epB still resolves to the same shared connection after epA stopped. var qmB2 = await epB.GetQueueManagerAsync(); ReferenceEquals(qmB2, conns[0]).Should().BeTrue(); await epB.Stop(); await component.DisposeAsync(); } [Fact] public async Task Pool_DisposeAsync_DisconnectsAllPooledQueueManagers() { var component = new IbmMqComponent(); var endpoint = CreateEndpoint(component, Queue); await endpoint.GetQueueManagerAsync(); var conns = await component.GetPooledConnectionsAsync(); conns.Should().HaveCount(1); var pooled = conns[0]; pooled.IsConnected.Should().BeTrue(); await endpoint.Stop(); await component.DisposeAsync(); pooled.IsConnected.Should().BeFalse("DisposeAsync must disconnect all pooled MQQueueManager instances"); component.PooledConnectionCount.Should().Be(0); } [Fact] public async Task Pool_RestartEndpoint_ReusesPooledQueueManager() { var component = new IbmMqComponent(); var epA = CreateEndpoint(component, Queue); var initial = await epA.GetQueueManagerAsync(); await epA.Stop(); // Pool survives endpoint Stop \u2014 it is released only on Component.DisposeAsync. var afterStop = await component.GetPooledConnectionsAsync(); afterStop.Should().HaveCount(1); afterStop[0].IsConnected.Should().BeTrue(); ReferenceEquals(afterStop[0], initial).Should().BeTrue(); // A fresh endpoint with identical params reuses the same pooled MQQueueManager. var epB = CreateEndpoint(component, Queue); var reused = await epB.GetQueueManagerAsync(); component.PooledConnectionCount.Should().Be(1); ReferenceEquals(reused, initial).Should().BeTrue("pool reuses the existing MQQueueManager"); await epB.Stop(); await component.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConnectionPoolTests.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.IbmMq/IbmMqConnectionPoolTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// Pure-logic tests for the IBM MQ connection-pool key resolution implemented in /// . Same identity model as RabbitMQ and AMQP: factory-name /// keyed, inline auto-deduplicated. /// public sealed class IbmMqConnectionPoolTests { private static IbmMqEndpointOptions OptionsFromUri(string uri) { var parsed = EndpointUriParser.Parse(uri); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(parsed.RawParameters); opts.Validate(); return opts; } [Fact] public void ResolveKey_FactoryName_ProducesFactoryKey() { var opts = OptionsFromUri("wmq:Q.IN?host=h&queueManager=QM1&connectionFactory=primary"); IbmMqComponent.ResolveConnectionKey(opts).Should().Be("factory:primary"); } [Fact] public void ResolveKey_NoFactory_ProducesInlineKey() { var opts = OptionsFromUri( "wmq:Q.IN?host=mq&port=1414&queueManager=QM1&channel=DEV.APP.SVRCONN&user=alice"); var key = IbmMqComponent.ResolveConnectionKey(opts); key.Should().Be("inline:mq:1414/QM1#DEV.APP.SVRCONN@alice"); } [Fact] public void ResolveKey_TwoFactoriesDifferentNamesSameInlineParams_ProduceDistinctKeys() { var a = OptionsFromUri("wmq:Q?host=h&queueManager=QM1&connectionFactory=conn1"); var b = OptionsFromUri("wmq:Q?host=h&queueManager=QM1&connectionFactory=conn2"); IbmMqComponent.ResolveConnectionKey(a).Should().Be("factory:conn1"); IbmMqComponent.ResolveConnectionKey(b).Should().Be("factory:conn2"); } [Fact] public void ResolveKey_TwoEndpointsIdenticalInlineParams_ShareKey() { var a = OptionsFromUri("wmq:Q.A?host=mq&port=1414&queueManager=QM1&channel=CH1&user=u"); var b = OptionsFromUri("wmq:Q.B?host=mq&port=1414&queueManager=QM1&channel=CH1&user=u"); IbmMqComponent.ResolveConnectionKey(a) .Should().Be(IbmMqComponent.ResolveConnectionKey(b)); } [Fact] public void ResolveKey_DifferentQueueManagers_ProduceDistinctKeys() { var a = OptionsFromUri("wmq:Q?host=mq&queueManager=QM1"); var b = OptionsFromUri("wmq:Q?host=mq&queueManager=QM2"); IbmMqComponent.ResolveConnectionKey(a) .Should().NotBe(IbmMqComponent.ResolveConnectionKey(b)); } [Fact] public void ResolveKey_DifferentChannels_ProduceDistinctKeys() { var a = OptionsFromUri("wmq:Q?host=mq&queueManager=QM1&channel=CH.A"); var b = OptionsFromUri("wmq:Q?host=mq&queueManager=QM1&channel=CH.B"); IbmMqComponent.ResolveConnectionKey(a) .Should().NotBe(IbmMqComponent.ResolveConnectionKey(b)); } [Fact] public void ResolveKey_InlineWithSslCipherSpec_AppendsSslMarker() { var opts = OptionsFromUri( "wmq:Q?host=mq&queueManager=QM1&user=u&sslCipherSpec=TLS_RSA_WITH_AES_256_CBC_SHA256"); IbmMqComponent.ResolveConnectionKey(opts).Should().EndWith("#ssl"); } [Fact] public async Task Component_DisposeAsync_OnEmptyPool_DoesNotThrow() { var component = new IbmMqComponent(); var act = async () => await component.DisposeAsync(); await act.Should().NotThrowAsync(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqConnectionResolutionTests.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.IbmMq/IbmMqConnectionResolutionTests.cs ---- using IBM.WMQ; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// Row 54: connectionFactory=name connects through the registered under that /// name, which takes priority over the inline options; a name nothing is registered under fails when the endpoint is /// created. Before, the name only split the connection pool and the connection came from the inline options or their /// defaults. Without connectionFactory the inline options describe the connection exactly as before. No broker. /// public sealed class IbmMqConnectionResolutionTests : IAsyncDisposable { private readonly RouteContext _context = new(); private readonly IbmMqComponent _component = new(); public IbmMqConnectionResolutionTests() => _context.AddComponent(_component); public async ValueTask DisposeAsync() => await _context.DisposeAsync(); private IbmMqEndpoint Endpoint(string query) => (IbmMqEndpoint)_component.CreateEndpoint(EndpointUriParser.Parse($"wmq:DEV.QUEUE.1?{query}")); [Fact] public void ARegisteredFactory_IsWhatTheConnectionIsBuiltFrom_OverTheInlineOptions() { var factory = new IbmMqConnectionFactory { Host = "mq.prod.internal", Port = 1515, Channel = "PROD.APP.SVRCONN", QueueManager = "QMPROD", User = "svc-orders", Password = "s3cret", ClientName = "orders", }; _context.AddToRegistry("prod", factory); var connection = Endpoint("connectionFactory=prod&host=inline-host&channel=INLINE.SVRCONN").Connection; connection.Should().BeSameAs(factory); var properties = connection.BuildConnectionProperties(); properties[MQC.HOST_NAME_PROPERTY].Should().Be("mq.prod.internal"); properties[MQC.PORT_PROPERTY].Should().Be(1515); properties[MQC.CHANNEL_PROPERTY].Should().Be("PROD.APP.SVRCONN"); properties[MQC.USER_ID_PROPERTY].Should().Be("svc-orders"); properties[MQC.PASSWORD_PROPERTY].Should().Be("s3cret"); connection.QueueManager.Should().Be("QMPROD"); } [Fact] public void ANameNothingIsRegisteredUnder_FailsWhenTheEndpointIsCreated() { var act = () => Endpoint("connectionFactory=nope"); act.Should().Throw() .WithMessage("'nope' is not registered in the context registry (expected IbmMqConnectionFactory)*"); } [Fact] public void AHashName_IsTheSameRegistryKey() { var factory = new IbmMqConnectionFactory { Host = "mq.hash" }; _context.AddToRegistry("prod", factory); Endpoint("connectionFactory=%23prod").Connection.Should().BeSameAs(factory); } [Fact] public void WithoutAFactory_TheInlineOptionsDescribeTheConnectionAsBefore() { var connection = Endpoint("host=mq.inline&port=1416&channel=IN.SVRCONN&queueManager=QMI&user=u1&password=p1" + "&clientId=app1&sslCipherSpec=TLS_AES_128_GCM_SHA256&sslKeyResetCount=4096" + "&sslCertLabel=lbl&sslPeerName=CN%3Dmq&ccsid=819").Connection; connection.QueueManager.Should().Be("QMI"); // The table the inline builder of the component produced before the change, entry for entry. connection.BuildConnectionProperties().Cast() .ToDictionary(e => (string)e.Key, e => e.Value) .Should().BeEquivalentTo(new Dictionary { [MQC.TRANSPORT_PROPERTY] = MQC.TRANSPORT_MQSERIES_MANAGED, [MQC.HOST_NAME_PROPERTY] = "mq.inline", [MQC.PORT_PROPERTY] = 1416, [MQC.CHANNEL_PROPERTY] = "IN.SVRCONN", [MQC.CCSID_PROPERTY] = 819, [MQC.USER_ID_PROPERTY] = "u1", [MQC.PASSWORD_PROPERTY] = "p1", [MQC.APPNAME_PROPERTY] = "app1", [MQC.SSL_CIPHER_SPEC_PROPERTY] = "TLS_AES_128_GCM_SHA256", [MQC.SSL_RESET_COUNT_PROPERTY] = 4096, [MQC.SSL_CERT_STORE_PROPERTY] = "lbl", [MQC.SSL_PEER_NAME_PROPERTY] = "CN=mq", }); } [Fact] public void TheOption_IsMarkedAsARegistryReferenceToTheFactory() { typeof(IbmMqEndpointOptions).GetProperty(nameof(IbmMqEndpointOptions.ConnectionFactory))! .GetCustomAttributes(typeof(RegistryReferenceAttribute), inherit: true) .Cast().Single().Expected.Should().Be(typeof(IbmMqConnectionFactory)); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqContentTypeMappingTests.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.IbmMq/IbmMqContentTypeMappingTests.cs ---- using IBM.WMQ; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// Tests for and /// mappings. /// public sealed class IbmMqContentTypeMappingTests { [Theory] [InlineData("MQSTR ", "text/plain")] // MQFMT_STRING is padded [InlineData("MQHRF2 ", "text/plain")] // MQFMT_RF_HEADER_2 [InlineData(" ", "application/octet-stream")] // MQFMT_NONE (spaces) public void FormatToContentType_MapsKnownFormats(string format, string expected) { IbmMqMessageHelper.FormatToContentType(format).Should().Be(expected); } [Fact] public void FormatToContentType_Null_ReturnsNull() { IbmMqMessageHelper.FormatToContentType(null).Should().BeNull(); } [Theory] [InlineData("")] [InlineData(" ")] public void FormatToContentType_EmptyOrWhitespace_ReturnsBinary(string format) { // Empty / whitespace-only = MQFMT_NONE semantics → binary IbmMqMessageHelper.FormatToContentType(format).Should().Be("application/octet-stream"); } [Theory] [InlineData("MQCICS ")] [InlineData("MQIMS ")] public void FormatToContentType_UnknownFormat_ReturnsNull(string format) { IbmMqMessageHelper.FormatToContentType(format).Should().BeNull(); } [Theory] [InlineData("application/json")] [InlineData("text/plain")] [InlineData("text/xml")] [InlineData(null)] public void ContentTypeToFormat_TextTypes_ReturnsMqfmtString(string? contentType) { var fmt = IbmMqMessageHelper.ContentTypeToFormat(contentType); fmt.Trim().Should().Be(MQC.MQFMT_STRING.Trim()); } [Fact] public void ContentTypeToFormat_OctetStream_ReturnsMqfmtNone() { var fmt = IbmMqMessageHelper.ContentTypeToFormat("application/octet-stream"); fmt.Trim().Should().Be(MQC.MQFMT_NONE.Trim()); } [Fact] public void RoundTrip_StringFormat() { var ct = IbmMqMessageHelper.FormatToContentType(MQC.MQFMT_STRING); ct.Should().Be("text/plain"); var fmt = IbmMqMessageHelper.ContentTypeToFormat(ct); fmt.Trim().Should().Be(MQC.MQFMT_STRING.Trim()); } [Fact] public void RoundTrip_NoneFormat() { var ct = IbmMqMessageHelper.FormatToContentType(MQC.MQFMT_NONE); ct.Should().Be("application/octet-stream"); var fmt = IbmMqMessageHelper.ContentTypeToFormat(ct); fmt.Trim().Should().Be(MQC.MQFMT_NONE.Trim()); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqEndpointOptionsTests.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.IbmMq/IbmMqEndpointOptionsTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; public sealed class IbmMqEndpointOptionsTests { // ── Defaults ──────────────────────────────────────────────────── [Fact] public void Defaults_AreCorrect() { var opts = new IbmMqEndpointOptions(); opts.Host.Should().Be("localhost"); opts.Port.Should().Be(1414); opts.Channel.Should().Be("DEV.APP.SVRCONN"); opts.QueueManager.Should().Be("QM1"); opts.DestinationType.Should().Be(IbmMqDestinationType.Queue); opts.ResolvedConcurrentConsumers.Should().Be(1); opts.WaitInterval.Should().Be(5000); opts.Batching.Should().BeFalse(); opts.MaxBatchMessages.Should().BeNull(); opts.DisableReplyTo.Should().BeFalse(); opts.Transacted.Should().BeNull("unset, a producer follows the enclosing .Transacted() block"); opts.Persistence.Should().Be(IbmMqPersistence.AsQDef); opts.Priority.Should().Be(-1); opts.Expiry.Should().Be(-1); opts.TargetClient.Should().Be(IbmMqTargetClient.Jms); opts.MessageType.Should().Be(IbmMqMessageType.Datagram); opts.ReplyTo.Should().BeFalse(); opts.Timeout.Should().Be(30); opts.CorrelationPattern.Should().Be(IbmMqCorrelationPattern.MsgId); opts.CCSID.Should().Be(1208); opts.MqmdWriteEnabled.Should().BeFalse(); opts.MqmdReadEnabled.Should().BeTrue(); opts.Convert.Should().BeTrue(); opts.TemporaryModel.Should().Be("SYSTEM.DEFAULT.MODEL.QUEUE"); } // ── BindFromUri ───────────────────────────────────────────────── [Fact] public void BindFromUri_ConnectionParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=broker1&port=1415&channel=MY.SVRCONN&queueManager=QM2&user=admin&password=secret&clientId=app1"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Host.Should().Be("broker1"); opts.Port.Should().Be(1415); opts.Channel.Should().Be("MY.SVRCONN"); opts.QueueManager.Should().Be("QM2"); opts.User.Should().Be("admin"); opts.Password.Should().Be("secret"); opts.ClientId.Should().Be("app1"); } [Fact] public void BindFromUri_ConsumerParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=localhost&concurrentConsumers=4&waitInterval=10000&backoutThreshold=5&backoutQueue=DLQ&convert=false"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.ResolvedConcurrentConsumers.Should().Be(4); opts.WaitInterval.Should().Be(10000); opts.BackoutThreshold.Should().Be(5); opts.BackoutQueue.Should().Be("DLQ"); opts.Convert.Should().BeFalse(); } [Fact] public void BindFromUri_ProducerParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=localhost&persistence=Persistent&priority=7&expiry=3000&targetClient=Mq&messageType=Request"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Persistence.Should().Be(IbmMqPersistence.Persistent); opts.Priority.Should().Be(7); opts.Expiry.Should().Be(3000); opts.TargetClient.Should().Be(IbmMqTargetClient.Mq); opts.MessageType.Should().Be(IbmMqMessageType.Request); } [Fact] public void BindFromUri_DestinationType_Topic() { var uri = EndpointUriParser.Parse("wmq:EVENTS?host=localhost&destinationType=Topic"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.DestinationType.Should().Be(IbmMqDestinationType.Topic); } [Fact] public void BindFromUri_TransactionParams_Bind() { var uri = EndpointUriParser.Parse("wmq:Q?host=localhost&transacted=true"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.Transacted.Should().BeTrue(); } [Fact] public void BindFromUri_RpcParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=localhost&replyTo=true&replyToQueue=REPLY.Q&replyToQueueManager=QM2&timeout=60&correlationPattern=CorrelId"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.ReplyTo.Should().BeTrue(); opts.ReplyToQueue.Should().Be("REPLY.Q"); opts.ReplyToQueueManager.Should().Be("QM2"); opts.Timeout.Should().Be(60); opts.CorrelationPattern.Should().Be(IbmMqCorrelationPattern.CorrelId); } [Fact] public void BindFromUri_SslParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=localhost&sslCipherSpec=TLS_RSA_WITH_AES_256_CBC_SHA256&sslPeerName=CN%3Dbroker&sslCertLabel=mycert&sslKeyRepository=/opt/keys/key"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.SslCipherSpec.Should().Be("TLS_RSA_WITH_AES_256_CBC_SHA256"); opts.SslPeerName.Should().Be("CN=broker"); opts.SslCertLabel.Should().Be("mycert"); opts.SslKeyRepository.Should().Be("/opt/keys/key"); } [Fact] public void BindFromUri_AdvancedParams_Bind() { var uri = EndpointUriParser.Parse( "wmq:Q?host=localhost&cCSID=437&mqmdWriteEnabled=true&mqmdReadEnabled=false"); var opts = new IbmMqEndpointOptions(); opts.BindFromUri(uri.RawParameters); opts.CCSID.Should().Be(437); opts.MqmdWriteEnabled.Should().BeTrue(); opts.MqmdReadEnabled.Should().BeFalse(); } // ── Validate ──────────────────────────────────────────────────── [Fact] public void Validate_ValidDefaults_DoesNotThrow() { var opts = new IbmMqEndpointOptions(); var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_EmptyQueueManager_Throws() { var opts = new IbmMqEndpointOptions { QueueManager = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*queueManager*"); } [Fact] public void Validate_TemporaryModel_EmptyOrLongerThan48_Throws() { foreach (var model in new[] { "", " ", new string('M', 49) }) { var act = () => new IbmMqEndpointOptions { TemporaryModel = model }.Validate(); act.Should().Throw().WithMessage("*temporaryModel*"); } } [Fact] public void TemporaryModel_BindsFromUri_AndReachesTheInlineConnection() { var uri = EndpointUriParser.Parse("wmq:Q?host=localhost&temporaryModel=DEV.APP.MODEL.QUEUE"); var endpoint = (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(uri); endpoint.EndpointOptions.TemporaryModel.Should().Be("DEV.APP.MODEL.QUEUE"); endpoint.Connection.TemporaryModel.Should().Be("DEV.APP.MODEL.QUEUE"); } [Fact] public void Validate_EmptyHost_Throws() { var opts = new IbmMqEndpointOptions { Host = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*host*"); } [Fact] public void Validate_EmptyChannel_Throws() { var opts = new IbmMqEndpointOptions { Channel = "" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*channel*"); } [Fact] public void Validate_InvalidPort_Throws() { var opts = new IbmMqEndpointOptions { Port = 0 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*port*"); } [Fact] public void Validate_PortTooHigh_Throws() { var opts = new IbmMqEndpointOptions { Port = 70000 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*port*"); } [Fact] public void Validate_InvalidConcurrentConsumers_Throws() { var opts = new IbmMqEndpointOptions { ConcurrentConsumers = "0" }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*concurrentConsumers*"); } [Fact] public void Validate_NegativeWaitInterval_Throws() { var opts = new IbmMqEndpointOptions { WaitInterval = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*waitInterval*"); } [Fact] public void Validate_InvalidRpcTimeout_Throws() { var opts = new IbmMqEndpointOptions { Timeout = 0 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*timeout*"); } // ── Enum values ───────────────────────────────────────────────── [Theory] [InlineData(IbmMqPersistence.AsQDef, -1)] [InlineData(IbmMqPersistence.NonPersistent, 0)] [InlineData(IbmMqPersistence.Persistent, 1)] public void IbmMqPersistence_HasCorrectValues(IbmMqPersistence value, int expected) { ((int)value).Should().Be(expected); } [Theory] [InlineData(IbmMqMessageType.Datagram, 8)] [InlineData(IbmMqMessageType.Request, 1)] [InlineData(IbmMqMessageType.Reply, 2)] [InlineData(IbmMqMessageType.Report, 4)] public void IbmMqMessageType_HasCorrectValues(IbmMqMessageType value, int expected) { ((int)value).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqExpressionTests.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.IbmMq/IbmMqExpressionTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Expressions; using redb.Route.IbmMq; using IbmMqDsl = redb.Route.IbmMq.Wmq; namespace redb.Route.Tests.IbmMq; /// /// Tests for expression resolution in IBM MQ producer options (Phase 2). /// Verifies that expression properties bind correctly and resolve at runtime. /// public class IbmMqExpressionTests { // ── BindFromUri: expression binds to *Expression property ──────── [Fact] public void BindFromUri_PersistenceExpression_BindsCorrectly() { var opts = new IbmMqEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "localhost", ["persistenceExpression"] = "${header.pers}" }); opts.PersistenceExpression.Should().Be("${header.pers}"); opts.Persistence.Should().Be(IbmMqPersistence.AsQDef); // default unchanged } [Fact] public void BindFromUri_PriorityExpression_BindsCorrectly() { var opts = new IbmMqEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "localhost", ["priorityExpression"] = "${header.prio}" }); opts.PriorityExpression.Should().Be("${header.prio}"); opts.Priority.Should().Be(-1); // default unchanged } [Fact] public void BindFromUri_ExpiryExpression_BindsCorrectly() { var opts = new IbmMqEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "localhost", ["expiryExpression"] = "${header.exp}" }); opts.ExpiryExpression.Should().Be("${header.exp}"); opts.Expiry.Should().Be(-1); // default unchanged } [Fact] public void BindFromUri_MessageTypeExpression_BindsCorrectly() { var opts = new IbmMqEndpointOptions(); opts.BindFromUri(new Dictionary { ["host"] = "localhost", ["messageTypeExpression"] = "${header.mt}" }); opts.MessageTypeExpression.Should().Be("${header.mt}"); opts.MessageType.Should().Be(IbmMqMessageType.Datagram); // default unchanged } // ── ResolveOption: expressions resolve from exchange ───────────── [Fact] public void ResolveOption_PersistenceExpression_ResolvesByName() { var opts = new IbmMqEndpointOptions { PersistenceExpression = "${header.pers}" }; var msg = new Message("body"); msg.Headers["pers"] = "Persistent"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.PersistenceExpression, exchange); resolved.Should().Be("Persistent"); Enum.TryParse(resolved, true, out var parsed).Should().BeTrue(); parsed.Should().Be(IbmMqPersistence.Persistent); } [Fact] public void ResolveOption_PersistenceExpression_ResolvesByNumericValue() { var opts = new IbmMqEndpointOptions { PersistenceExpression = "${header.pers}" }; var msg = new Message("body"); msg.Headers["pers"] = "1"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.PersistenceExpression, exchange); resolved.Should().Be("1"); Enum.TryParse(resolved, true, out var parsed).Should().BeTrue(); parsed.Should().Be(IbmMqPersistence.Persistent); } [Fact] public void ResolveOption_PriorityExpression_ResolvesFromExchange() { var opts = new IbmMqEndpointOptions { PriorityExpression = "${header.prio}" }; var msg = new Message("body"); msg.Headers["prio"] = "5"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.PriorityExpression, exchange); resolved.Should().Be("5"); int.TryParse(resolved, out var prio).Should().BeTrue(); prio.Should().Be(5); } [Fact] public void ResolveOption_ExpiryExpression_ResolvesFromExchange() { var opts = new IbmMqEndpointOptions { ExpiryExpression = "${header.exp}" }; var msg = new Message("body"); msg.Headers["exp"] = "3000"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.ExpiryExpression, exchange); resolved.Should().Be("3000"); int.TryParse(resolved, out var expiry).Should().BeTrue(); expiry.Should().Be(3000); } [Fact] public void ResolveOption_MessageTypeExpression_ResolvesByName() { var opts = new IbmMqEndpointOptions { MessageTypeExpression = "${header.mt}" }; var msg = new Message("body"); msg.Headers["mt"] = "Request"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.MessageTypeExpression, exchange); resolved.Should().Be("Request"); Enum.TryParse(resolved, true, out var parsed).Should().BeTrue(); parsed.Should().Be(IbmMqMessageType.Request); } [Fact] public void ResolveOption_MessageTypeExpression_ResolvesByNumericValue() { var opts = new IbmMqEndpointOptions { MessageTypeExpression = "${header.mt}" }; var msg = new Message("body"); msg.Headers["mt"] = "1"; var exchange = new Exchange(msg); var resolved = opts.ResolveOption(opts.MessageTypeExpression, exchange); resolved.Should().Be("1"); Enum.TryParse(resolved, true, out var parsed).Should().BeTrue(); parsed.Should().Be(IbmMqMessageType.Request); } [Fact] public void ResolveOption_StaticValue_ReturnsAsIs() { var opts = new IbmMqEndpointOptions(); var exchange = new Exchange(new Message("body")); opts.ResolveOption("static-value", exchange).Should().Be("static-value"); } // ── DSL: expression routing in Build ───────────────────────────── [Fact] public void DslBuild_PersistenceExpression_RoutesToExpressionParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Persistence(new HeaderExpression("pers")) .Build(); uri.Should().Contain("persistenceExpression="); uri.Should().NotContain("&persistence="); } [Fact] public void DslBuild_PersistenceStatic_RoutesToEnumParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Persistent() .Build(); uri.Should().Contain("persistence=Persistent"); uri.Should().NotContain("persistenceExpression"); } [Fact] public void DslBuild_PriorityExpression_RoutesToExpressionParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Priority(new HeaderExpression("prio")) .Build(); uri.Should().Contain("priorityExpression="); uri.Should().NotContain("&priority="); } [Fact] public void DslBuild_PriorityStatic_RoutesToNormalParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Priority(5) .Build(); uri.Should().Contain("priority=5"); uri.Should().NotContain("priorityExpression"); } [Fact] public void DslBuild_ExpiryExpression_RoutesToExpressionParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Expiry(new HeaderExpression("exp")) .Build(); uri.Should().Contain("expiryExpression="); uri.Should().NotContain("&expiry="); } [Fact] public void DslBuild_ExpiryStatic_RoutesToNormalParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .Expiry(3000) .Build(); uri.Should().Contain("expiry=3000"); uri.Should().NotContain("expiryExpression"); } [Fact] public void DslBuild_MessageTypeExpression_RoutesToExpressionParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .MessageType(new HeaderExpression("mt")) .Build(); uri.Should().Contain("messageTypeExpression="); uri.Should().NotContain("&messageType="); } [Fact] public void DslBuild_MessageTypeStatic_RoutesToEnumParam() { var uri = IbmMqDsl.Queue("DEV.QUEUE.1") .Host("localhost") .MessageType(IbmMqMessageType.Request) .Build(); uri.Should().Contain("messageType=Request"); uri.Should().NotContain("messageTypeExpression"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqHeaderFilterStrategyTests.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.IbmMq/IbmMqHeaderFilterStrategyTests.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// headerFilterStrategy=#name on IBM MQ endpoints, on the poll and the XMS (receiveMode=listener) paths: /// on a producer it decides which exchange headers go into the header catalogue and which catalogued headers of a /// reply come back, on a consumer which catalogued headers come in and which headers go out with the reply. The /// redbIbmMq.* metadata is set whatever the strategy says. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqHeaderFilterStrategyTests { private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static RouteContext Context() { var ctx = new RouteContext(); ctx.AddComponent(new IbmMqComponent()); ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false }); ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] }); return ctx; } private static async Task> Deliver(string producerOptions, string consumerOptions) { const string queue = "DEV.QUEUE.2"; var tag = $"hdr-strategy-{Guid.NewGuid():N}"; var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = Context(); // The dev queue is shared: only this test's message is taken. ctx.AddRoutes(r => r.From($"wmq:{queue}?{Connection}{consumerOptions}").Process(e => { var body = e.In.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : e.In.Body?.ToString(); if (body == tag) received.TrySetResult(e); })); await ctx.Start(); var exchange = new Exchange(new Message(tag)); exchange.In.Headers["Correlation-ID"] = "c-42"; exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["Authorization"] = "Bearer secret"; var producer = ctx.GetEndpoint($"wmq:{queue}?{Connection}{producerOptions}").CreateProducer(); await producer.Start(); await producer.Process(exchange); await producer.Stop(); return new Dictionary((await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers); } private static async Task> Reply(string producerOptions, string consumerOptions) { const string queue = "DEV.QUEUE.3"; await using var ctx = Context(); ctx.AddRoutes(r => r.From($"wmq:{queue}?{Connection}{consumerOptions}").Process(e => { e.Out = new Message("reply"); e.Out.Headers["Correlation-ID"] = "c-42"; e.Out.Headers["X-Reply"] = "r1"; e.Out.Headers["Authorization"] = "Bearer secret"; })); await ctx.Start(); var producer = ctx.GetEndpoint($"wmq:{queue}?{Connection}&replyTo=true&timeout=15{producerOptions}").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("request")); await producer.Process(exchange); await producer.Stop(); exchange.HasOut.Should().BeTrue("the request-reply producer must receive the reply"); return new Dictionary(exchange.Out!.Headers); } [Theory] [InlineData("")] [InlineData("&receiveMode=listener")] public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader(string receiveMode) { var headers = await Deliver("&headerFilterStrategy=#correlationOnly", receiveMode); headers["Correlation-ID"].Should().Be("c-42"); headers.Should().NotContainKey("X-Corr"); headers.Should().NotContainKey("Authorization"); headers.Should().ContainKey(IbmMqHeaders.MsgId, "the consumer's own metadata is set whatever the strategy says"); } [Theory] [InlineData("")] [InlineData("&receiveMode=listener")] public async Task OnAConsumer_TheStrategyDecidesWhatComesIn(string receiveMode) { var headers = await Deliver("", "&headerFilterStrategy=#noSecrets" + receiveMode); headers["X-Corr"].Should().Be("c1"); headers.Should().NotContainKey("Authorization", "the consumer's strategy drops it on the way in"); } [Fact] public async Task OnAReplyingConsumer_TheStrategyDecidesWhatTheReplyCarries() { var headers = await Reply("", "&headerFilterStrategy=#correlationOnly"); headers["Correlation-ID"].Should().Be("c-42"); headers.Should().NotContainKey("X-Reply"); headers.Should().NotContainKey("Authorization"); } [Theory] [InlineData("")] [InlineData("&receiveMode=listener")] public async Task OnARequestReplyProducer_TheStrategyDecidesWhatComesBackWithTheReply(string receiveMode) { var headers = await Reply("&headerFilterStrategy=#noSecrets" + receiveMode, ""); headers["X-Reply"].Should().Be("r1"); headers.Should().NotContainKey("Authorization", "the producer's strategy drops it on the way back in"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqHeaderMappingCharacterizationTests.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.IbmMq/IbmMqHeaderMappingCharacterizationTests.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// What crosses an IBM MQ message today, producer to consumer: pinned before the header filter strategy /// takes the rule over, so the transport's default keeps it exactly. /// The producer packs every exchange header but its own redbIbmMq.* and null values into one JSON-encoded /// message property (MQ property names forbid hyphens), every value as text; the consumer unpacks every one of them, /// on the poll path and on the event-driven XMS path (receiveMode=listener, its own mapper) alike. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqHeaderMappingCharacterizationTests { private const string Queue = "DEV.QUEUE.2"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; [Theory] [InlineData("")] [InlineData("&receiveMode=listener")] public async Task ProducerToConsumer_TheHeadersThatCrossTheMessage(string receiveMode) { var tag = $"hdr-char-{Guid.NewGuid():N}"; var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var ctx = new RouteContext(); ctx.AddComponent(new IbmMqComponent()); // The dev queue is shared: only this test's message is taken. ctx.AddRoutes(r => r.From($"wmq:{Queue}?{Connection}{receiveMode}").Process(e => { var body = e.In.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : e.In.Body?.ToString(); if (body == tag) received.TrySetResult(e); })); await ctx.Start(); var exchange = new Exchange(new Message(tag)); exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["X-Int"] = 42; exchange.In.Headers["X-Null"] = null; exchange.In.Headers["Authorization"] = "Bearer secret"; exchange.In.Headers["redbHttp.Method"] = "DELETE"; exchange.In.Headers[IbmMqHeaders.Prefix + "Custom"] = "own"; var producer = ctx.GetEndpoint($"wmq:{Queue}?{Connection}").CreateProducer(); await producer.Start(); await producer.Process(exchange); await producer.Stop(); var headers = (await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers; headers["X-Corr"].Should().Be("c1"); headers["X-Int"].Should().Be("42", "every value crosses as text in the JSON property"); headers.Should().NotContainKey("X-Null", "a null value is skipped"); headers["Authorization"].Should().Be("Bearer secret", "nothing filters a credential"); headers["redbHttp.Method"].Should().Be("DELETE", "a control header of another transport crosses (finding 3.1)"); headers.Should().NotContainKey(IbmMqHeaders.Prefix + "Custom", "the producer keeps its own redbIbmMq.* back"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqHeadersTests.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.IbmMq/IbmMqHeadersTests.cs ---- using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; public sealed class IbmMqHeadersTests { [Fact] public void Prefix_IsCorrect() { IbmMqHeaders.Prefix.Should().Be("redbIbmMq."); } [Fact] public void AllConstants_StartWithPrefix() { IbmMqHeaders.Destination.Should().StartWith("redbIbmMq."); IbmMqHeaders.QueueManager.Should().StartWith("redbIbmMq."); IbmMqHeaders.MsgId.Should().StartWith("redbIbmMq."); IbmMqHeaders.CorrelId.Should().StartWith("redbIbmMq."); IbmMqHeaders.Format.Should().StartWith("redbIbmMq."); IbmMqHeaders.CCSID.Should().StartWith("redbIbmMq."); IbmMqHeaders.Encoding.Should().StartWith("redbIbmMq."); IbmMqHeaders.Persistence.Should().StartWith("redbIbmMq."); IbmMqHeaders.Priority.Should().StartWith("redbIbmMq."); IbmMqHeaders.Expiry.Should().StartWith("redbIbmMq."); IbmMqHeaders.ReplyToQueue.Should().StartWith("redbIbmMq."); IbmMqHeaders.ReplyToQueueManager.Should().StartWith("redbIbmMq."); IbmMqHeaders.MsgType.Should().StartWith("redbIbmMq."); IbmMqHeaders.PutApplName.Should().StartWith("redbIbmMq."); IbmMqHeaders.PutApplType.Should().StartWith("redbIbmMq."); IbmMqHeaders.GroupId.Should().StartWith("redbIbmMq."); IbmMqHeaders.MsgSeqNumber.Should().StartWith("redbIbmMq."); IbmMqHeaders.Feedback.Should().StartWith("redbIbmMq."); IbmMqHeaders.ReportOptions.Should().StartWith("redbIbmMq."); IbmMqHeaders.UserIdentifier.Should().StartWith("redbIbmMq."); IbmMqHeaders.BackoutCount.Should().StartWith("redbIbmMq."); IbmMqHeaders.PutDateTime.Should().StartWith("redbIbmMq."); } [Fact] public void IsRedbHeader_WithRedbPrefix_ReturnsTrue() { IbmMqHeaders.IsRedbHeader("redbIbmMq.MsgId").Should().BeTrue(); IbmMqHeaders.IsRedbHeader("redbIbmMq.CorrelId").Should().BeTrue(); IbmMqHeaders.IsRedbHeader("redbIbmMq.Destination").Should().BeTrue(); } [Fact] public void IsRedbHeader_CaseInsensitive_ReturnsTrue() { IbmMqHeaders.IsRedbHeader("REDBIBMMQ.MsgId").Should().BeTrue(); IbmMqHeaders.IsRedbHeader("redBibmMq.something").Should().BeTrue(); } [Fact] public void IsRedbHeader_WithoutPrefix_ReturnsFalse() { IbmMqHeaders.IsRedbHeader("X-Custom-Header").Should().BeFalse(); IbmMqHeaders.IsRedbHeader("traceparent").Should().BeFalse(); IbmMqHeaders.IsRedbHeader("Content-Type").Should().BeFalse(); } [Fact] public void IsRedbHeader_Empty_ReturnsFalse() { IbmMqHeaders.IsRedbHeader("").Should().BeFalse(); } [Fact] public void IsRedbHeader_Null_ThrowsOrReturnsFalse() { var act = () => IbmMqHeaders.IsRedbHeader(null!); try { act().Should().BeFalse(); } catch (NullReferenceException) { // also acceptable } } [Fact] public void AllConstants_AreDistinct() { var all = new[] { IbmMqHeaders.Destination, IbmMqHeaders.QueueManager, IbmMqHeaders.MsgId, IbmMqHeaders.CorrelId, IbmMqHeaders.Format, IbmMqHeaders.CCSID, IbmMqHeaders.Encoding, IbmMqHeaders.Persistence, IbmMqHeaders.Priority, IbmMqHeaders.Expiry, IbmMqHeaders.ReplyToQueue, IbmMqHeaders.ReplyToQueueManager, IbmMqHeaders.MsgType, IbmMqHeaders.PutApplName, IbmMqHeaders.PutApplType, IbmMqHeaders.GroupId, IbmMqHeaders.MsgSeqNumber, IbmMqHeaders.Feedback, IbmMqHeaders.ReportOptions, IbmMqHeaders.UserIdentifier, IbmMqHeaders.BackoutCount, IbmMqHeaders.PutDateTime }; all.Should().OnlyHaveUniqueItems(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqIntegrationCollection.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.IbmMq/IbmMqIntegrationCollection.cs ---- namespace redb.Route.Tests.IbmMq; /// /// Disables parallel execution between the IBM MQ integration test classes so that /// shared DEV.QUEUE.* queues are not contended across classes. /// [CollectionDefinition("IbmMqIntegration", DisableParallelization = true)] public sealed class IbmMqIntegrationCollection { } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqIntegrationTests.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.IbmMq/IbmMqIntegrationTests.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Transactions; using redb.Route.Processors; using redb.Route.IbmMq; using Xunit.Abstractions; namespace redb.Route.Tests.IbmMq; /// /// Integration tests against a real IBM MQ broker (Developer Edition). /// Expects IBM MQ at localhost:1414, QM1, channel DEV.APP.SVRCONN, user app/admin. /// Docker: docker compose -f redb.Route/docker-compose.tests.yml --profile ibmmq up -d --wait /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqIntegrationTests { private const string Host = "localhost"; private const int Port = 1414; private const string Channel = "DEV.APP.SVRCONN"; private const string QueueManager = "QM1"; private const string User = "app"; private const string Password = "admin"; private readonly ITestOutputHelper _output; public IbmMqIntegrationTests(ITestOutputHelper output) => _output = output; // ───── Helpers ───── private IbmMqEndpoint CreateEndpoint(string destination, string? extraParams = null) { var qs = $"host={Host}&port={Port}&channel={Channel}&queueManager={QueueManager}&user={User}&password={Password}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"wmq:{destination}?{qs}"); var component = new IbmMqComponent(); return (IbmMqEndpoint)component.CreateEndpoint(uri); } // ───── Basic send/receive ───── [Fact] public async Task Producer_SendsMessage_ConsumerReceives() { var queue = "DEV.QUEUE.1"; _output.WriteLine($"Queue: {queue}"); // Send var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("Hello IBM MQ")); await producer.Process(exchange); await producer.Stop(); await epProd.Stop(); // The message length depends on the body's CCSID: 12 bytes in a single-byte or UTF-8 code page, more in UTF-16. ((IEndpointStatistics)epProd).BytesOut.Should().BeGreaterThanOrEqualTo(12, "the put counts its message bytes"); // Receive var epCons = CreateEndpoint(queue, "waitInterval=5000"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); received.Add(ex.In.Body?.ToString() ?? ""); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); received.Should().Contain("Hello IBM MQ"); } // ───── Metadata headers ───── [Fact] public async Task Consumer_SetsIbmMqMetadataHeaders() { var queue = "DEV.QUEUE.2"; var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("meta-test")); await producer.Process(exchange); await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(queue, "waitInterval=5000"); IExchange? capturedExchange = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { capturedExchange = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); capturedExchange.Should().NotBeNull(); capturedExchange!.In.Headers.Should().ContainKey(IbmMqHeaders.Destination); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.QueueManager); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.MsgId); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.Format); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.Persistence); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.Priority); capturedExchange.In.Headers.Should().ContainKey(IbmMqHeaders.MsgType); capturedExchange.In.Headers[IbmMqHeaders.Destination].Should().Be(queue); capturedExchange.In.Headers[IbmMqHeaders.QueueManager].Should().Be(QueueManager); } // ───── Transacted producer: the block decides ───── /// Runs inside a transacted block, as .Transacted() on a route does. private static Task InTransaction(IExchange exchange, Func body) => new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange); /// /// Sends one uniquely marked message from inside a .Transacted() block that then fails; returns what reached /// the shared queue during the receive window. /// private async Task> SendFromAFailedBlock(string body, string? producerParams) { const string queue = "DEV.QUEUE.2"; var epProd = CreateEndpoint(queue, producerParams); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var failed = () => InTransaction(new Exchange(new Message(body)), async (ex, ct) => { await producer.Process(ex, ct); throw new InvalidOperationException("the unit of work failed"); }); await failed.Should().ThrowAsync(); await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(queue, "waitInterval=2000"); var received = new ConcurrentBag(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { received.Add(callInfo.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.Delay(5_000); await consumer.Stop(); await epCons.Stop(); return received; } [Fact] public async Task Producer_without_transacted_joins_the_block_and_sends_nothing_when_it_fails() { var body = $"join-{Guid.NewGuid():N}"; var received = await SendFromAFailedBlock(body, producerParams: null); received.Should().NotContain(body, "inside .Transacted() a send joins the transaction unless transacted=false opts out"); } [Fact] public async Task Producer_with_transacted_false_sends_at_once_even_from_a_failed_block() { var body = $"optout-{Guid.NewGuid():N}"; var received = await SendFromAFailedBlock(body, "transacted=false"); received.Should().Contain(body); } [Fact] public async Task Deferred_puts_of_one_producer_commit_together_or_not_at_all() { const string queue = "DEV.QUEUE.2"; var first = $"batch-first-{Guid.NewGuid():N}"; var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); // Two puts in one block; the second is larger than the queue and channel accept, so it fails at the commit. var commitFailed = () => InTransaction(new Exchange(new Message(first)), async (ex, ct) => { await producer.Process(ex, ct); ex.In.Body = new string('x', 5 * 1024 * 1024); await producer.Process(ex, ct); }); await commitFailed.Should().ThrowAsync(); await producer.Stop(); await epProd.Stop(); ((IEndpointStatistics)epProd).BytesOut.Should().Be(0, "a batch backed out at the commit sent nothing"); var epCons = CreateEndpoint(queue, "waitInterval=2000"); var received = new ConcurrentBag(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { received.Add(callInfo.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.Delay(5_000); await consumer.Stop(); await epCons.Stop(); received.Should().NotContain(first, "the puts of one producer in a block commit in one unit of work or not at all"); } [Fact] public void Request_reply_producer_refuses_transacted_true() { var endpoint = CreateEndpoint("DEV.QUEUE.1", "replyTo=true&transacted=true"); var act = () => endpoint.CreateProducer(); act.Should().Throw().WithMessage("*replyTo*transacted*"); } // ───── Multiple messages roundtrip ───── [Fact] public async Task Roundtrip_MultipleMessages() { var queue = "DEV.QUEUE.3"; const int messageCount = 10; var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); for (int i = 0; i < messageCount; i++) { var exchange = new Exchange(new Message($"msg-{i}")); await producer.Process(exchange); } await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(queue, "waitInterval=5000"); var received = new ConcurrentBag(); var allReceived = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { received.Add(callInfo.Arg().In.Body?.ToString() ?? ""); if (received.Count >= messageCount) allReceived.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allReceived.Task, Task.Delay(30_000)); await consumer.Stop(); await epCons.Stop(); received.Count.Should().BeGreaterThanOrEqualTo(messageCount); for (int i = 0; i < messageCount; i++) received.Should().Contain($"msg-{i}"); } // ───── RPC request/reply ───── [Fact] public async Task Rpc_RequestReply_ReturnsResponse() { var queue = "DEV.QUEUE.4"; // Server: consumer echoes back var epServer = CreateEndpoint(queue); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); var body = ex.In.Body?.ToString() ?? ""; ex.Out = new Message($"ECHO:{body}"); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epServer.CreateConsumer(processor); await consumer.Start(); // Client: RPC call var epClient = CreateEndpoint(queue, "replyTo=true&timeout=30"); var rpcProducer = (IbmMqProducer)epClient.CreateProducer(); await rpcProducer.Start(); var exchange = new Exchange(new Message("ping")); await rpcProducer.Process(exchange); await rpcProducer.Stop(); await epClient.Stop(); await consumer.Stop(); await epServer.Stop(); exchange.HasOut.Should().BeTrue(); exchange.Out!.Body?.ToString().Should().Be("ECHO:ping"); } // ───── Persistent message ───── [Fact] public async Task PersistentMessage_SurvivesAndDelivers() { var queue = "DEV.QUEUE.1"; var epProd = CreateEndpoint(queue, "persistence=Persistent"); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("persistent-msg")); await producer.Process(exchange); await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(queue, "waitInterval=5000"); IExchange? captured = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); captured.Should().NotBeNull(); captured!.In.Body?.ToString().Should().Be("persistent-msg"); } // ───── Transacted consumer ───── [Fact] public async Task TransactedConsumer_CommitsOnSuccess() { var queue = "DEV.QUEUE.2"; // Send a message normally var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("tx-consumer-msg"))); await producer.Stop(); await epProd.Stop(); // Consume with transacted=true var epCons = CreateEndpoint(queue, "transacted=true&waitInterval=5000"); IExchange? captured = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); // Wait for ProcessedCount to increment var sw = System.Diagnostics.Stopwatch.StartNew(); while (consumer.ProcessedCount < 1 && sw.ElapsedMilliseconds < 3_000) await Task.Delay(50); await consumer.Stop(); await epCons.Stop(); captured.Should().NotBeNull(); captured!.In.Body?.ToString().Should().Be("tx-consumer-msg"); consumer.ProcessedCount.Should().BeGreaterThanOrEqualTo(1); } // ───── Topic pub/sub ───── [Fact] public async Task Topic_PublishSubscribe() { var topic = "DEV/TEST/EVENTS"; // Start subscriber first var epSub = CreateEndpoint(topic, "destinationType=Topic&waitInterval=5000"); var received = new ConcurrentBag(); var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { received.Add(callInfo.Arg().In.Body?.ToString() ?? ""); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epSub.CreateConsumer(processor); await consumer.Start(); await Task.Delay(2000); // let subscription establish // Publish var epPub = CreateEndpoint(topic, "destinationType=Topic"); var producer = (IbmMqProducer)epPub.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("topic-event")); await producer.Process(exchange); await producer.Stop(); await epPub.Stop(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epSub.Stop(); received.Should().Contain("topic-event"); } // ───── Binary payload ───── [Fact] public async Task BinaryPayload_RoundTrip() { var queue = "DEV.QUEUE.4"; var epProd = CreateEndpoint(queue, "targetClient=Mq"); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var payload = new byte[] { 0x01, 0x02, 0x03, 0xFE, 0xFF }; await producer.Process(new Exchange(new Message(payload))); await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(queue, "waitInterval=5000"); IExchange? captured = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); captured.Should().NotBeNull(); captured!.In.Body.Should().BeOfType(); ((byte[])captured.In.Body!).Should().BeEquivalentTo(payload); } // ───── Expression support: Priority + Expiry from exchange headers ───── [Fact] public async Task Producer_ExpressionPriorityAndExpiry_ResolvedOnSend() { var queue = "DEV.QUEUE.1"; // Producer with expression-based priority and expiry var epProd = CreateEndpoint(queue, "priorityExpression=${header.prio}&expiryExpression=${header.exp}"); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var msg = new Message("expression-mqmd"); msg.Headers["prio"] = "7"; msg.Headers["exp"] = "3000"; var exchange = new Exchange(msg); await producer.Process(exchange); await producer.Stop(); await epProd.Stop(); // Receive and verify MQMD fields var epCons = CreateEndpoint(queue, "waitInterval=5000"); IExchange? captured = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); captured.Should().NotBeNull(); captured!.In.Body?.ToString().Should().Be("expression-mqmd"); captured.In.Headers[IbmMqHeaders.Priority].Should().Be(7); captured.In.Headers[IbmMqHeaders.Expiry].Should().BeOfType() .Which.Should().BeGreaterThanOrEqualTo(1); // Expiry ticks down from 3000 } // ───── Expression support: Persistence from exchange headers ───── [Fact] public async Task Producer_ExpressionPersistence_ResolvedOnSend() { var queue = "DEV.QUEUE.2"; // Producer with expression-based persistence (by enum name) var epProd = CreateEndpoint(queue, "persistenceExpression=${header.pers}"); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var msg = new Message("expression-persist"); msg.Headers["pers"] = "Persistent"; var exchange = new Exchange(msg); await producer.Process(exchange); await producer.Stop(); await epProd.Stop(); // Receive and verify MQMD persistence var epCons = CreateEndpoint(queue, "waitInterval=5000"); IExchange? captured = null; var tcs = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await consumer.Stop(); await epCons.Stop(); captured.Should().NotBeNull(); captured!.In.Body?.ToString().Should().Be("expression-persist"); // MQC.MQPER_PERSISTENT = 1 captured.In.Headers[IbmMqHeaders.Persistence].Should().Be(1); } // ── The options sweep: targetClient ────────────────────────────────────── [Fact] public async Task TargetClientMq_SendsRawMessageWithoutProperties() { // targetClient=Mq: a legacy MQ app expects raw MQMD+body. Message properties are what // materializes as MQRFH2 on property-aware paths - in Mq mode none may be written. // The option was declared and read by nothing. var queue = "DEV.QUEUE.2"; var marker = Guid.NewGuid().ToString("N"); var endpoint = CreateEndpoint(queue, "targetClient=Mq"); var producer = (IbmMqProducer)endpoint.CreateProducer(); await producer.Start(); var msg = new Message(marker); msg.Headers["X-Custom"] = "must-not-travel"; await producer.Process(new Exchange(msg)); await producer.Stop(); // Raw read via MQ classes: the message must carry NO custom properties. var props = new System.Collections.Hashtable { [IBM.WMQ.MQC.HOST_NAME_PROPERTY] = Host, [IBM.WMQ.MQC.PORT_PROPERTY] = Port, [IBM.WMQ.MQC.CHANNEL_PROPERTY] = Channel, [IBM.WMQ.MQC.USER_ID_PROPERTY] = User, [IBM.WMQ.MQC.PASSWORD_PROPERTY] = Password, [IBM.WMQ.MQC.TRANSPORT_PROPERTY] = IBM.WMQ.MQC.TRANSPORT_MQSERIES_MANAGED, }; using var qm = new IBM.WMQ.MQQueueManager(QueueManager, props); var q = qm.AccessQueue(queue, IBM.WMQ.MQC.MQOO_INPUT_SHARED | IBM.WMQ.MQC.MQOO_FAIL_IF_QUIESCING); try { var raw = new IBM.WMQ.MQMessage(); var gmo = new IBM.WMQ.MQGetMessageOptions { Options = IBM.WMQ.MQC.MQGMO_WAIT, WaitInterval = 10000 }; string? body = null; while (body != marker) { raw = new IBM.WMQ.MQMessage(); q.Get(raw, gmo); body = raw.ReadString(raw.MessageLength); } var catalogue = (string?)null; try { catalogue = raw.GetStringProperty(IbmMqHeaders.HeaderCatalogue); } catch (IBM.WMQ.MQException) { /* property absent - exactly what Mq mode promises */ } catalogue.Should().BeNull( "targetClient=Mq must send a bare MQMD+body without message properties"); } finally { q.Close(); qm.Disconnect(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqListSendTests.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.IbmMq/IbmMqListSendTests.cs ---- using IBM.WMQ; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// A list body at the IBM MQ producer: each element of a list of IMessage is its own MQ message with its own body and /// headers, all put under syncpoint and committed once; a failure in the middle backs the unit of work out and nothing /// goes; a plain list and a list at a request-reply producer are refused. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqListSendTests { private const string Queue = "DEV.QUEUE.LIST"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static async Task StartProducer(string options = "") { var uri = EndpointUriParser.Parse($"wmq:{Queue}?{Connection}{options}"); var producer = (IbmMqProducer)((IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(uri)).CreateProducer(); await producer.Start(); return producer; } private static List<(string Body, string? Catalogue)> TakeAll(int waitMs) { var got = new List<(string, string?)>(); using var qm = IbmMqPoisonTests.Connect(); var q = qm.AccessQueue(Queue, MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING); try { var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_WAIT | MQC.MQGMO_NO_SYNCPOINT, WaitInterval = waitMs }; while (true) { var message = new MQMessage(); try { q.Get(message, gmo); } catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { return got; } string? catalogue = null; try { catalogue = message.GetStringProperty(IbmMqHeaders.HeaderCatalogue); } catch (MQException) { /* no headers */ } got.Add((message.ReadString(message.MessageLength), catalogue)); gmo.WaitInterval = 0; } } finally { q.Close(); qm.Disconnect(); } } [Fact] public async Task Each_message_of_a_list_is_its_own_MQ_message_with_its_own_body_and_headers() { IbmMqPoisonTests.Drain(Queue); var producer = await StartProducer(); var a = new Message("a"); a.Headers["XRecord"] = "rec-a"; var b = new Message("b"); b.Headers["XRecord"] = "rec-b"; var parent = new Exchange(new Message(new List { a, b })); parent.In.Headers["XParent"] = "must-not-travel"; await producer.Process(parent); await producer.Stop(); var got = TakeAll(waitMs: 10_000); got.Select(g => g.Body).Should().Equal("a", "b"); got[0].Catalogue.Should().Contain("rec-a").And.NotContain("must-not-travel"); got[1].Catalogue.Should().Contain("rec-b").And.NotContain("must-not-travel"); } [Fact] public async Task A_failure_in_the_middle_backs_the_list_out_and_nothing_goes() { IbmMqPoisonTests.Drain(Queue); var producer = await StartProducer(); // Over the queue's default MAXMSGL (4 MB): the put of the second element fails. var tooLarge = new Message(new byte[5 * 1024 * 1024]); var act = () => producer.Process(new Exchange(new Message(new List { new Message("first"), tooLarge, new Message("third") }))); await act.Should().ThrowAsync(); await producer.Stop(); TakeAll(waitMs: 2000).Should().BeEmpty("the list is one unit of work: MQBACK took the first put back"); } [Fact] public async Task A_plain_list_is_refused() { IbmMqPoisonTests.Drain(Queue); var producer = await StartProducer(); try { var act = () => producer.Process(new Exchange(new Message(new List { 1, 2 }))); await act.Should().ThrowAsync().WithMessage("*List*IMessage*"); } finally { await producer.Stop(); } TakeAll(waitMs: 1000).Should().BeEmpty("nothing, not even the type name, was sent"); } [Fact] public async Task A_list_at_a_request_reply_producer_is_refused() { var producer = await StartProducer("&replyTo=true&timeout=5"); try { var act = () => producer.Process(new Exchange(new Message(new List { new Message("a"), new Message("b") }))); await act.Should().ThrowAsync().WithMessage("*Split the list for request-reply*"); } finally { await producer.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqPoisonCanonTests.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.IbmMq/IbmMqPoisonCanonTests.cs ---- using System.Text; using IBM.WMQ; using redb.Route.Core; using redb.Route.IbmMq; using Xunit.Abstractions; namespace redb.Route.Tests.IbmMq; /// /// The IBM MQ provider's chain for a poison message, in both receive modes (listener mode: the XMS client's own): the input queue's own BOTHRESH and BOQNAME /// when the endpoint sets nothing, the endpoint's backoutThreshold and backoutQueue over them, and the queue manager's /// dead letter queue (with a dead letter header) when a threshold is in force and there is no backout queue. Expects /// IBM MQ at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqPoisonCanonTests(ITestOutputHelper output) { private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static string DeadLetterQueue() { using var qm = IbmMqPoisonTests.Connect(); var name = qm.DeadLetterQueueName?.Trim() ?? ""; qm.Disconnect(); return name; } /// Runs a route that always fails on until sees the message. private static async Task RunPoison(string queue, string options, string marker, Func landed) { var runs = 0; await using var context = new RouteContext(); context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{queue}?{Connection}&transacted=true&{options}") .Process(_ => { Interlocked.Increment(ref runs); throw new InvalidOperationException("always fails"); })); await context.Start(); var deadline = DateTime.UtcNow.AddSeconds(60); while (!landed() && DateTime.UtcNow < deadline) await Task.Delay(500); return runs; } [Theory] [InlineData("poll")] [InlineData("listener")] public async Task Without_endpoint_options_the_queues_own_BOTHRESH_and_BOQNAME_apply(string receiveMode) { IbmMqPoisonTests.Drain("DEV.QUEUE.ATTR"); IbmMqPoisonTests.Drain("DEV.QUEUE.ATTR.BOQ"); var marker = $"attr-{Guid.NewGuid():N}"; IbmMqPoisonTests.Put("DEV.QUEUE.ATTR", marker); var moved = new List(); var runs = await RunPoison("DEV.QUEUE.ATTR", $"receiveMode={receiveMode}", marker, () => { moved.AddRange(IbmMqPoisonTests.Drain("DEV.QUEUE.ATTR.BOQ")); return moved.Contains(marker); }); output.WriteLine($"{receiveMode}: runs={runs}, moved={string.Join(",", moved)}"); moved.Should().Contain(marker); runs.Should().Be(2, "BOTHRESH(2): the route ran at backout counts 0 and 1"); } [Theory] [InlineData("poll")] [InlineData("listener")] public async Task The_endpoints_options_override_the_queues_attributes(string receiveMode) { IbmMqPoisonTests.Drain("DEV.QUEUE.ATTR"); IbmMqPoisonTests.Drain("DEV.QUEUE.POISON.BOQ"); var marker = $"override-{Guid.NewGuid():N}"; IbmMqPoisonTests.Put("DEV.QUEUE.ATTR", marker); var moved = new List(); var runs = await RunPoison("DEV.QUEUE.ATTR", $"receiveMode={receiveMode}&backoutThreshold=1&backoutQueue=DEV.QUEUE.POISON.BOQ", marker, () => { moved.AddRange(IbmMqPoisonTests.Drain("DEV.QUEUE.POISON.BOQ")); return moved.Contains(marker); }); output.WriteLine($"{receiveMode}: runs={runs}, moved={string.Join(",", moved)}"); moved.Should().Contain(marker); runs.Should().Be(1, "backoutThreshold=1 on the endpoint wins over the queue's BOTHRESH(2)"); } [Theory] [InlineData("poll")] [InlineData("listener")] public async Task A_threshold_without_a_backout_queue_goes_to_the_dead_letter_queue_with_a_dead_letter_header(string receiveMode) { var deadLetterQueue = DeadLetterQueue(); output.WriteLine($"queue manager DEADQ: '{deadLetterQueue}'"); deadLetterQueue.Should().NotBeEmpty("the stand's queue manager has a dead letter queue"); IbmMqPoisonTests.Drain("DEV.QUEUE.NOBOQ"); var marker = $"dlq-{Guid.NewGuid():N}"; IbmMqPoisonTests.Put("DEV.QUEUE.NOBOQ", marker); MQMessage? found = null; var runs = await RunPoison("DEV.QUEUE.NOBOQ", $"receiveMode={receiveMode}", marker, () => { found ??= TakeFromDeadLetterQueue(deadLetterQueue, marker); return found is not null; }); output.WriteLine($"{receiveMode}: runs={runs}, dlq format={found?.Format}"); found.Should().NotBeNull("the message reached the queue manager's dead letter queue"); found!.Format.Should().Be(MQC.MQFMT_DEAD_LETTER_HEADER); runs.Should().Be(2, "BOTHRESH(2) on the queue"); } private static MQMessage? TakeFromDeadLetterQueue(string queue, string marker) { using var qm = IbmMqPoisonTests.Connect(); var q = qm.AccessQueue(queue, MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING); try { var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_NO_WAIT | MQC.MQGMO_NO_SYNCPOINT }; while (true) { var message = new MQMessage(); try { q.Get(message, gmo); } catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { return null; } var bytes = message.ReadBytes(message.MessageLength); // The XMS client puts the text of a message it dead-letters in UTF-16; the MQI path keeps the bytes. if (Encoding.UTF8.GetString(bytes).Contains(marker, StringComparison.Ordinal) || Encoding.BigEndianUnicode.GetString(bytes).Contains(marker, StringComparison.Ordinal) || Encoding.Unicode.GetString(bytes).Contains(marker, StringComparison.Ordinal) || Encoding.BigEndianUnicode.GetString(bytes, 1, bytes.Length - 1).Contains(marker, StringComparison.Ordinal) || Encoding.Unicode.GetString(bytes, 1, bytes.Length - 1).Contains(marker, StringComparison.Ordinal)) return message; } } finally { q.Close(); qm.Disconnect(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqPoisonTests.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.IbmMq/IbmMqPoisonTests.cs ---- using System.Collections; using IBM.WMQ; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// The failed-message rule of the IBM MQ consumer in XMS listener mode (poll mode is the poison case of /// ): a transacted consumer backs a failed message out, and once the message was /// backed out backoutThreshold times it goes to the backout queue instead of the route, as the IBM MQ classes /// for JMS requeue it. Expects IBM MQ at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqPoisonTests { private const string Queue = "DEV.QUEUE.POISON"; private const string BackoutQueue = "DEV.QUEUE.POISON.BOQ"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; internal static MQQueueManager Connect() => new("QM1", new Hashtable { [MQC.HOST_NAME_PROPERTY] = "localhost", [MQC.PORT_PROPERTY] = 1414, [MQC.CHANNEL_PROPERTY] = "DEV.APP.SVRCONN", [MQC.USER_ID_PROPERTY] = "app", [MQC.PASSWORD_PROPERTY] = "admin", [MQC.TRANSPORT_PROPERTY] = MQC.TRANSPORT_MQSERIES_MANAGED, }); /// Empties a queue and returns the bodies it held. internal static List Drain(string queue, int waitMs = 0) { var bodies = new List(); using var qm = Connect(); var q = qm.AccessQueue(queue, MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING); try { var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_WAIT | MQC.MQGMO_NO_SYNCPOINT, WaitInterval = waitMs }; while (true) { var message = new MQMessage(); try { q.Get(message, gmo); } catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { return bodies; } bodies.Add(message.ReadString(message.MessageLength)); gmo.WaitInterval = 0; } } finally { q.Close(); qm.Disconnect(); } } internal static void Put(string queue, params string[] bodies) { using var qm = Connect(); var q = qm.AccessQueue(queue, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING); foreach (var body in bodies) { var message = new MQMessage { Format = MQC.MQFMT_STRING }; message.WriteString(body); q.Put(message); } q.Close(); qm.Disconnect(); } [Theory] [InlineData("listener")] public async Task A_message_backed_out_backoutThreshold_times_goes_to_the_backout_queue_not_the_route(string receiveMode) { Drain(Queue); Drain(BackoutQueue); Put(Queue, "poison"); var runs = 0; await using (var context = new RouteContext()) { context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{Queue}?{Connection}&receiveMode={receiveMode}&transacted=true&backoutThreshold=2&backoutQueue={BackoutQueue}") .Process(_ => { Interlocked.Increment(ref runs); throw new InvalidOperationException("always fails"); })); await context.Start(); Drain(BackoutQueue, waitMs: 30_000).Should().Equal("poison"); } runs.Should().Be(2, "the route ran on backout counts 0 and 1; at 2 the message went to the backout queue"); Drain(Queue).Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqReconnectTests.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.IbmMq/IbmMqReconnectTests.cs ---- using System.Collections.Concurrent; using IBM.WMQ; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.Processors; using redb.Route.Tests.Conformance; using redb.Route.Transactions; namespace redb.Route.Tests.IbmMq; /// /// A consumer outlives a queue manager restart: the restart breaks its connection (MQRC_CONNECTION_BROKEN or /// MQRC_Q_MGR_QUIESCING), and once the queue manager is back the same route reads the queue again: batch and XMS /// listener (poll mode is the restart case of ); a producer sends again: plain, /// transacted (the commit finds the lost connection), request-reply with the poll and the XMS reply receiver. /// Each reconnect is counted on the endpoint by its connection supervisor. /// The restart is on : it runs only where /// REDB_TEST_IBMMQ_CONTAINER names the queue manager's container and the docker CLI reaches it, elsewhere it is /// skipped. Run it with tests/docker/run-fault-suite.sh --broker ibmmq, which starts the queue manager with host /// networking (behind docker's published-port proxy a client connect made while the queue manager starts can hang, and /// the managed client holds every later connect of the process behind it) and builds apart from the test run. /// Expects IBM MQ at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqReconnectTests { private const string Queue = "DEV.QUEUE.RECONNECT"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static readonly IbmMqStand Stand = IbmMqStand.Instance; // A reconnect attempt that hangs while the queue manager starts is given up after 30 s; then the next one connects. private static TimeSpan Wait => Stand.Wait; [BrokerFaultTheory(IbmMqStand.ContainerVariable)] [InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=500&backoutQueue=DEV.QUEUE.BATCH.BOQ")] [InlineData("&receiveMode=listener")] [InlineData("&receiveMode=listener&transacted=true")] public async Task A_consumer_reads_the_queue_again_after_the_queue_manager_restarts(string extra) { await Stand.DrainAsync(Queue, TimeSpan.Zero); var received = new ConcurrentQueue(); var log = new ListLog(); await using var context = new RouteContext(loggerFactory: log); context.AddComponent(new IbmMqComponent()); var uri = $"wmq:{Queue}?{Connection}&waitInterval=500{extra}"; context.AddRoutes(r => r.From(uri) .Process(e => { if (e.In.Body is List batch) foreach (var m in batch) received.Enqueue(Text(m)); else received.Enqueue(Text(e.In)); })); await context.Start(); await Stand.PutAsync(Queue, "before"); (await Until(() => received.Contains("before"), Wait)).Should().BeTrue("the route reads the queue before the restart"); await Stand.Fault!.RestartAsync(); // The queue manager reports itself running a moment before its listener takes connections. (await BrokerFault.UntilAsync(async () => { try { await Stand.PutAsync(Queue, "after"); return true; } catch (MQException) { return false; } }, Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the queue manager takes the message once its listener is up"); (await Until(() => received.Contains("after"), Wait)).Should() .BeTrue($"the consumer reconnects once the queue manager is back and reads what was put after the restart; log:{Environment.NewLine}{log}"); var statistics = (IEndpointStatistics)context.GetEndpoint(uri); statistics.Reconnects.Should().BeGreaterThan(0, "the connection supervisor counts the reconnect on the endpoint"); statistics.HealthStatus.Should().NotBe(EndpointHealthStatus.Critical, "the connection is back"); } [BrokerFaultTheory(IbmMqStand.ContainerVariable)] [InlineData(false, false, "")] [InlineData(false, true, "")] [InlineData(true, false, "")] [InlineData(true, false, "&receiveMode=listener")] public async Task A_producer_sends_again_after_the_queue_manager_restarts(bool requestReply, bool transacted, string extra) { await Stand.DrainAsync(Queue, TimeSpan.Zero); var log = new ListLog(); await using var context = new RouteContext(loggerFactory: log); context.AddComponent(new IbmMqComponent()); if (requestReply) // The responder: a consumer on the same queue answers every request. context.AddRoutes(r => r.From($"wmq:{Queue}?{Connection}&waitInterval=500") .Process(e => e.Out = new Message($"ECHO:{Text(e.In)}"))); await context.Start(); var endpoint = context.GetEndpoint($"wmq:{Queue}?{Connection}" + (requestReply ? "&replyTo=true&timeout=10" : "") + (transacted ? "&transacted=true" : "") + extra); var producer = endpoint.CreateProducer(); await producer.Start(); try { (await Send(producer, "before", requestReply, transacted)).Should().BeTrue("the producer sends before the restart"); await Stand.Fault!.RestartAsync(); // Sends right after the restart fail (the lost connection, then a reconnect not yet due or refused); the // producer reconnects on a later send. var sent = await BrokerFault.UntilAsync(() => Send(producer, "after", requestReply, transacted), Wait, TimeSpan.FromSeconds(1)); sent.Should().BeTrue($"the producer reconnects once the queue manager is back; log:{Environment.NewLine}{log}"); if (!requestReply) (await Stand.DrainAsync(Queue, TimeSpan.FromSeconds(2))).Should().Contain("after"); ((IEndpointStatistics)endpoint).Reconnects.Should().BeGreaterThan(0, "the connection supervisor counts the reconnect on the endpoint"); } finally { await producer.Stop(); } } /// /// One send; for request-reply it succeeds only with the responder's answer. A transacted send runs inside a /// transacted block, as .Transacted() on a route does: the put and its MQCMIT happen as the block ends. /// private static async Task Send(IProducer producer, string body, bool requestReply, bool transacted) { var exchange = new Exchange(new Message(body)); try { if (transacted) await new TransactedProcessor(new DelegateProcessor((ex, ct) => producer.Process(ex, ct)), new TransactionPolicy()) .Process(exchange); else await producer.Process(exchange); } catch (Exception) { return false; } return !requestReply || exchange.Out?.Body?.ToString() == $"ECHO:{body}"; } private static string Text(IMessage message) => message.Body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : message.Body?.ToString() ?? ""; private static async Task Until(Func done, TimeSpan wait) { var deadline = DateTime.UtcNow + wait; while (DateTime.UtcNow < deadline) { if (done()) return true; await Task.Delay(500); } return done(); } /// The warnings and errors the route logged, for the failure message. private sealed class ListLog : Microsoft.Extensions.Logging.ILoggerFactory, Microsoft.Extensions.Logging.ILogger { private readonly ConcurrentQueue _lines = new(); public void AddProvider(Microsoft.Extensions.Logging.ILoggerProvider provider) { } public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => this; public void Dispose() { } public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => logLevel >= Microsoft.Extensions.Logging.LogLevel.Information; public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception? exception, Func formatter) => _lines.Enqueue($"{DateTime.UtcNow:HH:mm:ss.fff} {logLevel} {formatter(state, exception)} {exception?.GetType().Name} {exception?.Message}"); public override string ToString() => string.Join("\n", _lines.TakeLast(40)); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqReplyToBridgeTests.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.IbmMq/IbmMqReplyToBridgeTests.cs ---- using System.Collections; using IBM.WMQ; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// A sender's reply-to does not travel across a bridge, as in Apache Camel's JMS: a message consumed with a reply-to /// queue and forwarded by an ordinary put goes out without it, unless the producer sets preserveMessageQos=true. /// The correlation id is carried; a request-reply producer sets its own reply-to. Expects IBM MQ at localhost:1414 /// with the queues of tests/docker/ibmmq/redb-tests.mqsc. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqReplyToBridgeTests { private const string Input = "DEV.QUEUE.BRIDGE.IN"; private const string Output = "DEV.QUEUE.BRIDGE.OUT"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static MQQueueManager Connect() => new("QM1", new Hashtable { [MQC.HOST_NAME_PROPERTY] = "localhost", [MQC.PORT_PROPERTY] = 1414, [MQC.CHANNEL_PROPERTY] = "DEV.APP.SVRCONN", [MQC.USER_ID_PROPERTY] = "app", [MQC.PASSWORD_PROPERTY] = "admin", [MQC.TRANSPORT_PROPERTY] = MQC.TRANSPORT_MQSERIES_MANAGED, }); private static readonly byte[] CorrelationId = Enumerable.Range(1, 24).Select(i => (byte)i).ToArray(); /// /// Puts one datagram on the input queue with the given reply-to queue and correlation id, bridges it by a route to /// the output queue, and returns the message as it arrived there. /// private static async Task Bridge(string producerOptions, string? senderReplyTo, Action? routeStep = null) { var marker = Guid.NewGuid().ToString("N"); using (var qm = Connect()) { var q = qm.AccessQueue(Input, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING); var put = new MQMessage { CorrelationId = CorrelationId, Format = MQC.MQFMT_STRING }; if (senderReplyTo is not null) put.ReplyToQueueName = senderReplyTo; put.WriteString(marker); q.Put(put); q.Close(); qm.Disconnect(); } await using var context = new RouteContext(); context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{Input}?{Connection}") .Process(ex => routeStep?.Invoke(ex)) .To($"wmq:{Output}?{Connection}{producerOptions}")); await context.Start(); using var reader = Connect(); var output = reader.AccessQueue(Output, MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING); try { var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_WAIT, WaitInterval = 20_000 }; while (true) { var got = new MQMessage(); output.Get(got, gmo); // throws MQRC_NO_MSG_AVAILABLE after the wait if (got.ReadString(got.MessageLength) == marker) return got; } } finally { output.Close(); reader.Disconnect(); } } [Fact] public async Task A_forwarded_message_goes_out_without_the_senders_reply_to_and_keeps_its_correlation_id() { var forwarded = await Bridge(producerOptions: "", senderReplyTo: "SENDER.REPLIES"); forwarded.ReplyToQueueName.Trim().Should().BeEmpty("an ordinary put does not carry a sender's reply-to on"); forwarded.CorrelationId.Should().Equal(CorrelationId); } [Fact] public async Task With_preserveMessageQos_the_forwarded_message_keeps_the_senders_reply_to() { var forwarded = await Bridge(producerOptions: "&preserveMessageQos=true", senderReplyTo: "SENDER.REPLIES"); forwarded.ReplyToQueueName.Trim().Should().Be("SENDER.REPLIES"); forwarded.CorrelationId.Should().Equal(CorrelationId); } [Theory] [InlineData("", false)] [InlineData("&preserveMessageQos=true", true)] public async Task A_reply_to_header_set_by_the_route_follows_the_same_rule(string producerOptions, bool kept) { var forwarded = await Bridge(producerOptions, senderReplyTo: null, routeStep: ex => ex.In.Headers[IbmMqHeaders.ReplyToQueue] = "ROUTE.NAMED.REPLIES"); if (kept) forwarded.ReplyToQueueName.Trim().Should().Be("ROUTE.NAMED.REPLIES"); else forwarded.ReplyToQueueName.Trim().Should().BeEmpty(); } [Fact] public async Task A_request_reply_producer_sets_its_own_reply_to_over_a_forwarded_one() { const string queue = "DEV.QUEUE.4"; await using var context = new RouteContext(); context.AddComponent(new IbmMqComponent()); context.AddRoutes(r => r .From($"wmq:{queue}?{Connection}") .Process(ex => ex.Out = new Message("pong"))); await context.Start(); var producer = context.GetEndpoint($"wmq:{queue}?{Connection}&replyTo=true&timeout=20&preserveMessageQos=true") .CreateProducer(); await producer.Start(); try { var exchange = new Exchange(new Message("ping")); exchange.In.Headers[IbmMqHeaders.ReplyToQueue] = "A.QUEUE.OF.ANOTHER.SYSTEM"; exchange.In.Headers[IbmMqHeaders.ReplyToQueueManager] = "QM.OF.ANOTHER.SYSTEM"; await producer.Process(exchange); exchange.HasOut.Should().BeTrue("the reply came back to the producer's own reply queue"); var body = exchange.Out!.Body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : exchange.Out.Body?.ToString(); body.Should().Be("pong"); } finally { await producer.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqStand.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.IbmMq/IbmMqStand.cs ---- using redb.Route.Tests.Conformance; namespace redb.Route.Tests.IbmMq; /// /// The IBM MQ stand: queue manager QM1 at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc, /// reached through the MQI client of . Its container, when /// names it, is broken with ; the queue manager is ready when /// the image's chkmqhealthy passes. /// public sealed class IbmMqStand : IConnectorStand { /// The variable that names the IBM MQ container a test may restart. public const string ContainerVariable = "REDB_TEST_IBMMQ_CONTAINER"; /// The stand of this process. public static IbmMqStand Instance { get; } = new(); private IbmMqStand() { } /// public BrokerFault? Fault { get; } = BrokerFault.FromEnvironment(ContainerVariable, "chkmqhealthy"); /// public TimeSpan Wait { get; } = BrokerFault.DefaultWait; /// public Task PutAsync(string destination, string body, CancellationToken ct = default) => Task.Run(() => IbmMqPoisonTests.Put(destination, body), ct); /// public Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default) => Task.Run>(() => IbmMqPoisonTests.Drain(destination, (int)wait.TotalMilliseconds), ct); } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqTemporaryModelTests.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.IbmMq/IbmMqTemporaryModelTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// temporaryModel (IBM MQ TEMPMODEL) against a real IBM MQ broker: the dynamic reply queue of a /// request-reply producer is created from the model queue the option names, on the poll path (MQ classes, /// AccessQueue on the model) and the listener path (XMS CreateTemporaryQueue) alike. /// Expects IBM MQ at localhost:1414, QM1, channel DEV.APP.SVRCONN, user app/admin; the developer image grants /// app DEV.APP.MODEL.QUEUE. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqTemporaryModelTests { private const string Queue = "DEV.QUEUE.2"; private static IbmMqEndpoint CreateEndpoint(string destination, string? extraParams = null) { var qs = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"wmq:{destination}?{qs}"); return (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(uri); } [Theory] [InlineData("poll")] [InlineData("listener")] public async Task Rpc_DynamicReplyQueueFromTheNamedModel_GetsTheReply(string receiveMode) { await using var server = await EchoServer.StartAsync(); var epClient = CreateEndpoint(Queue, $"replyTo=true&timeout=15&receiveMode={receiveMode}&temporaryModel=DEV.APP.MODEL.QUEUE"); var rpc = (IbmMqProducer)epClient.CreateProducer(); await rpc.Start(); try { var exchange = new Exchange(new Message("ping")); await rpc.Process(exchange); exchange.HasOut.Should().BeTrue("the reply comes back on the queue made from DEV.APP.MODEL.QUEUE"); exchange.Out!.Body?.ToString().Should().Be("ECHO:ping"); } finally { await rpc.Stop(); await epClient.Stop(); } } [Theory] [InlineData("poll")] [InlineData("listener")] public async Task Rpc_ModelQueueThatDoesNotExist_Fails(string receiveMode) { var epClient = CreateEndpoint(Queue, $"replyTo=true&timeout=5&receiveMode={receiveMode}&temporaryModel=REDB.NO.SUCH.MODEL"); var rpc = (IbmMqProducer)epClient.CreateProducer(); try { var act = async () => { await rpc.Start(); var exchange = new Exchange(new Message("ping")); await rpc.Process(exchange); if (exchange.Exception is { } failure) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw(); }; // MQRC_UNKNOWN_OBJECT_NAME (2085): the option reaches the broker, not the old fixed model. (await act.Should().ThrowAsync()).Which.ToString().Should().Contain("2085"); } finally { await rpc.Stop(); await epClient.Stop(); } } /// A poll consumer on that answers every request with ECHO: and its body. private sealed class EchoServer : IAsyncDisposable { private readonly IbmMqEndpoint _endpoint; private readonly IConsumer _consumer; private EchoServer(IbmMqEndpoint endpoint, IConsumer consumer) { _endpoint = endpoint; _consumer = consumer; } public static async Task StartAsync() { var endpoint = CreateEndpoint(Queue, "waitInterval=200"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(call => { var ex = call.Arg(); ex.Out = new Message($"ECHO:{ex.In.Body}"); return Task.CompletedTask; }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); return new EchoServer(endpoint, consumer); } public async ValueTask DisposeAsync() { await _consumer.Stop(); await _endpoint.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqTracePropagationTests.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.IbmMq/IbmMqTracePropagationTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.IbmMq; /// /// W3C trace context through the MQ message properties, on both receive paths (poll and XMS listener), through the /// connector against a real queue manager. The consumer opens a receive span per message: a child of the sender's /// context, or a root without one — never a child of the activity the receive loop inherited from whoever started it, /// and a message without properties (targetClient=Mq) reads as one without context — with the sender's baggage back on /// it and the route's spans under it; a failed route marks it red. The producer writes the context of its own send span /// over a copied one. EnableTelemetry=false opens none of these spans, while the ambient context still goes out. /// Expects IBM MQ at localhost:1414, QM1, channel DEV.APP.SVRCONN, user app/admin. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqTracePropagationTests { private const string Queue = "DEV.QUEUE.5"; private const string Connection = "host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin"; private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20); public static TheoryData ReceiveModes => new() { "poll", "listener" }; private static string Uri(string? extra = null) => $"wmq:{Queue}?{Connection}{(extra is null ? "" : "&" + extra)}"; private static string ConsumerUri(string mode) => Uri(mode == "listener" ? "receiveMode=listener&waitInterval=200" : "waitInterval=200"); private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller() { var traceId = ActivityTraceId.CreateRandom(); var spanId = ActivitySpanId.CreateRandom(); return (traceId, spanId, $"00-{traceId}-{spanId}-01"); } private static RouteTelemetryProbe SpansOf(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, "messaging.destination.name") == Queue); private static string Tag() => $"trace-{Guid.NewGuid():N}"; /// Empties the queue so the test's message is the only one its consumer sees. private static async Task Drain() { await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false }); ctx.AddComponent(new IbmMqComponent()); ctx.AddRoutes(r => r.From(Uri("waitInterval=200")).Process(_ => { })); await ctx.Start(); await Task.Delay(1000); } /// Sends through a context of its own. private static async Task Send(string body, string? extra = null, bool telemetry = true, IDictionary? headers = null) { await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new IbmMqComponent()); await ctx.Start(); var exchange = new Exchange(new Message(body)); foreach (var (key, value) in headers ?? new Dictionary()) exchange.In.Headers[key] = value; using var template = new ProducerTemplate(ctx); template.Start(); await template.SendAsync(Uri(extra), exchange); } /// /// A context with one consuming route, started inside a host span: the receive loop inherits it, the way it inherits /// whatever activity the application held when it started the routes. /// private static async Task StartConsumer(string mode, string tag, Action step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new IbmMqComponent()); ctx.AddRoutes(r => r.From(ConsumerUri(mode)).RouteId($"wmq-{tag}") .Process(e => { if (e.In.Body?.ToString() == tag) step(e); })); using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start()) await ctx.Start(); return ctx; } private static async Task Arrived(Task task) => (await Task.WhenAny(task, Task.Delay(Wait))).Should().Be(task, "the message should reach the route"); [Theory] [MemberData(nameof(ReceiveModes))] public async Task A_message_without_context_opens_a_root_receive_span(string mode) { await Drain(); var tag = Tag(); using var probe = SpansOf(ActivityKind.Consumer); var done = new TaskCompletionSource(); await using (await StartConsumer(mode, tag, _ => done.TrySetResult())) { await Send(tag, "targetClient=Mq", telemetry: false); // raw MQMD, no properties at all await Arrived(done.Task); } var receive = probe.Activities.Should().ContainSingle().Subject; receive.ParentSpanId.Should().Be(default(ActivitySpanId), "a message that carries no context starts a trace, not a child of the host's startup span"); receive.GetTagItem("messaging.system").Should().Be("wmq"); RouteTelemetryProbe.Tag(receive, RouteTelemetryProbe.EndpointTag).Should().StartWith("wmq:"); } [Theory] [MemberData(nameof(ReceiveModes))] public async Task A_message_with_context_continues_the_senders_trace_and_the_route_runs_under_it(string mode) { await Drain(); var tag = Tag(); using var receives = SpansOf(ActivityKind.Consumer); using var sends = SpansOf(ActivityKind.Producer); using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"wmq-{tag}"); var done = new TaskCompletionSource(); await using (await StartConsumer(mode, tag, _ => done.TrySetResult())) { await Send(tag); await Arrived(done.Task); } var send = sends.Activities.Should().ContainSingle().Subject; var receive = receives.Activities.Should().ContainSingle().Subject; receive.TraceId.Should().Be(send.TraceId); receive.ParentSpanId.Should().Be(send.SpanId); routes.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(receive.SpanId); } [Theory] [MemberData(nameof(ReceiveModes))] public async Task The_senders_baggage_reaches_the_route(string mode) { await Drain(); var tag = Tag(); using var probe = SpansOf(ActivityKind.Consumer); var seen = new TaskCompletionSource(); await using (await StartConsumer(mode, tag, _ => seen.TrySetResult(Activity.Current?.GetBaggageItem("tenant")))) { using (var caller = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start()) { caller.AddBaggage("tenant", "t1"); await Send(tag); } await Arrived(seen.Task); } seen.Task.Result.Should().Be("t1"); } [Theory] [MemberData(nameof(ReceiveModes))] public async Task A_failed_route_marks_the_receive_span_red(string mode) { await Drain(); var tag = Tag(); using var probe = SpansOf(ActivityKind.Consumer); var failed = new TaskCompletionSource(); await using (await StartConsumer(mode, tag, _ => { failed.TrySetResult(); throw new InvalidOperationException("route failed"); })) { await Send(tag, telemetry: false); await Arrived(failed.Task); var deadline = DateTime.UtcNow + Wait; while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(100); } probe.Activities.Should().NotBeEmpty(); probe.Activities[0].Status.Should().Be(ActivityStatusCode.Error); } [Theory] [MemberData(nameof(ReceiveModes))] public async Task A_timeout_inside_the_route_marks_the_receive_span_red(string mode) { await Drain(); var tag = Tag(); using var probe = SpansOf(ActivityKind.Consumer); var thrown = new TaskCompletionSource(); await using (await StartConsumer(mode, tag, _ => { thrown.TrySetResult(); throw new TaskCanceledException("a call inside the route timed out"); })) { await Send(tag, telemetry: false); await Arrived(thrown.Task); var deadline = DateTime.UtcNow + Wait; while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(100); } probe.Activities.Should().NotBeEmpty(); probe.Activities[0].Status.Should().Be(ActivityStatusCode.Error, "a cancellation nobody asked for is a failure"); } [Theory] [MemberData(nameof(ReceiveModes))] public async Task Stopping_the_consumer_does_not_mark_the_interrupted_message_red(string mode) { await Drain(); var tag = Tag(); using var probe = SpansOf(ActivityKind.Consumer); var started = new TaskCompletionSource(); var ctx = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(2) }); ctx.AddComponent(new IbmMqComponent()); ctx.AddRoutes(r => r.From(ConsumerUri(mode)).Process(async (e, ct) => { if (e.In.Body?.ToString() != tag) return; started.TrySetResult(); await Task.Delay(Timeout.Infinite, ct); })); await ctx.Start(); await Send(tag, telemetry: false); await Arrived(started.Task); await ctx.DisposeAsync(); // the drain gives up and cancels the processing token var deadline = DateTime.UtcNow + Wait; while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(100); probe.Activities.Should().NotBeEmpty(); probe.Activities.Should().OnlyContain(a => a.Status != ActivityStatusCode.Error, "our own stop is not a failure"); } [Fact] public async Task The_producer_sends_the_context_of_its_own_span_over_a_copied_one() { await Drain(); var tag = Tag(); using var sends = SpansOf(ActivityKind.Producer); using var receives = SpansOf(ActivityKind.Consumer); var done = new TaskCompletionSource(); await using (await StartConsumer("poll", tag, _ => done.TrySetResult())) { using (new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start()) { // What the header bridge copies from a received message. It travels on in the header catalogue; the // trace context is the traceparent property, and that one names this send. await Send(tag, headers: new Dictionary { ["traceparent"] = Caller().Header }); } await Arrived(done.Task); } var send = sends.Activities.Should().ContainSingle().Subject; var receive = receives.Activities.Should().ContainSingle().Subject; receive.TraceId.Should().Be(send.TraceId); receive.ParentSpanId.Should().Be(send.SpanId, "the next hop is a child of the send, not of the copied header"); } [Fact] public async Task Tracing_off_opens_no_span_and_still_passes_the_context_on() { await Drain(); var tag = Tag(); using var sends = SpansOf(ActivityKind.Producer); using var receives = SpansOf(ActivityKind.Consumer); var done = new TaskCompletionSource(); ActivityTraceId outerTrace; ActivitySpanId outerSpan; await using (await StartConsumer("poll", tag, _ => done.TrySetResult())) { using (var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start()) { (outerTrace, outerSpan) = (outer.TraceId, outer.SpanId); await Send(tag, telemetry: false); } await Arrived(done.Task); } sends.Activities.Should().BeEmpty("tracing is off for the sending context"); var receive = receives.Activities.Should().ContainSingle().Subject; receive.TraceId.Should().Be(outerTrace, "with no send span the ambient context goes out"); receive.ParentSpanId.Should().Be(outerSpan); var offTag = Tag(); var offDone = new TaskCompletionSource(); await using (await StartConsumer("poll", offTag, _ => offDone.TrySetResult(), telemetry: false)) { await Send(offTag, telemetry: false); await Arrived(offDone.Task); } receives.Activities.Should().ContainSingle("the context with tracing off opens no receive span"); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqXmsFailedStartTests.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.IbmMq/IbmMqXmsFailedStartTests.cs ---- using System.Net.NetworkInformation; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// An XMS listener consumer whose start fails part-way (the connection is up, the queue does not exist, so the consumer /// is refused) closes the connection it opened: repeated failed starts leave no half-open connection to the broker. /// Counted from this process's established TCP connections to the listener port, against a real IBM MQ broker /// (localhost:1414, QM1, DEV.APP.SVRCONN, app/admin). /// [Trait("Category", "Integration")] [Collection("IbmMqConnectionCount")] public sealed class IbmMqXmsFailedStartTests { private const int Port = 1414; private static IbmMqEndpoint Endpoint(string destination) => (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(EndpointUriParser.Parse( $"wmq:{destination}?host=localhost&port={Port}&channel=DEV.APP.SVRCONN&queueManager=QM1" + "&user=app&password=admin&receiveMode=listener")); private static int BrokerConnections() => IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections() .Count(c => c.RemoteEndPoint.Port == Port && c.State == TcpState.Established); private static async Task SettledBrokerConnections() { // A closed socket leaves ESTABLISHED within moments; read until two samples agree. var last = BrokerConnections(); for (var i = 0; i < 20; i++) { await Task.Delay(250); var now = BrokerConnections(); if (now == last) return now; last = now; } return last; } [Fact] public async Task Failed_starts_on_a_missing_queue_leave_no_connection_open() { var endpoint = Endpoint($"REDB.MISSING.{Guid.NewGuid():N}"); var consumer = (IbmMqConsumer)endpoint.CreateConsumer(Substitute.For()); var before = await SettledBrokerConnections(); for (var i = 0; i < 3; i++) { var start = () => consumer.Start(); await start.Should().ThrowAsync("the queue does not exist, so the consumer is refused"); } var after = await SettledBrokerConnections(); await endpoint.Stop(); after.Should().Be(before, "each failed start closes the connection it opened"); } } [CollectionDefinition("IbmMqConnectionCount", DisableParallelization = true)] public sealed class IbmMqConnectionCountCollection; Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqXmsFailedStartUnitTests.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.IbmMq/IbmMqXmsFailedStartUnitTests.cs ---- using IBM.XMS; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// An XMS listener consumer whose start fails part-way (the connection and the first worker's session are up, the second /// session is refused) closes what came up, and a later start opens one connection. Driven by a fake XMS connection /// through the endpoint's XmsConnectionSource, no broker needed ( proves the /// same against a real one). /// public sealed class IbmMqXmsFailedStartUnitTests { private sealed record FakeConnection(IConnection Connection, ISession Session, IMessageConsumer Consumer); private static FakeConnection Fake(bool refuseSecondSession) { var connection = Substitute.For(); var session = Substitute.For(); var consumer = Substitute.For(); session.CreateQueue(Arg.Any()).Returns(Substitute.For()); session.CreateConsumer(Arg.Any()).Returns(consumer); var sessions = 0; connection.CreateSession(Arg.Any(), Arg.Any()).Returns(_ => ++sessions == 2 && refuseSecondSession ? throw new XMSException("MQRC_NOT_AUTHORIZED") : session); return new FakeConnection(connection, session, consumer); } [Fact] public async Task A_start_refused_part_way_closes_what_came_up_and_the_next_start_opens_one_connection() { var endpoint = (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(EndpointUriParser.Parse( "wmq:DEV.QUEUE.1?host=mq.invalid&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&receiveMode=listener&concurrentConsumers=2")); var failing = Fake(refuseSecondSession: true); var working = Fake(refuseSecondSession: false); var opened = new Queue([failing, working]); var opens = 0; endpoint.XmsConnectionSource = () => { opens++; return opened.Dequeue().Connection; }; var consumer = (IbmMqConsumer)endpoint.CreateConsumer(Substitute.For()); var first = () => consumer.Start(); await first.Should().ThrowAsync(); failing.Consumer.Received(1).Close(); failing.Session.Received(1).Close(); failing.Connection.Received(1).Close(); await consumer.Start(); opens.Should().Be(2, "the second start opens one connection, none is left from the first"); working.Connection.Received(1).Start(); working.Connection.DidNotReceive().Close(); await consumer.Stop(); working.Connection.Received(1).Close(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqXmsListenerTests.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.IbmMq/IbmMqXmsListenerTests.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.Telemetry; using Xunit.Abstractions; namespace redb.Route.Tests.IbmMq; /// /// Integration tests for the event-driven XMS MessageListener receive path /// (receiveMode=listener) against a real IBM MQ broker. /// Expects IBM MQ at localhost:1414, QM1, channel DEV.APP.SVRCONN, user app/admin. /// [Trait("Category", "Integration")] [Collection("IbmMqIntegration")] public sealed class IbmMqXmsListenerTests { private const string Host = "localhost"; private const int Port = 1414; private const string Channel = "DEV.APP.SVRCONN"; private const string QueueManager = "QM1"; private const string User = "app"; private const string Password = "admin"; private readonly ITestOutputHelper _output; public IbmMqXmsListenerTests(ITestOutputHelper output) => _output = output; private IbmMqEndpoint CreateEndpoint(string destination, string? extraParams = null) { var qs = $"host={Host}&port={Port}&channel={Channel}&queueManager={QueueManager}&user={User}&password={Password}"; if (extraParams is not null) qs += $"&{extraParams}"; var uri = EndpointUriParser.Parse($"wmq:{destination}?{qs}"); var component = new IbmMqComponent(); return (IbmMqEndpoint)component.CreateEndpoint(uri); } [Fact] public async Task Listener_ReceivesMessage() { var queue = "DEV.QUEUE.1"; var epCons = CreateEndpoint(queue, "receiveMode=listener"); string? received = null; var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); received = ex.In.Body?.ToString(); tcs.TrySetResult(received ?? ""); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); try { // Publish AFTER the listener is up. await SendAsync(queue, "Hello XMS listener"); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); } finally { await consumer.Stop(); await epCons.Stop(); } received.Should().Be("Hello XMS listener"); consumer.ProcessedCount.Should().BeGreaterThan(0); } /// /// The acceptance criterion for the fix: publish→receive latency must collapse from the /// poll-path floor (~250–500 ms, the managed client's internal MQGET tick) to <50 ms. /// Measures several warm round-trips and takes the best to filter GC/scheduling jitter. /// [Fact] public async Task Listener_DeliveryLatency_IsUnder50ms() { var queue = "DEV.QUEUE.2"; var epCons = CreateEndpoint(queue, "receiveMode=listener"); TaskCompletionSource current = new(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { current.TrySetResult(Stopwatch.GetTimestamp()); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); // Reuse a single warm producer so the measurement is pure publish→receive, not connect+publish. var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var samples = new List(); try { const int rounds = 5; for (var i = 0; i < rounds; i++) { current = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var sentAt = Stopwatch.GetTimestamp(); await producer.Process(new Exchange(new Message($"latency-{i}"))); var completed = await Task.WhenAny(current.Task, Task.Delay(20_000)); completed.Should().Be(current.Task, "the XMS listener must deliver the message"); var receivedAt = await current.Task; var ms = Stopwatch.GetElapsedTime(sentAt, receivedAt).TotalMilliseconds; samples.Add(ms); _output.WriteLine($"round {i}: {ms:F1} ms"); // The first round warms the channel; ignore it in the assertion below. } } finally { await producer.Stop(); await epProd.Stop(); await consumer.Stop(); await epCons.Stop(); } // Warm rounds (skip the first) — the best must be well under the poll-path floor. var best = samples.Skip(1).Min(); _output.WriteLine($"best warm latency: {best:F1} ms (poll-path floor is ~250–500 ms)"); best.Should().BeLessThan(50, "event-driven XMS push should deliver in <50 ms"); } /// /// Transacted listener, happy path: a message that processes cleanly is committed on the delivering /// session and is NOT redelivered. /// [Fact] public async Task Listener_Transacted_CommitsOnSuccess_NoRedelivery() { var queue = "DEV.QUEUE.3"; await DrainQueueAsync(queue); var epCons = CreateEndpoint(queue, "receiveMode=listener&transacted=true"); var deliveries = 0; var firstSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { Interlocked.Increment(ref deliveries); firstSeen.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); try { await SendAsync(queue, "commit-me"); await Task.WhenAny(firstSeen.Task, Task.Delay(20_000)); // Grace window: if the message were rolled back it would be redelivered here. await Task.Delay(1500); } finally { await consumer.Stop(); await epCons.Stop(); } Volatile.Read(ref deliveries).Should().Be(1, "a committed message must not be redelivered"); } /// /// Transacted listener, failure path: a processing error rolls back the delivering session, so the /// broker redelivers the message. The processor throws on the first attempt and succeeds on the /// next — proving rollback → redelivery. /// [Fact] public async Task Listener_Transacted_RollsBackAndRedelivers_OnError() { var queue = "DEV.QUEUE.4"; await DrainQueueAsync(queue); var epCons = CreateEndpoint(queue, "receiveMode=listener&transacted=true"); var attempts = 0; var succeeded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { var n = Interlocked.Increment(ref attempts); if (n == 1) throw new InvalidOperationException("boom — force rollback on first delivery"); succeeded.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); try { await SendAsync(queue, "redeliver-me"); var done = await Task.WhenAny(succeeded.Task, Task.Delay(20_000)); done.Should().Be(succeeded.Task, "the rolled-back message must be redelivered and eventually succeed"); } finally { await consumer.Stop(); await epCons.Stop(); } Volatile.Read(ref attempts).Should().BeGreaterThanOrEqualTo(2, "rollback must trigger at least one redelivery"); } /// /// ConcurrentConsumers=N spins up N XMS sessions (competing consumers): messages are processed in /// parallel (observed in-flight > 1) and each queue message is delivered exactly once (no /// duplication across the N sessions). /// [Fact] public async Task Listener_ConcurrentConsumers_ProcessInParallel_NoDuplication() { var queue = "DEV.QUEUE.5"; await DrainQueueAsync(queue); const int messageCount = 8; var epCons = CreateEndpoint(queue, "receiveMode=listener&concurrentConsumers=4"); var received = new ConcurrentBag(); var inFlight = 0; var maxInFlight = 0; var countdown = new CountdownEvent(messageCount); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async callInfo => { var cur = Interlocked.Increment(ref inFlight); InterlockedMax(ref maxInFlight, cur); received.Add(callInfo.Arg().In.Body?.ToString() ?? ""); await Task.Delay(400); // hold the slot so parallel sessions overlap Interlocked.Decrement(ref inFlight); countdown.Signal(); }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); try { for (var i = 0; i < messageCount; i++) await SendAsync(queue, $"msg-{i}"); countdown.Wait(30_000); } finally { await consumer.Stop(); await epCons.Stop(); } received.Count.Should().Be(messageCount, "every queue message is delivered exactly once (no duplication, no loss)"); received.Distinct().Should().HaveCount(messageCount, "no message is delivered to more than one competing consumer"); Volatile.Read(ref maxInFlight).Should().BeGreaterThanOrEqualTo(2, "N sessions must process messages in parallel (a single session would peak at 1)"); } /// /// Request-reply on the listener path: a request carrying a reply destination gets an InOut /// exchange, and the route's Out body is sent back correlated to the request — so the standard /// RPC producer receives the response. /// [Fact] public async Task Listener_Rpc_RepliesToRequest() { var queue = "DEV.QUEUE.1"; await DrainQueueAsync(queue); // Server: XMS listener echoes the request back through Out. var epServer = CreateEndpoint(queue, "receiveMode=listener"); var seenPattern = ExchangePattern.InOnly; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); seenPattern = ex.Pattern; ex.Out = new Message($"ECHO:{ex.In.Body}"); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epServer.CreateConsumer(processor); await consumer.Start(); try { // Client: standard RPC producer (dynamic reply queue). var epClient = CreateEndpoint(queue, "replyTo=true&timeout=15"); var rpcProducer = (IbmMqProducer)epClient.CreateProducer(); await rpcProducer.Start(); var exchange = new Exchange(new Message("ping")); await rpcProducer.Process(exchange); await rpcProducer.Stop(); await epClient.Stop(); seenPattern.Should().Be(ExchangePattern.InOut, "the listener must see JMSReplyTo and mark the exchange request-reply"); exchange.HasOut.Should().BeTrue("the XMS listener must send an RPC reply"); exchange.Out!.Body?.ToString().Should().Be("ECHO:ping"); } finally { await consumer.Stop(); await epServer.Stop(); } } /// /// The listener path carries the same headers as the poll path: application (user) headers the /// producer stamped, plus redbIbmMq.* MQMD metadata (Destination, MsgId). /// [Fact] public async Task Listener_MapsUserAndMqmdHeaders() { var queue = "DEV.QUEUE.1"; await DrainQueueAsync(queue); var epCons = CreateEndpoint(queue, "receiveMode=listener"); IExchange? captured = null; var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { captured = callInfo.Arg(); tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); try { var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); var outgoing = new Message("hdr-test"); outgoing.Headers["x-order-id"] = "42"; outgoing.Headers["x-tenant"] = "acme"; await producer.Process(new Exchange(outgoing)); await producer.Stop(); await epProd.Stop(); await Task.WhenAny(tcs.Task, Task.Delay(20_000)); } finally { await consumer.Stop(); await epCons.Stop(); } captured.Should().NotBeNull(); captured!.In.Headers.Should().ContainKey("x-order-id"); captured.In.Headers["x-order-id"]!.ToString().Should().Be("42"); captured.In.Headers.Should().ContainKey("x-tenant"); captured.In.Headers.Should().ContainKey(IbmMqHeaders.Destination); captured.In.Headers.Should().ContainKey(IbmMqHeaders.MsgId); } /// /// Event-driven reply reception on the RPC client (`receiveMode=listener` on the producer): the /// reply is delivered via an XMS listener on the reply queue instead of the poll-MQGET loop, so the /// full request→reply round-trip is fast (the poll loop carried the managed client's ~500 ms tick). /// [Fact] public async Task Listener_RpcClient_ReplyReception_IsEventDrivenAndFast() { var queue = "DEV.QUEUE.3"; await DrainQueueAsync(queue); // Server: XMS listener echoes the request back through Out. var epServer = CreateEndpoint(queue, "receiveMode=listener"); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(callInfo => { var ex = callInfo.Arg(); ex.Out = new Message($"ECHO:{ex.In.Body}"); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epServer.CreateConsumer(processor); await consumer.Start(); // Client: RPC producer with EVENT-DRIVEN reply reception. var epClient = CreateEndpoint(queue, "replyTo=true&timeout=15&receiveMode=listener"); var rpc = (IbmMqProducer)epClient.CreateProducer(); await rpc.Start(); var samples = new List(); try { for (var i = 0; i < 5; i++) { var exchange = new Exchange(new Message($"ping-{i}")); var sentAt = Stopwatch.GetTimestamp(); await rpc.Process(exchange); var ms = Stopwatch.GetElapsedTime(sentAt).TotalMilliseconds; exchange.HasOut.Should().BeTrue("the RPC client must receive the reply"); exchange.Out!.Body?.ToString().Should().Be($"ECHO:ping-{i}"); samples.Add(ms); _output.WriteLine($"round-trip {i}: {ms:F1} ms"); } } finally { await rpc.Stop(); await epClient.Stop(); await consumer.Stop(); await epServer.Stop(); } var best = samples.Skip(1).Min(); _output.WriteLine($"best round-trip: {best:F1} ms (poll reply loop floor is ~250–500 ms)"); best.Should().BeLessThan(50, "event-driven reply reception makes the full RPC round-trip <50 ms"); } /// /// The listener path continues the W3C distributed trace: a traceparent carried on the message /// (injected by the producer under an ambient activity) is picked up so the consumer-side activity /// shares the same trace id. /// [Fact] public async Task Listener_PropagatesW3CTraceContext() { var queue = "DEV.QUEUE.2"; await DrainQueueAsync(queue); var consumerActivities = new ConcurrentBag(); using var listener = new ActivityListener { ShouldListenTo = s => s.Name == RouteActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, ActivityStopped = a => { if (a.Kind == ActivityKind.Consumer) consumerActivities.Add(a); }, }; ActivitySource.AddActivityListener(listener); var epCons = CreateEndpoint(queue, "receiveMode=listener"); var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { tcs.TrySetResult(); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)epCons.CreateConsumer(processor); await consumer.Start(); string expectedTraceId; try { // Produce under an ambient activity so the producer injects traceparent into the message. using (var root = RouteActivitySource.Source.StartActivity("test-root", ActivityKind.Producer)) { root.Should().NotBeNull("the ActivityListener must sample so the producer injects trace context"); expectedTraceId = root!.TraceId.ToString(); await SendAsync(queue, "traced"); } await Task.WhenAny(tcs.Task, Task.Delay(20_000)); await Task.Delay(300); // let the consumer activity stop and register } finally { await consumer.Stop(); await epCons.Stop(); } consumerActivities.Should().Contain( a => a.TraceId.ToString() == expectedTraceId, "the consumer activity must continue the trace carried in the message"); } private static void InterlockedMax(ref int target, int value) { int seen; while (value > (seen = Volatile.Read(ref target))) { if (Interlocked.CompareExchange(ref target, value, seen) == seen) return; } } /// Destructively drains any leftover messages so a test starts from an empty queue. private async Task DrainQueueAsync(string queue) { var ep = CreateEndpoint(queue, "waitInterval=200"); var drained = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { Interlocked.Increment(ref drained); return Task.CompletedTask; }); var consumer = (IbmMqConsumer)ep.CreateConsumer(processor); await consumer.Start(); await Task.Delay(800); // let the poll loop sweep whatever is queued await consumer.Stop(); await ep.Stop(); } /// Sends one message to via the standard (poll/WMQ) producer. private async Task SendAsync(string queue, string body) { var epProd = CreateEndpoint(queue); var producer = (IbmMqProducer)epProd.CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message(body))); } finally { await producer.Stop(); await epProd.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqXmsReconnectUnitTests.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.IbmMq/IbmMqXmsReconnectUnitTests.cs ---- using IBM.XMS; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.IbmMq; namespace redb.Route.Tests.IbmMq; /// /// An XMS listener consumer whose connection fails (the exception listener fires, as on a queue manager restart) closes /// it and opens a new one on its connection supervisor's schedule, while the endpoint's health says so. Driven by fake /// XMS connections through the endpoint's XmsConnectionSource, no broker needed; the restart against a real queue /// manager is . The schedule is the default one: first attempt 1 s after the loss. /// public sealed class IbmMqXmsReconnectUnitTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15); private sealed class FakeConnection { public IConnection Connection { get; } = Substitute.For(); public ISession Session { get; } = Substitute.For(); public IMessageConsumer Consumer { get; } = Substitute.For(); public ExceptionListener? Listener { get; private set; } public FakeConnection(bool refuseSession = false) { Session.CreateQueue(Arg.Any()).Returns(Substitute.For()); Session.CreateConsumer(Arg.Any()).Returns(Consumer); Connection.CreateSession(Arg.Any(), Arg.Any()).Returns(_ => refuseSession ? throw new XMSException("MQRC_Q_MGR_NOT_AVAILABLE") : Session); Connection.When(c => c.ExceptionListener = Arg.Any()) .Do(call => Listener = call.Arg()); } public void Break() => Listener!(new XMSException("MQRC_CONNECTION_BROKEN")); } private static (IbmMqEndpoint Endpoint, IbmMqConsumer Consumer, Func Opens) Listener(params FakeConnection[] connections) { var endpoint = (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(EndpointUriParser.Parse( "wmq:DEV.QUEUE.1?host=mq.invalid&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&receiveMode=listener")); var queue = new Queue(connections); var opens = 0; endpoint.XmsConnectionSource = () => { Interlocked.Increment(ref opens); lock (queue) return queue.Dequeue().Connection; }; var consumer = (IbmMqConsumer)endpoint.CreateConsumer(Substitute.For()); return (endpoint, consumer, () => Volatile.Read(ref opens)); } [Fact] public async Task A_broken_connection_is_closed_and_a_new_one_opened_and_health_follows() { var first = new FakeConnection(); var second = new FakeConnection(); var (endpoint, consumer, opens) = Listener(first, second); await consumer.Start(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); first.Break(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning, "the connection is lost, the first attempt is not due yet"); (await Until(() => opens() == 2)).Should().BeTrue("the supervisor opens a new connection once the attempt is due"); (await Until(() => endpoint.Reconnects == 1)).Should().BeTrue(); second.Connection.Received(1).Start(); first.Consumer.Received(1).Close(); first.Session.Received(1).Close(); first.Connection.Received(1).Close(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the connection is back; a loss is not an error"); first.Break(); await Task.Delay(1500); opens().Should().Be(2, "a late report from the replaced connection is ignored"); await consumer.Stop(); second.Connection.Received(1).Close(); } [Fact] public async Task A_refused_attempt_turns_the_endpoint_Critical_and_the_next_attempt_restores_it() { var first = new FakeConnection(); var refused = new FakeConnection(refuseSession: true); var third = new FakeConnection(); var (endpoint, consumer, opens) = Listener(first, refused, third); await consumer.Start(); first.Break(); (await Until(() => opens() == 2)).Should().BeTrue(); (await Until(() => endpoint.HealthStatus == EndpointHealthStatus.Critical)).Should() .BeTrue("a failed attempt makes the loss Critical"); refused.Connection.Received(1).Close(); (await Until(() => endpoint.Reconnects == 1)).Should().BeTrue("the next attempt, 2 s later, connects"); opens().Should().Be(3); endpoint.HealthStatus.Should().NotBe(EndpointHealthStatus.Critical); await consumer.Stop(); third.Connection.Received(1).Close(); } [Fact] public async Task A_stop_during_the_reconnect_ends_it_and_opens_nothing_more() { var first = new FakeConnection(); var (endpoint, consumer, opens) = Listener(first); await consumer.Start(); first.Break(); await consumer.Stop(); await Task.Delay(1500); opens().Should().Be(1, "the reconnect ended with the stop before its first attempt"); endpoint.HealthReason.Should().NotContain("listener", "the stopped consumer's supervisor is removed"); } [Fact] public async Task A_stop_while_the_lost_connection_waits_for_its_first_attempt_closes_it_and_opens_nothing() { var first = new FakeConnection(); var (_, consumer, opens) = Listener(first); await consumer.Start(); first.Break(); await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(1500); opens().Should().Be(1); first.Connection.Received(1).Close(); } [Fact] public async Task A_stop_after_a_refused_attempt_ends_the_reconnect_before_the_next_one() { var first = new FakeConnection(); var refused = new FakeConnection(refuseSession: true); var (endpoint, consumer, opens) = Listener(first, refused); await consumer.Start(); first.Break(); (await Until(() => endpoint.HealthStatus == EndpointHealthStatus.Critical)).Should().BeTrue(); await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(5)); await Task.Delay(2500); // the next attempt would be due 2 s after the refused one opens().Should().Be(2, "no attempt after the stop"); refused.Connection.Received(1).Close(); endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the stopped consumer's supervisor is removed"); } [Fact] public async Task A_stop_during_an_attempt_closes_the_connection_the_attempt_opens_late() { var first = new FakeConnection(); var late = new FakeConnection(); using var gate = new ManualResetEventSlim(); var endpoint = (IbmMqEndpoint)new IbmMqComponent().CreateEndpoint(EndpointUriParser.Parse( "wmq:DEV.QUEUE.1?host=mq.invalid&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&receiveMode=listener")); var opens = 0; endpoint.XmsConnectionSource = () => { if (Interlocked.Increment(ref opens) == 1) return first.Connection; gate.Wait(); // the second connect hangs, as one made while the queue manager starts can return late.Connection; }; var consumer = (IbmMqConsumer)endpoint.CreateConsumer(Substitute.For()); await consumer.Start(); first.Break(); (await Until(() => Volatile.Read(ref opens) == 2)).Should().BeTrue("the attempt is in its connect"); await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(5)); gate.Set(); (await Until(() => late.Connection.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Close"))) .Should().BeTrue("the connection the attempt opened after the stop is closed"); Volatile.Read(ref opens).Should().Be(2); } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (DateTime.UtcNow < deadline) { if (done()) return true; await Task.Delay(50); } return done(); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/PreserveMessageQosOptionTests.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.IbmMq/PreserveMessageQosOptionTests.cs ---- using redb.Route.Core; using redb.Route.IbmMq; using IbmMqDsl = redb.Route.IbmMq.Wmq; namespace redb.Route.Tests.IbmMq; /// /// preserveMessageQos (Apache Camel's name): off by default, set from the URI and the builder; an ordinary put /// carries the reply-to headers only with it, the correlation id always. /// public sealed class PreserveMessageQosOptionTests { [Fact] public void Off_by_default() => new IbmMqEndpointOptions().PreserveMessageQos.Should().BeFalse(); [Fact] public void Set_from_the_uri() { var options = new IbmMqEndpointOptions(); options.BindFromUri(EndpointUriParser.Parse("wmq:Q?preserveMessageQos=true").RawParameters); options.PreserveMessageQos.Should().BeTrue(); } [Fact] public void Set_by_the_builder() { IbmMqDsl.Queue("Q").PreserveMessageQos().Build().Should().Contain("preserveMessageQos=true"); IbmMqDsl.Queue("Q").Build().Should().NotContain("preserveMessageQos"); } [Theory] [InlineData(false)] [InlineData(true)] public void An_ordinary_put_carries_the_reply_to_only_with_the_option(bool preserve) { var exchange = new Exchange(new Message("body")); exchange.In.Headers[IbmMqHeaders.ReplyToQueue] = "SENDER.REPLIES"; exchange.In.Headers[IbmMqHeaders.ReplyToQueueManager] = "QM.SENDER"; exchange.In.Headers[IbmMqHeaders.CorrelId] = "0102030405060708090A0B0C0D0E0F101112131415161718"; var message = IbmMqMessageHelper.BuildOutgoingMessage( exchange, new IbmMqEndpointOptions { PreserveMessageQos = preserve }, new IbmMqHeaderFilterStrategy()); message.ReplyToQueueName.Trim().Should().Be(preserve ? "SENDER.REPLIES" : ""); message.ReplyToQueueManagerName.Trim().Should().Be(preserve ? "QM.SENDER" : ""); message.CorrelationId.Should().Equal(Enumerable.Range(1, 24).Select(i => (byte)i)); } } Path: redb-route/tests/redb.Route.Tests.IbmMq/redb.Route.Tests.IbmMq.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.IbmMq/redb.Route.Tests.IbmMq.csproj ----