Path: redb-route/tests/redb.Route.Tests/Processors/SplitterProcessorTests.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/Processors/SplitterProcessorTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.Processors; /// Tests for . public class SplitterProcessorTests { /// Splits array body into individual exchanges. [Fact] public async Task Process_SplitsArray_IntoIndividualExchanges() { var parts = new List(); var target = new DelegateProcessor(ex => parts.Add(ex.In.Body)); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var data = new object[] { "a", "b", "c" }; await splitter.Process(new Exchange(new Message(data))); parts.Should().Equal("a", "b", "c"); } /// Split metadata are exchange properties of each part, as Camel's, never message headers. [Fact] public async Task Process_SetsSplitMetadataProperties() { var indices = new List(); var sizes = new List(); var completes = new List(); var correlationIds = new List(); var metadataHeaders = new List(); var target = new DelegateProcessor(ex => { indices.Add(ex.GetProperty(ExchangePropertyKeys.SplitIndex)); sizes.Add(ex.GetProperty(ExchangePropertyKeys.SplitSize)); completes.Add(ex.GetProperty(ExchangePropertyKeys.SplitComplete)); correlationIds.Add(ex.GetProperty(ExchangePropertyKeys.CorrelationId)); metadataHeaders.AddRange(ex.In.Headers.Keys.Where(k => k.StartsWith("Camel", StringComparison.Ordinal))); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var parent = new Exchange(new Message(new object[] { 1, 2, 3 })); await splitter.Process(parent); indices.Should().Equal(0, 1, 2); sizes.Should().OnlyContain(s => s == 3); completes.Should().Equal(false, false, true); correlationIds.Should().OnlyContain(id => id == parent.ExchangeId); metadataHeaders.Should().BeEmpty(); } /// /// An element becomes the part's message, as Camel's Message element: its own body, headers /// and content type, none of the parent's headers; the part gets a copy, so the parent's collection is untouched. /// [Fact] public async Task Process_MessageElement_BecomesThePartMessage_AsACopy() { var first = new Message("one") { ContentType = "text/plain" }; first.Headers["key"] = "k1"; var second = new Message(new byte[] { 2 }); second.Headers["key"] = "k2"; var seen = new List<(object? Body, string? Key, string? ContentType, bool HasParentHeader)>(); var target = new DelegateProcessor(ex => { seen.Add((ex.In.Body, ex.In.GetHeader("key"), ex.In.ContentType, ex.In.Headers.ContainsKey("parent"))); ex.In.Body = "changed by the part"; ex.In.Headers["key"] = "changed"; }); var splitter = new SplitterProcessor(ex => (IEnumerable)ex.In.Body!, target); var batch = new List { first, second }; var parentMessage = new Message(batch); parentMessage.Headers["parent"] = "p"; await splitter.Process(new Exchange(parentMessage)); seen.Should().HaveCount(2); seen[0].Should().Be(((object?)"one", "k1", "text/plain", false)); seen[1].Body.Should().BeEquivalentTo(new byte[] { 2 }); seen[1].Key.Should().Be("k2"); seen[1].HasParentHeader.Should().BeFalse(); first.Body.Should().Be("one"); first.Headers["key"].Should().Be("k1"); second.Headers["key"].Should().Be("k2"); } /// Original headers are copied to split exchanges. [Fact] public async Task Process_CopiesHeaders() { string? capturedHeader = null; var target = new DelegateProcessor(ex => { capturedHeader = ex.In.GetHeader("source"); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var msg = new Message(new object[] { "x" }); msg.Headers["source"] = "test-source"; await splitter.Process(new Exchange(msg)); capturedHeader.Should().Be("test-source"); } /// Properties are copied to split exchanges. [Fact] public async Task Process_CopiesProperties() { object? capturedProp = null; var target = new DelegateProcessor(ex => { capturedProp = ex.Properties["routeId"]; }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); var exchange = new Exchange(new Message(new object[] { "x" })); exchange.Properties["routeId"] = "route-1"; await splitter.Process(exchange); capturedProp.Should().Be("route-1"); } /// Exchange.Stop() breaks splitting early. [Fact] public async Task Process_ExchangeStopped_BreaksSplit() { var count = 0; var exchange = new Exchange(new Message(new object[] { 1, 2, 3, 4, 5 })); var target = new DelegateProcessor(_ => { count++; if (count >= 2) exchange.Stop(); }); var splitter = new SplitterProcessor( ex => ((IEnumerable)ex.In.Body!), target); await splitter.Process(exchange); count.Should().Be(2); } /// Empty split produces no exchanges. [Fact] public async Task Process_EmptySplit_NoProcessing() { var count = 0; var target = new DelegateProcessor(_ => count++); var splitter = new SplitterProcessor(_ => Enumerable.Empty(), target); await splitter.Process(new Exchange()); count.Should().Be(0); } // ── Parallel Error Handling ── /// Single parallel split failure: exchange.Exception is that single exception. [Fact] public async Task ProcessParallel_SingleFailure_SetsExchangeException() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((string)ex.In.Body! == "bad") throw new InvalidOperationException("split-fail"); return Task.CompletedTask; }), parallelProcessing: true, stopOnException: false); var exchange = new Exchange(new Message(new object[] { "good", "bad" })); await splitter.Process(exchange); exchange.Exception.Should().BeOfType(); } /// Multiple parallel split failures produce AggregateException. [Fact] public async Task ProcessParallel_MultipleFailures_SetsAggregateException() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => throw new InvalidOperationException($"fail-{ex.In.Body}")), parallelProcessing: true, stopOnException: false); var exchange = new Exchange(new Message(new object[] { "a", "b", "c" })); await splitter.Process(exchange); exchange.Exception.Should().BeOfType(); var agg = (AggregateException)exchange.Exception!; agg.InnerExceptions.Should().HaveCount(3); } /// stopOnException=true rethrows in parallel mode. [Fact] public async Task ProcessParallel_StopOnException_Rethrows() { var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((_, _) => throw new InvalidOperationException("stop")), parallelProcessing: true, stopOnException: true); var exchange = new Exchange(new Message(new object[] { "a" })); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync().WithMessage("stop"); } /// Sequential stopOnException stops processing remaining parts. [Fact] public async Task ProcessSequential_StopOnException_SkipsRemaining() { var processed = new List(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { var body = (string)ex.In.Body!; processed.Add(body); if (body == "b") throw new InvalidOperationException("seq-stop"); return Task.CompletedTask; }), parallelProcessing: false, stopOnException: true); var exchange = new Exchange(new Message(new object[] { "a", "b", "c" })); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync().WithMessage("seq-stop"); processed.Should().Equal("a", "b"); // "c" was skipped } // ── Aggregation Strategy: Camel-compatible null-old contract ── /// T6.1 Sequential aggregation: first part goes through strategy with oldExchange=null. [Fact] public async Task Sequential_AggregationStrategy_FirstPartGoesThroughStrategy_WithNullOld() { var calls = new List<(IExchange? Old, object? NewBody)>(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: false, aggregationStrategy: (old, cur) => { calls.Add((old, cur.In.Body)); if (old == null) return cur; return old; }); await splitter.Process(new Exchange(new Message(new object[] { 10, 20, 30 }))); calls.Should().HaveCount(3); calls[0].Old.Should().BeNull(); calls[0].NewBody.Should().Be(10); calls[1].Old.Should().NotBeNull(); calls[2].Old.Should().NotBeNull(); } /// T6.2 Parallel aggregation: first part goes through strategy with oldExchange=null. [Fact] public async Task Parallel_AggregationStrategy_FirstPartGoesThroughStrategy_WithNullOld() { var calls = new List<(IExchange? Old, object? NewBody)>(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: true, aggregationStrategy: (old, cur) => { calls.Add((old, cur.In.Body)); if (old == null) return cur; return old; }); await splitter.Process(new Exchange(new Message(new object[] { 10, 20, 30 }))); // Deterministic post-pass over split exchanges in input order. calls.Should().HaveCount(3); calls[0].Old.Should().BeNull(); calls[0].NewBody.Should().Be(10); calls[1].NewBody.Should().Be(20); calls[2].NewBody.Should().Be(30); } /// T6.3 Parallel + stopOnException: failure skips final aggregation (no partial result on exchange). [Fact] public async Task ProcessParallel_StopOnException_SkipsFinalAggregation() { var aggCalls = 0; var originalBody = new object[] { 1, 2, 3 }; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 2) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: true, aggregationStrategy: (old, cur) => { Interlocked.Increment(ref aggCalls); return cur; }, stopOnException: true); var exchange = new Exchange(new Message(originalBody)); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync(); aggCalls.Should().Be(0); // ApplyAggregation skipped entirely exchange.In.Body.Should().BeSameAs(originalBody); } /// T6.4 Sequential + stopOnException: failure leaves exchange body untouched (no partial aggregation visible). [Fact] public async Task ProcessSequential_StopOnException_DoesNotPublishPartialAggregation() { var originalBody = new object[] { 1, 2, 3 }; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 2) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: false, aggregationStrategy: (old, cur) => { if (old == null) return cur; return old; }, stopOnException: true); var exchange = new Exchange(new Message(originalBody)); var act = async () => await splitter.Process(exchange); await act.Should().ThrowAsync(); exchange.In.Body.Should().BeSameAs(originalBody); // ApplyAggregation skipped } /// T6.5 parallelAggregate=true: aggregation runs in-task under lock; counter sees all parts. [Fact] public async Task ProcessParallel_WithParallelAggregate_AggregatesAllPartsThreadSafely() { var aggCalls = 0; var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor(_ => { }), parallelProcessing: true, maxDegreeOfParallelism: 4, aggregationStrategy: (old, cur) => { aggCalls++; // safe: under processor's lock when parallelAggregate=true return old ?? cur; }, stopOnException: false, parallelAggregate: true); var parts = Enumerable.Range(1, 20).Cast().ToArray(); await splitter.Process(new Exchange(new Message(parts))); aggCalls.Should().Be(20); } /// T6.6 aggregateOnException=true: failed split parts still feed into the strategy. [Fact] public async Task ProcessSequential_AggregateOnException_FeedsFailedPartsToStrategy() { var seenBodies = new List(); var splitter = new SplitterProcessor( ex => (IEnumerable)ex.In.Body!, new DelegateProcessor((ex, _) => { if ((int)ex.In.Body! == 1) throw new InvalidOperationException("boom"); return Task.CompletedTask; }), parallelProcessing: false, aggregationStrategy: (old, cur) => { seenBodies.Add(cur.In.Body); return old ?? cur; }, stopOnException: false, aggregateOnException: true); await splitter.Process(new Exchange(new Message(new object[] { 0, 1, 2 }))); seenBodies.Should().Equal(0, 1, 2); // failed part (1) included } }