/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
// CA2000: test code; the sampling group is short-lived and disposed per test.
#pragma warning disable CA2000
namespace Opc.Ua.Server.Tests.NodeManager
{
///
/// Deterministic, offline unit tests for that
/// exercise construction validation and the MeetsGroupCriteria
/// branches without ever starting the background sampling loop.
///
[TestFixture]
[Category("NodeManager")]
[Category("SamplingGroup")]
[Parallelizable(ParallelScope.All)]
public class SamplingGroupTests
{
private static List SamplingRates()
{
return [new SamplingRateGroup(1000, 0, 1)];
}
private static OperationContext SessionlessContext()
{
return new OperationContext(
new RequestHeader(), null, RequestType.CreateMonitoredItems, RequestLifetime.None);
}
private static OperationContext SessionContext(ISession session)
{
return new OperationContext(
new RequestHeader(), null!, RequestType.CreateMonitoredItems, RequestLifetime.None, session);
}
private static Mock CreateSessionMock(NodeId id, IUserIdentity identity)
{
var session = new Mock();
session.SetupGet(s => s.Id).Returns(id);
session.SetupGet(s => s.EffectiveIdentity).Returns(identity);
return session;
}
private static SamplingGroup CreateGroup(
IUserIdentity identity,
double samplingInterval = 500,
OperationContext? context = null)
{
Mock mockServer = DeterministicServerMock.Create(out _);
var mockNodeManager = new Mock();
return new SamplingGroup(
mockServer.Object,
mockNodeManager.Object,
SamplingRates(),
context ?? SessionlessContext(),
samplingInterval,
identity);
}
private static Mock CreateItem(
int type = MonitoredItemTypeMask.DataChange,
MonitoringMode mode = MonitoringMode.Reporting,
double samplingInterval = 500)
{
var item = new Mock();
item.SetupGet(m => m.Id).Returns(1);
item.SetupGet(m => m.MonitoredItemType).Returns(type);
item.SetupGet(m => m.MonitoringMode).Returns(mode);
item.SetupGet(m => m.SamplingInterval).Returns(samplingInterval);
return item;
}
///
/// Verifies that sampling-group construction rejects a null server.
///
[Test]
public void ConstructorWithNullServerThrows()
{
var nm = new Mock();
Assert.That(
() => new SamplingGroup(
null!, nm.Object, SamplingRates(), SessionlessContext(), 500,
new Mock().Object),
Throws.TypeOf());
}
///
/// Verifies that sampling-group construction rejects a null node manager.
///
[Test]
public void ConstructorWithNullNodeManagerThrows()
{
Mock mockServer = DeterministicServerMock.Create(out _);
Assert.That(
() => new SamplingGroup(
mockServer.Object, null!, SamplingRates(), SessionlessContext(), 500,
new Mock().Object),
Throws.TypeOf());
}
///
/// Verifies that sampling-group construction rejects null sampling rates.
///
[Test]
public void ConstructorWithNullSamplingRatesThrows()
{
Mock mockServer = DeterministicServerMock.Create(out _);
var nm = new Mock();
Assert.That(
() => new SamplingGroup(
mockServer.Object, nm.Object, null!, SessionlessContext(), 500,
new Mock().Object),
Throws.TypeOf());
}
///
/// Verifies that a sessionless sampling group requires an owner identity.
///
[Test]
public void ConstructorSessionlessWithoutOwnerIdentityThrows()
{
Mock mockServer = DeterministicServerMock.Create(out _);
var nm = new Mock();
Assert.That(
() => new SamplingGroup(
mockServer.Object, nm.Object, SamplingRates(), SessionlessContext(), 500,
savedOwnerIdentity: null),
Throws.TypeOf());
}
///
/// Verifies that a sampling group rejects items that do not monitor data changes.
///
[Test]
public void StartMonitoringRejectsNonDataChangeItem()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem(type: MonitoredItemTypeMask.Events);
bool added = group.StartMonitoring(SessionlessContext(), item.Object, identity.Object);
Assert.That(added, Is.False);
}
///
/// Verifies that a sampling group rejects disabled monitored items.
///
[Test]
public void StartMonitoringRejectsDisabledItem()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem(mode: MonitoringMode.Disabled);
bool added = group.StartMonitoring(SessionlessContext(), item.Object, identity.Object);
Assert.That(added, Is.False);
}
///
/// Verifies that a sampling group rejects items with a mismatched sampling interval.
///
[Test]
public void StartMonitoringRejectsMismatchedSamplingInterval()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem(samplingInterval: 5000);
bool added = group.StartMonitoring(SessionlessContext(), item.Object, identity.Object);
Assert.That(added, Is.False);
}
///
/// Verifies that a sampling group rejects items belonging to another session.
///
[Test]
public void StartMonitoringRejectsMismatchedSession()
{
var identity = new Mock();
Mock sessionA = CreateSessionMock(new NodeId(1, 1), identity.Object);
Mock sessionB = CreateSessionMock(new NodeId(2, 1), identity.Object);
using SamplingGroup group = CreateGroup(
identity.Object, context: SessionContext(sessionA.Object));
Mock item = CreateItem();
bool added = group.StartMonitoring(
SessionContext(sessionB.Object), item.Object, identity.Object);
Assert.That(added, Is.False);
}
///
/// Verifies that a sampling group accepts a matching monitored item.
///
[Test]
public void StartMonitoringAcceptsMatchingItem()
{
var identity = new Mock();
Mock session = CreateSessionMock(new NodeId(1234, 1), identity.Object);
OperationContext context = SessionContext(session.Object);
using SamplingGroup group = CreateGroup(identity.Object, context: context);
Mock item = CreateItem();
bool added = group.StartMonitoring(context, item.Object, identity.Object);
Assert.That(added, Is.True);
item.Verify(m => m.SetSamplingInterval(1000.0), Times.Once);
}
///
/// Verifies that a sessionless sampling group accepts an item with the matching owner identity.
///
[Test]
public void StartMonitoringAcceptsMatchingItemSessionlessByOwnerIdentity()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(
identity.Object, context: SessionlessContext());
Mock item = CreateItem();
bool added = group.StartMonitoring(
SessionlessContext(), item.Object, identity.Object);
bool addedWithNullContext = group.StartMonitoring(
null!, item.Object, identity.Object);
Assert.That(added, Is.True);
Assert.That(addedWithNullContext, Is.False);
item.Verify(m => m.SetSamplingInterval(1000.0), Times.Once);
}
///
/// Verifies that a sessionless sampling group rejects an item with a different owner identity.
///
[Test]
public void StartMonitoringRejectsMismatchedOwnerIdentitySessionless()
{
var identity = new Mock();
var otherIdentity = new Mock();
using SamplingGroup group = CreateGroup(
identity.Object, context: SessionlessContext());
Mock item = CreateItem();
bool added = group.StartMonitoring(
SessionlessContext(), item.Object, otherIdentity.Object);
Assert.That(added, Is.False);
}
///
/// Verifies that stopping an unknown monitored item returns false.
///
[Test]
public void StopMonitoringReturnsFalseForUnknownItem()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem();
Assert.That(group.StopMonitoring(item.Object), Is.False);
}
///
/// Verifies that stopping an item removes its pending addition to the sampling group.
///
[Test]
public void StopMonitoringRemovesItemPendingAddition()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem();
Assert.That(
group.StartMonitoring(
SessionlessContext(),
item.Object,
identity.Object),
Is.True);
Assert.That(group.StopMonitoring(item.Object), Is.True);
Assert.That(group.ApplyChanges(), Is.True);
}
///
/// Verifies that modifying an unknown monitored item returns false.
///
[Test]
public void ModifyMonitoringReturnsFalseForUnknownItem()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Mock item = CreateItem();
Assert.That(group.ModifyMonitoring(SessionlessContext(), item.Object), Is.False);
}
///
/// Verifies that applying changes without monitored items reports an empty sampling group.
///
[Test]
public void ApplyChangesWithoutItemsReportsGroupEmpty()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Assert.That(group.ApplyChanges(), Is.True);
}
///
/// Verifies that shutting down a sampling group before it starts is safe.
///
[Test]
public void ShutdownIsSafeWhenNotStarted()
{
var identity = new Mock();
using SamplingGroup group = CreateGroup(identity.Object);
Assert.DoesNotThrow(group.Shutdown);
}
///
/// Verifies that an item transferred to another session is read and permission-checked
/// as the new owner, not as the session that created the sampling group.
///
[Test]
public async Task SampleUsesSessionOfTransferredItemAsync()
{
var creatorIdentity = new Mock();
var ownerIdentity = new Mock();
Mock creator = CreateSessionMock(new NodeId(1, 1), creatorIdentity.Object);
Mock owner = CreateSessionMock(new NodeId(2, 1), ownerIdentity.Object);
OperationContext creatorContext = SessionContext(creator.Object);
var readIdentity = new TaskCompletionSource(
TaskCreationOptions.RunContinuationsAsynchronously);
var permissionIdentity = new TaskCompletionSource(
TaskCreationOptions.RunContinuationsAsynchronously);
var nodeManager = new Mock();
nodeManager
.Setup(m => m.ReadAsync(
It.IsAny(),
It.IsAny(),
It.IsAny>(),
It.IsAny>(),
It.IsAny>(),
It.IsAny()))
.Callback, IList,
IList, CancellationToken>(
(context, _, _, _, _, _) => readIdentity.TrySetResult(context.UserIdentity))
.Returns(default(ValueTask));
nodeManager
.Setup(m => m.ValidateRolePermissionsAsync(
It.IsAny(),
It.IsAny(),
PermissionType.Read,
It.IsAny()))
.Callback(
(context, _, _, _) => permissionIdentity.TrySetResult(context.UserIdentity))
.Returns(new ValueTask(ServiceResult.Good));
Mock mockServer = DeterministicServerMock.Create(out _);
using var group = new SamplingGroup(
mockServer.Object,
nodeManager.Object,
SamplingRates(),
creatorContext,
500);
Mock item = CreateItem();
item.SetupGet(m => m.Session).Returns(owner.Object);
item.Setup(m => m.GetReadValueId()).Returns(new ReadValueId
{
NodeId = new NodeId(10, 1),
AttributeId = Attributes.Value
});
Assert.That(group.StartMonitoring(creatorContext, item.Object), Is.True);
group.ApplyChanges();
Assert.That(
await readIdentity.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false),
Is.SameAs(ownerIdentity.Object));
Assert.That(
await permissionIdentity.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false),
Is.SameAs(ownerIdentity.Object));
}
}
}