Repository navigation
Expand file tree
/
Copy pathDurableTaskShowcaseTest.cs
More file actions
142 lines (120 loc) · 9.15 KB
/
Copy pathDurableTaskShowcaseTest.cs
File metadata and controls
142 lines (120 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
using Moq;
using NUnit.Framework;
using UnitTestEx.Azure.Functions;
using UnitTestEx.Azure.Functions.Durable.TestHost;
using UnitTestEx.DurableFunction;
using UnitTestEx.Expectations;
namespace UnitTestEx.Azure.Functions.Durable.Test;
/// <summary>Shows how to test a real batch orchestration with controlled activity responses.</summary>
/// <remarks>
/// Executes the real ProcessBatch, NormalizeReference and TotalItems bodies with mocked ProcessItem responses.
/// The first two tests replace FinalizeBatch; the third discovers it and runs its journal activities.
/// See the sample bodies in BatchOrchestration, ActivityTransforms and WorkflowActivities for the full workflow.
/// </remarks>
[TestFixture]
public sealed class DurableTaskShowcaseTest
{
/// <summary>Verifies that fan-in preserves input order when activity handlers finish in reverse order.</summary>
[Test]
public async Task BatchFanOutFanIn()
{
// Match by business input, not arrival order: the host may dispatch concurrent activities in any order.
// A and B wait for the test; C finishes after a short real-time delay, not a virtual-clock advance.
using var processItems = ActivityMock.ByMatch(
[
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "A", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "B", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "C", item => new ItemResult(item.Id, item.Amount * 2m)).After(TimeSpan.FromMilliseconds(100))
]);
// Use the application's normal startup and services without starting the Functions worker.
using var functions = FunctionTester.Create<WorkflowActivities>();
var request = new BatchRequest(" batch-7 ", [new("A", 10m), new("B", 20m), new("C", 30m)]);
// Run the real orchestration, normalization and total calculation through the in-memory SDK host.
// Replace item processing and finalization; this test does not exercise those production bodies.
await using var test = await functions.DurableTask()
.Orchestrator<BatchRequest, BatchResult>(nameof(BatchOrchestration.ProcessBatch), (context, _) => BatchOrchestration.ProcessBatch(context))
.Activity<string, string>(nameof(ActivityTransforms.NormalizeReference), (_, reference) => ActivityTransforms.NormalizeReference(reference), configure: options => options.Times(Times.Once()))
.Activity<WorkItem, ItemResult>(nameof(WorkflowActivities.ProcessItem), processItems.InvokeAsync, configure: options => options.Times(Times.Exactly(3)))
.Activity<ItemResult[], decimal>(nameof(ActivityTransforms.TotalItems), (_, results) => ActivityTransforms.TotalItems(results), configure: options => options.Times(Times.Once()))
.SubOrchestrator<BatchResult, BatchResult>(nameof(BatchOrchestration.FinalizeBatch), (_, input) => Task.FromResult(input))
.StartAsync(request);
test.ExpectSuccess().ExpectLogContains("Finalizing batch BATCH-7.");
// All three plans must be assigned before releasing the held responses; they need not have completed.
// Indexes identify declaration positions, so [2] always means C even if it was dispatched first.
await processItems.WaitForAllInvocationsAsync();
await processItems[2].WaitForCompletionAsync(TimeSpan.FromSeconds(5));
await processItems[1].ReleaseAsync(TimeSpan.FromSeconds(5));
await processItems[0].ReleaseAsync(TimeSpan.FromSeconds(5));
// Task.WhenAll must retain A/B/C input order despite the handlers finishing C/B/A.
var expected = new BatchResult("BATCH-7", 120m, [new("A", 20m), new("B", 40m), new("C", 60m)]);
await test.WaitForCompletionAsync(TimeSpan.FromSeconds(10), result => result.AssertCompleted().AssertOutput(expected));
// This records handler completion, not the order in which the engine processed their results.
Assert.That(processItems.CompletionOrder.Select(item => item.Id), Is.EqualTo(new[] { "C", "B", "A" }));
// Verify plan consumption separately from registered activity counts; retries count as extra invocations.
processItems.Verify();
test.Verify();
}
/// <summary>Discovers normalization and aggregation while explicitly replacing item processing and finalization.</summary>
[Test]
public async Task BatchFanOutFanInWithSelfDiscovery()
{
using var processItems = ActivityMock.ByMatch(
[
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "A", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "B", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "C", item => new ItemResult(item.Id, item.Amount * 2m)).After(TimeSpan.FromMilliseconds(100))
]);
using var functions = FunctionTester.Create<WorkflowActivities>();
var request = new BatchRequest(" batch-7 ", [new("A", 10m), new("B", 20m), new("C", 30m)]);
await using var test = await functions.DurableTask()
.WithSelfDiscovery()
.Orchestrator<BatchRequest, BatchResult>(nameof(BatchOrchestration.ProcessBatch), (context, _) => BatchOrchestration.ProcessBatch(context))
.Activity<WorkItem, ItemResult>(nameof(WorkflowActivities.ProcessItem), processItems.InvokeAsync, configure: options => options.Times(Times.Exactly(3)))
.SubOrchestrator<BatchResult, BatchResult>(nameof(BatchOrchestration.FinalizeBatch), (_, input) => Task.FromResult(input))
.StartAsync(request);
test.ExpectSuccess().ExpectLogContains("Finalizing batch BATCH-7.");
await processItems.WaitForAllInvocationsAsync();
await processItems[2].WaitForCompletionAsync(TimeSpan.FromSeconds(5));
await processItems[1].ReleaseAsync(TimeSpan.FromSeconds(5));
await processItems[0].ReleaseAsync(TimeSpan.FromSeconds(5));
var expected = new BatchResult("BATCH-7", 120m, [new("A", 20m), new("B", 40m), new("C", 60m)]);
await test.WaitForCompletionAsync(TimeSpan.FromSeconds(10), result => result.AssertCompleted().AssertOutput(expected));
Assert.That(processItems.CompletionOrder.Select(item => item.Id), Is.EqualTo(new[] { "C", "B", "A" }));
processItems.Verify();
test.Verify();
}
/// <summary>Discovers the real child orchestration and its journal activities while replacing item processing.</summary>
[Test]
public async Task BatchFanOutFanInWithDiscoveredSubOrchestrator()
{
using var processItems = ActivityMock.ByMatch(
[
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "A", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "B", item => new ItemResult(item.Id, item.Amount * 2m)).Pending(),
ActivityResponse.Match<WorkItem, ItemResult>(item => item.Id == "C", item => new ItemResult(item.Id, item.Amount * 2m)).After(TimeSpan.FromMilliseconds(100))
]);
var journal = new Mock<IWorkflowJournal>(MockBehavior.Strict);
journal.Setup(x => x.Record("BATCH-7"));
journal.Setup(x => x.PublishAsync(It.IsAny<BatchResult>())).Returns(Task.CompletedTask);
using var functions = FunctionTester.Create<WorkflowActivities>();
functions.ReplaceSingleton<IWorkflowJournal>(journal.Object);
var request = new BatchRequest(" batch-7 ", [new("A", 10m), new("B", 20m), new("C", 30m)]);
await using var test = await functions.DurableTask()
.WithSelfDiscovery()
.Orchestrator<BatchRequest, BatchResult>(nameof(BatchOrchestration.ProcessBatch), (context, _) => BatchOrchestration.ProcessBatch(context))
.Activity<WorkItem, ItemResult>(nameof(WorkflowActivities.ProcessItem), processItems.InvokeAsync, configure: options => options.Times(Times.Exactly(3)))
.StartAsync(request);
test.ExpectSuccess().ExpectLogContains("Finalizing batch BATCH-7.");
await processItems.WaitForAllInvocationsAsync();
await processItems[2].WaitForCompletionAsync(TimeSpan.FromSeconds(5));
await processItems[1].ReleaseAsync(TimeSpan.FromSeconds(5));
await processItems[0].ReleaseAsync(TimeSpan.FromSeconds(5));
var expected = new BatchResult("BATCH-7", 120m, [new("A", 20m), new("B", 40m), new("C", 60m)]);
await test.WaitForCompletionAsync(TimeSpan.FromSeconds(10), result => result.AssertCompleted().AssertOutput(expected));
Assert.That(processItems.CompletionOrder.Select(item => item.Id), Is.EqualTo(new[] { "C", "B", "A" }));
journal.Verify(x => x.Record("BATCH-7"), Times.Once());
journal.Verify(x => x.PublishAsync(It.Is<BatchResult>(result => result.Reference == "BATCH-7" && result.Total == 120m && result.Items.Select(item => item.Id).SequenceEqual(new[] { "A", "B", "C" }))), Times.Once());
processItems.Verify();
test.Verify();
}
}