Repository navigation
Expand file tree
/
Copy pathMachineToolNotificationLifetimeTests.cs
More file actions
177 lines (171 loc) · 9.61 KB
/
Copy pathMachineToolNotificationLifetimeTests.cs
File metadata and controls
177 lines (171 loc) · 9.61 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
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT
using System;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Opc.Ua.Client;
using Opc.Ua.Client.Alarms;
using Opc.Ua.Client.TestFramework;
using Opc.Ua.MachineTool.Server;
using Opc.Ua.Tests;
namespace Opc.Ua.MachineTool.Tests
{
/// <summary>
/// Exercises provider cancellation, callback reentrancy, per-instance disposal and standard method permissions.
/// </summary>
[TestFixture]
[NonParallelizable]
[Category("MachineTool")]
public sealed class MachineToolNotificationLifetimeTests
{
/// <summary>
/// Runtime removal cancels and drains only its own admitted notification acquisition.
/// </summary>
[TestCase(false)]
[TestCase(true)]
public async Task CancellationAndRemovalDrainAcquisitionWithoutChangingOtherMachinesAsync(bool remove)
{
await using var fixture = new MachineToolRuntimeFixture();
await fixture.StartAsync().ConfigureAwait(false);
int reads = 0;
var entered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var provider = new Mock<IMachineToolNotificationProvider>(MockBehavior.Strict);
provider.Setup(source => source.ReadAsync(It.IsAny<ulong>(), It.IsAny<CancellationToken>()))
.Returns((ulong _, CancellationToken ct) => ReadAsync(ct));
await using MachineToolRuntime<MachineToolState> runtime =
await MachineToolNotificationTests.BuildAsync(fixture, provider.Object, "Blocking")
.ConfigureAwait(false);
var otherProvider = new MachineToolNotificationTests.NotificationProvider(
new MachineToolNotificationSnapshot());
await using MachineToolRuntime<MachineToolState> other =
await MachineToolNotificationTests.BuildAsync(fixture, otherProvider, "Independent")
.ConfigureAwait(false);
using var cancellation = new CancellationTokenSource();
Task pending = runtime.RefreshNotificationsAsync(cancellation.Token).AsTask();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
if (remove)
{
await runtime.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
}
else
{
await cancellation.CancelAsync().ConfigureAwait(false);
}
await Assert.ThatAsync(async () => await pending.ConfigureAwait(false),
Throws.InstanceOf<OperationCanceledException>()).ConfigureAwait(false);
await other.RefreshNotificationsAsync().ConfigureAwait(false);
Assert.That(fixture.Context.Manager.FindPredefinedNode(other.NodeId), Is.SameAs(other.State));
if (remove)
{
Assert.That(fixture.Context.Manager.FindPredefinedNode(runtime.NodeId), Is.Null);
await Assert.ThrowsAsync<ObjectDisposedException>(async () =>
await runtime.RefreshNotificationsAsync().ConfigureAwait(false));
}
else
{
Assert.That(fixture.Context.Manager.FindPredefinedNode(runtime.NodeId), Is.SameAs(runtime.State));
Assert.That(runtime.Notifications!.Observation!.Revision, Is.Zero);
}
async ValueTask<MachineToolNotificationSnapshot> ReadAsync(CancellationToken ct)
{
if (Interlocked.Increment(ref reads) != 1)
{
entered.TrySetResult(true);
await Task.Delay(Timeout.InfiniteTimeSpan, ct).ConfigureAwait(false);
}
return new MachineToolNotificationSnapshot();
}
}
/// <summary>
/// Provider callbacks cannot recursively update or await disposal of their own runtime.
/// </summary>
[Test]
public async Task ReentrantProviderOperationsFailPromptlyWithoutDeadlockAsync()
{
await using var fixture = new MachineToolRuntimeFixture();
await fixture.StartAsync().ConfigureAwait(false);
MachineToolRuntime<MachineToolState>? runtime = null;
var provider = new Mock<IMachineToolNotificationProvider>(MockBehavior.Strict);
provider.Setup(source => source.ReadAsync(It.IsAny<ulong>(), It.IsAny<CancellationToken>()))
.Returns((ulong _, CancellationToken _) => ReadAsync());
runtime = await MachineToolNotificationTests.BuildAsync(fixture, provider.Object).ConfigureAwait(false);
await using (runtime.ConfigureAwait(false))
{
await runtime.RefreshNotificationsAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5))
.ConfigureAwait(false);
}
async ValueTask<MachineToolNotificationSnapshot> ReadAsync()
{
if (runtime != null)
{
await Assert.ThatAsync(async () => await runtime.DisposeAsync().ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadInvalidState)).ConfigureAwait(false);
await Assert.ThatAsync(async () => await runtime.RefreshAsync().ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadInvalidState)).ConfigureAwait(false);
await Assert.ThatAsync(
async () => await runtime.Notifications!.DisposeAsync().ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadInvalidState)).ConfigureAwait(false);
}
return new MachineToolNotificationSnapshot();
}
}
/// <summary>
/// Enable, disable, comment and acknowledge use existing Part 9 methods and the latest provider permissions.
/// </summary>
[Test]
public async Task StandardConditionMethodsRespectPermissionsAndNeverResetEquipmentAsync()
{
await using var fixture = new MachineToolRuntimeFixture();
await fixture.StartAsync().ConfigureAwait(false);
MachineToolAlert alert = MachineToolNotificationValidationTests.Alert();
var provider = new MachineToolNotificationTests.NotificationProvider(
new MachineToolNotificationSnapshot { Alerts = [alert] });
await using MachineToolRuntime<MachineToolState> runtime =
await MachineToolNotificationTests.BuildAsync(fixture, provider).ConfigureAwait(false);
Assert.That(runtime.Notifications!.TryGetAlert(alert.Key, out AlertState? state), Is.True);
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
await using var transport = new ClientFixture(telemetry);
await transport.LoadClientConfigurationAsync(fixture.Root, "ConditionPermissions").ConfigureAwait(false);
using ISession session = await transport.ConnectAsync(fixture.Endpoint, SecurityPolicies.None)
.ConfigureAwait(false);
var client = new AlarmClient(session, telemetry);
await client.AddCommentAsync(state!.NodeId, state.EventId!.Value, new LocalizedText("Inspected"))
.ConfigureAwait(false);
Assert.That(state.Comment!.Value.Text, Is.EqualTo("Inspected"));
await client.DisableAsync(state.NodeId).ConfigureAwait(false);
Assert.That(state.EnabledState!.Id!.Value, Is.False);
Assert.That(state.Retain!.Value, Is.False);
await client.EnableAsync(state.NodeId).ConfigureAwait(false);
Assert.That(state.Retain.Value, Is.True);
provider.Snapshot = new MachineToolNotificationSnapshot
{
Revision = 1,
Alerts = [alert with { AllowedOperations = MachineToolConditionOperations.None }]
};
await runtime.RefreshNotificationsAsync().ConfigureAwait(false);
await Assert.ThatAsync(async () =>
await client.AcknowledgeAsync(state.NodeId, state.EventId.Value, new LocalizedText("Denied"))
.ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadUserAccessDenied)).ConfigureAwait(false);
await Assert.ThatAsync(async () => await client.DisableAsync(state.NodeId).ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadUserAccessDenied)).ConfigureAwait(false);
await Assert.ThatAsync(async () =>
await client.AddCommentAsync(state.NodeId, state.EventId.Value, new LocalizedText("Denied"))
.ConfigureAwait(false),
Throws.TypeOf<ServiceResultException>().With.Property("StatusCode")
.EqualTo(StatusCodes.BadUserAccessDenied)).ConfigureAwait(false);
Assert.That(state.ActiveState!.Id!.Value, Is.True);
Assert.That(state.AckedState!.Id!.Value, Is.False);
Assert.That(state.Comment.Value.Text, Is.EqualTo("Inspected"));
Assert.That(state.Confirm, Is.Null);
await session.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
}
}