Repository navigation
Expand file tree
/
Copy pathMachineToolJobSourceTests.cs
More file actions
358 lines (344 loc) · 21.4 KB
/
Copy pathMachineToolJobSourceTests.cs
File metadata and controls
358 lines (344 loc) · 21.4 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Opc.Ua.ISA95.Server.Providers;
using Opc.Ua.MachineTool.Server;
using V2 = Opc.Ua.ISA95.JobControl.V2;
namespace Opc.Ua.MachineTool.Tests
{
/// <summary>
/// Exercises the public shared reference source without bypassing its existing ISA-95 provider facets.
/// </summary>
[TestFixture]
[Category("MachineTool")]
public sealed class MachineToolJobSourceTests
{
/// <summary>
/// Permission to start is not execution, and engine audit comments and work-master identities survive updates.
/// </summary>
[Test]
public async Task StartAuthorizationDoesNotExecuteOrReplaceAcquisitionMetadataAsync()
{
var monitoring = new MachineToolSnapshot
{
Operation = new MachineToolOperation { Sample = Acquired, Mode = MachineOperationMode.Automatic },
Channels = [new MachineToolChannel { Name = "NC", FeedOverride = 73, Sample = Acquired }]
};
await using var source = new MachineToolJobSource(Options(), monitoring);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await using IAsyncEnumerator<Isa95JobStatusNotificationV2> events =
source.SubscribeAsync(timeout.Token).GetAsyncEnumerator();
Task<bool> first = events.MoveNextAsync().AsTask();
V2.ISA95JobOrderDataType order = Order();
order.Priority = 3;
Success(await source.ReceiveJobOrderAsync(
Isa95JobOrderOperationV2.Store, order, [new LocalizedText("en", "approved plan")])
.ConfigureAwait(false));
Assert.That(await first.ConfigureAwait(false), Is.True);
Assert.That(events.Current.Comment[0].Text, Is.EqualTo("approved plan"));
order.Priority = 99;
order.WorkMasterID[0].ID = "tampered";
MachineToolJobSourceCapture stored = await source.CaptureAsync().ConfigureAwait(false);
Assert.That(stored.JobOrders[0].JobOrder.Priority, Is.EqualTo(3));
Assert.That(stored.JobOrders[0].JobOrder.WorkMasterID[0].ID, Is.EqualTo("WM-1"));
Assert.That(stored.Snapshot.ActiveProgram.Name, Is.Empty);
Assert.That(stored.Snapshot.Production.Jobs[0].Phase, Is.EqualTo(MachineToolProductionPhase.Initializing));
Assert.That(StatusCode.IsGood(stored.Snapshot.Production.Jobs[0].Sample.StatusCode), Is.False);
Assert.That(stored.Snapshot.Operation, Is.SameAs(monitoring.Operation));
Assert.That(stored.Snapshot.Channels, Is.EqualTo(monitoring.Channels));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Start, Order(),
[new LocalizedText("de", "freigegeben")]).ConfigureAwait(false));
Assert.That(await events.MoveNextAsync().ConfigureAwait(false), Is.True);
Assert.That(events.Current.StateNumber, Is.EqualTo(2));
Assert.That(events.Current.Comment[0].Text, Is.EqualTo("freigegeben"));
V2.ISA95JobOrderDataType updated = Order();
updated.Priority = 7;
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Update, updated).ConfigureAwait(false));
Assert.That(await events.MoveNextAsync().ConfigureAwait(false), Is.True);
Assert.That(events.Current.Comment[0].Text, Is.EqualTo("freigegeben"));
Assert.That(events.Current.JobOrder.Priority, Is.EqualTo(7));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.RevokeStart, Order())
.ConfigureAwait(false));
Assert.That(await events.MoveNextAsync().ConfigureAwait(false), Is.True);
Assert.That(events.Current.StateNumber, Is.EqualTo(1));
MachineToolSnapshot snapshot = await source.ReadAsync().ConfigureAwait(false);
Assert.That(snapshot.Production.Jobs[0].TransitionSequence, Is.Zero);
Assert.That(snapshot.ActiveProgram.Name, Is.Empty);
Assert.That(snapshot.Operation.Sample, Is.EqualTo(Acquired));
Assert.That((await source.GetJobOrdersV1Async().ConfigureAwait(false))[0].ID, Is.EqualTo("Job-1"));
}
/// <summary>
/// Intermediate and final runs preserve contiguous state history and explicit current/cumulative part totals.
/// </summary>
[Test]
public async Task CompleteRunsPreserveExactHistoryAndCurrentVersusCumulativeCountersAsync()
{
await using var source = new MachineToolJobSource(Options(Descriptor() with
{
RunsPlanned = 2,
PartSetKey = "Parts",
PartSetName = "Explicit batch",
PartsPlannedPerRun = 2
}));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.StoreAndStart, Order())
.ConfigureAwait(false));
Assert.That((await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.BeginExecution)
.ConfigureAwait(false)).ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.InvalidStatus));
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.MarkReady)
.ConfigureAwait(false));
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.BeginExecution)
.ConfigureAwait(false));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Pause, Order()).ConfigureAwait(false));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Resume, Order()).ConfigureAwait(false));
await source.RecordPartsAsync("Job-1", new MachineToolJobSourcePartCounts(2, 1, Acquired))
.ConfigureAwait(false);
await source.CompleteRunAsync("Job-1").ConfigureAwait(false);
MachineToolProductionJob repeated = (await source.ReadAsync().ConfigureAwait(false)).Production.Jobs[0];
Assert.Multiple(() =>
{
Assert.That(repeated.Phase, Is.EqualTo(MachineToolProductionPhase.Running));
Assert.That(repeated.TransitionSequence, Is.EqualTo(4));
Assert.That(repeated.RunsCompleted, Is.EqualTo(1));
Assert.That(repeated.PartsCompleted, Is.EqualTo(2));
Assert.That(repeated.PartsGood, Is.EqualTo(1));
Assert.That(repeated.PartsCompletedBeforeCurrentRun, Is.EqualTo(2));
Assert.That(repeated.PartsGoodBeforeCurrentRun, Is.EqualTo(1));
Assert.That(repeated.PartSets[0].PartsCompletedPerRun, Is.Zero);
Assert.That(repeated.PartSets[0].Sample, Is.EqualTo(MachineToolSampleInfo.Unavailable));
});
await source.RecordPartsAsync("Job-1", new MachineToolJobSourcePartCounts(2, 2, Acquired))
.ConfigureAwait(false);
await source.CompleteRunAsync("Job-1").ConfigureAwait(false);
MachineToolJobSourceCapture complete = await source.CaptureAsync().ConfigureAwait(false);
MachineToolProductionJob final = complete.Snapshot.Production.Jobs[0];
Assert.Multiple(() =>
{
Assert.That(final.Phase, Is.EqualTo(MachineToolProductionPhase.Ended));
Assert.That(final.TransitionSequence, Is.EqualTo(5));
Assert.That(final.RunsCompleted, Is.EqualTo(2));
Assert.That(final.PartsCompleted, Is.EqualTo(4));
Assert.That(final.PartsGood, Is.EqualTo(3));
Assert.That(final.PartSets[0].PartsCompletedPerRun, Is.EqualTo(2));
Assert.That(final.PartSets[0].Sample, Is.EqualTo(Acquired));
Assert.That(complete.JobOrders[0].State[0].StateNumber, Is.EqualTo(5));
Assert.That(complete.JobOrders[0].State[1].StateNumber, Is.EqualTo(1));
Assert.That(complete.Snapshot.ActiveProgram, Is.EqualTo(final.Programs[0]));
Assert.That(complete.Snapshot.Operation.Sample, Is.EqualTo(MachineToolSampleInfo.Unavailable));
Assert.That(complete.Snapshot.Operation.PartsProducedInLifetime, Is.Null);
});
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.Close).ConfigureAwait(false));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Clear, Order()).ConfigureAwait(false));
var history = new List<MachineToolSnapshot>();
await source.DrainAsync(async ct =>
{
MachineToolSnapshot snapshot = await source.ReadAsync(ct).ConfigureAwait(false);
MachineToolJobSourceCapture capture = await source.CaptureAsync(ct).ConfigureAwait(false);
Assert.That(capture.Snapshot, Is.SameAs(snapshot));
history.Add(snapshot);
}).ConfigureAwait(false);
Assert.That(history, Has.Count.EqualTo(12));
for (int i = 0; i < history.Count; i++)
{
Assert.That(history[i].Revision, Is.EqualTo((ulong)i));
}
Assert.That(history[6].Production.Jobs[0].PartSets[0].Sample, Is.EqualTo(Acquired));
Assert.That(history[9].Production.Jobs[0].TransitionSequence, Is.EqualTo(5));
Assert.That(history[10].Production.Jobs[0], Is.EqualTo(history[9].Production.Jobs[0]));
Assert.That(history[11].Production.Jobs, Is.Empty);
}
/// <summary>
/// Stop and interrupted completion cannot fabricate a normal completed run or an unobserved resume.
/// </summary>
[TestCase(false, false)]
[TestCase(true, false)]
[TestCase(true, true)]
public async Task EarlyStopOrInterruptedCompletionIsLegacyAbortedAsync(bool interrupted, bool complete)
{
await using var source = new MachineToolJobSource(Options());
await StartExecutingAsync(source).ConfigureAwait(false);
if (interrupted)
{
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.Hold).ConfigureAwait(false));
}
if (complete)
{
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.Complete)
.ConfigureAwait(false));
}
else
{
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Stop, Order())
.ConfigureAwait(false));
}
MachineToolJobSourceCapture capture = await source.CaptureAsync().ConfigureAwait(false);
Assert.That(capture.JobOrders[0].State[0].StateNumber, Is.EqualTo(5));
Assert.That(capture.Snapshot.Production.Jobs[0].Phase, Is.EqualTo(MachineToolProductionPhase.Aborted));
Assert.That(capture.Snapshot.Production.Jobs[0].RunsCompleted, Is.Zero);
Assert.That(capture.Snapshot.Production.Jobs[0].TransitionSequence, Is.EqualTo(interrupted ? 3 : 2));
}
/// <summary>
/// Cancellation retains the final canonical legacy state before removing a not-started order.
/// </summary>
[TestCase(false)]
[TestCase(true)]
public async Task CancelRetainsCanonicalFinalObservationBeforeRemovingTheJobAsync(bool allowed)
{
await using var source = new MachineToolJobSource(Options());
Success(await source.ReceiveJobOrderAsync(allowed
? Isa95JobOrderOperationV2.StoreAndStart : Isa95JobOrderOperationV2.Store, Order())
.ConfigureAwait(false));
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.Cancel, Order()).ConfigureAwait(false));
Assert.That(await source.GetJobOrdersV2Async().ConfigureAwait(false), Is.Empty);
var captures = new List<MachineToolJobSourceCapture>();
await source.DrainAsync(async ct => captures.Add(await source.CaptureAsync(ct).ConfigureAwait(false)))
.ConfigureAwait(false);
Assert.That(captures, Has.Count.EqualTo(4));
Assert.That(captures[2].JobOrders, Is.Empty);
Assert.That(captures[2].Snapshot.Production.Jobs[0].Phase, Is.EqualTo(MachineToolProductionPhase.Aborted));
Assert.That(captures[2].Snapshot.Production.Jobs[0].TransitionSequence, Is.EqualTo(1));
Assert.That(captures[3].Snapshot.Production.Jobs, Is.Empty);
}
/// <summary>
/// Responses are explicit historical results, not synthetic acknowledgments or execution commands.
/// </summary>
[Test]
public async Task ExplicitResponsesUseEngineQueriesAndCannotRewriteAcceptedStateAsync()
{
await using var source = new MachineToolJobSource(Options());
await StartExecutingAsync(source).ConfigureAwait(false);
MachineToolJobSourceCapture running = await source.CaptureAsync().ConfigureAwait(false);
Assert.That(running.JobResponses, Is.Empty);
var response = new V2.ISA95JobResponseDataType
{
EncodingMask = (uint)(V2.ISA95JobResponseDataTypeFields.Description |
V2.ISA95JobResponseDataTypeFields.JobResponseData),
JobResponseID = "Response-1",
JobOrderID = "Job-1",
JobState = running.JobOrders[0].State,
Description = new LocalizedText("Explicit external result"),
JobResponseData = [new V2.ISA95ParameterDataType { ID = "observed", Value = Variant.From(17) }]
};
Isa95JobResponseReceiptV2 received = await source.ReceiveJobResponseAsync(response).ConfigureAwait(false);
Assert.That(received.ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.Success));
response.JobResponseData[0].Value = Variant.From(999);
Isa95JobResponseByIdResultV2 query = await source.RequestJobResponseByJobOrderIdAsync("Job-1")
.ConfigureAwait(false);
Assert.That(query.ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.Success));
Assert.That(query.Response!.JobResponseData[0].Value.TryGetValue(out int observed), Is.True);
Assert.That(observed, Is.EqualTo(17));
query.Response.JobOrderID = "tampered";
MachineToolJobSourceCapture captured = await source.CaptureAsync().ConfigureAwait(false);
captured.JobOrders[0].JobOrder.JobOrderID = "tampered";
captured.JobResponses[0].JobResponseID = "tampered";
Assert.That((await source.GetJobOrdersV2Async().ConfigureAwait(false))[0].JobOrder.JobOrderID,
Is.EqualTo("Job-1"));
Assert.That((await source.GetJobResponsesV2Async().ConfigureAwait(false))[0].JobResponseID,
Is.EqualTo("Response-1"));
Isa95JobResponsesByStateResultV2 byState = await source.RequestJobResponsesByStateAsync(response.JobState)
.ConfigureAwait(false);
Assert.That(byState.ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.Success));
Assert.That(byState.Responses, Has.Count.EqualTo(1));
ulong revision = (await source.ReadAsync().ConfigureAwait(false)).Revision;
Assert.That((await source.ReceiveJobResponseAsync(response).ConfigureAwait(false)).ReturnStatus,
Is.EqualTo(Isa95JobReturnStatus.InvalidRequest));
response.JobResponseID = "Response-2";
response.JobState = [new V2.ISA95StateDataType { StateNumber = 5 }];
Assert.That((await source.ReceiveJobResponseAsync(response).ConfigureAwait(false)).ReturnStatus,
Is.EqualTo(Isa95JobReturnStatus.InvalidStatus));
response.JobOrderID = "Unknown";
Assert.That((await source.ReceiveJobResponseAsync(response).ConfigureAwait(false)).ReturnStatus,
Is.EqualTo(Isa95JobReturnStatus.UnknownJobOrderId));
Assert.That((await source.ReadAsync().ConfigureAwait(false)).Revision, Is.EqualTo(revision));
Assert.That((await source.RequestJobResponsesByStateAsync([]).ConfigureAwait(false)).ReturnStatus,
Is.EqualTo(Isa95JobReturnStatus.InvalidStatus));
Assert.That((await source.RequestJobResponseByJobOrderIdAsync("Unknown").ConfigureAwait(false))
.ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.UnknownJobOrderId));
}
/// <summary>
/// DI facets share one engine per scope, never execution, counters, or source lifetime across machines.
/// </summary>
[Test]
public async Task ScopedMachinesAreIndependentAndAllProviderFacetsResolveToOneSourceAsync()
{
var services = new ServiceCollection();
services.AddMachineToolJobSource(Options());
await using ServiceProvider provider = services.BuildServiceProvider();
await using AsyncServiceScope first = provider.CreateAsyncScope();
await using AsyncServiceScope second = provider.CreateAsyncScope();
MachineToolJobSource left = first.ServiceProvider.GetRequiredService<MachineToolJobSource>();
MachineToolJobSource right = second.ServiceProvider.GetRequiredService<MachineToolJobSource>();
Assert.That(first.ServiceProvider.GetRequiredService<IMachineToolProvider>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobOrderReceiverV2>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobResponseProviderV2>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobResponseReceiverV2>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobExecutionController>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobOrderCatalog>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobResponseCatalog>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobStatusSourceV2>(), Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobOrderCatalogChangeSource>(),
Is.SameAs(left));
Assert.That(first.ServiceProvider.GetRequiredService<IIsa95JobResponseChangeSource>(), Is.SameAs(left));
await StartExecutingAsync(left).ConfigureAwait(false);
Assert.That(await right.GetJobOrdersV2Async().ConfigureAwait(false), Is.Empty);
Assert.That((await right.ReadAsync().ConfigureAwait(false)).Revision, Is.Zero);
await left.DisposeAsync().ConfigureAwait(false);
await StartExecutingAsync(right).ConfigureAwait(false);
Assert.That((await right.ReadAsync().ConfigureAwait(false)).Production.Jobs[0].TransitionSequence,
Is.EqualTo(1));
}
/// <summary>
/// Creates explicit, deterministic identities for this test family.
/// </summary>
internal static MachineToolJobSourceDescriptor Descriptor(string id = "Job-1") => new()
{
JobOrderId = id,
WorkMasterId = "WM-1",
ProgramName = "SUPPLIED.NC",
CustomerOrderIdentifier = "Customer-1",
OrderIdentifier = "Order-1"
};
/// <summary>
/// Creates a source configuration with one declared job.
/// </summary>
internal static MachineToolJobSourceOptions Options(MachineToolJobSourceDescriptor? descriptor = null) =>
new() { Jobs = [descriptor ?? Descriptor()] };
/// <summary>
/// Creates an actual generated order with an explicit work-master reference.
/// </summary>
internal static V2.ISA95JobOrderDataType Order(string id = "Job-1") => new()
{
EncodingMask = (uint)(V2.ISA95JobOrderDataTypeFields.WorkMasterID |
V2.ISA95JobOrderDataTypeFields.Priority),
JobOrderID = id,
WorkMasterID = [new V2.ISA95WorkMasterDataType { ID = "WM-1" }]
};
/// <summary>
/// Requires the actual standard success bit, not an enum ordinal or an empty bitmap.
/// </summary>
internal static void Success(Isa95JobOrderReceiptV2 receipt)
{
Assert.That(receipt.ReturnStatus, Is.EqualTo(Isa95JobReturnStatus.Success), receipt.Result.ToString());
Assert.That(ServiceResult.IsGood(receipt.Result), Is.True);
}
/// <summary>
/// Explicitly authorizes then begins simulated execution through the existing controller facet.
/// </summary>
internal static async ValueTask StartExecutingAsync(MachineToolJobSource source)
{
Success(await source.ReceiveJobOrderAsync(Isa95JobOrderOperationV2.StoreAndStart, Order())
.ConfigureAwait(false));
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.MarkReady)
.ConfigureAwait(false));
Success(await source.TransitionAsync("Job-1", Isa95JobExecutionTransition.BeginExecution)
.ConfigureAwait(false));
}
/// <summary>Raw observation metadata that must survive modern job operations unchanged.</summary>
internal static readonly MachineToolSampleInfo Acquired =
new(new DateTimeUtc(2026, 10, 1, 2, 3, 4), StatusCodes.UncertainLastUsableValue);
}
}