Files
MrAlaskan ba1d5f0b7d Fix AliasName subcategory browse continuation (#4040)
### Summary

This PR fixes `AliasNameClient.EnumerateSubCategoriesAsync()` so it
follows OPC UA `Browse` continuation points until the server has
returned every `SubAliasNameCategories` reference, and adds a regression
test covering the paged browse case that was previously truncated after
the first page.

### Problem

`EnumerateSubCategoriesAsync()` is intended to expose the full set of
sub-categories organized beneath an `AliasNameCategoryType` node.
However, the previous implementation only issued a single
`BrowseAsync()` call and immediately enumerated
`BrowseResult.References` from that first response.

Under OPC UA, servers are allowed to split browse results across
multiple pages and return a `ContinuationPoint` when the first response
does not contain the full reference set. In that situation, the client
must continue with `BrowseNext` until the continuation point is
exhausted. Because this helper never consumed the returned continuation
point, it silently dropped every sub-category that appeared after the
first page.

### Changes

- Continue sub-category enumeration with `BrowseNextAsync()` whenever
the initial `BrowseAsync()` response contains a non-empty continuation
point.
- Keep the existing filtering behavior so the helper still returns only
`AliasNameCategoryType` references that can be resolved to local
`NodeId` values.
- Add scriptable `Browse` / `BrowseNext` support to the alias-name
session test harness so paged browse behavior can be covered with a
focused unit test.
- Add a regression test that verifies `EnumerateSubCategoriesAsync()`
returns sub-categories from both the initial browse response and the
follow-up `BrowseNext` response.
2026-07-21 17:55:15 +02:00

295 lines
12 KiB
C#

/* ========================================================================
* 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.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client.AliasNames;
namespace Opc.Ua.Client.Tests.AliasNames
{
/// <summary>
/// Mocked-session unit tests for <see cref="AliasNameClient"/>
/// — covers <c>FindAlias</c> / <c>AddAliasesToCategory</c> /
/// <c>DeleteAliasesFromCategory</c> / <c>ReadLastChange</c> and the
/// hardcoded standard-method-id fast-path used when the client is
/// rooted at the well-known categories.
/// </summary>
[TestFixture]
[Category("AliasNames")]
[Parallelizable]
public class AliasNameClientTests
{
[Test]
public async Task FindAliasAsyncTargetsAliasesFindAliasMethodAsync()
{
var harness = AliasNameSessionHarness.Create();
// Server returns a single AliasNameDataType.
harness.CallHandler = _ =>
{
var entry = new AliasNameDataType
{
AliasName = new QualifiedName("Tag1"),
ReferencedNodes = new[] { new ExpandedNodeId("Target", 2) }
.ToArrayOf()
};
ArrayOf<AliasNameDataType> arr = new[] { entry }.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments =
new[] { Variant.FromStructure(arr) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
IReadOnlyList<AliasNameDataType> result = await client
.FindAliasAsync("%", referenceTypeFilter: null).ConfigureAwait(false);
Assert.That(harness.CallRequests, Has.Count.EqualTo(1));
Assert.That(harness.CallRequests[0].ObjectId, Is.EqualTo(ObjectIds.Aliases));
Assert.That(harness.CallRequests[0].MethodId,
Is.EqualTo(MethodIds.AliasNameCategoryType_FindAlias),
"Generated AliasNameCategoryTypeClient proxy invokes the " +
"type's method-declaration NodeId; the server resolves it " +
"against the supplied ObjectId.");
Assert.That(harness.CallRequests[0].InputArguments.Count, Is.EqualTo(2));
Assert.That(result, Has.Count.EqualTo(1));
Assert.That(result[0].AliasName.Name, Is.EqualTo("Tag1"));
}
[Test]
public async Task FindAliasAsyncPassesNullFilterAsNodeIdNullAsync()
{
var harness = AliasNameSessionHarness.Create();
CallMethodRequest captured = null;
harness.CallHandler = req =>
{
captured = req;
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[]
{
Variant.FromStructure(
System.Array.Empty<AliasNameDataType>().ToArrayOf())
}.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardTopics(harness.Session);
await client.FindAliasAsync("Foo", null).ConfigureAwait(false);
Assert.That(captured, Is.Not.Null);
Assert.That(captured.ObjectId, Is.EqualTo(ObjectIds.Topics));
Assert.That(captured.MethodId,
Is.EqualTo(MethodIds.AliasNameCategoryType_FindAlias));
captured.InputArguments[1].TryGetValue(out NodeId filter);
Assert.That(filter.IsNull, Is.True);
}
[Test]
public async Task ReadLastChangeAsyncTargetsStandardAliasesLastChangeAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.ReadHandler = read =>
{
Assert.That(read.NodeId,
Is.EqualTo(VariableIds.Aliases_LastChange));
return new DataValue(new Variant((uint)42), StatusCodes.Good);
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
uint? lastChange = await client.ReadLastChangeAsync().ConfigureAwait(false);
Assert.That(lastChange, Is.EqualTo((uint?)42));
}
[Test]
public async Task AddAliasesToCategoryAsyncReturnsPerEntryStatusCodesAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ =>
{
ArrayOf<StatusCode> codes = new StatusCode[]
{
StatusCodes.Good,
StatusCodes.BadBrowseNameDuplicated
}.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[] { Variant.From(codes) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
client.Options.AllowVerboseProbe = false;
StatusCode[] result = await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T1", 2),
null, ReferenceTypeIds.AliasFor),
new AliasNameAddRequest("A",
new ExpandedNodeId("T1", 2),
null, ReferenceTypeIds.AliasFor)
]).ConfigureAwait(false);
Assert.That(result, Has.Length.EqualTo(2));
Assert.That(result[0].Code, Is.EqualTo(StatusCodes.Good));
Assert.That(result[1].Code,
Is.EqualTo(StatusCodes.BadBrowseNameDuplicated));
}
[Test]
public void AddAliasesToCategoryRejectsMixedReferenceTypes()
{
var harness = AliasNameSessionHarness.Create();
var client = AliasNameClient.OpenStandardAliases(harness.Session);
Assert.That(async () =>
{
await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.AliasFor),
new AliasNameAddRequest("B",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.Organizes)
]).ConfigureAwait(false);
}, Throws.ArgumentException);
}
[Test]
public async Task DeleteAliasesFromCategoryAsyncSendsParallelArraysAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ =>
{
ArrayOf<StatusCode> codes =
new StatusCode[] { StatusCodes.Good }.ToArrayOf();
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[] { Variant.From(codes) }.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
StatusCode[] result = await client.DeleteAliasesFromCategoryAsync(
[
new AliasNameDeleteRequest("A", new ExpandedNodeId("T", 2))
]).ConfigureAwait(false);
Assert.That(result, Has.Length.EqualTo(1));
Assert.That(harness.CallRequests, Has.Count.EqualTo(1));
Assert.That(harness.CallRequests[0].InputArguments.Count, Is.EqualTo(2));
}
[Test]
public void AddAliasesMapsBadUserAccessDeniedToUnauthorizedAccessException()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => new CallMethodResult
{
StatusCode = StatusCodes.BadUserAccessDenied
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
Assert.That(async () =>
{
await client.AddAliasesToCategoryAsync(
[
new AliasNameAddRequest("A",
new ExpandedNodeId("T", 2),
null, ReferenceTypeIds.AliasFor)
]).ConfigureAwait(false);
}, Throws.TypeOf<System.UnauthorizedAccessException>());
}
[Test]
public async Task EnumerateSubCategoriesAsyncFollowsBrowseContinuationPointsAsync()
{
var harness = AliasNameSessionHarness.Create();
var continuationPoint = new ByteString(new byte[] { 0x01 });
harness.BrowseHandler = description =>
{
Assert.That(description.NodeId, Is.EqualTo(ObjectIds.Aliases));
return new BrowseResult
{
StatusCode = StatusCodes.Good,
ContinuationPoint = continuationPoint,
References = new[]
{
CreateCategoryReference("Page1", "Page1")
}.ToArrayOf()
};
};
harness.BrowseNextHandler = cp =>
{
Assert.That(cp, Is.EqualTo(continuationPoint));
return new BrowseResult
{
StatusCode = StatusCodes.Good,
ContinuationPoint = ByteString.Empty,
References = new[]
{
CreateCategoryReference("Page2", "Page2")
}.ToArrayOf()
};
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
var names = new List<string>();
await foreach (AliasNameSubCategoryInfo info in
client.EnumerateSubCategoriesAsync().ConfigureAwait(false))
{
names.Add(info.BrowseName.Name);
}
var expectedNames = new[] { "Page1", "Page2" };
Assert.That(names, Is.EqualTo(expectedNames));
Assert.That(harness.BrowseRequests, Has.Count.EqualTo(1));
Assert.That(harness.BrowseNextRequests, Has.Count.EqualTo(1));
static ReferenceDescription CreateCategoryReference(
string browseName,
string nodeId)
{
return new ReferenceDescription
{
NodeId = new ExpandedNodeId(new NodeId(nodeId, 2)),
BrowseName = new QualifiedName(browseName, 2),
DisplayName = new LocalizedText(browseName),
TypeDefinition = ObjectTypeIds.AliasNameCategoryType
};
}
}
}
}